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 |
---|---|---|---|---|---|---|---|---|---|---|---|
opulent/opulent | lib/opulent/parser/filter.rb | Opulent.Parser.filter | def filter(parent, indent)
return unless (filter_name = accept :filter)
# Get element attributes
atts = attributes(shorthand_attributes) || {}
# Accept inline text or multiline text feed as first child
error :fiter unless accept(:line_feed).strip.empty?
# Get everything under the filter and set it as the node value
# and create a new node and set its extension
parent[@children] << [
:filter,
filter_name[1..-1].to_sym,
atts,
get_indented_lines(indent),
indent
]
end | ruby | def filter(parent, indent)
return unless (filter_name = accept :filter)
# Get element attributes
atts = attributes(shorthand_attributes) || {}
# Accept inline text or multiline text feed as first child
error :fiter unless accept(:line_feed).strip.empty?
# Get everything under the filter and set it as the node value
# and create a new node and set its extension
parent[@children] << [
:filter,
filter_name[1..-1].to_sym,
atts,
get_indented_lines(indent),
indent
]
end | [
"def",
"filter",
"(",
"parent",
",",
"indent",
")",
"return",
"unless",
"(",
"filter_name",
"=",
"accept",
":filter",
")",
"atts",
"=",
"attributes",
"(",
"shorthand_attributes",
")",
"||",
"{",
"}",
"error",
":fiter",
"unless",
"accept",
"(",
":line_feed",
")",
".",
"strip",
".",
"empty?",
"parent",
"[",
"@children",
"]",
"<<",
"[",
":filter",
",",
"filter_name",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"to_sym",
",",
"atts",
",",
"get_indented_lines",
"(",
"indent",
")",
",",
"indent",
"]",
"end"
] | Check if we match an compile time filter
:filter
@param parent [Node] Parent node to which we append the element | [
"Check",
"if",
"we",
"match",
"an",
"compile",
"time",
"filter"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/filter.rb#L11-L29 | train |
opulent/opulent | lib/opulent/compiler/text.rb | Opulent.Compiler.plain | def plain(node, indent)
# Text value
value = node[@options][:value]
# Pretty print
if @settings[:pretty]
indentation = ' ' * indent
inline = @sibling_stack[-1][-1] &&
@sibling_stack[-1][-1][0] == :node &&
Settings::INLINE_NODE.include?(@sibling_stack[-1][-1][1])
# Add current node to the siblings stack
@sibling_stack[-1] << [node[@type], node[@value]]
# If we have a text on multiple lines and the text isn't supposed to be
# inline, indent all the lines of the text
if node[@value] == :text
if !inline
value.gsub!(/^(?!$)/, indentation)
else
buffer_remove_trailing_newline
value.strip!
end
else
buffer_freeze indentation
end
end
# Leading whitespace
buffer_freeze ' ' if node[@options][:leading_whitespace]
# Evaluate text node if it's marked as such and print nodes in the
# current context
if node[@value] == :text
buffer_split_by_interpolation value, node[@options][:escaped]
else
node[@options][:escaped] ? buffer_escape(value) : buffer(value)
end
# Trailing whitespace
buffer_freeze ' ' if node[@options][:trailing_whitespace]
# Pretty print
if @settings[:pretty]
buffer_freeze "\n" if !inline or node[@value] == :print
end
end | ruby | def plain(node, indent)
# Text value
value = node[@options][:value]
# Pretty print
if @settings[:pretty]
indentation = ' ' * indent
inline = @sibling_stack[-1][-1] &&
@sibling_stack[-1][-1][0] == :node &&
Settings::INLINE_NODE.include?(@sibling_stack[-1][-1][1])
# Add current node to the siblings stack
@sibling_stack[-1] << [node[@type], node[@value]]
# If we have a text on multiple lines and the text isn't supposed to be
# inline, indent all the lines of the text
if node[@value] == :text
if !inline
value.gsub!(/^(?!$)/, indentation)
else
buffer_remove_trailing_newline
value.strip!
end
else
buffer_freeze indentation
end
end
# Leading whitespace
buffer_freeze ' ' if node[@options][:leading_whitespace]
# Evaluate text node if it's marked as such and print nodes in the
# current context
if node[@value] == :text
buffer_split_by_interpolation value, node[@options][:escaped]
else
node[@options][:escaped] ? buffer_escape(value) : buffer(value)
end
# Trailing whitespace
buffer_freeze ' ' if node[@options][:trailing_whitespace]
# Pretty print
if @settings[:pretty]
buffer_freeze "\n" if !inline or node[@value] == :print
end
end | [
"def",
"plain",
"(",
"node",
",",
"indent",
")",
"value",
"=",
"node",
"[",
"@options",
"]",
"[",
":value",
"]",
"if",
"@settings",
"[",
":pretty",
"]",
"indentation",
"=",
"' '",
"*",
"indent",
"inline",
"=",
"@sibling_stack",
"[",
"-",
"1",
"]",
"[",
"-",
"1",
"]",
"&&",
"@sibling_stack",
"[",
"-",
"1",
"]",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"==",
":node",
"&&",
"Settings",
"::",
"INLINE_NODE",
".",
"include?",
"(",
"@sibling_stack",
"[",
"-",
"1",
"]",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
")",
"@sibling_stack",
"[",
"-",
"1",
"]",
"<<",
"[",
"node",
"[",
"@type",
"]",
",",
"node",
"[",
"@value",
"]",
"]",
"if",
"node",
"[",
"@value",
"]",
"==",
":text",
"if",
"!",
"inline",
"value",
".",
"gsub!",
"(",
"/",
"/",
",",
"indentation",
")",
"else",
"buffer_remove_trailing_newline",
"value",
".",
"strip!",
"end",
"else",
"buffer_freeze",
"indentation",
"end",
"end",
"buffer_freeze",
"' '",
"if",
"node",
"[",
"@options",
"]",
"[",
":leading_whitespace",
"]",
"if",
"node",
"[",
"@value",
"]",
"==",
":text",
"buffer_split_by_interpolation",
"value",
",",
"node",
"[",
"@options",
"]",
"[",
":escaped",
"]",
"else",
"node",
"[",
"@options",
"]",
"[",
":escaped",
"]",
"?",
"buffer_escape",
"(",
"value",
")",
":",
"buffer",
"(",
"value",
")",
"end",
"buffer_freeze",
"' '",
"if",
"node",
"[",
"@options",
"]",
"[",
":trailing_whitespace",
"]",
"if",
"@settings",
"[",
":pretty",
"]",
"buffer_freeze",
"\"\\n\"",
"if",
"!",
"inline",
"or",
"node",
"[",
"@value",
"]",
"==",
":print",
"end",
"end"
] | Generate the code for a standard text node
@param node [Array] Node code generation data
@param indent [Fixnum] Size of the indentation to be added | [
"Generate",
"the",
"code",
"for",
"a",
"standard",
"text",
"node"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/compiler/text.rb#L10-L57 | train |
opulent/opulent | lib/opulent/parser/include.rb | Opulent.Parser.include_file | def include_file(_parent, indent)
return unless accept :include
# Process data
name = accept :line_feed || ''
name.strip!
# Check if there is any string after the include input
Logger.error :parse, @code, @i, @j, :include_end if name.empty?
# Get the complete file path based on the current file being compiled
include_path = File.expand_path name, File.dirname(@file[-1][0])
# Try to see if it has any existing extension, otherwise add .op
include_path += Settings::FILE_EXTENSION if File.extname(name).empty?
# Throw an error if the file doesn't exist
unless Dir[include_path].any?
Logger.error :parse, @code, @i, @j, :include, name
end
# include entire directory tree
Dir[include_path].each do |file|
# Skip current file when including from same directory
next if file == @file[-1][0]
@file << [include_path, indent]
# Throw an error if the file doesn't exist
if File.directory? file
Logger.error :parse, @code, @i, @j, :include_dir, file
end
# Throw an error if the file doesn't exist
unless File.file? file
Logger.error :parse, @code, @i, @j, :include, file
end
# Indent all lines and prepare them for the parser
lines = indent_lines File.read(file), ' ' * indent
lines << ' '
# Indent all the output lines with the current indentation
@code.insert @i + 1, *lines.lines
end
true
end | ruby | def include_file(_parent, indent)
return unless accept :include
# Process data
name = accept :line_feed || ''
name.strip!
# Check if there is any string after the include input
Logger.error :parse, @code, @i, @j, :include_end if name.empty?
# Get the complete file path based on the current file being compiled
include_path = File.expand_path name, File.dirname(@file[-1][0])
# Try to see if it has any existing extension, otherwise add .op
include_path += Settings::FILE_EXTENSION if File.extname(name).empty?
# Throw an error if the file doesn't exist
unless Dir[include_path].any?
Logger.error :parse, @code, @i, @j, :include, name
end
# include entire directory tree
Dir[include_path].each do |file|
# Skip current file when including from same directory
next if file == @file[-1][0]
@file << [include_path, indent]
# Throw an error if the file doesn't exist
if File.directory? file
Logger.error :parse, @code, @i, @j, :include_dir, file
end
# Throw an error if the file doesn't exist
unless File.file? file
Logger.error :parse, @code, @i, @j, :include, file
end
# Indent all lines and prepare them for the parser
lines = indent_lines File.read(file), ' ' * indent
lines << ' '
# Indent all the output lines with the current indentation
@code.insert @i + 1, *lines.lines
end
true
end | [
"def",
"include_file",
"(",
"_parent",
",",
"indent",
")",
"return",
"unless",
"accept",
":include",
"name",
"=",
"accept",
":line_feed",
"||",
"''",
"name",
".",
"strip!",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":include_end",
"if",
"name",
".",
"empty?",
"include_path",
"=",
"File",
".",
"expand_path",
"name",
",",
"File",
".",
"dirname",
"(",
"@file",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
")",
"include_path",
"+=",
"Settings",
"::",
"FILE_EXTENSION",
"if",
"File",
".",
"extname",
"(",
"name",
")",
".",
"empty?",
"unless",
"Dir",
"[",
"include_path",
"]",
".",
"any?",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":include",
",",
"name",
"end",
"Dir",
"[",
"include_path",
"]",
".",
"each",
"do",
"|",
"file",
"|",
"next",
"if",
"file",
"==",
"@file",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"@file",
"<<",
"[",
"include_path",
",",
"indent",
"]",
"if",
"File",
".",
"directory?",
"file",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":include_dir",
",",
"file",
"end",
"unless",
"File",
".",
"file?",
"file",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":include",
",",
"file",
"end",
"lines",
"=",
"indent_lines",
"File",
".",
"read",
"(",
"file",
")",
",",
"' '",
"*",
"indent",
"lines",
"<<",
"' '",
"@code",
".",
"insert",
"@i",
"+",
"1",
",",
"*",
"lines",
".",
"lines",
"end",
"true",
"end"
] | Check if we have an include node, which will include a new file inside
of the current one to be parsed
@param parent [Array] Parent node to which we append to | [
"Check",
"if",
"we",
"have",
"an",
"include",
"node",
"which",
"will",
"include",
"a",
"new",
"file",
"inside",
"of",
"the",
"current",
"one",
"to",
"be",
"parsed"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/include.rb#L10-L57 | train |
redbooth/redbooth-ruby | lib/redbooth-ruby/base.rb | RedboothRuby.Base.parse_timestamps | def parse_timestamps
@created_time = created_time.to_i if created_time.is_a? String
@created_time = Time.at(created_time) if created_time
end | ruby | def parse_timestamps
@created_time = created_time.to_i if created_time.is_a? String
@created_time = Time.at(created_time) if created_time
end | [
"def",
"parse_timestamps",
"@created_time",
"=",
"created_time",
".",
"to_i",
"if",
"created_time",
".",
"is_a?",
"String",
"@created_time",
"=",
"Time",
".",
"at",
"(",
"created_time",
")",
"if",
"created_time",
"end"
] | Parses UNIX timestamps and creates Time objects. | [
"Parses",
"UNIX",
"timestamps",
"and",
"creates",
"Time",
"objects",
"."
] | fb6bc228a9346d4db476032f0df16c9588fdfbe1 | https://github.com/redbooth/redbooth-ruby/blob/fb6bc228a9346d4db476032f0df16c9588fdfbe1/lib/redbooth-ruby/base.rb#L38-L41 | train |
opulent/opulent | lib/opulent/compiler/node.rb | Opulent.Compiler.node | def node(node, indent)
# Pretty print
if @settings[:pretty]
indentation = ' ' * indent
inline = Settings::INLINE_NODE.include? node[@value]
indentate = proc do
if @in_definition
buffer "' ' * (indent + #{indent})"
else
buffer_freeze indentation
end
end
if inline
inline_last_sibling = @sibling_stack[-1][-1] ? Settings::INLINE_NODE.include?(@sibling_stack[-1][-1][1]) : true
if @sibling_stack[-1][-1] && @sibling_stack[-1][-1][0] == :plain
buffer_remove_trailing_newline
end
if @in_definition || @sibling_stack[-1].length == 1 || !inline_last_sibling
indentate[]
end
else
indentate[]
end
@sibling_stack[-1] << [node[@type], node[@value]]
@sibling_stack << [[node[@type], node[@value]]]
end
# Add the tag opening, with leading whitespace to the code buffer
buffer_freeze ' ' if node[@options][:leading_whitespace]
buffer_freeze "<#{node[@value]}"
# Evaluate node extension in the current context
if node[@options][:extension]
extension_name = buffer_set_variable :extension,
node[@options][:extension][@value]
extension = {
name: extension_name,
escaped: node[@options][:extension][@options][:escaped]
}
end
# Evaluate and generate node attributes, then process each one to
# by generating the required attribute code
buffer_attributes node[@options][:attributes],
extension
# Check if the current node is self enclosing. Self enclosing nodes
# do not have any child elements
if node[@options][:self_enclosing]
# If the tag is self enclosing, it cannot have any child elements.
buffer_freeze '>'
# Pretty print
buffer_freeze "\n" if @settings[:pretty]
# If we mistakenly add children to self enclosing nodes,
# process each child element as if it was correctly indented
# node[@children].each do |child|
# root child, indent + @settings[:indent]
# end
else
# Set tag ending code
buffer_freeze '>'
# Pretty print
if @settings[:pretty]
if node[@children].length > 0
buffer_freeze "\n" unless inline
end
# @sibling_stack << [[node[@type], node[@value]]]
end
# Process each child element recursively, increasing indentation
node[@children].each do |child|
root child, indent + @settings[:indent]
end
inline_last_child = @sibling_stack[-1][-2] &&
(@sibling_stack[-1][-2][0] == :plain ||
Settings::INLINE_NODE.include?(@sibling_stack[-1][-2][1]))
# Pretty print
if @settings[:pretty]
if node[@children].length > 1 && inline_last_child
buffer_freeze "\n"
end
if node[@children].size > 0 && !inline
indentate[]
end
end
# Set tag closing code
buffer_freeze "</#{node[@value]}>"
buffer_freeze ' ' if node[@options][:trailing_whitespace]
# Pretty print
if @settings[:pretty]
buffer_freeze "\n" if !inline || @in_definition
end
end
if @settings[:pretty]
@sibling_stack.pop
end
end | ruby | def node(node, indent)
# Pretty print
if @settings[:pretty]
indentation = ' ' * indent
inline = Settings::INLINE_NODE.include? node[@value]
indentate = proc do
if @in_definition
buffer "' ' * (indent + #{indent})"
else
buffer_freeze indentation
end
end
if inline
inline_last_sibling = @sibling_stack[-1][-1] ? Settings::INLINE_NODE.include?(@sibling_stack[-1][-1][1]) : true
if @sibling_stack[-1][-1] && @sibling_stack[-1][-1][0] == :plain
buffer_remove_trailing_newline
end
if @in_definition || @sibling_stack[-1].length == 1 || !inline_last_sibling
indentate[]
end
else
indentate[]
end
@sibling_stack[-1] << [node[@type], node[@value]]
@sibling_stack << [[node[@type], node[@value]]]
end
# Add the tag opening, with leading whitespace to the code buffer
buffer_freeze ' ' if node[@options][:leading_whitespace]
buffer_freeze "<#{node[@value]}"
# Evaluate node extension in the current context
if node[@options][:extension]
extension_name = buffer_set_variable :extension,
node[@options][:extension][@value]
extension = {
name: extension_name,
escaped: node[@options][:extension][@options][:escaped]
}
end
# Evaluate and generate node attributes, then process each one to
# by generating the required attribute code
buffer_attributes node[@options][:attributes],
extension
# Check if the current node is self enclosing. Self enclosing nodes
# do not have any child elements
if node[@options][:self_enclosing]
# If the tag is self enclosing, it cannot have any child elements.
buffer_freeze '>'
# Pretty print
buffer_freeze "\n" if @settings[:pretty]
# If we mistakenly add children to self enclosing nodes,
# process each child element as if it was correctly indented
# node[@children].each do |child|
# root child, indent + @settings[:indent]
# end
else
# Set tag ending code
buffer_freeze '>'
# Pretty print
if @settings[:pretty]
if node[@children].length > 0
buffer_freeze "\n" unless inline
end
# @sibling_stack << [[node[@type], node[@value]]]
end
# Process each child element recursively, increasing indentation
node[@children].each do |child|
root child, indent + @settings[:indent]
end
inline_last_child = @sibling_stack[-1][-2] &&
(@sibling_stack[-1][-2][0] == :plain ||
Settings::INLINE_NODE.include?(@sibling_stack[-1][-2][1]))
# Pretty print
if @settings[:pretty]
if node[@children].length > 1 && inline_last_child
buffer_freeze "\n"
end
if node[@children].size > 0 && !inline
indentate[]
end
end
# Set tag closing code
buffer_freeze "</#{node[@value]}>"
buffer_freeze ' ' if node[@options][:trailing_whitespace]
# Pretty print
if @settings[:pretty]
buffer_freeze "\n" if !inline || @in_definition
end
end
if @settings[:pretty]
@sibling_stack.pop
end
end | [
"def",
"node",
"(",
"node",
",",
"indent",
")",
"if",
"@settings",
"[",
":pretty",
"]",
"indentation",
"=",
"' '",
"*",
"indent",
"inline",
"=",
"Settings",
"::",
"INLINE_NODE",
".",
"include?",
"node",
"[",
"@value",
"]",
"indentate",
"=",
"proc",
"do",
"if",
"@in_definition",
"buffer",
"\"' ' * (indent + #{indent})\"",
"else",
"buffer_freeze",
"indentation",
"end",
"end",
"if",
"inline",
"inline_last_sibling",
"=",
"@sibling_stack",
"[",
"-",
"1",
"]",
"[",
"-",
"1",
"]",
"?",
"Settings",
"::",
"INLINE_NODE",
".",
"include?",
"(",
"@sibling_stack",
"[",
"-",
"1",
"]",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
")",
":",
"true",
"if",
"@sibling_stack",
"[",
"-",
"1",
"]",
"[",
"-",
"1",
"]",
"&&",
"@sibling_stack",
"[",
"-",
"1",
"]",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"==",
":plain",
"buffer_remove_trailing_newline",
"end",
"if",
"@in_definition",
"||",
"@sibling_stack",
"[",
"-",
"1",
"]",
".",
"length",
"==",
"1",
"||",
"!",
"inline_last_sibling",
"indentate",
"[",
"]",
"end",
"else",
"indentate",
"[",
"]",
"end",
"@sibling_stack",
"[",
"-",
"1",
"]",
"<<",
"[",
"node",
"[",
"@type",
"]",
",",
"node",
"[",
"@value",
"]",
"]",
"@sibling_stack",
"<<",
"[",
"[",
"node",
"[",
"@type",
"]",
",",
"node",
"[",
"@value",
"]",
"]",
"]",
"end",
"buffer_freeze",
"' '",
"if",
"node",
"[",
"@options",
"]",
"[",
":leading_whitespace",
"]",
"buffer_freeze",
"\"<#{node[@value]}\"",
"if",
"node",
"[",
"@options",
"]",
"[",
":extension",
"]",
"extension_name",
"=",
"buffer_set_variable",
":extension",
",",
"node",
"[",
"@options",
"]",
"[",
":extension",
"]",
"[",
"@value",
"]",
"extension",
"=",
"{",
"name",
":",
"extension_name",
",",
"escaped",
":",
"node",
"[",
"@options",
"]",
"[",
":extension",
"]",
"[",
"@options",
"]",
"[",
":escaped",
"]",
"}",
"end",
"buffer_attributes",
"node",
"[",
"@options",
"]",
"[",
":attributes",
"]",
",",
"extension",
"if",
"node",
"[",
"@options",
"]",
"[",
":self_enclosing",
"]",
"buffer_freeze",
"'>'",
"buffer_freeze",
"\"\\n\"",
"if",
"@settings",
"[",
":pretty",
"]",
"else",
"buffer_freeze",
"'>'",
"if",
"@settings",
"[",
":pretty",
"]",
"if",
"node",
"[",
"@children",
"]",
".",
"length",
">",
"0",
"buffer_freeze",
"\"\\n\"",
"unless",
"inline",
"end",
"end",
"node",
"[",
"@children",
"]",
".",
"each",
"do",
"|",
"child",
"|",
"root",
"child",
",",
"indent",
"+",
"@settings",
"[",
":indent",
"]",
"end",
"inline_last_child",
"=",
"@sibling_stack",
"[",
"-",
"1",
"]",
"[",
"-",
"2",
"]",
"&&",
"(",
"@sibling_stack",
"[",
"-",
"1",
"]",
"[",
"-",
"2",
"]",
"[",
"0",
"]",
"==",
":plain",
"||",
"Settings",
"::",
"INLINE_NODE",
".",
"include?",
"(",
"@sibling_stack",
"[",
"-",
"1",
"]",
"[",
"-",
"2",
"]",
"[",
"1",
"]",
")",
")",
"if",
"@settings",
"[",
":pretty",
"]",
"if",
"node",
"[",
"@children",
"]",
".",
"length",
">",
"1",
"&&",
"inline_last_child",
"buffer_freeze",
"\"\\n\"",
"end",
"if",
"node",
"[",
"@children",
"]",
".",
"size",
">",
"0",
"&&",
"!",
"inline",
"indentate",
"[",
"]",
"end",
"end",
"buffer_freeze",
"\"</#{node[@value]}>\"",
"buffer_freeze",
"' '",
"if",
"node",
"[",
"@options",
"]",
"[",
":trailing_whitespace",
"]",
"if",
"@settings",
"[",
":pretty",
"]",
"buffer_freeze",
"\"\\n\"",
"if",
"!",
"inline",
"||",
"@in_definition",
"end",
"end",
"if",
"@settings",
"[",
":pretty",
"]",
"@sibling_stack",
".",
"pop",
"end",
"end"
] | Generate the code for a standard node element, with closing tags or
self enclosing elements
@param node [Array] Node code generation data
@param indent [Fixnum] Size of the indentation to be added | [
"Generate",
"the",
"code",
"for",
"a",
"standard",
"node",
"element",
"with",
"closing",
"tags",
"or",
"self",
"enclosing",
"elements"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/compiler/node.rb#L11-L123 | train |
ageweke/flex_columns | lib/flex_columns/has_flex_columns.rb | FlexColumns.HasFlexColumns._flex_columns_before_save! | def _flex_columns_before_save!
self.class._all_flex_column_names.each do |flex_column_name|
klass = self.class._flex_column_class_for(flex_column_name)
if klass.requires_serialization_on_save?(self)
_flex_column_object_for(flex_column_name).before_save!
end
end
end | ruby | def _flex_columns_before_save!
self.class._all_flex_column_names.each do |flex_column_name|
klass = self.class._flex_column_class_for(flex_column_name)
if klass.requires_serialization_on_save?(self)
_flex_column_object_for(flex_column_name).before_save!
end
end
end | [
"def",
"_flex_columns_before_save!",
"self",
".",
"class",
".",
"_all_flex_column_names",
".",
"each",
"do",
"|",
"flex_column_name",
"|",
"klass",
"=",
"self",
".",
"class",
".",
"_flex_column_class_for",
"(",
"flex_column_name",
")",
"if",
"klass",
".",
"requires_serialization_on_save?",
"(",
"self",
")",
"_flex_column_object_for",
"(",
"flex_column_name",
")",
".",
"before_save!",
"end",
"end",
"end"
] | Before we save this model, make sure each flex column has a chance to serialize itself up and assign itself
properly to this model object. Note that we only need to call through to flex-column objects that have actually
been instantiated, since, by definition, there's no way the contents of any other flex columns could possibly
have been changed. | [
"Before",
"we",
"save",
"this",
"model",
"make",
"sure",
"each",
"flex",
"column",
"has",
"a",
"chance",
"to",
"serialize",
"itself",
"up",
"and",
"assign",
"itself",
"properly",
"to",
"this",
"model",
"object",
".",
"Note",
"that",
"we",
"only",
"need",
"to",
"call",
"through",
"to",
"flex",
"-",
"column",
"objects",
"that",
"have",
"actually",
"been",
"instantiated",
"since",
"by",
"definition",
"there",
"s",
"no",
"way",
"the",
"contents",
"of",
"any",
"other",
"flex",
"columns",
"could",
"possibly",
"have",
"been",
"changed",
"."
] | 3870086352ac1a0342e96e86c403c4870fea9d6f | https://github.com/ageweke/flex_columns/blob/3870086352ac1a0342e96e86c403c4870fea9d6f/lib/flex_columns/has_flex_columns.rb#L30-L37 | train |
ageweke/flex_columns | lib/flex_columns/has_flex_columns.rb | FlexColumns.HasFlexColumns._flex_column_owned_object_for | def _flex_column_owned_object_for(column_name, create_if_needed = true)
column_name = self.class._flex_column_normalize_name(column_name)
out = _flex_column_objects[column_name]
if (! out) && create_if_needed
out = _flex_column_objects[column_name] = self.class._flex_column_class_for(column_name).new(self)
end
out
end | ruby | def _flex_column_owned_object_for(column_name, create_if_needed = true)
column_name = self.class._flex_column_normalize_name(column_name)
out = _flex_column_objects[column_name]
if (! out) && create_if_needed
out = _flex_column_objects[column_name] = self.class._flex_column_class_for(column_name).new(self)
end
out
end | [
"def",
"_flex_column_owned_object_for",
"(",
"column_name",
",",
"create_if_needed",
"=",
"true",
")",
"column_name",
"=",
"self",
".",
"class",
".",
"_flex_column_normalize_name",
"(",
"column_name",
")",
"out",
"=",
"_flex_column_objects",
"[",
"column_name",
"]",
"if",
"(",
"!",
"out",
")",
"&&",
"create_if_needed",
"out",
"=",
"_flex_column_objects",
"[",
"column_name",
"]",
"=",
"self",
".",
"class",
".",
"_flex_column_class_for",
"(",
"column_name",
")",
".",
"new",
"(",
"self",
")",
"end",
"out",
"end"
] | Returns the correct flex-column object for the given column name. This simply creates an instance of the
appropriate flex-column class, and saves it away so it will be returned again if someone requests the object for
the same column later.
This method almost never gets invoked directly; instead, everything calls it via
FlexColumns::ActiveRecord::Base#_flex_column_object_for. | [
"Returns",
"the",
"correct",
"flex",
"-",
"column",
"object",
"for",
"the",
"given",
"column",
"name",
".",
"This",
"simply",
"creates",
"an",
"instance",
"of",
"the",
"appropriate",
"flex",
"-",
"column",
"class",
"and",
"saves",
"it",
"away",
"so",
"it",
"will",
"be",
"returned",
"again",
"if",
"someone",
"requests",
"the",
"object",
"for",
"the",
"same",
"column",
"later",
"."
] | 3870086352ac1a0342e96e86c403c4870fea9d6f | https://github.com/ageweke/flex_columns/blob/3870086352ac1a0342e96e86c403c4870fea9d6f/lib/flex_columns/has_flex_columns.rb#L55-L63 | train |
opulent/opulent | lib/opulent/parser/define.rb | Opulent.Parser.define | def define(parent, indent)
return unless accept(:def)
# Definition parent check
Logger.error :parse, @code, @i, @j, :definition if parent[@type] != :root
# Process data
name = accept(:node, :*).to_sym
# Create node
definition = [
:def,
name,
{ parameters: attributes({}, true) },
[],
indent
]
# Set definition as root node and let the parser know that we're inside
# a definition. This is used because inside definitions we do not
# process nodes (we do not check if they are have a definition or not).
root definition, indent
# Add to parent
@definitions[name] = definition
end | ruby | def define(parent, indent)
return unless accept(:def)
# Definition parent check
Logger.error :parse, @code, @i, @j, :definition if parent[@type] != :root
# Process data
name = accept(:node, :*).to_sym
# Create node
definition = [
:def,
name,
{ parameters: attributes({}, true) },
[],
indent
]
# Set definition as root node and let the parser know that we're inside
# a definition. This is used because inside definitions we do not
# process nodes (we do not check if they are have a definition or not).
root definition, indent
# Add to parent
@definitions[name] = definition
end | [
"def",
"define",
"(",
"parent",
",",
"indent",
")",
"return",
"unless",
"accept",
"(",
":def",
")",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":definition",
"if",
"parent",
"[",
"@type",
"]",
"!=",
":root",
"name",
"=",
"accept",
"(",
":node",
",",
":*",
")",
".",
"to_sym",
"definition",
"=",
"[",
":def",
",",
"name",
",",
"{",
"parameters",
":",
"attributes",
"(",
"{",
"}",
",",
"true",
")",
"}",
",",
"[",
"]",
",",
"indent",
"]",
"root",
"definition",
",",
"indent",
"@definitions",
"[",
"name",
"]",
"=",
"definition",
"end"
] | Check if we match a new node definition to use within our page.
Definitions will not be recursive because, by the time we parse
the definition children, the definition itself is not in the
knowledgebase yet.
However, we may use previously defined nodes inside new definitions,
due to the fact that they are known at parse time.
@param nodes [Array] Parent node to which we append to | [
"Check",
"if",
"we",
"match",
"a",
"new",
"node",
"definition",
"to",
"use",
"within",
"our",
"page",
"."
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/define.rb#L16-L41 | train |
kjvarga/ajax | lib/rack-ajax.rb | Rack.Ajax.encode_env | def encode_env(env)
env = env.dup
env.keep_if { |k, v| k =~ /[A-Z]/ }
env.to_yaml(:Encoding => :Utf8)
end | ruby | def encode_env(env)
env = env.dup
env.keep_if { |k, v| k =~ /[A-Z]/ }
env.to_yaml(:Encoding => :Utf8)
end | [
"def",
"encode_env",
"(",
"env",
")",
"env",
"=",
"env",
".",
"dup",
"env",
".",
"keep_if",
"{",
"|",
"k",
",",
"v",
"|",
"k",
"=~",
"/",
"/",
"}",
"env",
".",
"to_yaml",
"(",
":Encoding",
"=>",
":Utf8",
")",
"end"
] | Convert the environment hash to yaml so it can be unserialized later | [
"Convert",
"the",
"environment",
"hash",
"to",
"yaml",
"so",
"it",
"can",
"be",
"unserialized",
"later"
] | e60acbc51855cd85b4907d509ea41fe0965ce72e | https://github.com/kjvarga/ajax/blob/e60acbc51855cd85b4907d509ea41fe0965ce72e/lib/rack-ajax.rb#L63-L67 | train |
cottonwoodcoding/repack | lib/repack/helper.rb | Repack.Helper.webpack_asset_paths | def webpack_asset_paths(source, extension: nil)
return "" unless source.present?
paths = Repack::Manifest.asset_paths(source)
paths = paths.select {|p| p.ends_with? ".#{extension}" } if extension
host = ::Rails.configuration.repack.dev_server.host
port = ::Rails.configuration.repack.dev_server.port
if ::Rails.configuration.repack.dev_server.enabled
paths.map! do |p|
"//#{host}:#{port}#{p}"
end
end
paths
end | ruby | def webpack_asset_paths(source, extension: nil)
return "" unless source.present?
paths = Repack::Manifest.asset_paths(source)
paths = paths.select {|p| p.ends_with? ".#{extension}" } if extension
host = ::Rails.configuration.repack.dev_server.host
port = ::Rails.configuration.repack.dev_server.port
if ::Rails.configuration.repack.dev_server.enabled
paths.map! do |p|
"//#{host}:#{port}#{p}"
end
end
paths
end | [
"def",
"webpack_asset_paths",
"(",
"source",
",",
"extension",
":",
"nil",
")",
"return",
"\"\"",
"unless",
"source",
".",
"present?",
"paths",
"=",
"Repack",
"::",
"Manifest",
".",
"asset_paths",
"(",
"source",
")",
"paths",
"=",
"paths",
".",
"select",
"{",
"|",
"p",
"|",
"p",
".",
"ends_with?",
"\".#{extension}\"",
"}",
"if",
"extension",
"host",
"=",
"::",
"Rails",
".",
"configuration",
".",
"repack",
".",
"dev_server",
".",
"host",
"port",
"=",
"::",
"Rails",
".",
"configuration",
".",
"repack",
".",
"dev_server",
".",
"port",
"if",
"::",
"Rails",
".",
"configuration",
".",
"repack",
".",
"dev_server",
".",
"enabled",
"paths",
".",
"map!",
"do",
"|",
"p",
"|",
"\"//#{host}:#{port}#{p}\"",
"end",
"end",
"paths",
"end"
] | Return asset paths for a particular webpack entry point.
Response may either be full URLs (eg http://localhost/...) if the dev server
is in use or a host-relative URl (eg /webpack/...) if assets are precompiled.
Will raise an error if our manifest can't be found or the entry point does
not exist. | [
"Return",
"asset",
"paths",
"for",
"a",
"particular",
"webpack",
"entry",
"point",
"."
] | a1d05799502779afdc97970cc6e79a2b2e8695fd | https://github.com/cottonwoodcoding/repack/blob/a1d05799502779afdc97970cc6e79a2b2e8695fd/lib/repack/helper.rb#L14-L30 | train |
3ofcoins/chef-helpers | lib/chef-helpers/has_source.rb | ChefHelpers.HasSource.has_source? | def has_source?(source, segment, cookbook=nil)
cookbook ||= cookbook_name
begin
run_context.cookbook_collection[cookbook].
send(:find_preferred_manifest_record, run_context.node, segment, source)
rescue Chef::Exceptions::FileNotFound
nil
end
end | ruby | def has_source?(source, segment, cookbook=nil)
cookbook ||= cookbook_name
begin
run_context.cookbook_collection[cookbook].
send(:find_preferred_manifest_record, run_context.node, segment, source)
rescue Chef::Exceptions::FileNotFound
nil
end
end | [
"def",
"has_source?",
"(",
"source",
",",
"segment",
",",
"cookbook",
"=",
"nil",
")",
"cookbook",
"||=",
"cookbook_name",
"begin",
"run_context",
".",
"cookbook_collection",
"[",
"cookbook",
"]",
".",
"send",
"(",
":find_preferred_manifest_record",
",",
"run_context",
".",
"node",
",",
"segment",
",",
"source",
")",
"rescue",
"Chef",
"::",
"Exceptions",
"::",
"FileNotFound",
"nil",
"end",
"end"
] | Checks for existence of a cookbook file or template source in a cookbook.
@param [String] source name of the desired template or cookbook file source
@param [Symbol] segment `:files` or `:templates`
@param [String, nil] cookbook to look in, defaults to current cookbook
@return [String, nil] full path to the source or `nil` if it doesn't exist
@example
has_source?("foo.erb", :templates)
has_source?("bar.conf", :files, "a_cookbook") | [
"Checks",
"for",
"existence",
"of",
"a",
"cookbook",
"file",
"or",
"template",
"source",
"in",
"a",
"cookbook",
"."
] | 6d784d53751528c28b8c6e5c69c206740d22ada0 | https://github.com/3ofcoins/chef-helpers/blob/6d784d53751528c28b8c6e5c69c206740d22ada0/lib/chef-helpers/has_source.rb#L16-L24 | train |
chadrem/tribe | lib/tribe/actable.rb | Tribe.Actable.process_events | def process_events
while (event = @_actable.mailbox.obtain_and_shift)
event_handler(event)
end
rescue Exception => exception
cleanup_handler(exception)
exception_handler(exception)
ensure
@_actable.mailbox.release do
process_events
end
nil
end | ruby | def process_events
while (event = @_actable.mailbox.obtain_and_shift)
event_handler(event)
end
rescue Exception => exception
cleanup_handler(exception)
exception_handler(exception)
ensure
@_actable.mailbox.release do
process_events
end
nil
end | [
"def",
"process_events",
"while",
"(",
"event",
"=",
"@_actable",
".",
"mailbox",
".",
"obtain_and_shift",
")",
"event_handler",
"(",
"event",
")",
"end",
"rescue",
"Exception",
"=>",
"exception",
"cleanup_handler",
"(",
"exception",
")",
"exception_handler",
"(",
"exception",
")",
"ensure",
"@_actable",
".",
"mailbox",
".",
"release",
"do",
"process_events",
"end",
"nil",
"end"
] | All system commands are prefixed with an underscore. | [
"All",
"system",
"commands",
"are",
"prefixed",
"with",
"an",
"underscore",
"."
] | 7cca0c3f66c710b4f361f8a371b6d126b22d7f6a | https://github.com/chadrem/tribe/blob/7cca0c3f66c710b4f361f8a371b6d126b22d7f6a/lib/tribe/actable.rb#L157-L171 | train |
opulent/opulent | lib/opulent/context.rb | Opulent.Context.evaluate | def evaluate(code, &block)
begin
eval code, @binding, &block
rescue NameError => variable
Compiler.error :binding, variable, code
end
end | ruby | def evaluate(code, &block)
begin
eval code, @binding, &block
rescue NameError => variable
Compiler.error :binding, variable, code
end
end | [
"def",
"evaluate",
"(",
"code",
",",
"&",
"block",
")",
"begin",
"eval",
"code",
",",
"@binding",
",",
"&",
"block",
"rescue",
"NameError",
"=>",
"variable",
"Compiler",
".",
"error",
":binding",
",",
"variable",
",",
"code",
"end",
"end"
] | Create a context from the environment binding, extended with the locals
given as arguments
@param locals [Hash] Binding extension
@param block [Binding] Call environment block
@param content [Binding] Content yielding
Evaluate ruby code in current context
@param code [String] Code to be evaluated | [
"Create",
"a",
"context",
"from",
"the",
"environment",
"binding",
"extended",
"with",
"the",
"locals",
"given",
"as",
"arguments"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/context.rb#L36-L42 | train |
opulent/opulent | lib/opulent/context.rb | Opulent.Context.extend_locals | def extend_locals(locals)
# Create new local variables from the input hash
locals.each do |key, value|
begin
@binding.local_variable_set key.to_sym, value
rescue NameError => variable
Compiler.error :variable_name, variable, key
end
end
end | ruby | def extend_locals(locals)
# Create new local variables from the input hash
locals.each do |key, value|
begin
@binding.local_variable_set key.to_sym, value
rescue NameError => variable
Compiler.error :variable_name, variable, key
end
end
end | [
"def",
"extend_locals",
"(",
"locals",
")",
"locals",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"begin",
"@binding",
".",
"local_variable_set",
"key",
".",
"to_sym",
",",
"value",
"rescue",
"NameError",
"=>",
"variable",
"Compiler",
".",
"error",
":variable_name",
",",
"variable",
",",
"key",
"end",
"end",
"end"
] | Extend the call context with a Hash, String or other Object
@param context [Object] Extension object | [
"Extend",
"the",
"call",
"context",
"with",
"a",
"Hash",
"String",
"or",
"other",
"Object"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/context.rb#L54-L63 | train |
opulent/opulent | lib/opulent/context.rb | Opulent.Context.extend_nonlocals | def extend_nonlocals(bind)
bind.eval('instance_variables').each do |var|
@binding.eval('self').instance_variable_set var, bind.eval(var.to_s)
end
bind.eval('self.class.class_variables').each do |var|
@binding.eval('self').class_variable_set var, bind.eval(var.to_s)
end
end | ruby | def extend_nonlocals(bind)
bind.eval('instance_variables').each do |var|
@binding.eval('self').instance_variable_set var, bind.eval(var.to_s)
end
bind.eval('self.class.class_variables').each do |var|
@binding.eval('self').class_variable_set var, bind.eval(var.to_s)
end
end | [
"def",
"extend_nonlocals",
"(",
"bind",
")",
"bind",
".",
"eval",
"(",
"'instance_variables'",
")",
".",
"each",
"do",
"|",
"var",
"|",
"@binding",
".",
"eval",
"(",
"'self'",
")",
".",
"instance_variable_set",
"var",
",",
"bind",
".",
"eval",
"(",
"var",
".",
"to_s",
")",
"end",
"bind",
".",
"eval",
"(",
"'self.class.class_variables'",
")",
".",
"each",
"do",
"|",
"var",
"|",
"@binding",
".",
"eval",
"(",
"'self'",
")",
".",
"class_variable_set",
"var",
",",
"bind",
".",
"eval",
"(",
"var",
".",
"to_s",
")",
"end",
"end"
] | Extend instance, class and global variables for use in definitions
@param bind [Binding] Binding to extend current context binding | [
"Extend",
"instance",
"class",
"and",
"global",
"variables",
"for",
"use",
"in",
"definitions"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/context.rb#L69-L77 | train |
Yellowen/Faalis | lib/faalis/dashboard/dsl/index.rb | Faalis::Dashboard::DSL.Index.attributes | def attributes(*fields_name, **options, &block)
if options.include? :except
@fields = resolve_model_reflections.reject do |field|
options[:except].include? field.to_sym
end
elsif options.include? :append
@fields += options[:append]
else
# set new value for fields
@fields = fields_name.map(&:to_s) unless fields_name.empty?
end
@fields.concat(block.call.map(&:to_s)) if block_given?
end | ruby | def attributes(*fields_name, **options, &block)
if options.include? :except
@fields = resolve_model_reflections.reject do |field|
options[:except].include? field.to_sym
end
elsif options.include? :append
@fields += options[:append]
else
# set new value for fields
@fields = fields_name.map(&:to_s) unless fields_name.empty?
end
@fields.concat(block.call.map(&:to_s)) if block_given?
end | [
"def",
"attributes",
"(",
"*",
"fields_name",
",",
"**",
"options",
",",
"&",
"block",
")",
"if",
"options",
".",
"include?",
":except",
"@fields",
"=",
"resolve_model_reflections",
".",
"reject",
"do",
"|",
"field",
"|",
"options",
"[",
":except",
"]",
".",
"include?",
"field",
".",
"to_sym",
"end",
"elsif",
"options",
".",
"include?",
":append",
"@fields",
"+=",
"options",
"[",
":append",
"]",
"else",
"@fields",
"=",
"fields_name",
".",
"map",
"(",
"&",
":to_s",
")",
"unless",
"fields_name",
".",
"empty?",
"end",
"@fields",
".",
"concat",
"(",
"block",
".",
"call",
".",
"map",
"(",
"&",
":to_s",
")",
")",
"if",
"block_given?",
"end"
] | Allow user to specify an array of model attributes to be used
in respected section. For example attributes to show as header
columns in index section | [
"Allow",
"user",
"to",
"specify",
"an",
"array",
"of",
"model",
"attributes",
"to",
"be",
"used",
"in",
"respected",
"section",
".",
"For",
"example",
"attributes",
"to",
"show",
"as",
"header",
"columns",
"in",
"index",
"section"
] | d12abdb8559dabbf6b2044e3ba437038527039b2 | https://github.com/Yellowen/Faalis/blob/d12abdb8559dabbf6b2044e3ba437038527039b2/lib/faalis/dashboard/dsl/index.rb#L10-L23 | train |
Yellowen/Faalis | lib/faalis/dashboard/sections/resources_index.rb | Faalis::Dashboard::Sections.ResourcesIndex.fetch_index_objects | def fetch_index_objects
scope = index_properties.default_scope
puts "<<<<<<<" * 100, scope
if !scope.nil?
# If user provided an scope for `index` section.
if scope.respond_to? :call
# If scope provided by a block
scope = scope.call
else
# If scope provided by a symbol
# which should be a method name
scope = self.send(scope)
end
else
scope = model.all
#scope = ApplicationPolicy::Scope.new(current_user, model.all).resolve
end
scope = scope.order('created_at DESC').page(params[:page])
policy_scope(scope)
end | ruby | def fetch_index_objects
scope = index_properties.default_scope
puts "<<<<<<<" * 100, scope
if !scope.nil?
# If user provided an scope for `index` section.
if scope.respond_to? :call
# If scope provided by a block
scope = scope.call
else
# If scope provided by a symbol
# which should be a method name
scope = self.send(scope)
end
else
scope = model.all
#scope = ApplicationPolicy::Scope.new(current_user, model.all).resolve
end
scope = scope.order('created_at DESC').page(params[:page])
policy_scope(scope)
end | [
"def",
"fetch_index_objects",
"scope",
"=",
"index_properties",
".",
"default_scope",
"puts",
"\"<<<<<<<\"",
"*",
"100",
",",
"scope",
"if",
"!",
"scope",
".",
"nil?",
"if",
"scope",
".",
"respond_to?",
":call",
"scope",
"=",
"scope",
".",
"call",
"else",
"scope",
"=",
"self",
".",
"send",
"(",
"scope",
")",
"end",
"else",
"scope",
"=",
"model",
".",
"all",
"end",
"scope",
"=",
"scope",
".",
"order",
"(",
"'created_at DESC'",
")",
".",
"page",
"(",
"params",
"[",
":page",
"]",
")",
"policy_scope",
"(",
"scope",
")",
"end"
] | Fetch all or part of the corresponding resource
from data base with respect to `scope` DSL.
The important thing here is that by using `scope`
DSL this method will chain the resulted scope
with other scopes like `page` and `policy_scope` | [
"Fetch",
"all",
"or",
"part",
"of",
"the",
"corresponding",
"resource",
"from",
"data",
"base",
"with",
"respect",
"to",
"scope",
"DSL",
"."
] | d12abdb8559dabbf6b2044e3ba437038527039b2 | https://github.com/Yellowen/Faalis/blob/d12abdb8559dabbf6b2044e3ba437038527039b2/lib/faalis/dashboard/sections/resources_index.rb#L29-L53 | train |
vjt/sanitize-rails | lib/sanitize/rails/matchers.rb | Sanitize::Rails::Matchers.SanitizeFieldsMatcher.matches? | def matches?(instance)
self.instance = instance
# assign invalid value to each field
fields.each { |field| instance.send("#{field}=", invalid_value) }
# sanitize the object calling the method
instance.send(sanitizer) rescue nil
# check expectation on results
fields.all? { |field| valid_value == instance.send(field) }
end | ruby | def matches?(instance)
self.instance = instance
# assign invalid value to each field
fields.each { |field| instance.send("#{field}=", invalid_value) }
# sanitize the object calling the method
instance.send(sanitizer) rescue nil
# check expectation on results
fields.all? { |field| valid_value == instance.send(field) }
end | [
"def",
"matches?",
"(",
"instance",
")",
"self",
".",
"instance",
"=",
"instance",
"fields",
".",
"each",
"{",
"|",
"field",
"|",
"instance",
".",
"send",
"(",
"\"#{field}=\"",
",",
"invalid_value",
")",
"}",
"instance",
".",
"send",
"(",
"sanitizer",
")",
"rescue",
"nil",
"fields",
".",
"all?",
"{",
"|",
"field",
"|",
"valid_value",
"==",
"instance",
".",
"send",
"(",
"field",
")",
"}",
"end"
] | Actual match code | [
"Actual",
"match",
"code"
] | 85541b447427347b59f1c3b584cffcecbc884476 | https://github.com/vjt/sanitize-rails/blob/85541b447427347b59f1c3b584cffcecbc884476/lib/sanitize/rails/matchers.rb#L84-L92 | train |
opulent/opulent | lib/opulent/parser/control.rb | Opulent.Parser.control | def control(parent, indent)
# Accept eval or multiline eval syntax and return a new node,
return unless (structure = accept(:control))
structure = structure.to_sym
# Handle each and the other control structures
condition = accept(:line_feed).strip
# Process each control structure condition
if structure == :each
# Check if arguments provided correctly
unless condition.match Tokens[:each_pattern]
Logger.error :parse, @code, @i, @j, :each_arguments
end
# Conditions for each iterator
condition = [
Regexp.last_match[1].split(' '),
Regexp.last_match[2].split(/,(.+)$/).map(&:strip).map(&:to_sym)
]
# Array loop as default
condition[0].unshift '{}' if condition[0].length == 1
end
# Else and default structures are not allowed to have any condition
# set and the other control structures require a condition
if structure == :else
unless condition.empty?
Logger.error :parse, @code, @i, @j, :condition_exists
end
else
if condition.empty?
Logger.error :parse, @code, @i, @j, :condition_missing
end
end
# Add the condition and create a new child to the control parent.
# The control parent keeps condition -> children matches for our
# document's content
# add_options = proc do |control_parent|
# control_parent.value << condition
# control_parent.children << []
#
# root control_parent
# end
# If the current control structure is a parent which allows multiple
# branches, such as an if or case, we create an array of conditions
# which can be matched and an array of children belonging to each
# conditional branch
if [:if, :unless].include? structure
# Create the control structure and get its child nodes
control_structure = [structure, [condition], {}, [], indent]
root control_structure, indent
# Turn children into an array because we allow multiple branches
control_structure[@children] = [control_structure[@children]]
# Add it to the parent node
parent[@children] << control_structure
elsif structure == :case
# Create the control structure and get its child nodes
control_structure = [
structure,
[],
{ condition: condition },
[],
indent
]
# Add it to the parent node
parent[@children] << control_structure
# If the control structure is a child structure, we need to find the
# node it belongs to amont the current parent. Search from end to
# beginning until we find the node parent
elsif control_child structure
# During the search, we try to find the matching parent type
unless control_parent(structure).include? parent[@children][-1][@type]
Logger.error :parse,
@code,
@i,
@j,
:control_child,
control_parent(structure)
end
# Gather child elements for current structure
control_structure = [structure, [condition], {}, [], indent]
root control_structure, indent
# Add the new condition and children to our parent structure
parent[@children][-1][@value] << condition
parent[@children][-1][@children] << control_structure[@children]
# When our control structure isn't a complex composite, we create
# it the same way as a normal node
else
control_structure = [structure, condition, {}, [], indent]
root control_structure, indent
parent[@children] << control_structure
end
end | ruby | def control(parent, indent)
# Accept eval or multiline eval syntax and return a new node,
return unless (structure = accept(:control))
structure = structure.to_sym
# Handle each and the other control structures
condition = accept(:line_feed).strip
# Process each control structure condition
if structure == :each
# Check if arguments provided correctly
unless condition.match Tokens[:each_pattern]
Logger.error :parse, @code, @i, @j, :each_arguments
end
# Conditions for each iterator
condition = [
Regexp.last_match[1].split(' '),
Regexp.last_match[2].split(/,(.+)$/).map(&:strip).map(&:to_sym)
]
# Array loop as default
condition[0].unshift '{}' if condition[0].length == 1
end
# Else and default structures are not allowed to have any condition
# set and the other control structures require a condition
if structure == :else
unless condition.empty?
Logger.error :parse, @code, @i, @j, :condition_exists
end
else
if condition.empty?
Logger.error :parse, @code, @i, @j, :condition_missing
end
end
# Add the condition and create a new child to the control parent.
# The control parent keeps condition -> children matches for our
# document's content
# add_options = proc do |control_parent|
# control_parent.value << condition
# control_parent.children << []
#
# root control_parent
# end
# If the current control structure is a parent which allows multiple
# branches, such as an if or case, we create an array of conditions
# which can be matched and an array of children belonging to each
# conditional branch
if [:if, :unless].include? structure
# Create the control structure and get its child nodes
control_structure = [structure, [condition], {}, [], indent]
root control_structure, indent
# Turn children into an array because we allow multiple branches
control_structure[@children] = [control_structure[@children]]
# Add it to the parent node
parent[@children] << control_structure
elsif structure == :case
# Create the control structure and get its child nodes
control_structure = [
structure,
[],
{ condition: condition },
[],
indent
]
# Add it to the parent node
parent[@children] << control_structure
# If the control structure is a child structure, we need to find the
# node it belongs to amont the current parent. Search from end to
# beginning until we find the node parent
elsif control_child structure
# During the search, we try to find the matching parent type
unless control_parent(structure).include? parent[@children][-1][@type]
Logger.error :parse,
@code,
@i,
@j,
:control_child,
control_parent(structure)
end
# Gather child elements for current structure
control_structure = [structure, [condition], {}, [], indent]
root control_structure, indent
# Add the new condition and children to our parent structure
parent[@children][-1][@value] << condition
parent[@children][-1][@children] << control_structure[@children]
# When our control structure isn't a complex composite, we create
# it the same way as a normal node
else
control_structure = [structure, condition, {}, [], indent]
root control_structure, indent
parent[@children] << control_structure
end
end | [
"def",
"control",
"(",
"parent",
",",
"indent",
")",
"return",
"unless",
"(",
"structure",
"=",
"accept",
"(",
":control",
")",
")",
"structure",
"=",
"structure",
".",
"to_sym",
"condition",
"=",
"accept",
"(",
":line_feed",
")",
".",
"strip",
"if",
"structure",
"==",
":each",
"unless",
"condition",
".",
"match",
"Tokens",
"[",
":each_pattern",
"]",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":each_arguments",
"end",
"condition",
"=",
"[",
"Regexp",
".",
"last_match",
"[",
"1",
"]",
".",
"split",
"(",
"' '",
")",
",",
"Regexp",
".",
"last_match",
"[",
"2",
"]",
".",
"split",
"(",
"/",
"/",
")",
".",
"map",
"(",
"&",
":strip",
")",
".",
"map",
"(",
"&",
":to_sym",
")",
"]",
"condition",
"[",
"0",
"]",
".",
"unshift",
"'{}'",
"if",
"condition",
"[",
"0",
"]",
".",
"length",
"==",
"1",
"end",
"if",
"structure",
"==",
":else",
"unless",
"condition",
".",
"empty?",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":condition_exists",
"end",
"else",
"if",
"condition",
".",
"empty?",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":condition_missing",
"end",
"end",
"if",
"[",
":if",
",",
":unless",
"]",
".",
"include?",
"structure",
"control_structure",
"=",
"[",
"structure",
",",
"[",
"condition",
"]",
",",
"{",
"}",
",",
"[",
"]",
",",
"indent",
"]",
"root",
"control_structure",
",",
"indent",
"control_structure",
"[",
"@children",
"]",
"=",
"[",
"control_structure",
"[",
"@children",
"]",
"]",
"parent",
"[",
"@children",
"]",
"<<",
"control_structure",
"elsif",
"structure",
"==",
":case",
"control_structure",
"=",
"[",
"structure",
",",
"[",
"]",
",",
"{",
"condition",
":",
"condition",
"}",
",",
"[",
"]",
",",
"indent",
"]",
"parent",
"[",
"@children",
"]",
"<<",
"control_structure",
"elsif",
"control_child",
"structure",
"unless",
"control_parent",
"(",
"structure",
")",
".",
"include?",
"parent",
"[",
"@children",
"]",
"[",
"-",
"1",
"]",
"[",
"@type",
"]",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":control_child",
",",
"control_parent",
"(",
"structure",
")",
"end",
"control_structure",
"=",
"[",
"structure",
",",
"[",
"condition",
"]",
",",
"{",
"}",
",",
"[",
"]",
",",
"indent",
"]",
"root",
"control_structure",
",",
"indent",
"parent",
"[",
"@children",
"]",
"[",
"-",
"1",
"]",
"[",
"@value",
"]",
"<<",
"condition",
"parent",
"[",
"@children",
"]",
"[",
"-",
"1",
"]",
"[",
"@children",
"]",
"<<",
"control_structure",
"[",
"@children",
"]",
"else",
"control_structure",
"=",
"[",
"structure",
",",
"condition",
",",
"{",
"}",
",",
"[",
"]",
",",
"indent",
"]",
"root",
"control_structure",
",",
"indent",
"parent",
"[",
"@children",
"]",
"<<",
"control_structure",
"end",
"end"
] | Match an if-else control structure | [
"Match",
"an",
"if",
"-",
"else",
"control",
"structure"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/control.rb#L7-L112 | train |
taganaka/polipus | lib/polipus/robotex.rb | Polipus.Robotex.delay! | def delay!(uri)
delay = delay(uri)
sleep delay - (Time.now - @last_accessed) if delay
@last_accessed = Time.now
end | ruby | def delay!(uri)
delay = delay(uri)
sleep delay - (Time.now - @last_accessed) if delay
@last_accessed = Time.now
end | [
"def",
"delay!",
"(",
"uri",
")",
"delay",
"=",
"delay",
"(",
"uri",
")",
"sleep",
"delay",
"-",
"(",
"Time",
".",
"now",
"-",
"@last_accessed",
")",
"if",
"delay",
"@last_accessed",
"=",
"Time",
".",
"now",
"end"
] | Sleep for the amount of time necessary to obey the Crawl-Delay specified by the server | [
"Sleep",
"for",
"the",
"amount",
"of",
"time",
"necessary",
"to",
"obey",
"the",
"Crawl",
"-",
"Delay",
"specified",
"by",
"the",
"server"
] | 8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6 | https://github.com/taganaka/polipus/blob/8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6/lib/polipus/robotex.rb#L139-L143 | train |
Yellowen/Faalis | app/helpers/faalis/dashboard_helper.rb | Faalis.DashboardHelper.get_url | def get_url(route_name, id = nil, engine = Rails.application)
return route_name.call if id.nil?
return route_name.call(id) unless id.nil?
end | ruby | def get_url(route_name, id = nil, engine = Rails.application)
return route_name.call if id.nil?
return route_name.call(id) unless id.nil?
end | [
"def",
"get_url",
"(",
"route_name",
",",
"id",
"=",
"nil",
",",
"engine",
"=",
"Rails",
".",
"application",
")",
"return",
"route_name",
".",
"call",
"if",
"id",
".",
"nil?",
"return",
"route_name",
".",
"call",
"(",
"id",
")",
"unless",
"id",
".",
"nil?",
"end"
] | Translate route name to url dynamically | [
"Translate",
"route",
"name",
"to",
"url",
"dynamically"
] | d12abdb8559dabbf6b2044e3ba437038527039b2 | https://github.com/Yellowen/Faalis/blob/d12abdb8559dabbf6b2044e3ba437038527039b2/app/helpers/faalis/dashboard_helper.rb#L59-L62 | train |
hassox/warden_strategies | lib/warden_strategies/simple.rb | WardenStrategies.Simple.authenticate! | def authenticate!
if u = user_class.send(config[:authenticate_method], *required_param_values)
success!(u)
else
fail!(config[:error_message])
end
end | ruby | def authenticate!
if u = user_class.send(config[:authenticate_method], *required_param_values)
success!(u)
else
fail!(config[:error_message])
end
end | [
"def",
"authenticate!",
"if",
"u",
"=",
"user_class",
".",
"send",
"(",
"config",
"[",
":authenticate_method",
"]",
",",
"*",
"required_param_values",
")",
"success!",
"(",
"u",
")",
"else",
"fail!",
"(",
"config",
"[",
":error_message",
"]",
")",
"end",
"end"
] | The workhorse. Will pass all requred_param_values to the configured authenticate_method
@see WardenStrategies::Simple.config
@see Warden::Strategy::Base#authenticate!
@api private | [
"The",
"workhorse",
".",
"Will",
"pass",
"all",
"requred_param_values",
"to",
"the",
"configured",
"authenticate_method"
] | 8d249132c56d519c19adc92fbac0553456375cc9 | https://github.com/hassox/warden_strategies/blob/8d249132c56d519c19adc92fbac0553456375cc9/lib/warden_strategies/simple.rb#L101-L107 | train |
myfreecomm/charging-client-ruby | lib/charging/invoice.rb | Charging.Invoice.create! | def create!
super do
raise 'can not create without a domain' if invalid_domain?
raise 'can not create wihtout a charge account' if invalid_charge_account?
Invoice.post_charge_accounts_invoices(domain, charge_account, attributes)
end
reload_attributes!(Helpers.extract_uuid(last_response.headers[:location]) || uuid)
end | ruby | def create!
super do
raise 'can not create without a domain' if invalid_domain?
raise 'can not create wihtout a charge account' if invalid_charge_account?
Invoice.post_charge_accounts_invoices(domain, charge_account, attributes)
end
reload_attributes!(Helpers.extract_uuid(last_response.headers[:location]) || uuid)
end | [
"def",
"create!",
"super",
"do",
"raise",
"'can not create without a domain'",
"if",
"invalid_domain?",
"raise",
"'can not create wihtout a charge account'",
"if",
"invalid_charge_account?",
"Invoice",
".",
"post_charge_accounts_invoices",
"(",
"domain",
",",
"charge_account",
",",
"attributes",
")",
"end",
"reload_attributes!",
"(",
"Helpers",
".",
"extract_uuid",
"(",
"last_response",
".",
"headers",
"[",
":location",
"]",
")",
"||",
"uuid",
")",
"end"
] | Creates current invoice at API.
API method: <tt>POST /charge-accounts/:uuid/invoices/</tt>
API documentation: https://charging.financeconnect.com.br/static/docs/charges.html#post-charge-accounts-uuid-invoices | [
"Creates",
"current",
"invoice",
"at",
"API",
"."
] | d2b164a3536a8c5faa8656c8477b399b22181e7f | https://github.com/myfreecomm/charging-client-ruby/blob/d2b164a3536a8c5faa8656c8477b399b22181e7f/lib/charging/invoice.rb#L28-L37 | train |
myfreecomm/charging-client-ruby | lib/charging/invoice.rb | Charging.Invoice.payments | def payments
reset_errors!
response = Http.get("/invoices/#{uuid}/payments/", domain.token)
return [] if response.code != 200
MultiJson.decode(response.body)
end | ruby | def payments
reset_errors!
response = Http.get("/invoices/#{uuid}/payments/", domain.token)
return [] if response.code != 200
MultiJson.decode(response.body)
end | [
"def",
"payments",
"reset_errors!",
"response",
"=",
"Http",
".",
"get",
"(",
"\"/invoices/#{uuid}/payments/\"",
",",
"domain",
".",
"token",
")",
"return",
"[",
"]",
"if",
"response",
".",
"code",
"!=",
"200",
"MultiJson",
".",
"decode",
"(",
"response",
".",
"body",
")",
"end"
] | List all payments for an invoice
API method: <tt>GET /invoices/:uuid/payments/</tt>
API documentation: https://charging.financeconnect.com.br/static/docs/charges.html#get-invoices-uuid-payments | [
"List",
"all",
"payments",
"for",
"an",
"invoice"
] | d2b164a3536a8c5faa8656c8477b399b22181e7f | https://github.com/myfreecomm/charging-client-ruby/blob/d2b164a3536a8c5faa8656c8477b399b22181e7f/lib/charging/invoice.rb#L84-L92 | train |
myfreecomm/charging-client-ruby | lib/charging/invoice.rb | Charging.Invoice.billet_url | def billet_url
return if unpersisted?
response = Http.get("/invoices/#{uuid}/billet/", domain.token)
return if response.code != 200
MultiJson.decode(response.body)["billet"]
rescue
nil
end | ruby | def billet_url
return if unpersisted?
response = Http.get("/invoices/#{uuid}/billet/", domain.token)
return if response.code != 200
MultiJson.decode(response.body)["billet"]
rescue
nil
end | [
"def",
"billet_url",
"return",
"if",
"unpersisted?",
"response",
"=",
"Http",
".",
"get",
"(",
"\"/invoices/#{uuid}/billet/\"",
",",
"domain",
".",
"token",
")",
"return",
"if",
"response",
".",
"code",
"!=",
"200",
"MultiJson",
".",
"decode",
"(",
"response",
".",
"body",
")",
"[",
"\"billet\"",
"]",
"rescue",
"nil",
"end"
] | Returns a String with the temporary URL for print current invoice.
API method: <tt>GET /invoices/:uuid/billet/</tt>
API documentation: https://charging.financeconnect.com.br/static/docs/charges.html#get-invoices-uuid-billet | [
"Returns",
"a",
"String",
"with",
"the",
"temporary",
"URL",
"for",
"print",
"current",
"invoice",
"."
] | d2b164a3536a8c5faa8656c8477b399b22181e7f | https://github.com/myfreecomm/charging-client-ruby/blob/d2b164a3536a8c5faa8656c8477b399b22181e7f/lib/charging/invoice.rb#L99-L109 | train |
myfreecomm/rexpense-client-ruby | lib/rexpense/resources/nested_endpoints/participant.rb | Rexpense::Resources.Participant.participants | def participants(resource_id)
http.get(participants_endpoint(resource_id)) do |response|
Rexpense::Entities::UserCollection.build response
end
end | ruby | def participants(resource_id)
http.get(participants_endpoint(resource_id)) do |response|
Rexpense::Entities::UserCollection.build response
end
end | [
"def",
"participants",
"(",
"resource_id",
")",
"http",
".",
"get",
"(",
"participants_endpoint",
"(",
"resource_id",
")",
")",
"do",
"|",
"response",
"|",
"Rexpense",
"::",
"Entities",
"::",
"UserCollection",
".",
"build",
"response",
"end",
"end"
] | Get resource participants tags
[API]
Method: <tt>GET /api/v1/reimbursements/:id/participants</tt>
Method: <tt>GET /api/v1/expenses/:id/participants</tt>
Method: <tt>GET /api/v1/advancements/:id/participants</tt>
Documentation: http://developers.rexpense.com/api/participants#index
Documentation: http://developers.rexpense.com/api/expense_participants#index
Documentation: http://developers.rexpense.com/api/reimbursement_participants#index | [
"Get",
"resource",
"participants",
"tags"
] | c3a36440876dda29e0747d45807e70b246e99945 | https://github.com/myfreecomm/rexpense-client-ruby/blob/c3a36440876dda29e0747d45807e70b246e99945/lib/rexpense/resources/nested_endpoints/participant.rb#L14-L18 | train |
myfreecomm/charging-client-ruby | lib/charging/charge_account.rb | Charging.ChargeAccount.update_attribute! | def update_attribute!(attribute, value, should_reload_attributes = true)
execute_and_capture_raises_at_errors(204) do
@last_response = Http.patch("/charge-accounts/#{uuid}/", domain.token, etag, attribute => value)
end
reload_attributes! if should_reload_attributes
end | ruby | def update_attribute!(attribute, value, should_reload_attributes = true)
execute_and_capture_raises_at_errors(204) do
@last_response = Http.patch("/charge-accounts/#{uuid}/", domain.token, etag, attribute => value)
end
reload_attributes! if should_reload_attributes
end | [
"def",
"update_attribute!",
"(",
"attribute",
",",
"value",
",",
"should_reload_attributes",
"=",
"true",
")",
"execute_and_capture_raises_at_errors",
"(",
"204",
")",
"do",
"@last_response",
"=",
"Http",
".",
"patch",
"(",
"\"/charge-accounts/#{uuid}/\"",
",",
"domain",
".",
"token",
",",
"etag",
",",
"attribute",
"=>",
"value",
")",
"end",
"reload_attributes!",
"if",
"should_reload_attributes",
"end"
] | Update an attribute on charge account at API.
API method: <tt>PATCH /charge-accounts/:uuid/</tt>
API documentation: https://charging.financeconnect.com.br/static/docs/charges.html#patch-charge-accounts-uuid | [
"Update",
"an",
"attribute",
"on",
"charge",
"account",
"at",
"API",
"."
] | d2b164a3536a8c5faa8656c8477b399b22181e7f | https://github.com/myfreecomm/charging-client-ruby/blob/d2b164a3536a8c5faa8656c8477b399b22181e7f/lib/charging/charge_account.rb#L56-L62 | train |
myfreecomm/rexpense-client-ruby | lib/rexpense/resources/nested_endpoints/membership.rb | Rexpense::Resources.Membership.memberships | def memberships(organization_id)
http.get(membership_endpoint(organization_id)) do |response|
Rexpense::Entities::MembershipCollection.build response
end
end | ruby | def memberships(organization_id)
http.get(membership_endpoint(organization_id)) do |response|
Rexpense::Entities::MembershipCollection.build response
end
end | [
"def",
"memberships",
"(",
"organization_id",
")",
"http",
".",
"get",
"(",
"membership_endpoint",
"(",
"organization_id",
")",
")",
"do",
"|",
"response",
"|",
"Rexpense",
"::",
"Entities",
"::",
"MembershipCollection",
".",
"build",
"response",
"end",
"end"
] | Get organization memberships
[API]
Method: <tt>GET /api/v1/organizations/:id/memberships</tt>
Documentation: http://developers.rexpense.com/api/memberships#index | [
"Get",
"organization",
"memberships"
] | c3a36440876dda29e0747d45807e70b246e99945 | https://github.com/myfreecomm/rexpense-client-ruby/blob/c3a36440876dda29e0747d45807e70b246e99945/lib/rexpense/resources/nested_endpoints/membership.rb#L10-L14 | train |
myfreecomm/rexpense-client-ruby | lib/rexpense/resources/nested_endpoints/membership.rb | Rexpense::Resources.Membership.create_membership | def create_membership(organization_id, params)
http.post(membership_endpoint(organization_id), body: params) do |response|
response.parsed_body
end
end | ruby | def create_membership(organization_id, params)
http.post(membership_endpoint(organization_id), body: params) do |response|
response.parsed_body
end
end | [
"def",
"create_membership",
"(",
"organization_id",
",",
"params",
")",
"http",
".",
"post",
"(",
"membership_endpoint",
"(",
"organization_id",
")",
",",
"body",
":",
"params",
")",
"do",
"|",
"response",
"|",
"response",
".",
"parsed_body",
"end",
"end"
] | Create organization membership
[API]
Method: <tt>POST /api/v1/organizations/:id/memberships</tt>
Documentation: http://developers.rexpense.com/api/memberships#create | [
"Create",
"organization",
"membership"
] | c3a36440876dda29e0747d45807e70b246e99945 | https://github.com/myfreecomm/rexpense-client-ruby/blob/c3a36440876dda29e0747d45807e70b246e99945/lib/rexpense/resources/nested_endpoints/membership.rb#L36-L40 | train |
myfreecomm/rexpense-client-ruby | lib/rexpense/resources/nested_endpoints/membership.rb | Rexpense::Resources.Membership.update_membership | def update_membership(organization_id, membership_id, params)
http.put("#{membership_endpoint(organization_id)}/#{membership_id}", body: params) do |response|
Rexpense::Entities::Membership.new response.parsed_body
end
end | ruby | def update_membership(organization_id, membership_id, params)
http.put("#{membership_endpoint(organization_id)}/#{membership_id}", body: params) do |response|
Rexpense::Entities::Membership.new response.parsed_body
end
end | [
"def",
"update_membership",
"(",
"organization_id",
",",
"membership_id",
",",
"params",
")",
"http",
".",
"put",
"(",
"\"#{membership_endpoint(organization_id)}/#{membership_id}\"",
",",
"body",
":",
"params",
")",
"do",
"|",
"response",
"|",
"Rexpense",
"::",
"Entities",
"::",
"Membership",
".",
"new",
"response",
".",
"parsed_body",
"end",
"end"
] | Update organization membership
[API]
Method: <tt>PUT /api/v1/organizations/:id/memberships/:membership_id</tt>
Documentation: http://developers.rexpense.com/api/memberships#update | [
"Update",
"organization",
"membership"
] | c3a36440876dda29e0747d45807e70b246e99945 | https://github.com/myfreecomm/rexpense-client-ruby/blob/c3a36440876dda29e0747d45807e70b246e99945/lib/rexpense/resources/nested_endpoints/membership.rb#L49-L53 | train |
myfreecomm/rexpense-client-ruby | lib/rexpense/resources/nested_endpoints/attachment.rb | Rexpense::Resources.Attachment.attachments | def attachments(resource_id)
http.get(attachment_endpoint(resource_id)) do |response|
Rexpense::Entities::AttachmentCollection.build response
end
end | ruby | def attachments(resource_id)
http.get(attachment_endpoint(resource_id)) do |response|
Rexpense::Entities::AttachmentCollection.build response
end
end | [
"def",
"attachments",
"(",
"resource_id",
")",
"http",
".",
"get",
"(",
"attachment_endpoint",
"(",
"resource_id",
")",
")",
"do",
"|",
"response",
"|",
"Rexpense",
"::",
"Entities",
"::",
"AttachmentCollection",
".",
"build",
"response",
"end",
"end"
] | Get resource attachments
[API]
Method: <tt>GET /api/v1/expenses/:id/attachments</tt>
Documentation: http://developers.rexpense.com/api/attachments#index | [
"Get",
"resource",
"attachments"
] | c3a36440876dda29e0747d45807e70b246e99945 | https://github.com/myfreecomm/rexpense-client-ruby/blob/c3a36440876dda29e0747d45807e70b246e99945/lib/rexpense/resources/nested_endpoints/attachment.rb#L10-L14 | train |
myfreecomm/rexpense-client-ruby | lib/rexpense/resources/nested_endpoints/attachment.rb | Rexpense::Resources.Attachment.find_attachment | def find_attachment(resource_id, attachment_id)
http.get("#{attachment_endpoint(resource_id)}/#{attachment_id}") do |response|
Rexpense::Entities::Attachment.new response.parsed_body
end
end | ruby | def find_attachment(resource_id, attachment_id)
http.get("#{attachment_endpoint(resource_id)}/#{attachment_id}") do |response|
Rexpense::Entities::Attachment.new response.parsed_body
end
end | [
"def",
"find_attachment",
"(",
"resource_id",
",",
"attachment_id",
")",
"http",
".",
"get",
"(",
"\"#{attachment_endpoint(resource_id)}/#{attachment_id}\"",
")",
"do",
"|",
"response",
"|",
"Rexpense",
"::",
"Entities",
"::",
"Attachment",
".",
"new",
"response",
".",
"parsed_body",
"end",
"end"
] | Get resource attachment
[API]
Method: <tt>GET /api/v1/expenses/:id/attachments/:id</tt>
Documentation: http://developers.rexpense.com/api/attachments#show | [
"Get",
"resource",
"attachment"
] | c3a36440876dda29e0747d45807e70b246e99945 | https://github.com/myfreecomm/rexpense-client-ruby/blob/c3a36440876dda29e0747d45807e70b246e99945/lib/rexpense/resources/nested_endpoints/attachment.rb#L23-L27 | train |
myfreecomm/rexpense-client-ruby | lib/rexpense/resources/nested_endpoints/comment.rb | Rexpense::Resources.Comment.comments | def comments(resource_id)
http.get(comment_endpoint(resource_id)) do |response|
Rexpense::Entities::CommentCollection.build response
end
end | ruby | def comments(resource_id)
http.get(comment_endpoint(resource_id)) do |response|
Rexpense::Entities::CommentCollection.build response
end
end | [
"def",
"comments",
"(",
"resource_id",
")",
"http",
".",
"get",
"(",
"comment_endpoint",
"(",
"resource_id",
")",
")",
"do",
"|",
"response",
"|",
"Rexpense",
"::",
"Entities",
"::",
"CommentCollection",
".",
"build",
"response",
"end",
"end"
] | Get resource comments
[API]
Method: <tt>GET /api/v1/reimbursements/:id/comments</tt>
Method: <tt>GET /api/v1/expenses/:id/comments</tt>
Method: <tt>GET /api/v1/advancements/:id/comments</tt>
Documentation: http://developers.rexpense.com/api/comments#index | [
"Get",
"resource",
"comments"
] | c3a36440876dda29e0747d45807e70b246e99945 | https://github.com/myfreecomm/rexpense-client-ruby/blob/c3a36440876dda29e0747d45807e70b246e99945/lib/rexpense/resources/nested_endpoints/comment.rb#L12-L16 | train |
myfreecomm/rexpense-client-ruby | lib/rexpense/resources/nested_endpoints/comment.rb | Rexpense::Resources.Comment.find_comment | def find_comment(resource_id, comment_id)
http.get("#{comment_endpoint(resource_id)}/#{comment_id}") do |response|
Rexpense::Entities::Comment.new response.parsed_body
end
end | ruby | def find_comment(resource_id, comment_id)
http.get("#{comment_endpoint(resource_id)}/#{comment_id}") do |response|
Rexpense::Entities::Comment.new response.parsed_body
end
end | [
"def",
"find_comment",
"(",
"resource_id",
",",
"comment_id",
")",
"http",
".",
"get",
"(",
"\"#{comment_endpoint(resource_id)}/#{comment_id}\"",
")",
"do",
"|",
"response",
"|",
"Rexpense",
"::",
"Entities",
"::",
"Comment",
".",
"new",
"response",
".",
"parsed_body",
"end",
"end"
] | Get resource comment
[API]
Method: <tt>GET /api/v1/reimbursements/:id/comments/:comment_id</tt>
Method: <tt>GET /api/v1/expenses/:id/comments/:comment_id</tt>
Method: <tt>GET /api/v1/advancements/:id/comments/:comment_id</tt>
Documentation: http://developers.rexpense.com/api/comments#show | [
"Get",
"resource",
"comment"
] | c3a36440876dda29e0747d45807e70b246e99945 | https://github.com/myfreecomm/rexpense-client-ruby/blob/c3a36440876dda29e0747d45807e70b246e99945/lib/rexpense/resources/nested_endpoints/comment.rb#L27-L31 | train |
myfreecomm/rexpense-client-ruby | lib/rexpense/resources/nested_endpoints/comment.rb | Rexpense::Resources.Comment.create_comment | def create_comment(resource_id, params)
http.post(comment_endpoint(resource_id), body: params) do |response|
Rexpense::Entities::Comment.new response.parsed_body
end
end | ruby | def create_comment(resource_id, params)
http.post(comment_endpoint(resource_id), body: params) do |response|
Rexpense::Entities::Comment.new response.parsed_body
end
end | [
"def",
"create_comment",
"(",
"resource_id",
",",
"params",
")",
"http",
".",
"post",
"(",
"comment_endpoint",
"(",
"resource_id",
")",
",",
"body",
":",
"params",
")",
"do",
"|",
"response",
"|",
"Rexpense",
"::",
"Entities",
"::",
"Comment",
".",
"new",
"response",
".",
"parsed_body",
"end",
"end"
] | Create resource comment
[API]
Method: <tt>POST /api/v1/reimbursements/:id/comments</tt>
Method: <tt>POST /api/v1/expenses/:id/comments</tt>
Method: <tt>POST /api/v1/advancements/:id/comments</tt>
Documentation: http://developers.rexpense.com/api/comments#create | [
"Create",
"resource",
"comment"
] | c3a36440876dda29e0747d45807e70b246e99945 | https://github.com/myfreecomm/rexpense-client-ruby/blob/c3a36440876dda29e0747d45807e70b246e99945/lib/rexpense/resources/nested_endpoints/comment.rb#L42-L46 | train |
myfreecomm/rexpense-client-ruby | lib/rexpense/resources/nested_endpoints/comment.rb | Rexpense::Resources.Comment.update_comment | def update_comment(resource_id, comment_id, params)
http.put("#{comment_endpoint(resource_id)}/#{comment_id}", body: params) do |response|
Rexpense::Entities::Comment.new response.parsed_body
end
end | ruby | def update_comment(resource_id, comment_id, params)
http.put("#{comment_endpoint(resource_id)}/#{comment_id}", body: params) do |response|
Rexpense::Entities::Comment.new response.parsed_body
end
end | [
"def",
"update_comment",
"(",
"resource_id",
",",
"comment_id",
",",
"params",
")",
"http",
".",
"put",
"(",
"\"#{comment_endpoint(resource_id)}/#{comment_id}\"",
",",
"body",
":",
"params",
")",
"do",
"|",
"response",
"|",
"Rexpense",
"::",
"Entities",
"::",
"Comment",
".",
"new",
"response",
".",
"parsed_body",
"end",
"end"
] | Update resource comment
[API]
Method: <tt>PUT /api/v1/reimbursements/:id/comments/:comment_id</tt>
Method: <tt>PUT /api/v1/expenses/:id/comments/:comment_id</tt>
Method: <tt>PUT /api/v1/advancements/:id/comments/:comment_id</tt>
Documentation: http://developers.rexpense.com/api/comments#update | [
"Update",
"resource",
"comment"
] | c3a36440876dda29e0747d45807e70b246e99945 | https://github.com/myfreecomm/rexpense-client-ruby/blob/c3a36440876dda29e0747d45807e70b246e99945/lib/rexpense/resources/nested_endpoints/comment.rb#L57-L61 | train |
bensie/enom | lib/enom/domain.rb | Enom.Domain.sync_auth_info | def sync_auth_info(options = {})
opts = {
"RunSynchAutoInfo" => 'True',
"EmailEPP" => 'True'
}
opts["EmailEPP"] = 'True' if options[:email]
Client.request({"Command" => "SynchAuthInfo", "SLD" => sld, "TLD" => tld}.merge(opts))
return self
end | ruby | def sync_auth_info(options = {})
opts = {
"RunSynchAutoInfo" => 'True',
"EmailEPP" => 'True'
}
opts["EmailEPP"] = 'True' if options[:email]
Client.request({"Command" => "SynchAuthInfo", "SLD" => sld, "TLD" => tld}.merge(opts))
return self
end | [
"def",
"sync_auth_info",
"(",
"options",
"=",
"{",
"}",
")",
"opts",
"=",
"{",
"\"RunSynchAutoInfo\"",
"=>",
"'True'",
",",
"\"EmailEPP\"",
"=>",
"'True'",
"}",
"opts",
"[",
"\"EmailEPP\"",
"]",
"=",
"'True'",
"if",
"options",
"[",
":email",
"]",
"Client",
".",
"request",
"(",
"{",
"\"Command\"",
"=>",
"\"SynchAuthInfo\"",
",",
"\"SLD\"",
"=>",
"sld",
",",
"\"TLD\"",
"=>",
"tld",
"}",
".",
"merge",
"(",
"opts",
")",
")",
"return",
"self",
"end"
] | synchronize EPP key with Registry, and optionally email it to owner | [
"synchronize",
"EPP",
"key",
"with",
"Registry",
"and",
"optionally",
"email",
"it",
"to",
"owner"
] | a5f493a61422ea8da5d327d541c300c8756aed1e | https://github.com/bensie/enom/blob/a5f493a61422ea8da5d327d541c300c8756aed1e/lib/enom/domain.rb#L212-L222 | train |
bensie/enom | lib/enom/domain.rb | Enom.Domain.get_extended_domain_attributes | def get_extended_domain_attributes
sld, tld = name.split(".")
attributes = Client.request("Command" => "GetDomainInfo", "SLD" => sld, "TLD" => tld)["interface_response"]["GetDomainInfo"]
set_extended_domain_attributes(attributes)
end | ruby | def get_extended_domain_attributes
sld, tld = name.split(".")
attributes = Client.request("Command" => "GetDomainInfo", "SLD" => sld, "TLD" => tld)["interface_response"]["GetDomainInfo"]
set_extended_domain_attributes(attributes)
end | [
"def",
"get_extended_domain_attributes",
"sld",
",",
"tld",
"=",
"name",
".",
"split",
"(",
"\".\"",
")",
"attributes",
"=",
"Client",
".",
"request",
"(",
"\"Command\"",
"=>",
"\"GetDomainInfo\"",
",",
"\"SLD\"",
"=>",
"sld",
",",
"\"TLD\"",
"=>",
"tld",
")",
"[",
"\"interface_response\"",
"]",
"[",
"\"GetDomainInfo\"",
"]",
"set_extended_domain_attributes",
"(",
"attributes",
")",
"end"
] | Make another API call to get all domain info. Often necessary when domains are
found using Domain.all instead of Domain.find. | [
"Make",
"another",
"API",
"call",
"to",
"get",
"all",
"domain",
"info",
".",
"Often",
"necessary",
"when",
"domains",
"are",
"found",
"using",
"Domain",
".",
"all",
"instead",
"of",
"Domain",
".",
"find",
"."
] | a5f493a61422ea8da5d327d541c300c8756aed1e | https://github.com/bensie/enom/blob/a5f493a61422ea8da5d327d541c300c8756aed1e/lib/enom/domain.rb#L292-L296 | train |
bdurand/acts_as_revisionable | lib/acts_as_revisionable/revision_record.rb | ActsAsRevisionable.RevisionRecord.restore | def restore
restore_class = self.revisionable_type.constantize
# Check if we have a type field, if yes, assume single table inheritance and restore the actual class instead of the stored base class
sti_type = self.revision_attributes[restore_class.inheritance_column]
if sti_type
begin
if !restore_class.store_full_sti_class && !sti_type.start_with?("::")
sti_type = "#{restore_class.parent.name}::#{sti_type}"
end
restore_class = sti_type.constantize
rescue NameError => e
raise e
# Seems our assumption was wrong and we have no STI
end
end
record = restore_class.new
restore_record(record, revision_attributes)
return record
end | ruby | def restore
restore_class = self.revisionable_type.constantize
# Check if we have a type field, if yes, assume single table inheritance and restore the actual class instead of the stored base class
sti_type = self.revision_attributes[restore_class.inheritance_column]
if sti_type
begin
if !restore_class.store_full_sti_class && !sti_type.start_with?("::")
sti_type = "#{restore_class.parent.name}::#{sti_type}"
end
restore_class = sti_type.constantize
rescue NameError => e
raise e
# Seems our assumption was wrong and we have no STI
end
end
record = restore_class.new
restore_record(record, revision_attributes)
return record
end | [
"def",
"restore",
"restore_class",
"=",
"self",
".",
"revisionable_type",
".",
"constantize",
"sti_type",
"=",
"self",
".",
"revision_attributes",
"[",
"restore_class",
".",
"inheritance_column",
"]",
"if",
"sti_type",
"begin",
"if",
"!",
"restore_class",
".",
"store_full_sti_class",
"&&",
"!",
"sti_type",
".",
"start_with?",
"(",
"\"::\"",
")",
"sti_type",
"=",
"\"#{restore_class.parent.name}::#{sti_type}\"",
"end",
"restore_class",
"=",
"sti_type",
".",
"constantize",
"rescue",
"NameError",
"=>",
"e",
"raise",
"e",
"end",
"end",
"record",
"=",
"restore_class",
".",
"new",
"restore_record",
"(",
"record",
",",
"revision_attributes",
")",
"return",
"record",
"end"
] | Restore the revision to the original record. If any errors are encountered restoring attributes, they
will be added to the errors object of the restored record. | [
"Restore",
"the",
"revision",
"to",
"the",
"original",
"record",
".",
"If",
"any",
"errors",
"are",
"encountered",
"restoring",
"attributes",
"they",
"will",
"be",
"added",
"to",
"the",
"errors",
"object",
"of",
"the",
"restored",
"record",
"."
] | cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc | https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable/revision_record.rb#L95-L115 | train |
bdurand/acts_as_revisionable | lib/acts_as_revisionable/revision_record.rb | ActsAsRevisionable.RevisionRecord.restore_record | def restore_record(record, attributes)
primary_key = record.class.primary_key
primary_key = [primary_key].compact unless primary_key.is_a?(Array)
primary_key.each do |key|
record.send("#{key.to_s}=", attributes[key.to_s])
end
attrs, association_attrs = attributes_and_associations(record.class, attributes)
attrs.each_pair do |key, value|
begin
record.send("#{key}=", value)
rescue
record.errors.add(key.to_sym, "could not be restored to #{value.inspect}")
end
end
association_attrs.each_pair do |key, values|
restore_association(record, key, values) if values
end
# Check if the record already exists in the database and restore its state.
# This must be done last because otherwise associations on an existing record
# can be deleted when a revision is restored to memory.
exists = record.class.find(record.send(record.class.primary_key)) rescue nil
if exists
record.instance_variable_set(:@new_record, nil) if record.instance_variable_defined?(:@new_record)
# ActiveRecord 3.0.2 and 3.0.3 used @persisted instead of @new_record
record.instance_variable_set(:@persisted, true) if record.instance_variable_defined?(:@persisted)
end
end | ruby | def restore_record(record, attributes)
primary_key = record.class.primary_key
primary_key = [primary_key].compact unless primary_key.is_a?(Array)
primary_key.each do |key|
record.send("#{key.to_s}=", attributes[key.to_s])
end
attrs, association_attrs = attributes_and_associations(record.class, attributes)
attrs.each_pair do |key, value|
begin
record.send("#{key}=", value)
rescue
record.errors.add(key.to_sym, "could not be restored to #{value.inspect}")
end
end
association_attrs.each_pair do |key, values|
restore_association(record, key, values) if values
end
# Check if the record already exists in the database and restore its state.
# This must be done last because otherwise associations on an existing record
# can be deleted when a revision is restored to memory.
exists = record.class.find(record.send(record.class.primary_key)) rescue nil
if exists
record.instance_variable_set(:@new_record, nil) if record.instance_variable_defined?(:@new_record)
# ActiveRecord 3.0.2 and 3.0.3 used @persisted instead of @new_record
record.instance_variable_set(:@persisted, true) if record.instance_variable_defined?(:@persisted)
end
end | [
"def",
"restore_record",
"(",
"record",
",",
"attributes",
")",
"primary_key",
"=",
"record",
".",
"class",
".",
"primary_key",
"primary_key",
"=",
"[",
"primary_key",
"]",
".",
"compact",
"unless",
"primary_key",
".",
"is_a?",
"(",
"Array",
")",
"primary_key",
".",
"each",
"do",
"|",
"key",
"|",
"record",
".",
"send",
"(",
"\"#{key.to_s}=\"",
",",
"attributes",
"[",
"key",
".",
"to_s",
"]",
")",
"end",
"attrs",
",",
"association_attrs",
"=",
"attributes_and_associations",
"(",
"record",
".",
"class",
",",
"attributes",
")",
"attrs",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"begin",
"record",
".",
"send",
"(",
"\"#{key}=\"",
",",
"value",
")",
"rescue",
"record",
".",
"errors",
".",
"add",
"(",
"key",
".",
"to_sym",
",",
"\"could not be restored to #{value.inspect}\"",
")",
"end",
"end",
"association_attrs",
".",
"each_pair",
"do",
"|",
"key",
",",
"values",
"|",
"restore_association",
"(",
"record",
",",
"key",
",",
"values",
")",
"if",
"values",
"end",
"exists",
"=",
"record",
".",
"class",
".",
"find",
"(",
"record",
".",
"send",
"(",
"record",
".",
"class",
".",
"primary_key",
")",
")",
"rescue",
"nil",
"if",
"exists",
"record",
".",
"instance_variable_set",
"(",
":@new_record",
",",
"nil",
")",
"if",
"record",
".",
"instance_variable_defined?",
"(",
":@new_record",
")",
"record",
".",
"instance_variable_set",
"(",
":@persisted",
",",
"true",
")",
"if",
"record",
".",
"instance_variable_defined?",
"(",
":@persisted",
")",
"end",
"end"
] | Restore a record and all its associations. | [
"Restore",
"a",
"record",
"and",
"all",
"its",
"associations",
"."
] | cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc | https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable/revision_record.rb#L237-L266 | train |
ShipCompliant/ship_compliant-ruby | lib/ship_compliant/search_sales_orders_result.rb | ShipCompliant.SearchSalesOrdersResult.parse! | def parse!
unless raw.has_key?(:sales_orders)
raw[:sales_orders] = {}
end
# force orders to be an array
orders = raw[:sales_orders].fetch(:sales_order_summary, {})
unless orders.kind_of?(Array)
raw[:sales_orders][:sales_order_summary] = [orders]
end
# typecast :count_more_sales_orders_available to integer
if raw.has_key?(:count_more_sales_orders_available)
convert_to_integer!(:count_more_sales_orders_available, raw)
end
# typecast :count_sales_orders_returned to integer
if raw.has_key?(:count_sales_orders_returned)
convert_to_integer!(:count_sales_orders_returned, raw)
end
raw[:sales_orders][:sales_order_summary].each do |summary|
# typecast :shipment_key to integer
if summary.fetch(:shipments, {}).fetch(:shipment_summary, {}).has_key?(:shipment_key)
convert_to_integer!(:shipment_key, summary[:shipments][:shipment_summary])
end
# typecast :zip1 to integer
if summary.fetch(:shipments, {}).fetch(:shipment_summary, {}).fetch(:ship_to, {}).has_key?(:zip1)
convert_to_integer!(:zip1, summary[:shipments][:shipment_summary][:ship_to])
end
end
end | ruby | def parse!
unless raw.has_key?(:sales_orders)
raw[:sales_orders] = {}
end
# force orders to be an array
orders = raw[:sales_orders].fetch(:sales_order_summary, {})
unless orders.kind_of?(Array)
raw[:sales_orders][:sales_order_summary] = [orders]
end
# typecast :count_more_sales_orders_available to integer
if raw.has_key?(:count_more_sales_orders_available)
convert_to_integer!(:count_more_sales_orders_available, raw)
end
# typecast :count_sales_orders_returned to integer
if raw.has_key?(:count_sales_orders_returned)
convert_to_integer!(:count_sales_orders_returned, raw)
end
raw[:sales_orders][:sales_order_summary].each do |summary|
# typecast :shipment_key to integer
if summary.fetch(:shipments, {}).fetch(:shipment_summary, {}).has_key?(:shipment_key)
convert_to_integer!(:shipment_key, summary[:shipments][:shipment_summary])
end
# typecast :zip1 to integer
if summary.fetch(:shipments, {}).fetch(:shipment_summary, {}).fetch(:ship_to, {}).has_key?(:zip1)
convert_to_integer!(:zip1, summary[:shipments][:shipment_summary][:ship_to])
end
end
end | [
"def",
"parse!",
"unless",
"raw",
".",
"has_key?",
"(",
":sales_orders",
")",
"raw",
"[",
":sales_orders",
"]",
"=",
"{",
"}",
"end",
"orders",
"=",
"raw",
"[",
":sales_orders",
"]",
".",
"fetch",
"(",
":sales_order_summary",
",",
"{",
"}",
")",
"unless",
"orders",
".",
"kind_of?",
"(",
"Array",
")",
"raw",
"[",
":sales_orders",
"]",
"[",
":sales_order_summary",
"]",
"=",
"[",
"orders",
"]",
"end",
"if",
"raw",
".",
"has_key?",
"(",
":count_more_sales_orders_available",
")",
"convert_to_integer!",
"(",
":count_more_sales_orders_available",
",",
"raw",
")",
"end",
"if",
"raw",
".",
"has_key?",
"(",
":count_sales_orders_returned",
")",
"convert_to_integer!",
"(",
":count_sales_orders_returned",
",",
"raw",
")",
"end",
"raw",
"[",
":sales_orders",
"]",
"[",
":sales_order_summary",
"]",
".",
"each",
"do",
"|",
"summary",
"|",
"if",
"summary",
".",
"fetch",
"(",
":shipments",
",",
"{",
"}",
")",
".",
"fetch",
"(",
":shipment_summary",
",",
"{",
"}",
")",
".",
"has_key?",
"(",
":shipment_key",
")",
"convert_to_integer!",
"(",
":shipment_key",
",",
"summary",
"[",
":shipments",
"]",
"[",
":shipment_summary",
"]",
")",
"end",
"if",
"summary",
".",
"fetch",
"(",
":shipments",
",",
"{",
"}",
")",
".",
"fetch",
"(",
":shipment_summary",
",",
"{",
"}",
")",
".",
"fetch",
"(",
":ship_to",
",",
"{",
"}",
")",
".",
"has_key?",
"(",
":zip1",
")",
"convert_to_integer!",
"(",
":zip1",
",",
"summary",
"[",
":shipments",
"]",
"[",
":shipment_summary",
"]",
"[",
":ship_to",
"]",
")",
"end",
"end",
"end"
] | Standardizes the XML response by converting fields to integers
and forcing the order summaries into an array. | [
"Standardizes",
"the",
"XML",
"response",
"by",
"converting",
"fields",
"to",
"integers",
"and",
"forcing",
"the",
"order",
"summaries",
"into",
"an",
"array",
"."
] | aa12852a58cd6cb7939eb9fbb7fdc03e46e18197 | https://github.com/ShipCompliant/ship_compliant-ruby/blob/aa12852a58cd6cb7939eb9fbb7fdc03e46e18197/lib/ship_compliant/search_sales_orders_result.rb#L64-L97 | train |
ShipCompliant/ship_compliant-ruby | lib/ship_compliant/client.rb | ShipCompliant.Client.call | def call(operation, locals = {})
locals['Security'] = ShipCompliant.configuration.credentials
response = savon_call(operation, message: {
'Request' => locals
})
get_result_from_response(operation, response)
end | ruby | def call(operation, locals = {})
locals['Security'] = ShipCompliant.configuration.credentials
response = savon_call(operation, message: {
'Request' => locals
})
get_result_from_response(operation, response)
end | [
"def",
"call",
"(",
"operation",
",",
"locals",
"=",
"{",
"}",
")",
"locals",
"[",
"'Security'",
"]",
"=",
"ShipCompliant",
".",
"configuration",
".",
"credentials",
"response",
"=",
"savon_call",
"(",
"operation",
",",
"message",
":",
"{",
"'Request'",
"=>",
"locals",
"}",
")",
"get_result_from_response",
"(",
"operation",
",",
"response",
")",
"end"
] | Adds the required security credentials and formats
the message to match the ShipCompliant structure.
ShipCompliant.client.call(:some_operation, {
'SomeKey' => 'SomeValue'
}) | [
"Adds",
"the",
"required",
"security",
"credentials",
"and",
"formats",
"the",
"message",
"to",
"match",
"the",
"ShipCompliant",
"structure",
"."
] | aa12852a58cd6cb7939eb9fbb7fdc03e46e18197 | https://github.com/ShipCompliant/ship_compliant-ruby/blob/aa12852a58cd6cb7939eb9fbb7fdc03e46e18197/lib/ship_compliant/client.rb#L35-L43 | train |
rossf7/elasticrawl | lib/elasticrawl/job.rb | Elasticrawl.Job.confirm_message | def confirm_message
cluster = Cluster.new
case self.type
when 'Elasticrawl::ParseJob'
message = segment_list
else
message = []
end
message.push('Job configuration')
message.push(self.job_desc)
message.push('')
message.push(cluster.cluster_desc)
message.join("\n")
end | ruby | def confirm_message
cluster = Cluster.new
case self.type
when 'Elasticrawl::ParseJob'
message = segment_list
else
message = []
end
message.push('Job configuration')
message.push(self.job_desc)
message.push('')
message.push(cluster.cluster_desc)
message.join("\n")
end | [
"def",
"confirm_message",
"cluster",
"=",
"Cluster",
".",
"new",
"case",
"self",
".",
"type",
"when",
"'Elasticrawl::ParseJob'",
"message",
"=",
"segment_list",
"else",
"message",
"=",
"[",
"]",
"end",
"message",
".",
"push",
"(",
"'Job configuration'",
")",
"message",
".",
"push",
"(",
"self",
".",
"job_desc",
")",
"message",
".",
"push",
"(",
"''",
")",
"message",
".",
"push",
"(",
"cluster",
".",
"cluster_desc",
")",
"message",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | Displays a confirmation message showing the configuration of the
Elastic MapReduce job flow and cluster. | [
"Displays",
"a",
"confirmation",
"message",
"showing",
"the",
"configuration",
"of",
"the",
"Elastic",
"MapReduce",
"job",
"flow",
"and",
"cluster",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/job.rb#L8-L24 | train |
rossf7/elasticrawl | lib/elasticrawl/job.rb | Elasticrawl.Job.run_job_flow | def run_job_flow(emr_config)
cluster = Cluster.new
job_flow = cluster.create_job_flow(self, emr_config)
job_steps.each do |step|
job_flow.add_step(step.job_flow_step(job_config))
end
begin
job_flow.run
rescue StandardError => e
raise ElasticMapReduceAccessError, e.message
end
end | ruby | def run_job_flow(emr_config)
cluster = Cluster.new
job_flow = cluster.create_job_flow(self, emr_config)
job_steps.each do |step|
job_flow.add_step(step.job_flow_step(job_config))
end
begin
job_flow.run
rescue StandardError => e
raise ElasticMapReduceAccessError, e.message
end
end | [
"def",
"run_job_flow",
"(",
"emr_config",
")",
"cluster",
"=",
"Cluster",
".",
"new",
"job_flow",
"=",
"cluster",
".",
"create_job_flow",
"(",
"self",
",",
"emr_config",
")",
"job_steps",
".",
"each",
"do",
"|",
"step",
"|",
"job_flow",
".",
"add_step",
"(",
"step",
".",
"job_flow_step",
"(",
"job_config",
")",
")",
"end",
"begin",
"job_flow",
".",
"run",
"rescue",
"StandardError",
"=>",
"e",
"raise",
"ElasticMapReduceAccessError",
",",
"e",
".",
"message",
"end",
"end"
] | Calls the Elastic MapReduce API to create a Job Flow. Returns the Job Flow ID. | [
"Calls",
"the",
"Elastic",
"MapReduce",
"API",
"to",
"create",
"a",
"Job",
"Flow",
".",
"Returns",
"the",
"Job",
"Flow",
"ID",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/job.rb#L40-L54 | train |
brasten/scruffy | lib/scruffy/layers/scatter.rb | Scruffy::Layers.Scatter.draw | def draw(svg, coords, options={})
options.merge!(@options)
if options[:shadow]
svg.g(:class => 'shadow', :transform => "translate(#{relative(0.5)}, #{relative(0.5)})") {
coords.each { |coord| svg.circle( :cx => coord.first, :cy => coord.last + relative(0.9), :r => relative(2),
:style => "stroke-width: #{relative(2)}; stroke: black; opacity: 0.35;" ) }
}
end
coords.each { |coord| svg.circle( :cx => coord.first, :cy => coord.last, :r => relative(2),
:style => "stroke-width: #{relative(2)}; stroke: #{color.to_s}; fill: #{color.to_s}" ) }
end | ruby | def draw(svg, coords, options={})
options.merge!(@options)
if options[:shadow]
svg.g(:class => 'shadow', :transform => "translate(#{relative(0.5)}, #{relative(0.5)})") {
coords.each { |coord| svg.circle( :cx => coord.first, :cy => coord.last + relative(0.9), :r => relative(2),
:style => "stroke-width: #{relative(2)}; stroke: black; opacity: 0.35;" ) }
}
end
coords.each { |coord| svg.circle( :cx => coord.first, :cy => coord.last, :r => relative(2),
:style => "stroke-width: #{relative(2)}; stroke: #{color.to_s}; fill: #{color.to_s}" ) }
end | [
"def",
"draw",
"(",
"svg",
",",
"coords",
",",
"options",
"=",
"{",
"}",
")",
"options",
".",
"merge!",
"(",
"@options",
")",
"if",
"options",
"[",
":shadow",
"]",
"svg",
".",
"g",
"(",
":class",
"=>",
"'shadow'",
",",
":transform",
"=>",
"\"translate(#{relative(0.5)}, #{relative(0.5)})\"",
")",
"{",
"coords",
".",
"each",
"{",
"|",
"coord",
"|",
"svg",
".",
"circle",
"(",
":cx",
"=>",
"coord",
".",
"first",
",",
":cy",
"=>",
"coord",
".",
"last",
"+",
"relative",
"(",
"0.9",
")",
",",
":r",
"=>",
"relative",
"(",
"2",
")",
",",
":style",
"=>",
"\"stroke-width: #{relative(2)}; stroke: black; opacity: 0.35;\"",
")",
"}",
"}",
"end",
"coords",
".",
"each",
"{",
"|",
"coord",
"|",
"svg",
".",
"circle",
"(",
":cx",
"=>",
"coord",
".",
"first",
",",
":cy",
"=>",
"coord",
".",
"last",
",",
":r",
"=>",
"relative",
"(",
"2",
")",
",",
":style",
"=>",
"\"stroke-width: #{relative(2)}; stroke: #{color.to_s}; fill: #{color.to_s}\"",
")",
"}",
"end"
] | Renders scatter graph. | [
"Renders",
"scatter",
"graph",
"."
] | 4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e | https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/scatter.rb#L13-L26 | train |
brasten/scruffy | lib/scruffy/layers/area.rb | Scruffy::Layers.Area.draw | def draw(svg, coords, options={})
# svg.polygon wants a long string of coords.
points_value = "0,#{height} #{stringify_coords(coords).join(' ')} #{width},#{height}"
# Experimental, for later user.
# This was supposed to add some fun filters, 3d effects and whatnot.
# Neither ImageMagick nor Mozilla SVG render this well (at all). Maybe a future thing.
#
# svg.defs {
# svg.filter(:id => 'MyFilter', :filterUnits => 'userSpaceOnUse', :x => 0, :y => 0, :width => 200, :height => '120') {
# svg.feGaussianBlur(:in => 'SourceAlpha', :stdDeviation => 4, :result => 'blur')
# svg.feOffset(:in => 'blur', :dx => 4, :dy => 4, :result => 'offsetBlur')
# svg.feSpecularLighting( :in => 'blur', :surfaceScale => 5, :specularConstant => '.75',
# :specularExponent => 20, 'lighting-color' => '#bbbbbb',
# :result => 'specOut') {
# svg.fePointLight(:x => '-5000', :y => '-10000', :z => '20000')
# }
#
# svg.feComposite(:in => 'specOut', :in2 => 'SourceAlpha', :operator => 'in', :result => 'specOut')
# svg.feComposite(:in => 'sourceGraphic', :in2 => 'specOut', :operator => 'arithmetic',
# :k1 => 0, :k2 => 1, :k3 => 1, :k4 => 0, :result => 'litPaint')
#
# svg.feMerge {
# svg.feMergeNode(:in => 'offsetBlur')
# svg.feMergeNode(:in => 'litPaint')
# }
# }
# }
svg.g(:transform => "translate(0, -#{relative(2)})") {
svg.polygon(:points => points_value, :style => "fill: black; stroke: black; fill-opacity: 0.06; stroke-opacity: 0.06;")
}
svg.polygon(:points => points_value, :fill => color.to_s, :stroke => color.to_s, 'style' => "opacity: #{opacity}")
end | ruby | def draw(svg, coords, options={})
# svg.polygon wants a long string of coords.
points_value = "0,#{height} #{stringify_coords(coords).join(' ')} #{width},#{height}"
# Experimental, for later user.
# This was supposed to add some fun filters, 3d effects and whatnot.
# Neither ImageMagick nor Mozilla SVG render this well (at all). Maybe a future thing.
#
# svg.defs {
# svg.filter(:id => 'MyFilter', :filterUnits => 'userSpaceOnUse', :x => 0, :y => 0, :width => 200, :height => '120') {
# svg.feGaussianBlur(:in => 'SourceAlpha', :stdDeviation => 4, :result => 'blur')
# svg.feOffset(:in => 'blur', :dx => 4, :dy => 4, :result => 'offsetBlur')
# svg.feSpecularLighting( :in => 'blur', :surfaceScale => 5, :specularConstant => '.75',
# :specularExponent => 20, 'lighting-color' => '#bbbbbb',
# :result => 'specOut') {
# svg.fePointLight(:x => '-5000', :y => '-10000', :z => '20000')
# }
#
# svg.feComposite(:in => 'specOut', :in2 => 'SourceAlpha', :operator => 'in', :result => 'specOut')
# svg.feComposite(:in => 'sourceGraphic', :in2 => 'specOut', :operator => 'arithmetic',
# :k1 => 0, :k2 => 1, :k3 => 1, :k4 => 0, :result => 'litPaint')
#
# svg.feMerge {
# svg.feMergeNode(:in => 'offsetBlur')
# svg.feMergeNode(:in => 'litPaint')
# }
# }
# }
svg.g(:transform => "translate(0, -#{relative(2)})") {
svg.polygon(:points => points_value, :style => "fill: black; stroke: black; fill-opacity: 0.06; stroke-opacity: 0.06;")
}
svg.polygon(:points => points_value, :fill => color.to_s, :stroke => color.to_s, 'style' => "opacity: #{opacity}")
end | [
"def",
"draw",
"(",
"svg",
",",
"coords",
",",
"options",
"=",
"{",
"}",
")",
"points_value",
"=",
"\"0,#{height} #{stringify_coords(coords).join(' ')} #{width},#{height}\"",
"svg",
".",
"g",
"(",
":transform",
"=>",
"\"translate(0, -#{relative(2)})\"",
")",
"{",
"svg",
".",
"polygon",
"(",
":points",
"=>",
"points_value",
",",
":style",
"=>",
"\"fill: black; stroke: black; fill-opacity: 0.06; stroke-opacity: 0.06;\"",
")",
"}",
"svg",
".",
"polygon",
"(",
":points",
"=>",
"points_value",
",",
":fill",
"=>",
"color",
".",
"to_s",
",",
":stroke",
"=>",
"color",
".",
"to_s",
",",
"'style'",
"=>",
"\"opacity: #{opacity}\"",
")",
"end"
] | Render area graph. | [
"Render",
"area",
"graph",
"."
] | 4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e | https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/area.rb#L11-L44 | train |
waiting-for-dev/landing_page | app/controllers/landing_page/users_controller.rb | LandingPage.UsersController.create | def create
params.require(:user).permit!
user = User.new(params[:user])
if user.valid?
user.save
flash.now[:success] = t('landing_page.subscribed')
render :create
else
@user = user
render :new
end
end | ruby | def create
params.require(:user).permit!
user = User.new(params[:user])
if user.valid?
user.save
flash.now[:success] = t('landing_page.subscribed')
render :create
else
@user = user
render :new
end
end | [
"def",
"create",
"params",
".",
"require",
"(",
":user",
")",
".",
"permit!",
"user",
"=",
"User",
".",
"new",
"(",
"params",
"[",
":user",
"]",
")",
"if",
"user",
".",
"valid?",
"user",
".",
"save",
"flash",
".",
"now",
"[",
":success",
"]",
"=",
"t",
"(",
"'landing_page.subscribed'",
")",
"render",
":create",
"else",
"@user",
"=",
"user",
"render",
":new",
"end",
"end"
] | Register a new user or show errors | [
"Register",
"a",
"new",
"user",
"or",
"show",
"errors"
] | be564fc12fd838f8845d42b5c8ade54e3c3c7c1a | https://github.com/waiting-for-dev/landing_page/blob/be564fc12fd838f8845d42b5c8ade54e3c3c7c1a/app/controllers/landing_page/users_controller.rb#L10-L21 | train |
orta/travish | lib/environment_parser.rb | Travish.EnvironmentParser.build_environment_hash | def build_environment_hash
parsed_variables = {}
@env.each do |env_row|
# Each row can potentially contain multiple environment
# variables
variables = extract_variables(env_row)
variables.each do |variables_with_values|
variables_with_values.each do |key, value|
parsed_variables[key] = value
end
end
end
@override_envs.each do |env|
parsed_variables = parsed_variables.merge env
end
parsed_variables
end | ruby | def build_environment_hash
parsed_variables = {}
@env.each do |env_row|
# Each row can potentially contain multiple environment
# variables
variables = extract_variables(env_row)
variables.each do |variables_with_values|
variables_with_values.each do |key, value|
parsed_variables[key] = value
end
end
end
@override_envs.each do |env|
parsed_variables = parsed_variables.merge env
end
parsed_variables
end | [
"def",
"build_environment_hash",
"parsed_variables",
"=",
"{",
"}",
"@env",
".",
"each",
"do",
"|",
"env_row",
"|",
"variables",
"=",
"extract_variables",
"(",
"env_row",
")",
"variables",
".",
"each",
"do",
"|",
"variables_with_values",
"|",
"variables_with_values",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"parsed_variables",
"[",
"key",
"]",
"=",
"value",
"end",
"end",
"end",
"@override_envs",
".",
"each",
"do",
"|",
"env",
"|",
"parsed_variables",
"=",
"parsed_variables",
".",
"merge",
"env",
"end",
"parsed_variables",
"end"
] | Build the environment hash by extracting the environment
variables from the provided travis environment and merging
with any provided overrides | [
"Build",
"the",
"environment",
"hash",
"by",
"extracting",
"the",
"environment",
"variables",
"from",
"the",
"provided",
"travis",
"environment",
"and",
"merging",
"with",
"any",
"provided",
"overrides"
] | fe71115690c8cef69979cea0dca8176eba304ab1 | https://github.com/orta/travish/blob/fe71115690c8cef69979cea0dca8176eba304ab1/lib/environment_parser.rb#L31-L50 | train |
orta/travish | lib/environment_parser.rb | Travish.EnvironmentParser.extract_variables | def extract_variables(variable)
return [variable] if variable.is_a? Hash
return extract_variables_from_string(variable) if variable.is_a? String
[]
end | ruby | def extract_variables(variable)
return [variable] if variable.is_a? Hash
return extract_variables_from_string(variable) if variable.is_a? String
[]
end | [
"def",
"extract_variables",
"(",
"variable",
")",
"return",
"[",
"variable",
"]",
"if",
"variable",
".",
"is_a?",
"Hash",
"return",
"extract_variables_from_string",
"(",
"variable",
")",
"if",
"variable",
".",
"is_a?",
"String",
"[",
"]",
"end"
] | Extract environment variables from a value
The value is expected to be either a hash or a string with
one or more key value pairs on the form
KEY=VALUE | [
"Extract",
"environment",
"variables",
"from",
"a",
"value",
"The",
"value",
"is",
"expected",
"to",
"be",
"either",
"a",
"hash",
"or",
"a",
"string",
"with",
"one",
"or",
"more",
"key",
"value",
"pairs",
"on",
"the",
"form",
"KEY",
"=",
"VALUE"
] | fe71115690c8cef69979cea0dca8176eba304ab1 | https://github.com/orta/travish/blob/fe71115690c8cef69979cea0dca8176eba304ab1/lib/environment_parser.rb#L56-L61 | train |
orta/travish | lib/environment_parser.rb | Travish.EnvironmentParser.extract_variables_from_string | def extract_variables_from_string(string)
string.split(/ /).map do |defintion|
match = defintion.match STRING_REG_EX
next nil unless match
{ match[1] => match[2] }
end.reject(&:nil?)
end | ruby | def extract_variables_from_string(string)
string.split(/ /).map do |defintion|
match = defintion.match STRING_REG_EX
next nil unless match
{ match[1] => match[2] }
end.reject(&:nil?)
end | [
"def",
"extract_variables_from_string",
"(",
"string",
")",
"string",
".",
"split",
"(",
"/",
"/",
")",
".",
"map",
"do",
"|",
"defintion",
"|",
"match",
"=",
"defintion",
".",
"match",
"STRING_REG_EX",
"next",
"nil",
"unless",
"match",
"{",
"match",
"[",
"1",
"]",
"=>",
"match",
"[",
"2",
"]",
"}",
"end",
".",
"reject",
"(",
"&",
":nil?",
")",
"end"
] | Extract variables from a string on the form
KEY1=VALUE1 KEY2="VALUE2"
Optional quoting around the value is allowed | [
"Extract",
"variables",
"from",
"a",
"string",
"on",
"the",
"form",
"KEY1",
"=",
"VALUE1",
"KEY2",
"=",
"VALUE2",
"Optional",
"quoting",
"around",
"the",
"value",
"is",
"allowed"
] | fe71115690c8cef69979cea0dca8176eba304ab1 | https://github.com/orta/travish/blob/fe71115690c8cef69979cea0dca8176eba304ab1/lib/environment_parser.rb#L66-L73 | train |
poise/poise-profiler | lib/poise_profiler/base.rb | PoiseProfiler.Base._monkey_patch_old_chef! | def _monkey_patch_old_chef!
require 'chef/event_dispatch/dispatcher'
instance = self
orig_method = Chef::EventDispatch::Dispatcher.instance_method(:library_file_loaded)
Chef::EventDispatch::Dispatcher.send(:define_method, :library_file_loaded) do |filename|
instance.events = self
instance.monkey_patched = false
@subscribers |= [instance]
Chef::EventDispatch::Dispatcher.send(:define_method, :library_file_loaded, orig_method)
orig_method.bind(self).call(filename)
end
end | ruby | def _monkey_patch_old_chef!
require 'chef/event_dispatch/dispatcher'
instance = self
orig_method = Chef::EventDispatch::Dispatcher.instance_method(:library_file_loaded)
Chef::EventDispatch::Dispatcher.send(:define_method, :library_file_loaded) do |filename|
instance.events = self
instance.monkey_patched = false
@subscribers |= [instance]
Chef::EventDispatch::Dispatcher.send(:define_method, :library_file_loaded, orig_method)
orig_method.bind(self).call(filename)
end
end | [
"def",
"_monkey_patch_old_chef!",
"require",
"'chef/event_dispatch/dispatcher'",
"instance",
"=",
"self",
"orig_method",
"=",
"Chef",
"::",
"EventDispatch",
"::",
"Dispatcher",
".",
"instance_method",
"(",
":library_file_loaded",
")",
"Chef",
"::",
"EventDispatch",
"::",
"Dispatcher",
".",
"send",
"(",
":define_method",
",",
":library_file_loaded",
")",
"do",
"|",
"filename",
"|",
"instance",
".",
"events",
"=",
"self",
"instance",
".",
"monkey_patched",
"=",
"false",
"@subscribers",
"|=",
"[",
"instance",
"]",
"Chef",
"::",
"EventDispatch",
"::",
"Dispatcher",
".",
"send",
"(",
":define_method",
",",
":library_file_loaded",
",",
"orig_method",
")",
"orig_method",
".",
"bind",
"(",
"self",
")",
".",
"call",
"(",
"filename",
")",
"end",
"end"
] | Inject this instance for Chef < 12.3. Don't call this on newer Chef.
@api private
@see Base.install
@return [void] | [
"Inject",
"this",
"instance",
"for",
"Chef",
"<",
"12",
".",
"3",
".",
"Don",
"t",
"call",
"this",
"on",
"newer",
"Chef",
"."
] | a190acc6bdd4fcdac34ef43bbe4f59dddb9c0f67 | https://github.com/poise/poise-profiler/blob/a190acc6bdd4fcdac34ef43bbe4f59dddb9c0f67/lib/poise_profiler/base.rb#L76-L87 | train |
botanicus/rango | lib/rango/controller.rb | Rango.Controller.rescue_http_error | def rescue_http_error(exception)
# we need to call it before we assign the variables
body = self.render_http_error(exception)
[exception.status, exception.headers, body]
end | ruby | def rescue_http_error(exception)
# we need to call it before we assign the variables
body = self.render_http_error(exception)
[exception.status, exception.headers, body]
end | [
"def",
"rescue_http_error",
"(",
"exception",
")",
"body",
"=",
"self",
".",
"render_http_error",
"(",
"exception",
")",
"[",
"exception",
".",
"status",
",",
"exception",
".",
"headers",
",",
"body",
"]",
"end"
] | redefine this method for your controller if you want to provide custom error pages
returns response array for rack
if you need to change just body of error message, define render_http_error method
@api plugin | [
"redefine",
"this",
"method",
"for",
"your",
"controller",
"if",
"you",
"want",
"to",
"provide",
"custom",
"error",
"pages",
"returns",
"response",
"array",
"for",
"rack",
"if",
"you",
"need",
"to",
"change",
"just",
"body",
"of",
"error",
"message",
"define",
"render_http_error",
"method"
] | b8904453f3b7d3cd65e2bcc5236bfe645aa78e8e | https://github.com/botanicus/rango/blob/b8904453f3b7d3cd65e2bcc5236bfe645aa78e8e/lib/rango/controller.rb#L139-L143 | train |
mezis/tsuga | lib/tsuga/service/clusterer.rb | Tsuga::Service.Clusterer._build_clusters | def _build_clusters(tile)
used_ids = []
clusters = []
_adapter.in_tile(*tile.children).find_each do |child|
cluster = _adapter.build_from(tile.depth, child)
clusters << cluster
used_ids << child.id
end
return [used_ids, clusters]
end | ruby | def _build_clusters(tile)
used_ids = []
clusters = []
_adapter.in_tile(*tile.children).find_each do |child|
cluster = _adapter.build_from(tile.depth, child)
clusters << cluster
used_ids << child.id
end
return [used_ids, clusters]
end | [
"def",
"_build_clusters",
"(",
"tile",
")",
"used_ids",
"=",
"[",
"]",
"clusters",
"=",
"[",
"]",
"_adapter",
".",
"in_tile",
"(",
"*",
"tile",
".",
"children",
")",
".",
"find_each",
"do",
"|",
"child",
"|",
"cluster",
"=",
"_adapter",
".",
"build_from",
"(",
"tile",
".",
"depth",
",",
"child",
")",
"clusters",
"<<",
"cluster",
"used_ids",
"<<",
"child",
".",
"id",
"end",
"return",
"[",
"used_ids",
",",
"clusters",
"]",
"end"
] | return the record IDs used | [
"return",
"the",
"record",
"IDs",
"used"
] | 418a1dac7af068fb388883c47f39eb52113af096 | https://github.com/mezis/tsuga/blob/418a1dac7af068fb388883c47f39eb52113af096/lib/tsuga/service/clusterer.rb#L245-L256 | train |
bdurand/acts_as_revisionable | lib/acts_as_revisionable.rb | ActsAsRevisionable.ClassMethods.restore_revision | def restore_revision(id, revision_number)
revision_record = revision(id, revision_number)
return revision_record.restore if revision_record
end | ruby | def restore_revision(id, revision_number)
revision_record = revision(id, revision_number)
return revision_record.restore if revision_record
end | [
"def",
"restore_revision",
"(",
"id",
",",
"revision_number",
")",
"revision_record",
"=",
"revision",
"(",
"id",
",",
"revision_number",
")",
"return",
"revision_record",
".",
"restore",
"if",
"revision_record",
"end"
] | Load a revision for a record with a particular id. Associations added since the revision
was created will still be in the restored record.
If you want to save a revision with associations properly, use restore_revision! | [
"Load",
"a",
"revision",
"for",
"a",
"record",
"with",
"a",
"particular",
"id",
".",
"Associations",
"added",
"since",
"the",
"revision",
"was",
"created",
"will",
"still",
"be",
"in",
"the",
"restored",
"record",
".",
"If",
"you",
"want",
"to",
"save",
"a",
"revision",
"with",
"associations",
"properly",
"use",
"restore_revision!"
] | cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc | https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable.rb#L84-L87 | train |
bdurand/acts_as_revisionable | lib/acts_as_revisionable.rb | ActsAsRevisionable.ClassMethods.restore_revision! | def restore_revision!(id, revision_number)
record = restore_revision(id, revision_number)
if record
record.store_revision do
save_restorable_associations(record, revisionable_associations)
end
end
return record
end | ruby | def restore_revision!(id, revision_number)
record = restore_revision(id, revision_number)
if record
record.store_revision do
save_restorable_associations(record, revisionable_associations)
end
end
return record
end | [
"def",
"restore_revision!",
"(",
"id",
",",
"revision_number",
")",
"record",
"=",
"restore_revision",
"(",
"id",
",",
"revision_number",
")",
"if",
"record",
"record",
".",
"store_revision",
"do",
"save_restorable_associations",
"(",
"record",
",",
"revisionable_associations",
")",
"end",
"end",
"return",
"record",
"end"
] | Load a revision for a record with a particular id and save it to the database. You should
always use this method to save a revision if it has associations. | [
"Load",
"a",
"revision",
"for",
"a",
"record",
"with",
"a",
"particular",
"id",
"and",
"save",
"it",
"to",
"the",
"database",
".",
"You",
"should",
"always",
"use",
"this",
"method",
"to",
"save",
"a",
"revision",
"if",
"it",
"has",
"associations",
"."
] | cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc | https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable.rb#L91-L99 | train |
bdurand/acts_as_revisionable | lib/acts_as_revisionable.rb | ActsAsRevisionable.ClassMethods.restore_last_revision! | def restore_last_revision!(id)
record = restore_last_revision(id)
if record
record.store_revision do
save_restorable_associations(record, revisionable_associations)
end
end
return record
end | ruby | def restore_last_revision!(id)
record = restore_last_revision(id)
if record
record.store_revision do
save_restorable_associations(record, revisionable_associations)
end
end
return record
end | [
"def",
"restore_last_revision!",
"(",
"id",
")",
"record",
"=",
"restore_last_revision",
"(",
"id",
")",
"if",
"record",
"record",
".",
"store_revision",
"do",
"save_restorable_associations",
"(",
"record",
",",
"revisionable_associations",
")",
"end",
"end",
"return",
"record",
"end"
] | Load the last revision for a record with the specified id and save it to the database. You should
always use this method to save a revision if it has associations. | [
"Load",
"the",
"last",
"revision",
"for",
"a",
"record",
"with",
"the",
"specified",
"id",
"and",
"save",
"it",
"to",
"the",
"database",
".",
"You",
"should",
"always",
"use",
"this",
"method",
"to",
"save",
"a",
"revision",
"if",
"it",
"has",
"associations",
"."
] | cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc | https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable.rb#L111-L119 | train |
bdurand/acts_as_revisionable | lib/acts_as_revisionable.rb | ActsAsRevisionable.ClassMethods.revisionable_associations | def revisionable_associations(options = acts_as_revisionable_options[:associations])
return nil unless options
options = [options] unless options.kind_of?(Array)
associations = {}
options.each do |association|
if association.kind_of?(Symbol)
associations[association] = true
elsif association.kind_of?(Hash)
association.each_pair do |key, value|
associations[key] = revisionable_associations(value)
end
end
end
return associations
end | ruby | def revisionable_associations(options = acts_as_revisionable_options[:associations])
return nil unless options
options = [options] unless options.kind_of?(Array)
associations = {}
options.each do |association|
if association.kind_of?(Symbol)
associations[association] = true
elsif association.kind_of?(Hash)
association.each_pair do |key, value|
associations[key] = revisionable_associations(value)
end
end
end
return associations
end | [
"def",
"revisionable_associations",
"(",
"options",
"=",
"acts_as_revisionable_options",
"[",
":associations",
"]",
")",
"return",
"nil",
"unless",
"options",
"options",
"=",
"[",
"options",
"]",
"unless",
"options",
".",
"kind_of?",
"(",
"Array",
")",
"associations",
"=",
"{",
"}",
"options",
".",
"each",
"do",
"|",
"association",
"|",
"if",
"association",
".",
"kind_of?",
"(",
"Symbol",
")",
"associations",
"[",
"association",
"]",
"=",
"true",
"elsif",
"association",
".",
"kind_of?",
"(",
"Hash",
")",
"association",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"associations",
"[",
"key",
"]",
"=",
"revisionable_associations",
"(",
"value",
")",
"end",
"end",
"end",
"return",
"associations",
"end"
] | Returns a hash structure used to identify the revisioned associations. | [
"Returns",
"a",
"hash",
"structure",
"used",
"to",
"identify",
"the",
"revisioned",
"associations",
"."
] | cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc | https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable.rb#L122-L136 | train |
bdurand/acts_as_revisionable | lib/acts_as_revisionable.rb | ActsAsRevisionable.InstanceMethods.store_revision | def store_revision
if new_record? || @revisions_disabled
return yield
else
retval = nil
revision = nil
begin
revision_record_class.transaction do
begin
read_only = self.class.first(:conditions => {self.class.primary_key => self.id}, :readonly => true)
if read_only
revision = read_only.create_revision!
truncate_revisions!
end
rescue => e
logger.warn(e) if logger
end
disable_revisioning do
retval = yield
end
raise ActiveRecord::Rollback unless errors.empty?
revision.trash! if destroyed?
end
rescue => e
# In case the database doesn't support transactions
if revision
begin
revision.destroy
rescue => e
logger.warn(e) if logger
end
end
raise e
end
return retval
end
end | ruby | def store_revision
if new_record? || @revisions_disabled
return yield
else
retval = nil
revision = nil
begin
revision_record_class.transaction do
begin
read_only = self.class.first(:conditions => {self.class.primary_key => self.id}, :readonly => true)
if read_only
revision = read_only.create_revision!
truncate_revisions!
end
rescue => e
logger.warn(e) if logger
end
disable_revisioning do
retval = yield
end
raise ActiveRecord::Rollback unless errors.empty?
revision.trash! if destroyed?
end
rescue => e
# In case the database doesn't support transactions
if revision
begin
revision.destroy
rescue => e
logger.warn(e) if logger
end
end
raise e
end
return retval
end
end | [
"def",
"store_revision",
"if",
"new_record?",
"||",
"@revisions_disabled",
"return",
"yield",
"else",
"retval",
"=",
"nil",
"revision",
"=",
"nil",
"begin",
"revision_record_class",
".",
"transaction",
"do",
"begin",
"read_only",
"=",
"self",
".",
"class",
".",
"first",
"(",
":conditions",
"=>",
"{",
"self",
".",
"class",
".",
"primary_key",
"=>",
"self",
".",
"id",
"}",
",",
":readonly",
"=>",
"true",
")",
"if",
"read_only",
"revision",
"=",
"read_only",
".",
"create_revision!",
"truncate_revisions!",
"end",
"rescue",
"=>",
"e",
"logger",
".",
"warn",
"(",
"e",
")",
"if",
"logger",
"end",
"disable_revisioning",
"do",
"retval",
"=",
"yield",
"end",
"raise",
"ActiveRecord",
"::",
"Rollback",
"unless",
"errors",
".",
"empty?",
"revision",
".",
"trash!",
"if",
"destroyed?",
"end",
"rescue",
"=>",
"e",
"if",
"revision",
"begin",
"revision",
".",
"destroy",
"rescue",
"=>",
"e",
"logger",
".",
"warn",
"(",
"e",
")",
"if",
"logger",
"end",
"end",
"raise",
"e",
"end",
"return",
"retval",
"end",
"end"
] | Call this method to implement revisioning. The object changes should happen inside the block. | [
"Call",
"this",
"method",
"to",
"implement",
"revisioning",
".",
"The",
"object",
"changes",
"should",
"happen",
"inside",
"the",
"block",
"."
] | cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc | https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable.rb#L205-L244 | train |
bdurand/acts_as_revisionable | lib/acts_as_revisionable.rb | ActsAsRevisionable.InstanceMethods.create_revision! | def create_revision!
revision_options = self.class.acts_as_revisionable_options
revision = revision_record_class.new(self, revision_options[:encoding])
if revision_options[:meta].is_a?(Hash)
revision_options[:meta].each do |attribute, value|
set_revision_meta_attribute(revision, attribute, value)
end
elsif revision_options[:meta].is_a?(Array)
revision_options[:meta].each do |attribute|
set_revision_meta_attribute(revision, attribute, attribute.to_sym)
end
elsif revision_options[:meta]
set_revision_meta_attribute(revision, revision_options[:meta], revision_options[:meta].to_sym)
end
revision.save!
return revision
end | ruby | def create_revision!
revision_options = self.class.acts_as_revisionable_options
revision = revision_record_class.new(self, revision_options[:encoding])
if revision_options[:meta].is_a?(Hash)
revision_options[:meta].each do |attribute, value|
set_revision_meta_attribute(revision, attribute, value)
end
elsif revision_options[:meta].is_a?(Array)
revision_options[:meta].each do |attribute|
set_revision_meta_attribute(revision, attribute, attribute.to_sym)
end
elsif revision_options[:meta]
set_revision_meta_attribute(revision, revision_options[:meta], revision_options[:meta].to_sym)
end
revision.save!
return revision
end | [
"def",
"create_revision!",
"revision_options",
"=",
"self",
".",
"class",
".",
"acts_as_revisionable_options",
"revision",
"=",
"revision_record_class",
".",
"new",
"(",
"self",
",",
"revision_options",
"[",
":encoding",
"]",
")",
"if",
"revision_options",
"[",
":meta",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"revision_options",
"[",
":meta",
"]",
".",
"each",
"do",
"|",
"attribute",
",",
"value",
"|",
"set_revision_meta_attribute",
"(",
"revision",
",",
"attribute",
",",
"value",
")",
"end",
"elsif",
"revision_options",
"[",
":meta",
"]",
".",
"is_a?",
"(",
"Array",
")",
"revision_options",
"[",
":meta",
"]",
".",
"each",
"do",
"|",
"attribute",
"|",
"set_revision_meta_attribute",
"(",
"revision",
",",
"attribute",
",",
"attribute",
".",
"to_sym",
")",
"end",
"elsif",
"revision_options",
"[",
":meta",
"]",
"set_revision_meta_attribute",
"(",
"revision",
",",
"revision_options",
"[",
":meta",
"]",
",",
"revision_options",
"[",
":meta",
"]",
".",
"to_sym",
")",
"end",
"revision",
".",
"save!",
"return",
"revision",
"end"
] | Create a revision record based on this record and save it to the database. | [
"Create",
"a",
"revision",
"record",
"based",
"on",
"this",
"record",
"and",
"save",
"it",
"to",
"the",
"database",
"."
] | cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc | https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable.rb#L247-L263 | train |
bdurand/acts_as_revisionable | lib/acts_as_revisionable.rb | ActsAsRevisionable.InstanceMethods.set_revision_meta_attribute | def set_revision_meta_attribute(revision, attribute, value)
case value
when Symbol
value = self.send(value)
when Proc
value = value.call(self)
end
revision.send("#{attribute}=", value)
end | ruby | def set_revision_meta_attribute(revision, attribute, value)
case value
when Symbol
value = self.send(value)
when Proc
value = value.call(self)
end
revision.send("#{attribute}=", value)
end | [
"def",
"set_revision_meta_attribute",
"(",
"revision",
",",
"attribute",
",",
"value",
")",
"case",
"value",
"when",
"Symbol",
"value",
"=",
"self",
".",
"send",
"(",
"value",
")",
"when",
"Proc",
"value",
"=",
"value",
".",
"call",
"(",
"self",
")",
"end",
"revision",
".",
"send",
"(",
"\"#{attribute}=\"",
",",
"value",
")",
"end"
] | Set an attribute based on a meta argument | [
"Set",
"an",
"attribute",
"based",
"on",
"a",
"meta",
"argument"
] | cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc | https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable.rb#L305-L313 | train |
ShipCompliant/ship_compliant-ruby | lib/ship_compliant/base_result.rb | ShipCompliant.BaseResult.errors | def errors
return [] if success?
@errors ||= Array.wrap(response[:errors]).map do |error|
ErrorResult.new(error[:error])
end
end | ruby | def errors
return [] if success?
@errors ||= Array.wrap(response[:errors]).map do |error|
ErrorResult.new(error[:error])
end
end | [
"def",
"errors",
"return",
"[",
"]",
"if",
"success?",
"@errors",
"||=",
"Array",
".",
"wrap",
"(",
"response",
"[",
":errors",
"]",
")",
".",
"map",
"do",
"|",
"error",
"|",
"ErrorResult",
".",
"new",
"(",
"error",
"[",
":error",
"]",
")",
"end",
"end"
] | An array of +ErrorResult+ items or an empty array if the response was
successful.
result.errors.each do |error|
puts "#{error.message} [#error.key]"
end | [
"An",
"array",
"of",
"+",
"ErrorResult",
"+",
"items",
"or",
"an",
"empty",
"array",
"if",
"the",
"response",
"was",
"successful",
"."
] | aa12852a58cd6cb7939eb9fbb7fdc03e46e18197 | https://github.com/ShipCompliant/ship_compliant-ruby/blob/aa12852a58cd6cb7939eb9fbb7fdc03e46e18197/lib/ship_compliant/base_result.rb#L29-L34 | train |
brasten/scruffy | lib/scruffy/graph.rb | Scruffy.Graph.render | def render(options = {})
options[:theme] ||= theme
options[:value_formatter] ||= value_formatter
options[:key_formatter] ||= key_formatter
options[:point_markers] ||= point_markers
options[:point_markers_rotation] ||= point_markers_rotation
options[:point_markers_ticks] ||= point_markers_ticks
options[:size] ||= (options[:width] ? [options[:width], (options.delete(:width) * 0.6).to_i] : [600, 360])
options[:title] ||= title
options[:x_legend] ||= x_legend
options[:y_legend] ||= y_legend
options[:layers] ||= layers
options[:min_value] ||= bottom_value(options[:padding] ? options[:padding] : nil)
options[:max_value] ||= top_value(options[:padding] ? options[:padding] : nil)
options[:min_key] ||= bottom_key
options[:max_key] ||= top_key
options[:graph] ||= self
# Removed for now.
# Added for making smaller fonts more legible, but may not be needed after all.
#
# if options[:as] && (options[:size][0] <= 300 || options[:size][1] <= 200)
# options[:actual_size] = options[:size]
# options[:size] = [800, (800.to_f * (options[:actual_size][1].to_f / options[:actual_size][0].to_f))]
# end
svg = ( options[:renderer].nil? ? self.renderer.render( options ) : options[:renderer].render( options ) )
# SVG to file.
if options[:to] && options[:as].nil?
File.open(options[:to], 'w') { |file|
file.write(svg)
}
end
options[:as] ? rasterizer.rasterize(svg, options) : svg
end | ruby | def render(options = {})
options[:theme] ||= theme
options[:value_formatter] ||= value_formatter
options[:key_formatter] ||= key_formatter
options[:point_markers] ||= point_markers
options[:point_markers_rotation] ||= point_markers_rotation
options[:point_markers_ticks] ||= point_markers_ticks
options[:size] ||= (options[:width] ? [options[:width], (options.delete(:width) * 0.6).to_i] : [600, 360])
options[:title] ||= title
options[:x_legend] ||= x_legend
options[:y_legend] ||= y_legend
options[:layers] ||= layers
options[:min_value] ||= bottom_value(options[:padding] ? options[:padding] : nil)
options[:max_value] ||= top_value(options[:padding] ? options[:padding] : nil)
options[:min_key] ||= bottom_key
options[:max_key] ||= top_key
options[:graph] ||= self
# Removed for now.
# Added for making smaller fonts more legible, but may not be needed after all.
#
# if options[:as] && (options[:size][0] <= 300 || options[:size][1] <= 200)
# options[:actual_size] = options[:size]
# options[:size] = [800, (800.to_f * (options[:actual_size][1].to_f / options[:actual_size][0].to_f))]
# end
svg = ( options[:renderer].nil? ? self.renderer.render( options ) : options[:renderer].render( options ) )
# SVG to file.
if options[:to] && options[:as].nil?
File.open(options[:to], 'w') { |file|
file.write(svg)
}
end
options[:as] ? rasterizer.rasterize(svg, options) : svg
end | [
"def",
"render",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":theme",
"]",
"||=",
"theme",
"options",
"[",
":value_formatter",
"]",
"||=",
"value_formatter",
"options",
"[",
":key_formatter",
"]",
"||=",
"key_formatter",
"options",
"[",
":point_markers",
"]",
"||=",
"point_markers",
"options",
"[",
":point_markers_rotation",
"]",
"||=",
"point_markers_rotation",
"options",
"[",
":point_markers_ticks",
"]",
"||=",
"point_markers_ticks",
"options",
"[",
":size",
"]",
"||=",
"(",
"options",
"[",
":width",
"]",
"?",
"[",
"options",
"[",
":width",
"]",
",",
"(",
"options",
".",
"delete",
"(",
":width",
")",
"*",
"0.6",
")",
".",
"to_i",
"]",
":",
"[",
"600",
",",
"360",
"]",
")",
"options",
"[",
":title",
"]",
"||=",
"title",
"options",
"[",
":x_legend",
"]",
"||=",
"x_legend",
"options",
"[",
":y_legend",
"]",
"||=",
"y_legend",
"options",
"[",
":layers",
"]",
"||=",
"layers",
"options",
"[",
":min_value",
"]",
"||=",
"bottom_value",
"(",
"options",
"[",
":padding",
"]",
"?",
"options",
"[",
":padding",
"]",
":",
"nil",
")",
"options",
"[",
":max_value",
"]",
"||=",
"top_value",
"(",
"options",
"[",
":padding",
"]",
"?",
"options",
"[",
":padding",
"]",
":",
"nil",
")",
"options",
"[",
":min_key",
"]",
"||=",
"bottom_key",
"options",
"[",
":max_key",
"]",
"||=",
"top_key",
"options",
"[",
":graph",
"]",
"||=",
"self",
"svg",
"=",
"(",
"options",
"[",
":renderer",
"]",
".",
"nil?",
"?",
"self",
".",
"renderer",
".",
"render",
"(",
"options",
")",
":",
"options",
"[",
":renderer",
"]",
".",
"render",
"(",
"options",
")",
")",
"if",
"options",
"[",
":to",
"]",
"&&",
"options",
"[",
":as",
"]",
".",
"nil?",
"File",
".",
"open",
"(",
"options",
"[",
":to",
"]",
",",
"'w'",
")",
"{",
"|",
"file",
"|",
"file",
".",
"write",
"(",
"svg",
")",
"}",
"end",
"options",
"[",
":as",
"]",
"?",
"rasterizer",
".",
"rasterize",
"(",
"svg",
",",
"options",
")",
":",
"svg",
"end"
] | Writer defined below
Returns a new Graph. You can optionally pass in a default graph type and an options hash.
Graph.new # New graph
Graph.new(:line) # New graph with default graph type of Line
Graph.new({...}) # New graph with options.
Options:
title:: Graph's title
x_legend :: Title for X Axis
y_legend :: Title for Y Axis
theme:: A theme object to use when rendering graph
layers:: An array of Layers for this graph to use
default_type:: A symbol indicating the default type of Layer for this graph
value_formatter:: Sets a formatter used to modify marker values prior to rendering
point_markers:: Sets the x-axis marker values
point_markers_rotation:: Sets the angle of rotation for x-axis marker values
point_markers_ticks:: Sets a small tick mark above each marker value. Helful when used with rotation.
rasterizer:: Sets the rasterizer to use when rendering to an image format. Defaults to RMagick.
Renders the graph in it's current state to an SVG object.
Options:
size:: An array indicating the size you wish to render the graph. ( [x, y] )
width:: The width of the rendered graph. A height is calculated at 3/4th of the width.
theme:: Theme used to render graph for this render only.
min_value:: Overrides the calculated minimum value used for the graph.
max_value:: Overrides the calculated maximum value used for the graph.
renderer:: Provide a Renderer object to use instead of the default.
For other image formats:
as:: File format to render to ('PNG', 'JPG', etc)
to:: Name of file to save graph to, if desired. If not provided, image is returned as blob/string. | [
"Writer",
"defined",
"below",
"Returns",
"a",
"new",
"Graph",
".",
"You",
"can",
"optionally",
"pass",
"in",
"a",
"default",
"graph",
"type",
"and",
"an",
"options",
"hash",
"."
] | 4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e | https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/graph.rb#L145-L181 | train |
brasten/scruffy | lib/scruffy/layers/stacked.rb | Scruffy::Layers.Stacked.render | def render(svg, options = {})
#TODO ensure this works with new points
current_points = points
layers.each do |layer|
real_points = layer.points
layer.points = current_points
layer_options = options.dup
layer_options[:color] = layer.preferred_color || layer.color || options[:theme].next_color
layer.render(svg, layer_options)
options.merge(layer_options)
layer.points = real_points
layer.points.each_with_index { |val, idx| current_points[idx] -= val }
end
end | ruby | def render(svg, options = {})
#TODO ensure this works with new points
current_points = points
layers.each do |layer|
real_points = layer.points
layer.points = current_points
layer_options = options.dup
layer_options[:color] = layer.preferred_color || layer.color || options[:theme].next_color
layer.render(svg, layer_options)
options.merge(layer_options)
layer.points = real_points
layer.points.each_with_index { |val, idx| current_points[idx] -= val }
end
end | [
"def",
"render",
"(",
"svg",
",",
"options",
"=",
"{",
"}",
")",
"current_points",
"=",
"points",
"layers",
".",
"each",
"do",
"|",
"layer",
"|",
"real_points",
"=",
"layer",
".",
"points",
"layer",
".",
"points",
"=",
"current_points",
"layer_options",
"=",
"options",
".",
"dup",
"layer_options",
"[",
":color",
"]",
"=",
"layer",
".",
"preferred_color",
"||",
"layer",
".",
"color",
"||",
"options",
"[",
":theme",
"]",
".",
"next_color",
"layer",
".",
"render",
"(",
"svg",
",",
"layer_options",
")",
"options",
".",
"merge",
"(",
"layer_options",
")",
"layer",
".",
"points",
"=",
"real_points",
"layer",
".",
"points",
".",
"each_with_index",
"{",
"|",
"val",
",",
"idx",
"|",
"current_points",
"[",
"idx",
"]",
"-=",
"val",
"}",
"end",
"end"
] | Returns new Stacked graph.
You can provide a block for easily adding layers during (just after) initialization.
Example:
Stacked.new do |stacked|
stacked << Scruffy::Layers::Line.new( ... )
stacked.add(:bar, 'My Bar', [...])
end
The initialize method passes itself to the block, and since stacked is a LayerContainer,
layers can be added just as if they were being added to Graph.
Overrides Base#render to fiddle with layers' points to achieve a stacked effect. | [
"Returns",
"new",
"Stacked",
"graph",
"."
] | 4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e | https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/stacked.rb#L32-L47 | train |
brasten/scruffy | lib/scruffy/layers/stacked.rb | Scruffy::Layers.Stacked.legend_data | def legend_data
if relevant_data?
retval = []
layers.each do |layer|
retval << layer.legend_data
end
retval
else
nil
end
end | ruby | def legend_data
if relevant_data?
retval = []
layers.each do |layer|
retval << layer.legend_data
end
retval
else
nil
end
end | [
"def",
"legend_data",
"if",
"relevant_data?",
"retval",
"=",
"[",
"]",
"layers",
".",
"each",
"do",
"|",
"layer",
"|",
"retval",
"<<",
"layer",
".",
"legend_data",
"end",
"retval",
"else",
"nil",
"end",
"end"
] | A stacked graph has many data sets. Return legend information for all of them. | [
"A",
"stacked",
"graph",
"has",
"many",
"data",
"sets",
".",
"Return",
"legend",
"information",
"for",
"all",
"of",
"them",
"."
] | 4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e | https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/stacked.rb#L50-L60 | train |
brasten/scruffy | lib/scruffy/renderers/base.rb | Scruffy::Renderers.Base.render | def render(options = {})
options[:graph_id] ||= 'scruffy_graph'
options[:complexity] ||= (global_complexity || :normal)
# Allow subclasses to muck with components prior to renders.
rendertime_renderer = self.clone
rendertime_renderer.instance_eval { before_render if respond_to?(:before_render) }
svg = Builder::XmlMarkup.new(:indent => 2)
unless options[:no_doctype_header]
svg.instruct!
svg.declare! :DOCTYPE, :svg, :PUBLIC, "-//W3C//DTD SVG 1.0//EN", "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"
end
svg.svg(:xmlns => "http://www.w3.org/2000/svg", 'xmlns:xlink' => "http://www.w3.org/1999/xlink", :width => options[:size].first, :height => options[:size].last) {
svg.g(:id => options[:graph_id]) {
rendertime_renderer.components.each do |component|
component.render(svg,
bounds_for( options[:size], component.position, component.size ),
options)
end
}
}
svg.target!
end | ruby | def render(options = {})
options[:graph_id] ||= 'scruffy_graph'
options[:complexity] ||= (global_complexity || :normal)
# Allow subclasses to muck with components prior to renders.
rendertime_renderer = self.clone
rendertime_renderer.instance_eval { before_render if respond_to?(:before_render) }
svg = Builder::XmlMarkup.new(:indent => 2)
unless options[:no_doctype_header]
svg.instruct!
svg.declare! :DOCTYPE, :svg, :PUBLIC, "-//W3C//DTD SVG 1.0//EN", "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"
end
svg.svg(:xmlns => "http://www.w3.org/2000/svg", 'xmlns:xlink' => "http://www.w3.org/1999/xlink", :width => options[:size].first, :height => options[:size].last) {
svg.g(:id => options[:graph_id]) {
rendertime_renderer.components.each do |component|
component.render(svg,
bounds_for( options[:size], component.position, component.size ),
options)
end
}
}
svg.target!
end | [
"def",
"render",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":graph_id",
"]",
"||=",
"'scruffy_graph'",
"options",
"[",
":complexity",
"]",
"||=",
"(",
"global_complexity",
"||",
":normal",
")",
"rendertime_renderer",
"=",
"self",
".",
"clone",
"rendertime_renderer",
".",
"instance_eval",
"{",
"before_render",
"if",
"respond_to?",
"(",
":before_render",
")",
"}",
"svg",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"(",
":indent",
"=>",
"2",
")",
"unless",
"options",
"[",
":no_doctype_header",
"]",
"svg",
".",
"instruct!",
"svg",
".",
"declare!",
":DOCTYPE",
",",
":svg",
",",
":PUBLIC",
",",
"\"-//W3C//DTD SVG 1.0//EN\"",
",",
"\"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\"",
"end",
"svg",
".",
"svg",
"(",
":xmlns",
"=>",
"\"http://www.w3.org/2000/svg\"",
",",
"'xmlns:xlink'",
"=>",
"\"http://www.w3.org/1999/xlink\"",
",",
":width",
"=>",
"options",
"[",
":size",
"]",
".",
"first",
",",
":height",
"=>",
"options",
"[",
":size",
"]",
".",
"last",
")",
"{",
"svg",
".",
"g",
"(",
":id",
"=>",
"options",
"[",
":graph_id",
"]",
")",
"{",
"rendertime_renderer",
".",
"components",
".",
"each",
"do",
"|",
"component",
"|",
"component",
".",
"render",
"(",
"svg",
",",
"bounds_for",
"(",
"options",
"[",
":size",
"]",
",",
"component",
".",
"position",
",",
"component",
".",
"size",
")",
",",
"options",
")",
"end",
"}",
"}",
"svg",
".",
"target!",
"end"
] | Renders the graph and all components. | [
"Renders",
"the",
"graph",
"and",
"all",
"components",
"."
] | 4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e | https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/renderers/base.rb#L24-L47 | train |
rossf7/elasticrawl | lib/elasticrawl/parse_job.rb | Elasticrawl.ParseJob.set_segments | def set_segments(crawl_segments, max_files = nil)
self.job_name = set_job_name
self.job_desc = set_job_desc(crawl_segments, max_files)
self.max_files = max_files
crawl_segments.each do |segment|
self.job_steps.push(create_job_step(segment))
end
end | ruby | def set_segments(crawl_segments, max_files = nil)
self.job_name = set_job_name
self.job_desc = set_job_desc(crawl_segments, max_files)
self.max_files = max_files
crawl_segments.each do |segment|
self.job_steps.push(create_job_step(segment))
end
end | [
"def",
"set_segments",
"(",
"crawl_segments",
",",
"max_files",
"=",
"nil",
")",
"self",
".",
"job_name",
"=",
"set_job_name",
"self",
".",
"job_desc",
"=",
"set_job_desc",
"(",
"crawl_segments",
",",
"max_files",
")",
"self",
".",
"max_files",
"=",
"max_files",
"crawl_segments",
".",
"each",
"do",
"|",
"segment",
"|",
"self",
".",
"job_steps",
".",
"push",
"(",
"create_job_step",
"(",
"segment",
")",
")",
"end",
"end"
] | Populates the job from the list of segments to be parsed. | [
"Populates",
"the",
"job",
"from",
"the",
"list",
"of",
"segments",
"to",
"be",
"parsed",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/parse_job.rb#L8-L16 | train |
rossf7/elasticrawl | lib/elasticrawl/parse_job.rb | Elasticrawl.ParseJob.run | def run
emr_config = job_config['emr_config']
job_flow_id = run_job_flow(emr_config)
if job_flow_id.present?
self.job_flow_id = job_flow_id
self.job_steps.each do |step|
segment = step.crawl_segment
segment.parse_time = DateTime.now
segment.save
end
self.save
self.result_message
end
end | ruby | def run
emr_config = job_config['emr_config']
job_flow_id = run_job_flow(emr_config)
if job_flow_id.present?
self.job_flow_id = job_flow_id
self.job_steps.each do |step|
segment = step.crawl_segment
segment.parse_time = DateTime.now
segment.save
end
self.save
self.result_message
end
end | [
"def",
"run",
"emr_config",
"=",
"job_config",
"[",
"'emr_config'",
"]",
"job_flow_id",
"=",
"run_job_flow",
"(",
"emr_config",
")",
"if",
"job_flow_id",
".",
"present?",
"self",
".",
"job_flow_id",
"=",
"job_flow_id",
"self",
".",
"job_steps",
".",
"each",
"do",
"|",
"step",
"|",
"segment",
"=",
"step",
".",
"crawl_segment",
"segment",
".",
"parse_time",
"=",
"DateTime",
".",
"now",
"segment",
".",
"save",
"end",
"self",
".",
"save",
"self",
".",
"result_message",
"end",
"end"
] | Runs the job by calling Elastic MapReduce API. If successful the
parse time is set for each segment. | [
"Runs",
"the",
"job",
"by",
"calling",
"Elastic",
"MapReduce",
"API",
".",
"If",
"successful",
"the",
"parse",
"time",
"is",
"set",
"for",
"each",
"segment",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/parse_job.rb#L20-L36 | train |
rossf7/elasticrawl | lib/elasticrawl/parse_job.rb | Elasticrawl.ParseJob.segment_list | def segment_list
segments = ['Segments']
job_steps.each do |job_step|
if job_step.crawl_segment.present?
segment = job_step.crawl_segment
segments.push(segment.segment_desc)
end
end
segments.push('')
end | ruby | def segment_list
segments = ['Segments']
job_steps.each do |job_step|
if job_step.crawl_segment.present?
segment = job_step.crawl_segment
segments.push(segment.segment_desc)
end
end
segments.push('')
end | [
"def",
"segment_list",
"segments",
"=",
"[",
"'Segments'",
"]",
"job_steps",
".",
"each",
"do",
"|",
"job_step",
"|",
"if",
"job_step",
".",
"crawl_segment",
".",
"present?",
"segment",
"=",
"job_step",
".",
"crawl_segment",
"segments",
".",
"push",
"(",
"segment",
".",
"segment_desc",
")",
"end",
"end",
"segments",
".",
"push",
"(",
"''",
")",
"end"
] | Return list of segment descriptions. | [
"Return",
"list",
"of",
"segment",
"descriptions",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/parse_job.rb#L45-L56 | train |
rossf7/elasticrawl | lib/elasticrawl/parse_job.rb | Elasticrawl.ParseJob.set_job_desc | def set_job_desc(segments, max_files)
if segments.count > 0
crawl_name = segments[0].crawl.crawl_name if segments[0].crawl.present?
file_desc = max_files.nil? ? 'all files' : "#{max_files} files per segment"
end
"Crawl: #{crawl_name} Segments: #{segments.count} Parsing: #{file_desc}"
end | ruby | def set_job_desc(segments, max_files)
if segments.count > 0
crawl_name = segments[0].crawl.crawl_name if segments[0].crawl.present?
file_desc = max_files.nil? ? 'all files' : "#{max_files} files per segment"
end
"Crawl: #{crawl_name} Segments: #{segments.count} Parsing: #{file_desc}"
end | [
"def",
"set_job_desc",
"(",
"segments",
",",
"max_files",
")",
"if",
"segments",
".",
"count",
">",
"0",
"crawl_name",
"=",
"segments",
"[",
"0",
"]",
".",
"crawl",
".",
"crawl_name",
"if",
"segments",
"[",
"0",
"]",
".",
"crawl",
".",
"present?",
"file_desc",
"=",
"max_files",
".",
"nil?",
"?",
"'all files'",
":",
"\"#{max_files} files per segment\"",
"end",
"\"Crawl: #{crawl_name} Segments: #{segments.count} Parsing: #{file_desc}\"",
"end"
] | Sets the job description which forms part of the Elastic MapReduce
job flow name. | [
"Sets",
"the",
"job",
"description",
"which",
"forms",
"part",
"of",
"the",
"Elastic",
"MapReduce",
"job",
"flow",
"name",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/parse_job.rb#L83-L90 | train |
58bits/partial-date | lib/partial-date/date.rb | PartialDate.Date.old_to_s | def old_to_s(format = :default)
format = FORMATS[format] if format.is_a?(Symbol)
result = format.dup
FORMAT_METHODS.each_pair do |key, value|
result.gsub!( key, value.call( self )) if result.include? key
end
# Remove any leading "/-," chars.
# Remove double white spaces.
# Remove any duplicate "/-," chars and replace with the single char.
# Remove any trailing "/-," chars.
# Anything else - you're on your own ;-)
lead_trim = (year != 0 && format.lstrip.start_with?("%Y")) ? /\A[\/\,\s]+/ : /\A[\/\,\-\s]+/
result = result.gsub(lead_trim, '').gsub(/\s\s/, ' ').gsub(/[\/\-\,]([\/\-\,])/, '\1').gsub(/[\/\,\-\s]+\z/, '')
end | ruby | def old_to_s(format = :default)
format = FORMATS[format] if format.is_a?(Symbol)
result = format.dup
FORMAT_METHODS.each_pair do |key, value|
result.gsub!( key, value.call( self )) if result.include? key
end
# Remove any leading "/-," chars.
# Remove double white spaces.
# Remove any duplicate "/-," chars and replace with the single char.
# Remove any trailing "/-," chars.
# Anything else - you're on your own ;-)
lead_trim = (year != 0 && format.lstrip.start_with?("%Y")) ? /\A[\/\,\s]+/ : /\A[\/\,\-\s]+/
result = result.gsub(lead_trim, '').gsub(/\s\s/, ' ').gsub(/[\/\-\,]([\/\-\,])/, '\1').gsub(/[\/\,\-\s]+\z/, '')
end | [
"def",
"old_to_s",
"(",
"format",
"=",
":default",
")",
"format",
"=",
"FORMATS",
"[",
"format",
"]",
"if",
"format",
".",
"is_a?",
"(",
"Symbol",
")",
"result",
"=",
"format",
".",
"dup",
"FORMAT_METHODS",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"result",
".",
"gsub!",
"(",
"key",
",",
"value",
".",
"call",
"(",
"self",
")",
")",
"if",
"result",
".",
"include?",
"key",
"end",
"lead_trim",
"=",
"(",
"year",
"!=",
"0",
"&&",
"format",
".",
"lstrip",
".",
"start_with?",
"(",
"\"%Y\"",
")",
")",
"?",
"/",
"\\A",
"\\/",
"\\,",
"\\s",
"/",
":",
"/",
"\\A",
"\\/",
"\\,",
"\\-",
"\\s",
"/",
"result",
"=",
"result",
".",
"gsub",
"(",
"lead_trim",
",",
"''",
")",
".",
"gsub",
"(",
"/",
"\\s",
"\\s",
"/",
",",
"' '",
")",
".",
"gsub",
"(",
"/",
"\\/",
"\\-",
"\\,",
"\\/",
"\\-",
"\\,",
"/",
",",
"'\\1'",
")",
".",
"gsub",
"(",
"/",
"\\/",
"\\,",
"\\-",
"\\s",
"\\z",
"/",
",",
"''",
")",
"end"
] | Here for the moment for benchmark comparisons | [
"Here",
"for",
"the",
"moment",
"for",
"benchmark",
"comparisons"
] | 1760d33bda3da42bb8c3f67fb63dd6bc5dc70bea | https://github.com/58bits/partial-date/blob/1760d33bda3da42bb8c3f67fb63dd6bc5dc70bea/lib/partial-date/date.rb#L316-L331 | train |
brasten/scruffy | lib/scruffy/layers/line.rb | Scruffy::Layers.Line.draw | def draw(svg, coords, options={})
# Include options provided when the object was created
options.merge!(@options)
stroke_width = (options[:relativestroke]) ? relative(options[:stroke_width]) : options[:stroke_width]
style = (options[:style]) ? options[:style] : ''
if options[:shadow]
svg.g(:class => 'shadow', :transform => "translate(#{relative(0.5)}, #{relative(0.5)})") {
svg.polyline( :points => stringify_coords(coords).join(' '), :fill => 'transparent',
:stroke => 'black', 'stroke-width' => stroke_width,
:style => 'fill-opacity: 0; stroke-opacity: 0.35' )
if options[:dots]
coords.each { |coord| svg.circle( :cx => coord.first, :cy => coord.last + relative(0.9), :r => stroke_width,
:style => "stroke-width: #{stroke_width}; stroke: black; opacity: 0.35;" ) }
end
}
end
svg.polyline( :points => stringify_coords(coords).join(' '), :fill => 'none', :stroke => @color.to_s,
'stroke-width' => stroke_width, :style => style )
if options[:dots]
coords.each { |coord| svg.circle( :cx => coord.first, :cy => coord.last, :r => stroke_width,
:style => "stroke-width: #{stroke_width}; stroke: #{color.to_s}; fill: #{color.to_s}" ) }
end
end | ruby | def draw(svg, coords, options={})
# Include options provided when the object was created
options.merge!(@options)
stroke_width = (options[:relativestroke]) ? relative(options[:stroke_width]) : options[:stroke_width]
style = (options[:style]) ? options[:style] : ''
if options[:shadow]
svg.g(:class => 'shadow', :transform => "translate(#{relative(0.5)}, #{relative(0.5)})") {
svg.polyline( :points => stringify_coords(coords).join(' '), :fill => 'transparent',
:stroke => 'black', 'stroke-width' => stroke_width,
:style => 'fill-opacity: 0; stroke-opacity: 0.35' )
if options[:dots]
coords.each { |coord| svg.circle( :cx => coord.first, :cy => coord.last + relative(0.9), :r => stroke_width,
:style => "stroke-width: #{stroke_width}; stroke: black; opacity: 0.35;" ) }
end
}
end
svg.polyline( :points => stringify_coords(coords).join(' '), :fill => 'none', :stroke => @color.to_s,
'stroke-width' => stroke_width, :style => style )
if options[:dots]
coords.each { |coord| svg.circle( :cx => coord.first, :cy => coord.last, :r => stroke_width,
:style => "stroke-width: #{stroke_width}; stroke: #{color.to_s}; fill: #{color.to_s}" ) }
end
end | [
"def",
"draw",
"(",
"svg",
",",
"coords",
",",
"options",
"=",
"{",
"}",
")",
"options",
".",
"merge!",
"(",
"@options",
")",
"stroke_width",
"=",
"(",
"options",
"[",
":relativestroke",
"]",
")",
"?",
"relative",
"(",
"options",
"[",
":stroke_width",
"]",
")",
":",
"options",
"[",
":stroke_width",
"]",
"style",
"=",
"(",
"options",
"[",
":style",
"]",
")",
"?",
"options",
"[",
":style",
"]",
":",
"''",
"if",
"options",
"[",
":shadow",
"]",
"svg",
".",
"g",
"(",
":class",
"=>",
"'shadow'",
",",
":transform",
"=>",
"\"translate(#{relative(0.5)}, #{relative(0.5)})\"",
")",
"{",
"svg",
".",
"polyline",
"(",
":points",
"=>",
"stringify_coords",
"(",
"coords",
")",
".",
"join",
"(",
"' '",
")",
",",
":fill",
"=>",
"'transparent'",
",",
":stroke",
"=>",
"'black'",
",",
"'stroke-width'",
"=>",
"stroke_width",
",",
":style",
"=>",
"'fill-opacity: 0; stroke-opacity: 0.35'",
")",
"if",
"options",
"[",
":dots",
"]",
"coords",
".",
"each",
"{",
"|",
"coord",
"|",
"svg",
".",
"circle",
"(",
":cx",
"=>",
"coord",
".",
"first",
",",
":cy",
"=>",
"coord",
".",
"last",
"+",
"relative",
"(",
"0.9",
")",
",",
":r",
"=>",
"stroke_width",
",",
":style",
"=>",
"\"stroke-width: #{stroke_width}; stroke: black; opacity: 0.35;\"",
")",
"}",
"end",
"}",
"end",
"svg",
".",
"polyline",
"(",
":points",
"=>",
"stringify_coords",
"(",
"coords",
")",
".",
"join",
"(",
"' '",
")",
",",
":fill",
"=>",
"'none'",
",",
":stroke",
"=>",
"@color",
".",
"to_s",
",",
"'stroke-width'",
"=>",
"stroke_width",
",",
":style",
"=>",
"style",
")",
"if",
"options",
"[",
":dots",
"]",
"coords",
".",
"each",
"{",
"|",
"coord",
"|",
"svg",
".",
"circle",
"(",
":cx",
"=>",
"coord",
".",
"first",
",",
":cy",
"=>",
"coord",
".",
"last",
",",
":r",
"=>",
"stroke_width",
",",
":style",
"=>",
"\"stroke-width: #{stroke_width}; stroke: #{color.to_s}; fill: #{color.to_s}\"",
")",
"}",
"end",
"end"
] | Renders line graph.
Options:
See initialize() | [
"Renders",
"line",
"graph",
"."
] | 4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e | https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/line.rb#L14-L44 | train |
rossf7/elasticrawl | lib/elasticrawl/crawl.rb | Elasticrawl.Crawl.status | def status
total = self.crawl_segments.count
remaining = CrawlSegment.where(:crawl_id => self.id,
:parse_time => nil).count
parsed = total - remaining
status = self.crawl_name
status += " Segments: to parse #{remaining}, "
status += "parsed #{parsed}, total #{total}"
end | ruby | def status
total = self.crawl_segments.count
remaining = CrawlSegment.where(:crawl_id => self.id,
:parse_time => nil).count
parsed = total - remaining
status = self.crawl_name
status += " Segments: to parse #{remaining}, "
status += "parsed #{parsed}, total #{total}"
end | [
"def",
"status",
"total",
"=",
"self",
".",
"crawl_segments",
".",
"count",
"remaining",
"=",
"CrawlSegment",
".",
"where",
"(",
":crawl_id",
"=>",
"self",
".",
"id",
",",
":parse_time",
"=>",
"nil",
")",
".",
"count",
"parsed",
"=",
"total",
"-",
"remaining",
"status",
"=",
"self",
".",
"crawl_name",
"status",
"+=",
"\" Segments: to parse #{remaining}, \"",
"status",
"+=",
"\"parsed #{parsed}, total #{total}\"",
"end"
] | Returns the status of the current crawl. | [
"Returns",
"the",
"status",
"of",
"the",
"current",
"crawl",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/crawl.rb#L28-L36 | train |
rossf7/elasticrawl | lib/elasticrawl/crawl.rb | Elasticrawl.Crawl.create_segments | def create_segments
file_paths = warc_paths(self.crawl_name)
segments = parse_segments(file_paths)
save if segments.count > 0
segments.keys.each do |segment_name|
file_count = segments[segment_name]
CrawlSegment.create_segment(self, segment_name, file_count)
end
segments.count
end | ruby | def create_segments
file_paths = warc_paths(self.crawl_name)
segments = parse_segments(file_paths)
save if segments.count > 0
segments.keys.each do |segment_name|
file_count = segments[segment_name]
CrawlSegment.create_segment(self, segment_name, file_count)
end
segments.count
end | [
"def",
"create_segments",
"file_paths",
"=",
"warc_paths",
"(",
"self",
".",
"crawl_name",
")",
"segments",
"=",
"parse_segments",
"(",
"file_paths",
")",
"save",
"if",
"segments",
".",
"count",
">",
"0",
"segments",
".",
"keys",
".",
"each",
"do",
"|",
"segment_name",
"|",
"file_count",
"=",
"segments",
"[",
"segment_name",
"]",
"CrawlSegment",
".",
"create_segment",
"(",
"self",
",",
"segment_name",
",",
"file_count",
")",
"end",
"segments",
".",
"count",
"end"
] | Creates crawl segments from the warc.paths file for this crawl. | [
"Creates",
"crawl",
"segments",
"from",
"the",
"warc",
".",
"paths",
"file",
"for",
"this",
"crawl",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/crawl.rb#L50-L62 | train |
rossf7/elasticrawl | lib/elasticrawl/crawl.rb | Elasticrawl.Crawl.reset | def reset
segments = CrawlSegment.where('crawl_id = ? and parse_time is not null',
self.id)
segments.map { |segment| segment.update_attribute(:parse_time, nil) }
status
end | ruby | def reset
segments = CrawlSegment.where('crawl_id = ? and parse_time is not null',
self.id)
segments.map { |segment| segment.update_attribute(:parse_time, nil) }
status
end | [
"def",
"reset",
"segments",
"=",
"CrawlSegment",
".",
"where",
"(",
"'crawl_id = ? and parse_time is not null'",
",",
"self",
".",
"id",
")",
"segments",
".",
"map",
"{",
"|",
"segment",
"|",
"segment",
".",
"update_attribute",
"(",
":parse_time",
",",
"nil",
")",
"}",
"status",
"end"
] | Resets parse time of all parsed segments to null so they will be parsed
again. Returns the updated crawl status. | [
"Resets",
"parse",
"time",
"of",
"all",
"parsed",
"segments",
"to",
"null",
"so",
"they",
"will",
"be",
"parsed",
"again",
".",
"Returns",
"the",
"updated",
"crawl",
"status",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/crawl.rb#L80-L86 | train |
rossf7/elasticrawl | lib/elasticrawl/crawl.rb | Elasticrawl.Crawl.warc_paths | def warc_paths(crawl_name)
s3_path = [Elasticrawl::COMMON_CRAWL_PATH,
crawl_name,
Elasticrawl::WARC_PATHS].join('/')
begin
s3 = AWS::S3.new
bucket = s3.buckets[Elasticrawl::COMMON_CRAWL_BUCKET]
object = bucket.objects[s3_path]
uncompress_file(object)
rescue AWS::Errors::Base => s3e
raise S3AccessError.new(s3e.http_response), 'Failed to get WARC paths'
rescue Exception => e
raise S3AccessError, 'Failed to get WARC paths'
end
end | ruby | def warc_paths(crawl_name)
s3_path = [Elasticrawl::COMMON_CRAWL_PATH,
crawl_name,
Elasticrawl::WARC_PATHS].join('/')
begin
s3 = AWS::S3.new
bucket = s3.buckets[Elasticrawl::COMMON_CRAWL_BUCKET]
object = bucket.objects[s3_path]
uncompress_file(object)
rescue AWS::Errors::Base => s3e
raise S3AccessError.new(s3e.http_response), 'Failed to get WARC paths'
rescue Exception => e
raise S3AccessError, 'Failed to get WARC paths'
end
end | [
"def",
"warc_paths",
"(",
"crawl_name",
")",
"s3_path",
"=",
"[",
"Elasticrawl",
"::",
"COMMON_CRAWL_PATH",
",",
"crawl_name",
",",
"Elasticrawl",
"::",
"WARC_PATHS",
"]",
".",
"join",
"(",
"'/'",
")",
"begin",
"s3",
"=",
"AWS",
"::",
"S3",
".",
"new",
"bucket",
"=",
"s3",
".",
"buckets",
"[",
"Elasticrawl",
"::",
"COMMON_CRAWL_BUCKET",
"]",
"object",
"=",
"bucket",
".",
"objects",
"[",
"s3_path",
"]",
"uncompress_file",
"(",
"object",
")",
"rescue",
"AWS",
"::",
"Errors",
"::",
"Base",
"=>",
"s3e",
"raise",
"S3AccessError",
".",
"new",
"(",
"s3e",
".",
"http_response",
")",
",",
"'Failed to get WARC paths'",
"rescue",
"Exception",
"=>",
"e",
"raise",
"S3AccessError",
",",
"'Failed to get WARC paths'",
"end",
"end"
] | Gets the WARC file paths from S3 for this crawl if it exists. | [
"Gets",
"the",
"WARC",
"file",
"paths",
"from",
"S3",
"for",
"this",
"crawl",
"if",
"it",
"exists",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/crawl.rb#L90-L106 | train |
rossf7/elasticrawl | lib/elasticrawl/crawl.rb | Elasticrawl.Crawl.uncompress_file | def uncompress_file(s3_object)
result = ''
if s3_object.exists?
io = StringIO.new
io.write(s3_object.read)
io.rewind
gz = Zlib::GzipReader.new(io)
result = gz.read
gz.close
end
result
end | ruby | def uncompress_file(s3_object)
result = ''
if s3_object.exists?
io = StringIO.new
io.write(s3_object.read)
io.rewind
gz = Zlib::GzipReader.new(io)
result = gz.read
gz.close
end
result
end | [
"def",
"uncompress_file",
"(",
"s3_object",
")",
"result",
"=",
"''",
"if",
"s3_object",
".",
"exists?",
"io",
"=",
"StringIO",
".",
"new",
"io",
".",
"write",
"(",
"s3_object",
".",
"read",
")",
"io",
".",
"rewind",
"gz",
"=",
"Zlib",
"::",
"GzipReader",
".",
"new",
"(",
"io",
")",
"result",
"=",
"gz",
".",
"read",
"gz",
".",
"close",
"end",
"result",
"end"
] | Takes in a S3 object and returns the contents as an uncompressed string. | [
"Takes",
"in",
"a",
"S3",
"object",
"and",
"returns",
"the",
"contents",
"as",
"an",
"uncompressed",
"string",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/crawl.rb#L109-L124 | train |
rossf7/elasticrawl | lib/elasticrawl/crawl.rb | Elasticrawl.Crawl.parse_segments | def parse_segments(warc_paths)
segments = Hash.new 0
warc_paths.split.each do |warc_path|
segment_name = warc_path.split('/')[3]
segments[segment_name] += 1 if segment_name.present?
end
segments
end | ruby | def parse_segments(warc_paths)
segments = Hash.new 0
warc_paths.split.each do |warc_path|
segment_name = warc_path.split('/')[3]
segments[segment_name] += 1 if segment_name.present?
end
segments
end | [
"def",
"parse_segments",
"(",
"warc_paths",
")",
"segments",
"=",
"Hash",
".",
"new",
"0",
"warc_paths",
".",
"split",
".",
"each",
"do",
"|",
"warc_path",
"|",
"segment_name",
"=",
"warc_path",
".",
"split",
"(",
"'/'",
")",
"[",
"3",
"]",
"segments",
"[",
"segment_name",
"]",
"+=",
"1",
"if",
"segment_name",
".",
"present?",
"end",
"segments",
"end"
] | Parses the segment names and file counts from the WARC file paths. | [
"Parses",
"the",
"segment",
"names",
"and",
"file",
"counts",
"from",
"the",
"WARC",
"file",
"paths",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/crawl.rb#L127-L136 | train |
brasten/scruffy | lib/scruffy/layers/multi_area.rb | Scruffy::Layers.MultiArea.draw | def draw(svg, coords, options={})
# Check whether to use color from theme, or whether to use user defined colors from the area_colors array
color_count = nil
if @area_colors && @area_colors.size > 0
area_color = @area_colors[0]
color_count = 1
else
puts "Never Set Area Color"
area_color = color
end
# Draw Bottom Level Polygons (Original Coords)
draw_poly(svg, coords, area_color, options = {})
# Draw Lower Area Polygons
if @baselines
# Get the Color of this Area
puts "Drawing Baselines"
@baselines.sort! {|x,y| y <=> x }
@baselines.each do |baseline|
if color_count
area_color = area_colors[color_count]
color_count = color_count + 1
puts area_color.to_s
if color_count >= area_colors.size
color_count = 0
end
end
lower_poly_coords = create_lower_polygon_coords(translate_number(baseline), coords, options)
draw_poly(svg, lower_poly_coords, area_color, options = {})
end
end
end | ruby | def draw(svg, coords, options={})
# Check whether to use color from theme, or whether to use user defined colors from the area_colors array
color_count = nil
if @area_colors && @area_colors.size > 0
area_color = @area_colors[0]
color_count = 1
else
puts "Never Set Area Color"
area_color = color
end
# Draw Bottom Level Polygons (Original Coords)
draw_poly(svg, coords, area_color, options = {})
# Draw Lower Area Polygons
if @baselines
# Get the Color of this Area
puts "Drawing Baselines"
@baselines.sort! {|x,y| y <=> x }
@baselines.each do |baseline|
if color_count
area_color = area_colors[color_count]
color_count = color_count + 1
puts area_color.to_s
if color_count >= area_colors.size
color_count = 0
end
end
lower_poly_coords = create_lower_polygon_coords(translate_number(baseline), coords, options)
draw_poly(svg, lower_poly_coords, area_color, options = {})
end
end
end | [
"def",
"draw",
"(",
"svg",
",",
"coords",
",",
"options",
"=",
"{",
"}",
")",
"color_count",
"=",
"nil",
"if",
"@area_colors",
"&&",
"@area_colors",
".",
"size",
">",
"0",
"area_color",
"=",
"@area_colors",
"[",
"0",
"]",
"color_count",
"=",
"1",
"else",
"puts",
"\"Never Set Area Color\"",
"area_color",
"=",
"color",
"end",
"draw_poly",
"(",
"svg",
",",
"coords",
",",
"area_color",
",",
"options",
"=",
"{",
"}",
")",
"if",
"@baselines",
"puts",
"\"Drawing Baselines\"",
"@baselines",
".",
"sort!",
"{",
"|",
"x",
",",
"y",
"|",
"y",
"<=>",
"x",
"}",
"@baselines",
".",
"each",
"do",
"|",
"baseline",
"|",
"if",
"color_count",
"area_color",
"=",
"area_colors",
"[",
"color_count",
"]",
"color_count",
"=",
"color_count",
"+",
"1",
"puts",
"area_color",
".",
"to_s",
"if",
"color_count",
">=",
"area_colors",
".",
"size",
"color_count",
"=",
"0",
"end",
"end",
"lower_poly_coords",
"=",
"create_lower_polygon_coords",
"(",
"translate_number",
"(",
"baseline",
")",
",",
"coords",
",",
"options",
")",
"draw_poly",
"(",
"svg",
",",
"lower_poly_coords",
",",
"area_color",
",",
"options",
"=",
"{",
"}",
")",
"end",
"end",
"end"
] | Render Multi Area graph. | [
"Render",
"Multi",
"Area",
"graph",
"."
] | 4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e | https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/multi_area.rb#L21-L54 | train |
rrrene/sparkr | lib/sparkr/sparkline.rb | Sparkr.Sparkline.normalize_numbers | def normalize_numbers(_numbers)
numbers = _numbers.map(&:to_i)
min = numbers.min
numbers.map do |n|
n - min
end
end | ruby | def normalize_numbers(_numbers)
numbers = _numbers.map(&:to_i)
min = numbers.min
numbers.map do |n|
n - min
end
end | [
"def",
"normalize_numbers",
"(",
"_numbers",
")",
"numbers",
"=",
"_numbers",
".",
"map",
"(",
"&",
":to_i",
")",
"min",
"=",
"numbers",
".",
"min",
"numbers",
".",
"map",
"do",
"|",
"n",
"|",
"n",
"-",
"min",
"end",
"end"
] | Returns the normalized equivalent of a given list
normalize_numbers([3, 4, 7])
# => [0, 1, 4]
@return [Fixnum] the normalized equivalent of the given +_numbers+ | [
"Returns",
"the",
"normalized",
"equivalent",
"of",
"a",
"given",
"list"
] | 2329d965ae421dfbc4743dd728884f2da501a107 | https://github.com/rrrene/sparkr/blob/2329d965ae421dfbc4743dd728884f2da501a107/lib/sparkr/sparkline.rb#L62-L68 | train |
opentox/lazar | lib/nanoparticle.rb | OpenTox.Nanoparticle.parse_ambit_value | def parse_ambit_value feature, v, dataset
# TODO add study id to warnings
v.delete "unit"
# TODO: ppm instead of weights
if v.keys == ["textValue"]
add_feature feature, v["textValue"], dataset
elsif v.keys == ["loValue"]
add_feature feature, v["loValue"], dataset
elsif v.keys.size == 2 and v["errorValue"]
add_feature feature, v["loValue"], dataset
#warn "Ignoring errorValue '#{v["errorValue"]}' for '#{feature.name}'."
elsif v.keys.size == 2 and v["loQualifier"] == "mean"
add_feature feature, v["loValue"], dataset
#warn "'#{feature.name}' is a mean value. Original data is not available."
elsif v.keys.size == 2 and v["loQualifier"] #== ">="
#warn "Only min value available for '#{feature.name}', entry ignored"
elsif v.keys.size == 2 and v["upQualifier"] #== ">="
#warn "Only max value available for '#{feature.name}', entry ignored"
elsif v.keys.size == 3 and v["loValue"] and v["loQualifier"].nil? and v["upQualifier"].nil?
add_feature feature, v["loValue"], dataset
#warn "loQualifier and upQualifier are empty."
elsif v.keys.size == 3 and v["loValue"] and v["loQualifier"] == "" and v["upQualifier"] == ""
add_feature feature, v["loValue"], dataset
#warn "loQualifier and upQualifier are empty."
elsif v.keys.size == 4 and v["loValue"] and v["loQualifier"].nil? and v["upQualifier"].nil?
add_feature feature, v["loValue"], dataset
#warn "loQualifier and upQualifier are empty."
elsif v.size == 4 and v["loQualifier"] and v["upQualifier"] and v["loValue"] and v["upValue"]
#add_feature feature, [v["loValue"],v["upValue"]].mean, dataset
#warn "Using mean value of range #{v["loValue"]} - #{v["upValue"]} for '#{feature.name}'. Original data is not available."
elsif v.size == 4 and v["loQualifier"] == "mean" and v["errorValue"]
#warn "'#{feature.name}' is a mean value. Original data is not available. Ignoring errorValue '#{v["errorValue"]}' for '#{feature.name}'."
add_feature feature, v["loValue"], dataset
elsif v == {} # do nothing
else
warn "Cannot parse Ambit eNanoMapper value '#{v}' for feature '#{feature.name}'."
end
end | ruby | def parse_ambit_value feature, v, dataset
# TODO add study id to warnings
v.delete "unit"
# TODO: ppm instead of weights
if v.keys == ["textValue"]
add_feature feature, v["textValue"], dataset
elsif v.keys == ["loValue"]
add_feature feature, v["loValue"], dataset
elsif v.keys.size == 2 and v["errorValue"]
add_feature feature, v["loValue"], dataset
#warn "Ignoring errorValue '#{v["errorValue"]}' for '#{feature.name}'."
elsif v.keys.size == 2 and v["loQualifier"] == "mean"
add_feature feature, v["loValue"], dataset
#warn "'#{feature.name}' is a mean value. Original data is not available."
elsif v.keys.size == 2 and v["loQualifier"] #== ">="
#warn "Only min value available for '#{feature.name}', entry ignored"
elsif v.keys.size == 2 and v["upQualifier"] #== ">="
#warn "Only max value available for '#{feature.name}', entry ignored"
elsif v.keys.size == 3 and v["loValue"] and v["loQualifier"].nil? and v["upQualifier"].nil?
add_feature feature, v["loValue"], dataset
#warn "loQualifier and upQualifier are empty."
elsif v.keys.size == 3 and v["loValue"] and v["loQualifier"] == "" and v["upQualifier"] == ""
add_feature feature, v["loValue"], dataset
#warn "loQualifier and upQualifier are empty."
elsif v.keys.size == 4 and v["loValue"] and v["loQualifier"].nil? and v["upQualifier"].nil?
add_feature feature, v["loValue"], dataset
#warn "loQualifier and upQualifier are empty."
elsif v.size == 4 and v["loQualifier"] and v["upQualifier"] and v["loValue"] and v["upValue"]
#add_feature feature, [v["loValue"],v["upValue"]].mean, dataset
#warn "Using mean value of range #{v["loValue"]} - #{v["upValue"]} for '#{feature.name}'. Original data is not available."
elsif v.size == 4 and v["loQualifier"] == "mean" and v["errorValue"]
#warn "'#{feature.name}' is a mean value. Original data is not available. Ignoring errorValue '#{v["errorValue"]}' for '#{feature.name}'."
add_feature feature, v["loValue"], dataset
elsif v == {} # do nothing
else
warn "Cannot parse Ambit eNanoMapper value '#{v}' for feature '#{feature.name}'."
end
end | [
"def",
"parse_ambit_value",
"feature",
",",
"v",
",",
"dataset",
"v",
".",
"delete",
"\"unit\"",
"if",
"v",
".",
"keys",
"==",
"[",
"\"textValue\"",
"]",
"add_feature",
"feature",
",",
"v",
"[",
"\"textValue\"",
"]",
",",
"dataset",
"elsif",
"v",
".",
"keys",
"==",
"[",
"\"loValue\"",
"]",
"add_feature",
"feature",
",",
"v",
"[",
"\"loValue\"",
"]",
",",
"dataset",
"elsif",
"v",
".",
"keys",
".",
"size",
"==",
"2",
"and",
"v",
"[",
"\"errorValue\"",
"]",
"add_feature",
"feature",
",",
"v",
"[",
"\"loValue\"",
"]",
",",
"dataset",
"elsif",
"v",
".",
"keys",
".",
"size",
"==",
"2",
"and",
"v",
"[",
"\"loQualifier\"",
"]",
"==",
"\"mean\"",
"add_feature",
"feature",
",",
"v",
"[",
"\"loValue\"",
"]",
",",
"dataset",
"elsif",
"v",
".",
"keys",
".",
"size",
"==",
"2",
"and",
"v",
"[",
"\"loQualifier\"",
"]",
"elsif",
"v",
".",
"keys",
".",
"size",
"==",
"2",
"and",
"v",
"[",
"\"upQualifier\"",
"]",
"elsif",
"v",
".",
"keys",
".",
"size",
"==",
"3",
"and",
"v",
"[",
"\"loValue\"",
"]",
"and",
"v",
"[",
"\"loQualifier\"",
"]",
".",
"nil?",
"and",
"v",
"[",
"\"upQualifier\"",
"]",
".",
"nil?",
"add_feature",
"feature",
",",
"v",
"[",
"\"loValue\"",
"]",
",",
"dataset",
"elsif",
"v",
".",
"keys",
".",
"size",
"==",
"3",
"and",
"v",
"[",
"\"loValue\"",
"]",
"and",
"v",
"[",
"\"loQualifier\"",
"]",
"==",
"\"\"",
"and",
"v",
"[",
"\"upQualifier\"",
"]",
"==",
"\"\"",
"add_feature",
"feature",
",",
"v",
"[",
"\"loValue\"",
"]",
",",
"dataset",
"elsif",
"v",
".",
"keys",
".",
"size",
"==",
"4",
"and",
"v",
"[",
"\"loValue\"",
"]",
"and",
"v",
"[",
"\"loQualifier\"",
"]",
".",
"nil?",
"and",
"v",
"[",
"\"upQualifier\"",
"]",
".",
"nil?",
"add_feature",
"feature",
",",
"v",
"[",
"\"loValue\"",
"]",
",",
"dataset",
"elsif",
"v",
".",
"size",
"==",
"4",
"and",
"v",
"[",
"\"loQualifier\"",
"]",
"and",
"v",
"[",
"\"upQualifier\"",
"]",
"and",
"v",
"[",
"\"loValue\"",
"]",
"and",
"v",
"[",
"\"upValue\"",
"]",
"elsif",
"v",
".",
"size",
"==",
"4",
"and",
"v",
"[",
"\"loQualifier\"",
"]",
"==",
"\"mean\"",
"and",
"v",
"[",
"\"errorValue\"",
"]",
"add_feature",
"feature",
",",
"v",
"[",
"\"loValue\"",
"]",
",",
"dataset",
"elsif",
"v",
"==",
"{",
"}",
"else",
"warn",
"\"Cannot parse Ambit eNanoMapper value '#{v}' for feature '#{feature.name}'.\"",
"end",
"end"
] | Parse values from Ambit database
@param [OpenTox::Feature]
@param [TrueClass,FalseClass,Float]
@param [OpenTox::Dataset] | [
"Parse",
"values",
"from",
"Ambit",
"database"
] | 1ee7de09c969e16fd11522d22179224e694b0161 | https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/nanoparticle.rb#L77-L114 | train |
opentox/lazar | lib/dataset.rb | OpenTox.Dataset.substances | def substances
@substances ||= data_entries.keys.collect{|id| OpenTox::Substance.find id}.uniq
@substances
end | ruby | def substances
@substances ||= data_entries.keys.collect{|id| OpenTox::Substance.find id}.uniq
@substances
end | [
"def",
"substances",
"@substances",
"||=",
"data_entries",
".",
"keys",
".",
"collect",
"{",
"|",
"id",
"|",
"OpenTox",
"::",
"Substance",
".",
"find",
"id",
"}",
".",
"uniq",
"@substances",
"end"
] | Get all substances
@return [Array<OpenTox::Substance>] | [
"Get",
"all",
"substances"
] | 1ee7de09c969e16fd11522d22179224e694b0161 | https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/dataset.rb#L27-L30 | train |
opentox/lazar | lib/dataset.rb | OpenTox.Dataset.features | def features
@features ||= data_entries.collect{|sid,data| data.keys.collect{|id| OpenTox::Feature.find(id)}}.flatten.uniq
@features
end | ruby | def features
@features ||= data_entries.collect{|sid,data| data.keys.collect{|id| OpenTox::Feature.find(id)}}.flatten.uniq
@features
end | [
"def",
"features",
"@features",
"||=",
"data_entries",
".",
"collect",
"{",
"|",
"sid",
",",
"data",
"|",
"data",
".",
"keys",
".",
"collect",
"{",
"|",
"id",
"|",
"OpenTox",
"::",
"Feature",
".",
"find",
"(",
"id",
")",
"}",
"}",
".",
"flatten",
".",
"uniq",
"@features",
"end"
] | Get all features
@return [Array<OpenTox::Feature>] | [
"Get",
"all",
"features"
] | 1ee7de09c969e16fd11522d22179224e694b0161 | https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/dataset.rb#L34-L37 | train |
opentox/lazar | lib/dataset.rb | OpenTox.Dataset.values | def values substance,feature
substance = substance.id if substance.is_a? Substance
feature = feature.id if feature.is_a? Feature
if data_entries[substance.to_s] and data_entries[substance.to_s][feature.to_s]
data_entries[substance.to_s][feature.to_s]
else
[nil]
end
end | ruby | def values substance,feature
substance = substance.id if substance.is_a? Substance
feature = feature.id if feature.is_a? Feature
if data_entries[substance.to_s] and data_entries[substance.to_s][feature.to_s]
data_entries[substance.to_s][feature.to_s]
else
[nil]
end
end | [
"def",
"values",
"substance",
",",
"feature",
"substance",
"=",
"substance",
".",
"id",
"if",
"substance",
".",
"is_a?",
"Substance",
"feature",
"=",
"feature",
".",
"id",
"if",
"feature",
".",
"is_a?",
"Feature",
"if",
"data_entries",
"[",
"substance",
".",
"to_s",
"]",
"and",
"data_entries",
"[",
"substance",
".",
"to_s",
"]",
"[",
"feature",
".",
"to_s",
"]",
"data_entries",
"[",
"substance",
".",
"to_s",
"]",
"[",
"feature",
".",
"to_s",
"]",
"else",
"[",
"nil",
"]",
"end",
"end"
] | Get all values for a given substance and feature
@param [OpenTox::Substance,BSON::ObjectId,String] substance or substance id
@param [OpenTox::Feature,BSON::ObjectId,String] feature or feature id
@return [TrueClass,FalseClass,Float] | [
"Get",
"all",
"values",
"for",
"a",
"given",
"substance",
"and",
"feature"
] | 1ee7de09c969e16fd11522d22179224e694b0161 | https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/dataset.rb#L43-L51 | train |
opentox/lazar | lib/dataset.rb | OpenTox.Dataset.add | def add(substance,feature,value)
substance = substance.id if substance.is_a? Substance
feature = feature.id if feature.is_a? Feature
data_entries[substance.to_s] ||= {}
data_entries[substance.to_s][feature.to_s] ||= []
data_entries[substance.to_s][feature.to_s] << value
#data_entries[substance.to_s][feature.to_s].uniq! if value.numeric? # assuming that identical values come from the same source
end | ruby | def add(substance,feature,value)
substance = substance.id if substance.is_a? Substance
feature = feature.id if feature.is_a? Feature
data_entries[substance.to_s] ||= {}
data_entries[substance.to_s][feature.to_s] ||= []
data_entries[substance.to_s][feature.to_s] << value
#data_entries[substance.to_s][feature.to_s].uniq! if value.numeric? # assuming that identical values come from the same source
end | [
"def",
"add",
"(",
"substance",
",",
"feature",
",",
"value",
")",
"substance",
"=",
"substance",
".",
"id",
"if",
"substance",
".",
"is_a?",
"Substance",
"feature",
"=",
"feature",
".",
"id",
"if",
"feature",
".",
"is_a?",
"Feature",
"data_entries",
"[",
"substance",
".",
"to_s",
"]",
"||=",
"{",
"}",
"data_entries",
"[",
"substance",
".",
"to_s",
"]",
"[",
"feature",
".",
"to_s",
"]",
"||=",
"[",
"]",
"data_entries",
"[",
"substance",
".",
"to_s",
"]",
"[",
"feature",
".",
"to_s",
"]",
"<<",
"value",
"end"
] | Writers
Add a value for a given substance and feature
@param [OpenTox::Substance,BSON::ObjectId,String] substance or substance id
@param [OpenTox::Feature,BSON::ObjectId,String] feature or feature id
@param [TrueClass,FalseClass,Float] | [
"Writers",
"Add",
"a",
"value",
"for",
"a",
"given",
"substance",
"and",
"feature"
] | 1ee7de09c969e16fd11522d22179224e694b0161 | https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/dataset.rb#L59-L66 | train |
opentox/lazar | lib/dataset.rb | OpenTox.Dataset.folds | def folds n
len = self.substances.size
indices = (0..len-1).to_a.shuffle
mid = (len/n)
chunks = []
start = 0
1.upto(n) do |i|
last = start+mid
last = last-1 unless len%n >= i
test_idxs = indices[start..last] || []
test_substances = test_idxs.collect{|i| substances[i]}
training_idxs = indices-test_idxs
training_substances = training_idxs.collect{|i| substances[i]}
chunk = [training_substances,test_substances].collect do |substances|
dataset = self.class.create(:name => "#{self.name} (Fold #{i-1})",:source => self.id )
substances.each do |substance|
substance.dataset_ids << dataset.id
substance.dataset_ids.uniq!
substance.save
dataset.data_entries[substance.id.to_s] = data_entries[substance.id.to_s] ||= {}
end
dataset.save
dataset
end
start = last+1
chunks << chunk
end
chunks
end | ruby | def folds n
len = self.substances.size
indices = (0..len-1).to_a.shuffle
mid = (len/n)
chunks = []
start = 0
1.upto(n) do |i|
last = start+mid
last = last-1 unless len%n >= i
test_idxs = indices[start..last] || []
test_substances = test_idxs.collect{|i| substances[i]}
training_idxs = indices-test_idxs
training_substances = training_idxs.collect{|i| substances[i]}
chunk = [training_substances,test_substances].collect do |substances|
dataset = self.class.create(:name => "#{self.name} (Fold #{i-1})",:source => self.id )
substances.each do |substance|
substance.dataset_ids << dataset.id
substance.dataset_ids.uniq!
substance.save
dataset.data_entries[substance.id.to_s] = data_entries[substance.id.to_s] ||= {}
end
dataset.save
dataset
end
start = last+1
chunks << chunk
end
chunks
end | [
"def",
"folds",
"n",
"len",
"=",
"self",
".",
"substances",
".",
"size",
"indices",
"=",
"(",
"0",
"..",
"len",
"-",
"1",
")",
".",
"to_a",
".",
"shuffle",
"mid",
"=",
"(",
"len",
"/",
"n",
")",
"chunks",
"=",
"[",
"]",
"start",
"=",
"0",
"1",
".",
"upto",
"(",
"n",
")",
"do",
"|",
"i",
"|",
"last",
"=",
"start",
"+",
"mid",
"last",
"=",
"last",
"-",
"1",
"unless",
"len",
"%",
"n",
">=",
"i",
"test_idxs",
"=",
"indices",
"[",
"start",
"..",
"last",
"]",
"||",
"[",
"]",
"test_substances",
"=",
"test_idxs",
".",
"collect",
"{",
"|",
"i",
"|",
"substances",
"[",
"i",
"]",
"}",
"training_idxs",
"=",
"indices",
"-",
"test_idxs",
"training_substances",
"=",
"training_idxs",
".",
"collect",
"{",
"|",
"i",
"|",
"substances",
"[",
"i",
"]",
"}",
"chunk",
"=",
"[",
"training_substances",
",",
"test_substances",
"]",
".",
"collect",
"do",
"|",
"substances",
"|",
"dataset",
"=",
"self",
".",
"class",
".",
"create",
"(",
":name",
"=>",
"\"#{self.name} (Fold #{i-1})\"",
",",
":source",
"=>",
"self",
".",
"id",
")",
"substances",
".",
"each",
"do",
"|",
"substance",
"|",
"substance",
".",
"dataset_ids",
"<<",
"dataset",
".",
"id",
"substance",
".",
"dataset_ids",
".",
"uniq!",
"substance",
".",
"save",
"dataset",
".",
"data_entries",
"[",
"substance",
".",
"id",
".",
"to_s",
"]",
"=",
"data_entries",
"[",
"substance",
".",
"id",
".",
"to_s",
"]",
"||=",
"{",
"}",
"end",
"dataset",
".",
"save",
"dataset",
"end",
"start",
"=",
"last",
"+",
"1",
"chunks",
"<<",
"chunk",
"end",
"chunks",
"end"
] | Dataset operations
Split a dataset into n folds
@param [Integer] number of folds
@return [Array] Array with folds [training_dataset,test_dataset] | [
"Dataset",
"operations",
"Split",
"a",
"dataset",
"into",
"n",
"folds"
] | 1ee7de09c969e16fd11522d22179224e694b0161 | https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/dataset.rb#L73-L101 | train |
opentox/lazar | lib/dataset.rb | OpenTox.Dataset.to_csv | def to_csv(inchi=false)
CSV.generate() do |csv|
compound = substances.first.is_a? Compound
if compound
csv << [inchi ? "InChI" : "SMILES"] + features.collect{|f| f.name}
else
csv << ["Name"] + features.collect{|f| f.name}
end
substances.each do |substance|
if compound
name = (inchi ? substance.inchi : substance.smiles)
else
name = substance.name
end
nr_measurements = features.collect{|f| data_entries[substance.id.to_s][f.id.to_s].size if data_entries[substance.id.to_s][f.id.to_s]}.compact.uniq
if nr_measurements.size > 1
warn "Unequal number of measurements (#{nr_measurements}) for '#{name}'. Skipping entries."
else
(0..nr_measurements.first-1).each do |i|
row = [name]
features.each do |f|
values(substance,f) ? row << values(substance,f)[i] : row << ""
end
csv << row
end
end
end
end
end | ruby | def to_csv(inchi=false)
CSV.generate() do |csv|
compound = substances.first.is_a? Compound
if compound
csv << [inchi ? "InChI" : "SMILES"] + features.collect{|f| f.name}
else
csv << ["Name"] + features.collect{|f| f.name}
end
substances.each do |substance|
if compound
name = (inchi ? substance.inchi : substance.smiles)
else
name = substance.name
end
nr_measurements = features.collect{|f| data_entries[substance.id.to_s][f.id.to_s].size if data_entries[substance.id.to_s][f.id.to_s]}.compact.uniq
if nr_measurements.size > 1
warn "Unequal number of measurements (#{nr_measurements}) for '#{name}'. Skipping entries."
else
(0..nr_measurements.first-1).each do |i|
row = [name]
features.each do |f|
values(substance,f) ? row << values(substance,f)[i] : row << ""
end
csv << row
end
end
end
end
end | [
"def",
"to_csv",
"(",
"inchi",
"=",
"false",
")",
"CSV",
".",
"generate",
"(",
")",
"do",
"|",
"csv",
"|",
"compound",
"=",
"substances",
".",
"first",
".",
"is_a?",
"Compound",
"if",
"compound",
"csv",
"<<",
"[",
"inchi",
"?",
"\"InChI\"",
":",
"\"SMILES\"",
"]",
"+",
"features",
".",
"collect",
"{",
"|",
"f",
"|",
"f",
".",
"name",
"}",
"else",
"csv",
"<<",
"[",
"\"Name\"",
"]",
"+",
"features",
".",
"collect",
"{",
"|",
"f",
"|",
"f",
".",
"name",
"}",
"end",
"substances",
".",
"each",
"do",
"|",
"substance",
"|",
"if",
"compound",
"name",
"=",
"(",
"inchi",
"?",
"substance",
".",
"inchi",
":",
"substance",
".",
"smiles",
")",
"else",
"name",
"=",
"substance",
".",
"name",
"end",
"nr_measurements",
"=",
"features",
".",
"collect",
"{",
"|",
"f",
"|",
"data_entries",
"[",
"substance",
".",
"id",
".",
"to_s",
"]",
"[",
"f",
".",
"id",
".",
"to_s",
"]",
".",
"size",
"if",
"data_entries",
"[",
"substance",
".",
"id",
".",
"to_s",
"]",
"[",
"f",
".",
"id",
".",
"to_s",
"]",
"}",
".",
"compact",
".",
"uniq",
"if",
"nr_measurements",
".",
"size",
">",
"1",
"warn",
"\"Unequal number of measurements (#{nr_measurements}) for '#{name}'. Skipping entries.\"",
"else",
"(",
"0",
"..",
"nr_measurements",
".",
"first",
"-",
"1",
")",
".",
"each",
"do",
"|",
"i",
"|",
"row",
"=",
"[",
"name",
"]",
"features",
".",
"each",
"do",
"|",
"f",
"|",
"values",
"(",
"substance",
",",
"f",
")",
"?",
"row",
"<<",
"values",
"(",
"substance",
",",
"f",
")",
"[",
"i",
"]",
":",
"row",
"<<",
"\"\"",
"end",
"csv",
"<<",
"row",
"end",
"end",
"end",
"end",
"end"
] | Serialisation
Convert dataset to csv format including compound smiles as first column, other column headers are feature names
@return [String] | [
"Serialisation",
"Convert",
"dataset",
"to",
"csv",
"format",
"including",
"compound",
"smiles",
"as",
"first",
"column",
"other",
"column",
"headers",
"are",
"feature",
"names"
] | 1ee7de09c969e16fd11522d22179224e694b0161 | https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/dataset.rb#L107-L136 | train |
botanicus/rango | lib/rango/mixins/logger.rb | Rango.LoggerMixin.inspect | def inspect(*args)
if args.first.is_a?(Hash) && args.length.eql?(1)
args.first.each do |name, value|
self.debug("#{name}: #{value.inspect}")
end
else
args = args.map { |arg| arg.inspect }
self.debug(*args)
end
end | ruby | def inspect(*args)
if args.first.is_a?(Hash) && args.length.eql?(1)
args.first.each do |name, value|
self.debug("#{name}: #{value.inspect}")
end
else
args = args.map { |arg| arg.inspect }
self.debug(*args)
end
end | [
"def",
"inspect",
"(",
"*",
"args",
")",
"if",
"args",
".",
"first",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"args",
".",
"length",
".",
"eql?",
"(",
"1",
")",
"args",
".",
"first",
".",
"each",
"do",
"|",
"name",
",",
"value",
"|",
"self",
".",
"debug",
"(",
"\"#{name}: #{value.inspect}\"",
")",
"end",
"else",
"args",
"=",
"args",
".",
"map",
"{",
"|",
"arg",
"|",
"arg",
".",
"inspect",
"}",
"self",
".",
"debug",
"(",
"*",
"args",
")",
"end",
"end"
] | Project.logger.inspect(@posts, item)
Project.logger.inspect("@post" => @post)
@since 0.0.1 | [
"Project",
".",
"logger",
".",
"inspect",
"("
] | b8904453f3b7d3cd65e2bcc5236bfe645aa78e8e | https://github.com/botanicus/rango/blob/b8904453f3b7d3cd65e2bcc5236bfe645aa78e8e/lib/rango/mixins/logger.rb#L8-L17 | train |
github/graphql-relay-walker | lib/graphql/relay/walker/queue.rb | GraphQL::Relay::Walker.Queue.add | def add(frame)
return false if max_size && queue.length >= max_size
return false if seen.include?(frame.gid)
seen.add(frame.gid)
idx = random_idx ? rand(queue.length + 1) : queue.length
queue.insert(idx, frame)
true
end | ruby | def add(frame)
return false if max_size && queue.length >= max_size
return false if seen.include?(frame.gid)
seen.add(frame.gid)
idx = random_idx ? rand(queue.length + 1) : queue.length
queue.insert(idx, frame)
true
end | [
"def",
"add",
"(",
"frame",
")",
"return",
"false",
"if",
"max_size",
"&&",
"queue",
".",
"length",
">=",
"max_size",
"return",
"false",
"if",
"seen",
".",
"include?",
"(",
"frame",
".",
"gid",
")",
"seen",
".",
"add",
"(",
"frame",
".",
"gid",
")",
"idx",
"=",
"random_idx",
"?",
"rand",
"(",
"queue",
".",
"length",
"+",
"1",
")",
":",
"queue",
".",
"length",
"queue",
".",
"insert",
"(",
"idx",
",",
"frame",
")",
"true",
"end"
] | Initialize a new Queue.
max_size: - The maximum size the queue can grow to. This helps when
walking a large graph by forcing us to walk deeper.
random_idx: - Add frames to the queue at random indicies. This helps when
walking a large graph by forcing us to walk deeper.
Returns nothing.
Add a frame to the queue if its GID hasn't been seen already and the queue
hasn't exceeded its max size.
frame - The Frame to add to the queue.
Returns true if the frame was added, false otherwise. | [
"Initialize",
"a",
"new",
"Queue",
"."
] | 1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7 | https://github.com/github/graphql-relay-walker/blob/1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7/lib/graphql/relay/walker/queue.rb#L28-L37 | train |
github/graphql-relay-walker | lib/graphql/relay/walker/queue.rb | GraphQL::Relay::Walker.Queue.add_gid | def add_gid(gid, parent = nil)
frame = Frame.new(self, gid, parent)
add(frame)
end | ruby | def add_gid(gid, parent = nil)
frame = Frame.new(self, gid, parent)
add(frame)
end | [
"def",
"add_gid",
"(",
"gid",
",",
"parent",
"=",
"nil",
")",
"frame",
"=",
"Frame",
".",
"new",
"(",
"self",
",",
"gid",
",",
"parent",
")",
"add",
"(",
"frame",
")",
"end"
] | Add a GID to the queue.
gid - The String GID to add to the queue.
parent - The frame where this GID was discovered (optional).
Returns true if a frame was added, false otherwise. | [
"Add",
"a",
"GID",
"to",
"the",
"queue",
"."
] | 1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7 | https://github.com/github/graphql-relay-walker/blob/1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7/lib/graphql/relay/walker/queue.rb#L45-L48 | train |
ShipCompliant/ship_compliant-ruby | lib/ship_compliant/get_inventory_details_result.rb | ShipCompliant.GetInventoryDetailsResult.location | def location(key)
location = locations.select { |l| l[:fulfillment_location] == key }.first
return {} if location.nil?
location
end | ruby | def location(key)
location = locations.select { |l| l[:fulfillment_location] == key }.first
return {} if location.nil?
location
end | [
"def",
"location",
"(",
"key",
")",
"location",
"=",
"locations",
".",
"select",
"{",
"|",
"l",
"|",
"l",
"[",
":fulfillment_location",
"]",
"==",
"key",
"}",
".",
"first",
"return",
"{",
"}",
"if",
"location",
".",
"nil?",
"location",
"end"
] | Finds a location by +FulfillmentLocation+.
result.location('WineShipping')[:supplier] #=> 'LOCATION-SUPPLIER' | [
"Finds",
"a",
"location",
"by",
"+",
"FulfillmentLocation",
"+",
"."
] | aa12852a58cd6cb7939eb9fbb7fdc03e46e18197 | https://github.com/ShipCompliant/ship_compliant-ruby/blob/aa12852a58cd6cb7939eb9fbb7fdc03e46e18197/lib/ship_compliant/get_inventory_details_result.rb#L21-L26 | train |
ktonon/cog | lib/cog/config.rb | Cog.Config.prepare | def prepare(opt={})
throw :ConfigInstanceAlreadyPrepared if @prepared && !opt[:force_reset]
@prepared = true
@fullpaths = opt[:fullpaths]
@project_path = nil
@project_generator_path = nil
@project_plugin_path = nil
@project_template_path = nil
@generator_path = []
@plugin_path = []
@template_path = []
@plugins = {}
@target_language = Language.new
@active_languages = [Language.new] # active language stack
@language = {}
@language_extension_map = {}
process_cogfiles opt
post_cogfile_processing
build_language_extension_map
end | ruby | def prepare(opt={})
throw :ConfigInstanceAlreadyPrepared if @prepared && !opt[:force_reset]
@prepared = true
@fullpaths = opt[:fullpaths]
@project_path = nil
@project_generator_path = nil
@project_plugin_path = nil
@project_template_path = nil
@generator_path = []
@plugin_path = []
@template_path = []
@plugins = {}
@target_language = Language.new
@active_languages = [Language.new] # active language stack
@language = {}
@language_extension_map = {}
process_cogfiles opt
post_cogfile_processing
build_language_extension_map
end | [
"def",
"prepare",
"(",
"opt",
"=",
"{",
"}",
")",
"throw",
":ConfigInstanceAlreadyPrepared",
"if",
"@prepared",
"&&",
"!",
"opt",
"[",
":force_reset",
"]",
"@prepared",
"=",
"true",
"@fullpaths",
"=",
"opt",
"[",
":fullpaths",
"]",
"@project_path",
"=",
"nil",
"@project_generator_path",
"=",
"nil",
"@project_plugin_path",
"=",
"nil",
"@project_template_path",
"=",
"nil",
"@generator_path",
"=",
"[",
"]",
"@plugin_path",
"=",
"[",
"]",
"@template_path",
"=",
"[",
"]",
"@plugins",
"=",
"{",
"}",
"@target_language",
"=",
"Language",
".",
"new",
"@active_languages",
"=",
"[",
"Language",
".",
"new",
"]",
"@language",
"=",
"{",
"}",
"@language_extension_map",
"=",
"{",
"}",
"process_cogfiles",
"opt",
"post_cogfile_processing",
"build_language_extension_map",
"end"
] | Must be called once before using cog.
In the context of a command-line invocation, this method will be called automatically. Outside of that context, for example in a unit test, it will have to be called manually.
@option opt [Boolean] :fullpaths (false) when listing files, full paths should be shown
@option opt [Boolean] :minimal (false) only load the built-in Cogfile
@option opt [String] :project_cogfile_path (nil) explicitly specify the location of the project {DSL::Cogfile}. If not provided, it will be searched for. If none can be found, {#project?} will be +false+ | [
"Must",
"be",
"called",
"once",
"before",
"using",
"cog",
".",
"In",
"the",
"context",
"of",
"a",
"command",
"-",
"line",
"invocation",
"this",
"method",
"will",
"be",
"called",
"automatically",
".",
"Outside",
"of",
"that",
"context",
"for",
"example",
"in",
"a",
"unit",
"test",
"it",
"will",
"have",
"to",
"be",
"called",
"manually",
"."
] | 156c81a0873135d7dc47c79c705c477893fff74a | https://github.com/ktonon/cog/blob/156c81a0873135d7dc47c79c705c477893fff74a/lib/cog/config.rb#L61-L81 | train |
ShipCompliant/ship_compliant-ruby | lib/ship_compliant/check_compliance_result.rb | ShipCompliant.CheckComplianceResult.taxes_for_shipment | def taxes_for_shipment(shipment_key)
shipment = shipment_sales_tax_rates.select { |s| s[:@shipment_key] == shipment_key }.first
# convert attribute keys to symbols
freight = attributes_to_symbols(shipment[:freight_sales_tax_rate])
# wrap products in ProductSalesTaxRate
products = wrap_products(shipment[:product_sales_tax_rates])
ShipmentSalesTaxRate.new(shipment_key, FreightSalesTaxRate.new(freight), products)
end | ruby | def taxes_for_shipment(shipment_key)
shipment = shipment_sales_tax_rates.select { |s| s[:@shipment_key] == shipment_key }.first
# convert attribute keys to symbols
freight = attributes_to_symbols(shipment[:freight_sales_tax_rate])
# wrap products in ProductSalesTaxRate
products = wrap_products(shipment[:product_sales_tax_rates])
ShipmentSalesTaxRate.new(shipment_key, FreightSalesTaxRate.new(freight), products)
end | [
"def",
"taxes_for_shipment",
"(",
"shipment_key",
")",
"shipment",
"=",
"shipment_sales_tax_rates",
".",
"select",
"{",
"|",
"s",
"|",
"s",
"[",
":@shipment_key",
"]",
"==",
"shipment_key",
"}",
".",
"first",
"freight",
"=",
"attributes_to_symbols",
"(",
"shipment",
"[",
":freight_sales_tax_rate",
"]",
")",
"products",
"=",
"wrap_products",
"(",
"shipment",
"[",
":product_sales_tax_rates",
"]",
")",
"ShipmentSalesTaxRate",
".",
"new",
"(",
"shipment_key",
",",
"FreightSalesTaxRate",
".",
"new",
"(",
"freight",
")",
",",
"products",
")",
"end"
] | Access the tax information for a shipment. Returns an instance of
ShipmentSalesTaxRate. | [
"Access",
"the",
"tax",
"information",
"for",
"a",
"shipment",
".",
"Returns",
"an",
"instance",
"of",
"ShipmentSalesTaxRate",
"."
] | aa12852a58cd6cb7939eb9fbb7fdc03e46e18197 | https://github.com/ShipCompliant/ship_compliant-ruby/blob/aa12852a58cd6cb7939eb9fbb7fdc03e46e18197/lib/ship_compliant/check_compliance_result.rb#L30-L40 | train |
ShipCompliant/ship_compliant-ruby | lib/ship_compliant/check_compliance_result.rb | ShipCompliant.CheckComplianceResult.compliance_rules_for_shipment | def compliance_rules_for_shipment(shipment_key)
shipment = shipment_compliance_rules.select { |s| s[:key] == shipment_key }.first
ShipmentCompliance.new(shipment)
end | ruby | def compliance_rules_for_shipment(shipment_key)
shipment = shipment_compliance_rules.select { |s| s[:key] == shipment_key }.first
ShipmentCompliance.new(shipment)
end | [
"def",
"compliance_rules_for_shipment",
"(",
"shipment_key",
")",
"shipment",
"=",
"shipment_compliance_rules",
".",
"select",
"{",
"|",
"s",
"|",
"s",
"[",
":key",
"]",
"==",
"shipment_key",
"}",
".",
"first",
"ShipmentCompliance",
".",
"new",
"(",
"shipment",
")",
"end"
] | Finds all the compliance rules for a shipment.
Returns an instance of ShipmentCompliance.
shipment_compliance = compliance_result.compliance_rules_for_shipment('SHIPMENT-KEY')
puts shipment_compliance.compliant? #=> false | [
"Finds",
"all",
"the",
"compliance",
"rules",
"for",
"a",
"shipment",
".",
"Returns",
"an",
"instance",
"of",
"ShipmentCompliance",
"."
] | aa12852a58cd6cb7939eb9fbb7fdc03e46e18197 | https://github.com/ShipCompliant/ship_compliant-ruby/blob/aa12852a58cd6cb7939eb9fbb7fdc03e46e18197/lib/ship_compliant/check_compliance_result.rb#L62-L65 | train |
poise/poise-profiler | lib/poise_profiler/config.rb | PoiseProfiler.Config.gather_from_env | def gather_from_env
ENV.each do |key, value|
if key.downcase =~ /^poise(_|-)profiler_(.+)$/
self[$2] = YAML.safe_load(value)
end
end
end | ruby | def gather_from_env
ENV.each do |key, value|
if key.downcase =~ /^poise(_|-)profiler_(.+)$/
self[$2] = YAML.safe_load(value)
end
end
end | [
"def",
"gather_from_env",
"ENV",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"key",
".",
"downcase",
"=~",
"/",
"/",
"self",
"[",
"$2",
"]",
"=",
"YAML",
".",
"safe_load",
"(",
"value",
")",
"end",
"end",
"end"
] | Find configuration data in environment variables. This is the only option
on Chef 12.0, 12.1, and 12.2.
@api private | [
"Find",
"configuration",
"data",
"in",
"environment",
"variables",
".",
"This",
"is",
"the",
"only",
"option",
"on",
"Chef",
"12",
".",
"0",
"12",
".",
"1",
"and",
"12",
".",
"2",
"."
] | a190acc6bdd4fcdac34ef43bbe4f59dddb9c0f67 | https://github.com/poise/poise-profiler/blob/a190acc6bdd4fcdac34ef43bbe4f59dddb9c0f67/lib/poise_profiler/config.rb#L49-L55 | train |
poise/poise-profiler | lib/poise_profiler/config.rb | PoiseProfiler.Config.gather_from_node | def gather_from_node
return unless defined?(Chef.node)
(Chef.node['poise-profiler'] || {}).each do |key, value|
self[key] = value
end
end | ruby | def gather_from_node
return unless defined?(Chef.node)
(Chef.node['poise-profiler'] || {}).each do |key, value|
self[key] = value
end
end | [
"def",
"gather_from_node",
"return",
"unless",
"defined?",
"(",
"Chef",
".",
"node",
")",
"(",
"Chef",
".",
"node",
"[",
"'poise-profiler'",
"]",
"||",
"{",
"}",
")",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"self",
"[",
"key",
"]",
"=",
"value",
"end",
"end"
] | Find configuration data in node attributes.
@api private | [
"Find",
"configuration",
"data",
"in",
"node",
"attributes",
"."
] | a190acc6bdd4fcdac34ef43bbe4f59dddb9c0f67 | https://github.com/poise/poise-profiler/blob/a190acc6bdd4fcdac34ef43bbe4f59dddb9c0f67/lib/poise_profiler/config.rb#L60-L65 | train |
ShipCompliant/ship_compliant-ruby | lib/ship_compliant/inventory_product.rb | ShipCompliant.InventoryProduct.inventory_levels | def inventory_levels
levels = {}
product[:inventory_levels][:inventory_level].each do |level|
key = level[:inventory_type].underscore.to_sym
value = level[:quantity].to_f
levels[key] = value
end
levels
end | ruby | def inventory_levels
levels = {}
product[:inventory_levels][:inventory_level].each do |level|
key = level[:inventory_type].underscore.to_sym
value = level[:quantity].to_f
levels[key] = value
end
levels
end | [
"def",
"inventory_levels",
"levels",
"=",
"{",
"}",
"product",
"[",
":inventory_levels",
"]",
"[",
":inventory_level",
"]",
".",
"each",
"do",
"|",
"level",
"|",
"key",
"=",
"level",
"[",
":inventory_type",
"]",
".",
"underscore",
".",
"to_sym",
"value",
"=",
"level",
"[",
":quantity",
"]",
".",
"to_f",
"levels",
"[",
"key",
"]",
"=",
"value",
"end",
"levels",
"end"
] | Returns a Hash of inventory levels.
- The key is the +InventoryType+.
- The value is +Quantity+ as a float.
product.inventory_levels #=> {
available: 2,
on_hold: 2,
back_order: 4
} | [
"Returns",
"a",
"Hash",
"of",
"inventory",
"levels",
"."
] | aa12852a58cd6cb7939eb9fbb7fdc03e46e18197 | https://github.com/ShipCompliant/ship_compliant-ruby/blob/aa12852a58cd6cb7939eb9fbb7fdc03e46e18197/lib/ship_compliant/inventory_product.rb#L82-L93 | train |
rossf7/elasticrawl | lib/elasticrawl/cluster.rb | Elasticrawl.Cluster.create_job_flow | def create_job_flow(job, emr_config = nil)
config = Config.new
Elasticity.configure do |c|
c.access_key = config.access_key_id
c.secret_key = config.secret_access_key
end
job_flow = Elasticity::JobFlow.new
job_flow.name = "Job: #{job.job_name} #{job.job_desc}"
job_flow.log_uri = job.log_uri
configure_job_flow(job_flow)
configure_instances(job_flow)
configure_bootstrap_actions(job_flow, emr_config)
job_flow
end | ruby | def create_job_flow(job, emr_config = nil)
config = Config.new
Elasticity.configure do |c|
c.access_key = config.access_key_id
c.secret_key = config.secret_access_key
end
job_flow = Elasticity::JobFlow.new
job_flow.name = "Job: #{job.job_name} #{job.job_desc}"
job_flow.log_uri = job.log_uri
configure_job_flow(job_flow)
configure_instances(job_flow)
configure_bootstrap_actions(job_flow, emr_config)
job_flow
end | [
"def",
"create_job_flow",
"(",
"job",
",",
"emr_config",
"=",
"nil",
")",
"config",
"=",
"Config",
".",
"new",
"Elasticity",
".",
"configure",
"do",
"|",
"c",
"|",
"c",
".",
"access_key",
"=",
"config",
".",
"access_key_id",
"c",
".",
"secret_key",
"=",
"config",
".",
"secret_access_key",
"end",
"job_flow",
"=",
"Elasticity",
"::",
"JobFlow",
".",
"new",
"job_flow",
".",
"name",
"=",
"\"Job: #{job.job_name} #{job.job_desc}\"",
"job_flow",
".",
"log_uri",
"=",
"job",
".",
"log_uri",
"configure_job_flow",
"(",
"job_flow",
")",
"configure_instances",
"(",
"job_flow",
")",
"configure_bootstrap_actions",
"(",
"job_flow",
",",
"emr_config",
")",
"job_flow",
"end"
] | Returns a configured job flow to the calling job. | [
"Returns",
"a",
"configured",
"job",
"flow",
"to",
"the",
"calling",
"job",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/cluster.rb#L12-L29 | train |
rossf7/elasticrawl | lib/elasticrawl/cluster.rb | Elasticrawl.Cluster.configure_job_flow | def configure_job_flow(job_flow)
ec2_key_name = config_setting('ec2_key_name')
placement = config_setting('placement')
emr_ami_version = config_setting('emr_ami_version')
job_flow_role = config_setting('job_flow_role')
service_role = config_setting('service_role')
ec2_subnet_id = config_setting('ec2_subnet_id')
job_flow.ec2_subnet_id = ec2_subnet_id if ec2_subnet_id.present?
job_flow.ec2_key_name = ec2_key_name if ec2_key_name.present?
job_flow.placement = placement if placement.present?
job_flow.ami_version = emr_ami_version if emr_ami_version.present?
job_flow.job_flow_role = job_flow_role if job_flow_role.present?
job_flow.service_role = service_role if service_role.present?
end | ruby | def configure_job_flow(job_flow)
ec2_key_name = config_setting('ec2_key_name')
placement = config_setting('placement')
emr_ami_version = config_setting('emr_ami_version')
job_flow_role = config_setting('job_flow_role')
service_role = config_setting('service_role')
ec2_subnet_id = config_setting('ec2_subnet_id')
job_flow.ec2_subnet_id = ec2_subnet_id if ec2_subnet_id.present?
job_flow.ec2_key_name = ec2_key_name if ec2_key_name.present?
job_flow.placement = placement if placement.present?
job_flow.ami_version = emr_ami_version if emr_ami_version.present?
job_flow.job_flow_role = job_flow_role if job_flow_role.present?
job_flow.service_role = service_role if service_role.present?
end | [
"def",
"configure_job_flow",
"(",
"job_flow",
")",
"ec2_key_name",
"=",
"config_setting",
"(",
"'ec2_key_name'",
")",
"placement",
"=",
"config_setting",
"(",
"'placement'",
")",
"emr_ami_version",
"=",
"config_setting",
"(",
"'emr_ami_version'",
")",
"job_flow_role",
"=",
"config_setting",
"(",
"'job_flow_role'",
")",
"service_role",
"=",
"config_setting",
"(",
"'service_role'",
")",
"ec2_subnet_id",
"=",
"config_setting",
"(",
"'ec2_subnet_id'",
")",
"job_flow",
".",
"ec2_subnet_id",
"=",
"ec2_subnet_id",
"if",
"ec2_subnet_id",
".",
"present?",
"job_flow",
".",
"ec2_key_name",
"=",
"ec2_key_name",
"if",
"ec2_key_name",
".",
"present?",
"job_flow",
".",
"placement",
"=",
"placement",
"if",
"placement",
".",
"present?",
"job_flow",
".",
"ami_version",
"=",
"emr_ami_version",
"if",
"emr_ami_version",
".",
"present?",
"job_flow",
".",
"job_flow_role",
"=",
"job_flow_role",
"if",
"job_flow_role",
".",
"present?",
"job_flow",
".",
"service_role",
"=",
"service_role",
"if",
"service_role",
".",
"present?",
"end"
] | Set job flow properties from settings in cluster.yml. | [
"Set",
"job",
"flow",
"properties",
"from",
"settings",
"in",
"cluster",
".",
"yml",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/cluster.rb#L44-L58 | train |
rossf7/elasticrawl | lib/elasticrawl/cluster.rb | Elasticrawl.Cluster.configure_bootstrap_actions | def configure_bootstrap_actions(job_flow, emr_config = nil)
bootstrap_scripts = config_setting('bootstrap_scripts')
if bootstrap_scripts.present?
bootstrap_scripts.each do |script_uri|
action = Elasticity::BootstrapAction.new(script_uri, '', '')
job_flow.add_bootstrap_action(action)
end
end
if emr_config.present?
action = Elasticity::HadoopFileBootstrapAction.new(emr_config)
job_flow.add_bootstrap_action(action)
end
end | ruby | def configure_bootstrap_actions(job_flow, emr_config = nil)
bootstrap_scripts = config_setting('bootstrap_scripts')
if bootstrap_scripts.present?
bootstrap_scripts.each do |script_uri|
action = Elasticity::BootstrapAction.new(script_uri, '', '')
job_flow.add_bootstrap_action(action)
end
end
if emr_config.present?
action = Elasticity::HadoopFileBootstrapAction.new(emr_config)
job_flow.add_bootstrap_action(action)
end
end | [
"def",
"configure_bootstrap_actions",
"(",
"job_flow",
",",
"emr_config",
"=",
"nil",
")",
"bootstrap_scripts",
"=",
"config_setting",
"(",
"'bootstrap_scripts'",
")",
"if",
"bootstrap_scripts",
".",
"present?",
"bootstrap_scripts",
".",
"each",
"do",
"|",
"script_uri",
"|",
"action",
"=",
"Elasticity",
"::",
"BootstrapAction",
".",
"new",
"(",
"script_uri",
",",
"''",
",",
"''",
")",
"job_flow",
".",
"add_bootstrap_action",
"(",
"action",
")",
"end",
"end",
"if",
"emr_config",
".",
"present?",
"action",
"=",
"Elasticity",
"::",
"HadoopFileBootstrapAction",
".",
"new",
"(",
"emr_config",
")",
"job_flow",
".",
"add_bootstrap_action",
"(",
"action",
")",
"end",
"end"
] | Configures bootstrap actions that will be run when each instance is
launched. EMR config is an XML file of Hadoop settings stored on S3.
There are applied to each node by a bootstrap action. | [
"Configures",
"bootstrap",
"actions",
"that",
"will",
"be",
"run",
"when",
"each",
"instance",
"is",
"launched",
".",
"EMR",
"config",
"is",
"an",
"XML",
"file",
"of",
"Hadoop",
"settings",
"stored",
"on",
"S3",
".",
"There",
"are",
"applied",
"to",
"each",
"node",
"by",
"a",
"bootstrap",
"action",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/cluster.rb#L71-L85 | train |
brasten/scruffy | lib/scruffy/components/legend.rb | Scruffy::Components.Legend.relevant_legend_info | def relevant_legend_info(layers, categories=(@options[:category] ? [@options[:category]] : @options[:categories]))
legend_info = layers.inject([]) do |arr, layer|
if categories.nil? ||
(categories.include?(layer.options[:category]) ||
(layer.options[:categories] && (categories & layer.options[:categories]).size > 0) )
data = layer.legend_data
arr << data if data.is_a?(Hash)
arr = arr + data if data.is_a?(Array)
end
arr
end
end | ruby | def relevant_legend_info(layers, categories=(@options[:category] ? [@options[:category]] : @options[:categories]))
legend_info = layers.inject([]) do |arr, layer|
if categories.nil? ||
(categories.include?(layer.options[:category]) ||
(layer.options[:categories] && (categories & layer.options[:categories]).size > 0) )
data = layer.legend_data
arr << data if data.is_a?(Hash)
arr = arr + data if data.is_a?(Array)
end
arr
end
end | [
"def",
"relevant_legend_info",
"(",
"layers",
",",
"categories",
"=",
"(",
"@options",
"[",
":category",
"]",
"?",
"[",
"@options",
"[",
":category",
"]",
"]",
":",
"@options",
"[",
":categories",
"]",
")",
")",
"legend_info",
"=",
"layers",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"arr",
",",
"layer",
"|",
"if",
"categories",
".",
"nil?",
"||",
"(",
"categories",
".",
"include?",
"(",
"layer",
".",
"options",
"[",
":category",
"]",
")",
"||",
"(",
"layer",
".",
"options",
"[",
":categories",
"]",
"&&",
"(",
"categories",
"&",
"layer",
".",
"options",
"[",
":categories",
"]",
")",
".",
"size",
">",
"0",
")",
")",
"data",
"=",
"layer",
".",
"legend_data",
"arr",
"<<",
"data",
"if",
"data",
".",
"is_a?",
"(",
"Hash",
")",
"arr",
"=",
"arr",
"+",
"data",
"if",
"data",
".",
"is_a?",
"(",
"Array",
")",
"end",
"arr",
"end",
"end"
] | Collects Legend Info from the provided Layers.
Automatically filters by legend's categories. | [
"Collects",
"Legend",
"Info",
"from",
"the",
"provided",
"Layers",
"."
] | 4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e | https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/components/legend.rb#L102-L114 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.