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
piotrmurach/tty-spinner
lib/tty/spinner.rb
TTY.Spinner.auto_spin
def auto_spin CURSOR_LOCK.synchronize do start sleep_time = 1.0 / @interval spin @thread = Thread.new do sleep(sleep_time) while @started_at if Thread.current['pause'] Thread.stop Thread.current['pause'] = false end spin sleep(sleep_time) end end end ensure if @hide_cursor write(TTY::Cursor.show, false) end end
ruby
def auto_spin CURSOR_LOCK.synchronize do start sleep_time = 1.0 / @interval spin @thread = Thread.new do sleep(sleep_time) while @started_at if Thread.current['pause'] Thread.stop Thread.current['pause'] = false end spin sleep(sleep_time) end end end ensure if @hide_cursor write(TTY::Cursor.show, false) end end
[ "def", "auto_spin", "CURSOR_LOCK", ".", "synchronize", "do", "start", "sleep_time", "=", "1.0", "/", "@interval", "spin", "@thread", "=", "Thread", ".", "new", "do", "sleep", "(", "sleep_time", ")", "while", "@started_at", "if", "Thread", ".", "current", "[", "'pause'", "]", "Thread", ".", "stop", "Thread", ".", "current", "[", "'pause'", "]", "=", "false", "end", "spin", "sleep", "(", "sleep_time", ")", "end", "end", "end", "ensure", "if", "@hide_cursor", "write", "(", "TTY", "::", "Cursor", ".", "show", ",", "false", ")", "end", "end" ]
Start automatic spinning animation @api public
[ "Start", "automatic", "spinning", "animation" ]
876449a4a10831b38aedd92004592efe417c6377
https://github.com/piotrmurach/tty-spinner/blob/876449a4a10831b38aedd92004592efe417c6377/lib/tty/spinner.rb#L240-L262
train
piotrmurach/tty-spinner
lib/tty/spinner.rb
TTY.Spinner.run
def run(stop_message = '', &block) job(&block) auto_spin @work = Thread.new { execute_job } @work.join ensure stop(stop_message) end
ruby
def run(stop_message = '', &block) job(&block) auto_spin @work = Thread.new { execute_job } @work.join ensure stop(stop_message) end
[ "def", "run", "(", "stop_message", "=", "''", ",", "&", "block", ")", "job", "(", "block", ")", "auto_spin", "@work", "=", "Thread", ".", "new", "{", "execute_job", "}", "@work", ".", "join", "ensure", "stop", "(", "stop_message", ")", "end" ]
Run spinner while executing job @param [String] stop_message the message displayed when block is finished @yield automatically animate and finish spinner @example spinner.run('Migrated DB') { ... } @api public
[ "Run", "spinner", "while", "executing", "job" ]
876449a4a10831b38aedd92004592efe417c6377
https://github.com/piotrmurach/tty-spinner/blob/876449a4a10831b38aedd92004592efe417c6377/lib/tty/spinner.rb#L304-L312
train
piotrmurach/tty-spinner
lib/tty/spinner.rb
TTY.Spinner.spin
def spin synchronize do return if @done emit(:spin) if @hide_cursor && !spinning? write(TTY::Cursor.hide) end data = message.gsub(MATCHER, @frames[@current]) data = replace_tokens(data) write(data, true) @current = (@current + 1) % @length @state = :spinning data end end
ruby
def spin synchronize do return if @done emit(:spin) if @hide_cursor && !spinning? write(TTY::Cursor.hide) end data = message.gsub(MATCHER, @frames[@current]) data = replace_tokens(data) write(data, true) @current = (@current + 1) % @length @state = :spinning data end end
[ "def", "spin", "synchronize", "do", "return", "if", "@done", "emit", "(", ":spin", ")", "if", "@hide_cursor", "&&", "!", "spinning?", "write", "(", "TTY", "::", "Cursor", ".", "hide", ")", "end", "data", "=", "message", ".", "gsub", "(", "MATCHER", ",", "@frames", "[", "@current", "]", ")", "data", "=", "replace_tokens", "(", "data", ")", "write", "(", "data", ",", "true", ")", "@current", "=", "(", "@current", "+", "1", ")", "%", "@length", "@state", "=", ":spinning", "data", "end", "end" ]
Perform a spin @return [String] the printed data @api public
[ "Perform", "a", "spin" ]
876449a4a10831b38aedd92004592efe417c6377
https://github.com/piotrmurach/tty-spinner/blob/876449a4a10831b38aedd92004592efe417c6377/lib/tty/spinner.rb#L352-L368
train
piotrmurach/tty-spinner
lib/tty/spinner.rb
TTY.Spinner.fetch_format
def fetch_format(token, property) if FORMATS.key?(token) FORMATS[token][property] else raise ArgumentError, "Unknown format token `:#{token}`" end end
ruby
def fetch_format(token, property) if FORMATS.key?(token) FORMATS[token][property] else raise ArgumentError, "Unknown format token `:#{token}`" end end
[ "def", "fetch_format", "(", "token", ",", "property", ")", "if", "FORMATS", ".", "key?", "(", "token", ")", "FORMATS", "[", "token", "]", "[", "property", "]", "else", "raise", "ArgumentError", ",", "\"Unknown format token `:#{token}`\"", "end", "end" ]
Find frames by token name @param [Symbol] token the name for the frames @return [Array, String] @api private
[ "Find", "frames", "by", "token", "name" ]
876449a4a10831b38aedd92004592efe417c6377
https://github.com/piotrmurach/tty-spinner/blob/876449a4a10831b38aedd92004592efe417c6377/lib/tty/spinner.rb#L547-L553
train
felixbuenemann/xlsxtream
lib/xlsxtream/row.rb
Xlsxtream.Row.auto_format
def auto_format(value) case value when TRUE_STRING true when FALSE_STRING false when NUMBER_PATTERN value.include?('.') ? value.to_f : value.to_i when DATE_PATTERN Date.parse(value) rescue value when TIME_PATTERN DateTime.parse(value) rescue value else value end end
ruby
def auto_format(value) case value when TRUE_STRING true when FALSE_STRING false when NUMBER_PATTERN value.include?('.') ? value.to_f : value.to_i when DATE_PATTERN Date.parse(value) rescue value when TIME_PATTERN DateTime.parse(value) rescue value else value end end
[ "def", "auto_format", "(", "value", ")", "case", "value", "when", "TRUE_STRING", "true", "when", "FALSE_STRING", "false", "when", "NUMBER_PATTERN", "value", ".", "include?", "(", "'.'", ")", "?", "value", ".", "to_f", ":", "value", ".", "to_i", "when", "DATE_PATTERN", "Date", ".", "parse", "(", "value", ")", "rescue", "value", "when", "TIME_PATTERN", "DateTime", ".", "parse", "(", "value", ")", "rescue", "value", "else", "value", "end", "end" ]
Detects and casts numbers, date, time in text
[ "Detects", "and", "casts", "numbers", "date", "time", "in", "text" ]
b2e14c9eac716b154f00280041b08a6535abacd1
https://github.com/felixbuenemann/xlsxtream/blob/b2e14c9eac716b154f00280041b08a6535abacd1/lib/xlsxtream/row.rb#L71-L86
train
felixbuenemann/xlsxtream
lib/xlsxtream/row.rb
Xlsxtream.Row.time_to_oa_date
def time_to_oa_date(time) time = time.to_time if time.respond_to?(:to_time) # Local dates are stored as UTC by truncating the offset: # 1970-01-01 00:00:00 +0200 => 1970-01-01 00:00:00 UTC # This is done because SpreadsheetML is not timezone aware. (time + time.utc_offset).utc.to_f / 24 / 3600 + 25569 end
ruby
def time_to_oa_date(time) time = time.to_time if time.respond_to?(:to_time) # Local dates are stored as UTC by truncating the offset: # 1970-01-01 00:00:00 +0200 => 1970-01-01 00:00:00 UTC # This is done because SpreadsheetML is not timezone aware. (time + time.utc_offset).utc.to_f / 24 / 3600 + 25569 end
[ "def", "time_to_oa_date", "(", "time", ")", "time", "=", "time", ".", "to_time", "if", "time", ".", "respond_to?", "(", ":to_time", ")", "# Local dates are stored as UTC by truncating the offset:", "# 1970-01-01 00:00:00 +0200 => 1970-01-01 00:00:00 UTC", "# This is done because SpreadsheetML is not timezone aware.", "(", "time", "+", "time", ".", "utc_offset", ")", ".", "utc", ".", "to_f", "/", "24", "/", "3600", "+", "25569", "end" ]
Converts Time objects to OLE Automation Date
[ "Converts", "Time", "objects", "to", "OLE", "Automation", "Date" ]
b2e14c9eac716b154f00280041b08a6535abacd1
https://github.com/felixbuenemann/xlsxtream/blob/b2e14c9eac716b154f00280041b08a6535abacd1/lib/xlsxtream/row.rb#L89-L96
train
chef/ffi-yajl
lib/ffi_yajl/map_library_name.rb
FFI_Yajl.MapLibraryName.expanded_library_names
def expanded_library_names library_names.map do |libname| pathname = File.expand_path(File.join(Libyajl2.opt_path, libname)) pathname if File.file?(pathname) end.compact end
ruby
def expanded_library_names library_names.map do |libname| pathname = File.expand_path(File.join(Libyajl2.opt_path, libname)) pathname if File.file?(pathname) end.compact end
[ "def", "expanded_library_names", "library_names", ".", "map", "do", "|", "libname", "|", "pathname", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "Libyajl2", ".", "opt_path", ",", "libname", ")", ")", "pathname", "if", "File", ".", "file?", "(", "pathname", ")", "end", ".", "compact", "end" ]
Array of yajl library names prepended with the libyajl2 path to use to load those directly and bypass the system libyajl by default. Since these are full paths, this API checks to ensure that the file exists on the filesystem. May return an empty array. @api private @return [Array<String>] Array of full paths to libyajl2 gem libraries
[ "Array", "of", "yajl", "library", "names", "prepended", "with", "the", "libyajl2", "path", "to", "use", "to", "load", "those", "directly", "and", "bypass", "the", "system", "libyajl", "by", "default", ".", "Since", "these", "are", "full", "paths", "this", "API", "checks", "to", "ensure", "that", "the", "file", "exists", "on", "the", "filesystem", ".", "May", "return", "an", "empty", "array", "." ]
4b001a89c8c63ef7b39c7fb30a63061add9a44d5
https://github.com/chef/ffi-yajl/blob/4b001a89c8c63ef7b39c7fb30a63061add9a44d5/lib/ffi_yajl/map_library_name.rb#L67-L72
train
chef/ffi-yajl
lib/ffi_yajl/map_library_name.rb
FFI_Yajl.MapLibraryName.dlopen_yajl_library
def dlopen_yajl_library found = false ( expanded_library_names + library_names ).each do |libname| begin dlopen(libname) found = true break rescue ArgumentError end end raise "cannot find yajl library for platform" unless found end
ruby
def dlopen_yajl_library found = false ( expanded_library_names + library_names ).each do |libname| begin dlopen(libname) found = true break rescue ArgumentError end end raise "cannot find yajl library for platform" unless found end
[ "def", "dlopen_yajl_library", "found", "=", "false", "(", "expanded_library_names", "+", "library_names", ")", ".", "each", "do", "|", "libname", "|", "begin", "dlopen", "(", "libname", ")", "found", "=", "true", "break", "rescue", "ArgumentError", "end", "end", "raise", "\"cannot find yajl library for platform\"", "unless", "found", "end" ]
Iterate across the expanded library names in the libyajl2-gem and then attempt to load the system libraries. Uses the native dlopen extension that ships in this gem. @api private
[ "Iterate", "across", "the", "expanded", "library", "names", "in", "the", "libyajl2", "-", "gem", "and", "then", "attempt", "to", "load", "the", "system", "libraries", ".", "Uses", "the", "native", "dlopen", "extension", "that", "ships", "in", "this", "gem", "." ]
4b001a89c8c63ef7b39c7fb30a63061add9a44d5
https://github.com/chef/ffi-yajl/blob/4b001a89c8c63ef7b39c7fb30a63061add9a44d5/lib/ffi_yajl/map_library_name.rb#L79-L90
train
chef/ffi-yajl
lib/ffi_yajl/map_library_name.rb
FFI_Yajl.MapLibraryName.ffi_open_yajl_library
def ffi_open_yajl_library found = false expanded_library_names.each do |libname| begin ffi_lib libname found = true rescue LoadError end end ffi_lib "yajl" unless found end
ruby
def ffi_open_yajl_library found = false expanded_library_names.each do |libname| begin ffi_lib libname found = true rescue LoadError end end ffi_lib "yajl" unless found end
[ "def", "ffi_open_yajl_library", "found", "=", "false", "expanded_library_names", ".", "each", "do", "|", "libname", "|", "begin", "ffi_lib", "libname", "found", "=", "true", "rescue", "LoadError", "end", "end", "ffi_lib", "\"yajl\"", "unless", "found", "end" ]
Iterate across the expanded library names in the libyajl2-gem and attempt to load them. If they are missing just use `ffi_lib 'yajl'` to accept the FFI default algorithm to find the library. @api private
[ "Iterate", "across", "the", "expanded", "library", "names", "in", "the", "libyajl2", "-", "gem", "and", "attempt", "to", "load", "them", ".", "If", "they", "are", "missing", "just", "use", "ffi_lib", "yajl", "to", "accept", "the", "FFI", "default", "algorithm", "to", "find", "the", "library", "." ]
4b001a89c8c63ef7b39c7fb30a63061add9a44d5
https://github.com/chef/ffi-yajl/blob/4b001a89c8c63ef7b39c7fb30a63061add9a44d5/lib/ffi_yajl/map_library_name.rb#L97-L107
train
cookpad/grpc_kit
lib/grpc_kit/server.rb
GrpcKit.Server.graceful_shutdown
def graceful_shutdown(timeout: true) @stopping = true Thread.new do GrpcKit.logger.debug('graceful shutdown') @mutex.synchronize { @sessions.each(&:drain) } begin sec = timeout ? @shutdown_timeout : 0 Timeout.timeout(sec) do sleep 1 until @sessions.empty? end rescue Timeout::Error => _ GrpcKit.logger.error("Graceful shutdown is timeout (#{@shutdown_timeout}sec). Perform shutdown forceibly") shutdown_sessions end end end
ruby
def graceful_shutdown(timeout: true) @stopping = true Thread.new do GrpcKit.logger.debug('graceful shutdown') @mutex.synchronize { @sessions.each(&:drain) } begin sec = timeout ? @shutdown_timeout : 0 Timeout.timeout(sec) do sleep 1 until @sessions.empty? end rescue Timeout::Error => _ GrpcKit.logger.error("Graceful shutdown is timeout (#{@shutdown_timeout}sec). Perform shutdown forceibly") shutdown_sessions end end end
[ "def", "graceful_shutdown", "(", "timeout", ":", "true", ")", "@stopping", "=", "true", "Thread", ".", "new", "do", "GrpcKit", ".", "logger", ".", "debug", "(", "'graceful shutdown'", ")", "@mutex", ".", "synchronize", "{", "@sessions", ".", "each", "(", ":drain", ")", "}", "begin", "sec", "=", "timeout", "?", "@shutdown_timeout", ":", "0", "Timeout", ".", "timeout", "(", "sec", ")", "do", "sleep", "1", "until", "@sessions", ".", "empty?", "end", "rescue", "Timeout", "::", "Error", "=>", "_", "GrpcKit", ".", "logger", ".", "error", "(", "\"Graceful shutdown is timeout (#{@shutdown_timeout}sec). Perform shutdown forceibly\"", ")", "shutdown_sessions", "end", "end", "end" ]
This method is expected to be called in trap context @params timeout [Boolean] timeout error could be raised or not @return [void]
[ "This", "method", "is", "expected", "to", "be", "called", "in", "trap", "context" ]
bc5180e4d05c68c3f85a823418951ef2e22bbb0c
https://github.com/cookpad/grpc_kit/blob/bc5180e4d05c68c3f85a823418951ef2e22bbb0c/lib/grpc_kit/server.rb#L69-L86
train
whitequark/ast
lib/ast/node.rb
AST.Node.updated
def updated(type=nil, children=nil, properties=nil) new_type = type || @type new_children = children || @children new_properties = properties || {} if @type == new_type && @children == new_children && properties.nil? self else original_dup.send :initialize, new_type, new_children, new_properties end end
ruby
def updated(type=nil, children=nil, properties=nil) new_type = type || @type new_children = children || @children new_properties = properties || {} if @type == new_type && @children == new_children && properties.nil? self else original_dup.send :initialize, new_type, new_children, new_properties end end
[ "def", "updated", "(", "type", "=", "nil", ",", "children", "=", "nil", ",", "properties", "=", "nil", ")", "new_type", "=", "type", "||", "@type", "new_children", "=", "children", "||", "@children", "new_properties", "=", "properties", "||", "{", "}", "if", "@type", "==", "new_type", "&&", "@children", "==", "new_children", "&&", "properties", ".", "nil?", "self", "else", "original_dup", ".", "send", ":initialize", ",", "new_type", ",", "new_children", ",", "new_properties", "end", "end" ]
Returns a new instance of Node where non-nil arguments replace the corresponding fields of `self`. For example, `Node.new(:foo, [ 1, 2 ]).updated(:bar)` would yield `(bar 1 2)`, and `Node.new(:foo, [ 1, 2 ]).updated(nil, [])` would yield `(foo)`. If the resulting node would be identical to `self`, does nothing. @param [Symbol, nil] type @param [Array, nil] children @param [Hash, nil] properties @return [AST::Node]
[ "Returns", "a", "new", "instance", "of", "Node", "where", "non", "-", "nil", "arguments", "replace", "the", "corresponding", "fields", "of", "self", "." ]
50ff345ab7152bf513865b88e03664570942318b
https://github.com/whitequark/ast/blob/50ff345ab7152bf513865b88e03664570942318b/lib/ast/node.rb#L133-L145
train
whitequark/ast
lib/ast/node.rb
AST.Node.to_sexp
def to_sexp(indent=0) indented = " " * indent sexp = "#{indented}(#{fancy_type}" children.each do |child| if child.is_a?(Node) sexp += "\n#{child.to_sexp(indent + 1)}" else sexp += " #{child.inspect}" end end sexp += ")" sexp end
ruby
def to_sexp(indent=0) indented = " " * indent sexp = "#{indented}(#{fancy_type}" children.each do |child| if child.is_a?(Node) sexp += "\n#{child.to_sexp(indent + 1)}" else sexp += " #{child.inspect}" end end sexp += ")" sexp end
[ "def", "to_sexp", "(", "indent", "=", "0", ")", "indented", "=", "\" \"", "*", "indent", "sexp", "=", "\"#{indented}(#{fancy_type}\"", "children", ".", "each", "do", "|", "child", "|", "if", "child", ".", "is_a?", "(", "Node", ")", "sexp", "+=", "\"\\n#{child.to_sexp(indent + 1)}\"", "else", "sexp", "+=", "\" #{child.inspect}\"", "end", "end", "sexp", "+=", "\")\"", "sexp", "end" ]
Converts `self` to a pretty-printed s-expression. @param [Integer] indent Base indentation level. @return [String]
[ "Converts", "self", "to", "a", "pretty", "-", "printed", "s", "-", "expression", "." ]
50ff345ab7152bf513865b88e03664570942318b
https://github.com/whitequark/ast/blob/50ff345ab7152bf513865b88e03664570942318b/lib/ast/node.rb#L185-L200
train
whitequark/ast
lib/ast/node.rb
AST.Node.to_sexp_array
def to_sexp_array children_sexp_arrs = children.map do |child| if child.is_a?(Node) child.to_sexp_array else child end end [type, *children_sexp_arrs] end
ruby
def to_sexp_array children_sexp_arrs = children.map do |child| if child.is_a?(Node) child.to_sexp_array else child end end [type, *children_sexp_arrs] end
[ "def", "to_sexp_array", "children_sexp_arrs", "=", "children", ".", "map", "do", "|", "child", "|", "if", "child", ".", "is_a?", "(", "Node", ")", "child", ".", "to_sexp_array", "else", "child", "end", "end", "[", "type", ",", "children_sexp_arrs", "]", "end" ]
Converts `self` to an Array where the first element is the type as a Symbol, and subsequent elements are the same representation of its children. @return [Array<Symbol, [...Array]>]
[ "Converts", "self", "to", "an", "Array", "where", "the", "first", "element", "is", "the", "type", "as", "a", "Symbol", "and", "subsequent", "elements", "are", "the", "same", "representation", "of", "its", "children", "." ]
50ff345ab7152bf513865b88e03664570942318b
https://github.com/whitequark/ast/blob/50ff345ab7152bf513865b88e03664570942318b/lib/ast/node.rb#L235-L245
train
stitchfix/pwwka
lib/pwwka/configuration.rb
Pwwka.Configuration.payload_parser
def payload_parser @payload_parser ||= if @receive_raw_payload ->(payload) { payload } else ->(payload) { ActiveSupport::HashWithIndifferentAccess.new(JSON.parse(payload)) } end end
ruby
def payload_parser @payload_parser ||= if @receive_raw_payload ->(payload) { payload } else ->(payload) { ActiveSupport::HashWithIndifferentAccess.new(JSON.parse(payload)) } end end
[ "def", "payload_parser", "@payload_parser", "||=", "if", "@receive_raw_payload", "->", "(", "payload", ")", "{", "payload", "}", "else", "->", "(", "payload", ")", "{", "ActiveSupport", "::", "HashWithIndifferentAccess", ".", "new", "(", "JSON", ".", "parse", "(", "payload", ")", ")", "}", "end", "end" ]
Returns a proc that, when called with the payload, parses it according to the configuration. By default, this will assume the payload is JSON, parse it, and return a HashWithIndifferentAccess.
[ "Returns", "a", "proc", "that", "when", "called", "with", "the", "payload", "parses", "it", "according", "to", "the", "configuration", "." ]
581a5261cabaa3e97cfe286da33ce80ffa2d750a
https://github.com/stitchfix/pwwka/blob/581a5261cabaa3e97cfe286da33ce80ffa2d750a/lib/pwwka/configuration.rb#L131-L139
train
stitchfix/pwwka
lib/pwwka/configuration.rb
Pwwka.Configuration.omit_payload_from_log?
def omit_payload_from_log?(level_of_message_with_payload) return true if @receive_raw_payload Pwwka::Logging::LEVELS[Pwwka.configuration.payload_logging.to_sym] > Pwwka::Logging::LEVELS[level_of_message_with_payload.to_sym] end
ruby
def omit_payload_from_log?(level_of_message_with_payload) return true if @receive_raw_payload Pwwka::Logging::LEVELS[Pwwka.configuration.payload_logging.to_sym] > Pwwka::Logging::LEVELS[level_of_message_with_payload.to_sym] end
[ "def", "omit_payload_from_log?", "(", "level_of_message_with_payload", ")", "return", "true", "if", "@receive_raw_payload", "Pwwka", "::", "Logging", "::", "LEVELS", "[", "Pwwka", ".", "configuration", ".", "payload_logging", ".", "to_sym", "]", ">", "Pwwka", "::", "Logging", "::", "LEVELS", "[", "level_of_message_with_payload", ".", "to_sym", "]", "end" ]
True if we should omit the payload from the log ::level_of_message_with_payload the level of the message about to be logged
[ "True", "if", "we", "should", "omit", "the", "payload", "from", "the", "log" ]
581a5261cabaa3e97cfe286da33ce80ffa2d750a
https://github.com/stitchfix/pwwka/blob/581a5261cabaa3e97cfe286da33ce80ffa2d750a/lib/pwwka/configuration.rb#L144-L147
train
AirHelp/danger-duplicate_localizable_strings
lib/duplicate_localizable_strings/plugin.rb
Danger.DangerDuplicateLocalizableStrings.localizable_duplicate_entries
def localizable_duplicate_entries localizable_files = (git.modified_files + git.added_files) - git.deleted_files localizable_files.select! { |line| line.end_with?('.strings') } duplicate_entries = [] localizable_files.each do |file| lines = File.readlines(file) # Grab just the keys, translations might be different keys = lines.map { |e| e.split('=').first } # Filter newlines and comments keys = keys.select do |e| e != "\n" && !e.start_with?('/*') && !e.start_with?('//') end # Grab keys that appear more than once duplicate_keys = keys.select { |e| keys.rindex(e) != keys.index(e) } # And make sure we have one entry per duplicate key duplicate_keys = duplicate_keys.uniq duplicate_keys.each do |key| duplicate_entries << { 'file' => file, 'key' => key } end end duplicate_entries end
ruby
def localizable_duplicate_entries localizable_files = (git.modified_files + git.added_files) - git.deleted_files localizable_files.select! { |line| line.end_with?('.strings') } duplicate_entries = [] localizable_files.each do |file| lines = File.readlines(file) # Grab just the keys, translations might be different keys = lines.map { |e| e.split('=').first } # Filter newlines and comments keys = keys.select do |e| e != "\n" && !e.start_with?('/*') && !e.start_with?('//') end # Grab keys that appear more than once duplicate_keys = keys.select { |e| keys.rindex(e) != keys.index(e) } # And make sure we have one entry per duplicate key duplicate_keys = duplicate_keys.uniq duplicate_keys.each do |key| duplicate_entries << { 'file' => file, 'key' => key } end end duplicate_entries end
[ "def", "localizable_duplicate_entries", "localizable_files", "=", "(", "git", ".", "modified_files", "+", "git", ".", "added_files", ")", "-", "git", ".", "deleted_files", "localizable_files", ".", "select!", "{", "|", "line", "|", "line", ".", "end_with?", "(", "'.strings'", ")", "}", "duplicate_entries", "=", "[", "]", "localizable_files", ".", "each", "do", "|", "file", "|", "lines", "=", "File", ".", "readlines", "(", "file", ")", "# Grab just the keys, translations might be different", "keys", "=", "lines", ".", "map", "{", "|", "e", "|", "e", ".", "split", "(", "'='", ")", ".", "first", "}", "# Filter newlines and comments", "keys", "=", "keys", ".", "select", "do", "|", "e", "|", "e", "!=", "\"\\n\"", "&&", "!", "e", ".", "start_with?", "(", "'/*'", ")", "&&", "!", "e", ".", "start_with?", "(", "'//'", ")", "end", "# Grab keys that appear more than once", "duplicate_keys", "=", "keys", ".", "select", "{", "|", "e", "|", "keys", ".", "rindex", "(", "e", ")", "!=", "keys", ".", "index", "(", "e", ")", "}", "# And make sure we have one entry per duplicate key", "duplicate_keys", "=", "duplicate_keys", ".", "uniq", "duplicate_keys", ".", "each", "do", "|", "key", "|", "duplicate_entries", "<<", "{", "'file'", "=>", "file", ",", "'key'", "=>", "key", "}", "end", "end", "duplicate_entries", "end" ]
Returns an array of all detected duplicate entries. An entry is represented by a has with file path under 'file' key and the Localizable.strings key under 'key' key. @return [Array of duplicate Localizable.strings entries]
[ "Returns", "an", "array", "of", "all", "detected", "duplicate", "entries", ".", "An", "entry", "is", "represented", "by", "a", "has", "with", "file", "path", "under", "file", "key", "and", "the", "Localizable", ".", "strings", "key", "under", "key", "key", "." ]
155d82a64bb280d277d9656d2afa2541b0883006
https://github.com/AirHelp/danger-duplicate_localizable_strings/blob/155d82a64bb280d277d9656d2afa2541b0883006/lib/duplicate_localizable_strings/plugin.rb#L20-L47
train
nbulaj/proxy_fetcher
lib/proxy_fetcher/document.rb
ProxyFetcher.Document.xpath
def xpath(*args) backend.xpath(*args).map { |node| backend.proxy_node.new(node) } end
ruby
def xpath(*args) backend.xpath(*args).map { |node| backend.proxy_node.new(node) } end
[ "def", "xpath", "(", "*", "args", ")", "backend", ".", "xpath", "(", "args", ")", ".", "map", "{", "|", "node", "|", "backend", ".", "proxy_node", ".", "new", "(", "node", ")", "}", "end" ]
Initialize abstract ProxyFetcher HTML Document @return [Document] Searches elements by XPath selector. @return [Array<ProxyFetcher::Document::Node>] collection of nodes
[ "Initialize", "abstract", "ProxyFetcher", "HTML", "Document" ]
da2e067acd930886d894490e229ba094f7f5ea53
https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/document.rb#L36-L38
train
nbulaj/proxy_fetcher
lib/proxy_fetcher/document.rb
ProxyFetcher.Document.css
def css(*args) backend.css(*args).map { |node| backend.proxy_node.new(node) } end
ruby
def css(*args) backend.css(*args).map { |node| backend.proxy_node.new(node) } end
[ "def", "css", "(", "*", "args", ")", "backend", ".", "css", "(", "args", ")", ".", "map", "{", "|", "node", "|", "backend", ".", "proxy_node", ".", "new", "(", "node", ")", "}", "end" ]
Searches elements by CSS selector. @return [Array<ProxyFetcher::Document::Node>] collection of nodes
[ "Searches", "elements", "by", "CSS", "selector", "." ]
da2e067acd930886d894490e229ba094f7f5ea53
https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/document.rb#L45-L47
train
nbulaj/proxy_fetcher
lib/proxy_fetcher/utils/proxy_validator.rb
ProxyFetcher.ProxyValidator.connectable?
def connectable? ssl_context = OpenSSL::SSL::SSLContext.new ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE @http.head(URL_TO_CHECK, ssl_context: ssl_context).status.success? rescue StandardError false end
ruby
def connectable? ssl_context = OpenSSL::SSL::SSLContext.new ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE @http.head(URL_TO_CHECK, ssl_context: ssl_context).status.success? rescue StandardError false end
[ "def", "connectable?", "ssl_context", "=", "OpenSSL", "::", "SSL", "::", "SSLContext", ".", "new", "ssl_context", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "@http", ".", "head", "(", "URL_TO_CHECK", ",", "ssl_context", ":", "ssl_context", ")", ".", "status", ".", "success?", "rescue", "StandardError", "false", "end" ]
Initialize new ProxyValidator instance @param proxy_addr [String] proxy address or IP @param proxy_port [String, Integer] proxy port @return [ProxyValidator] Checks if proxy is connectable (can be used to connect resources via proxy server). @return [Boolean] true if connection to the server using proxy established, otherwise false
[ "Initialize", "new", "ProxyValidator", "instance" ]
da2e067acd930886d894490e229ba094f7f5ea53
https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/utils/proxy_validator.rb#L42-L49
train
nbulaj/proxy_fetcher
lib/proxy_fetcher/configuration/providers_registry.rb
ProxyFetcher.ProvidersRegistry.class_for
def class_for(provider_name) provider_name = provider_name.to_sym providers.fetch(provider_name) rescue KeyError raise ProxyFetcher::Exceptions::UnknownProvider, provider_name end
ruby
def class_for(provider_name) provider_name = provider_name.to_sym providers.fetch(provider_name) rescue KeyError raise ProxyFetcher::Exceptions::UnknownProvider, provider_name end
[ "def", "class_for", "(", "provider_name", ")", "provider_name", "=", "provider_name", ".", "to_sym", "providers", ".", "fetch", "(", "provider_name", ")", "rescue", "KeyError", "raise", "ProxyFetcher", "::", "Exceptions", "::", "UnknownProvider", ",", "provider_name", "end" ]
Returns a class for specific provider if it is registered in the registry. Otherwise throws an exception. @param provider_name [String, Symbol] provider name @return [Class] provider class @raise [ProxyFetcher::Exceptions::UnknownProvider] provider is unknown
[ "Returns", "a", "class", "for", "specific", "provider", "if", "it", "is", "registered", "in", "the", "registry", ".", "Otherwise", "throws", "an", "exception", "." ]
da2e067acd930886d894490e229ba094f7f5ea53
https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/configuration/providers_registry.rb#L47-L53
train
nbulaj/proxy_fetcher
lib/proxy_fetcher/configuration.rb
ProxyFetcher.Configuration.setup_custom_class
def setup_custom_class(klass, required_methods: []) unless klass.respond_to?(*required_methods) raise ProxyFetcher::Exceptions::WrongCustomClass.new(klass, required_methods) end klass end
ruby
def setup_custom_class(klass, required_methods: []) unless klass.respond_to?(*required_methods) raise ProxyFetcher::Exceptions::WrongCustomClass.new(klass, required_methods) end klass end
[ "def", "setup_custom_class", "(", "klass", ",", "required_methods", ":", "[", "]", ")", "unless", "klass", ".", "respond_to?", "(", "required_methods", ")", "raise", "ProxyFetcher", "::", "Exceptions", "::", "WrongCustomClass", ".", "new", "(", "klass", ",", "required_methods", ")", "end", "klass", "end" ]
Checks if custom class has some required class methods
[ "Checks", "if", "custom", "class", "has", "some", "required", "class", "methods" ]
da2e067acd930886d894490e229ba094f7f5ea53
https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/configuration.rb#L175-L181
train
nbulaj/proxy_fetcher
lib/proxy_fetcher/utils/http_client.rb
ProxyFetcher.HTTPClient.fetch
def fetch response = process_http_request response.body.to_s rescue StandardError => error ProxyFetcher.logger.warn("Failed to process request to #{url} (#{error.message})") '' end
ruby
def fetch response = process_http_request response.body.to_s rescue StandardError => error ProxyFetcher.logger.warn("Failed to process request to #{url} (#{error.message})") '' end
[ "def", "fetch", "response", "=", "process_http_request", "response", ".", "body", ".", "to_s", "rescue", "StandardError", "=>", "error", "ProxyFetcher", ".", "logger", ".", "warn", "(", "\"Failed to process request to #{url} (#{error.message})\"", ")", "''", "end" ]
Initialize HTTP client instance @return [HTTPClient] Fetches resource content by sending HTTP request to it. @return [String] response body
[ "Initialize", "HTTP", "client", "instance" ]
da2e067acd930886d894490e229ba094f7f5ea53
https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/utils/http_client.rb#L70-L76
train
nbulaj/proxy_fetcher
lib/proxy_fetcher/manager.rb
ProxyFetcher.Manager.refresh_list!
def refresh_list!(filters = nil) @proxies = [] threads = [] lock = Mutex.new ProxyFetcher.config.providers.each do |provider_name| threads << Thread.new do provider = ProxyFetcher::Configuration.providers_registry.class_for(provider_name) provider_filters = filters && filters.fetch(provider_name.to_sym, filters) provider_proxies = provider.fetch_proxies!(provider_filters) lock.synchronize do @proxies.concat(provider_proxies) end end end threads.each(&:join) @proxies end
ruby
def refresh_list!(filters = nil) @proxies = [] threads = [] lock = Mutex.new ProxyFetcher.config.providers.each do |provider_name| threads << Thread.new do provider = ProxyFetcher::Configuration.providers_registry.class_for(provider_name) provider_filters = filters && filters.fetch(provider_name.to_sym, filters) provider_proxies = provider.fetch_proxies!(provider_filters) lock.synchronize do @proxies.concat(provider_proxies) end end end threads.each(&:join) @proxies end
[ "def", "refresh_list!", "(", "filters", "=", "nil", ")", "@proxies", "=", "[", "]", "threads", "=", "[", "]", "lock", "=", "Mutex", ".", "new", "ProxyFetcher", ".", "config", ".", "providers", ".", "each", "do", "|", "provider_name", "|", "threads", "<<", "Thread", ".", "new", "do", "provider", "=", "ProxyFetcher", "::", "Configuration", ".", "providers_registry", ".", "class_for", "(", "provider_name", ")", "provider_filters", "=", "filters", "&&", "filters", ".", "fetch", "(", "provider_name", ".", "to_sym", ",", "filters", ")", "provider_proxies", "=", "provider", ".", "fetch_proxies!", "(", "provider_filters", ")", "lock", ".", "synchronize", "do", "@proxies", ".", "concat", "(", "provider_proxies", ")", "end", "end", "end", "threads", ".", "each", "(", ":join", ")", "@proxies", "end" ]
Initialize ProxyFetcher Manager instance for managing proxies refresh: true - load proxy list from the remote server on initialization refresh: false - just initialize the class, proxy list will be empty ([]) @return [Manager] Update current proxy list using configured providers. @param filters [Hash] providers filters
[ "Initialize", "ProxyFetcher", "Manager", "instance", "for", "managing", "proxies" ]
da2e067acd930886d894490e229ba094f7f5ea53
https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/manager.rb#L31-L52
train
zeisler/active_mocker
lib/active_mocker/mock/queries.rb
ActiveMocker.Queries.delete_all
def delete_all(conditions = nil) check_for_limit_scope! collection = conditions.nil? ? to_a.each(&:delete).clear : where(conditions) collection.map(&:delete).count end
ruby
def delete_all(conditions = nil) check_for_limit_scope! collection = conditions.nil? ? to_a.each(&:delete).clear : where(conditions) collection.map(&:delete).count end
[ "def", "delete_all", "(", "conditions", "=", "nil", ")", "check_for_limit_scope!", "collection", "=", "conditions", ".", "nil?", "?", "to_a", ".", "each", "(", ":delete", ")", ".", "clear", ":", "where", "(", "conditions", ")", "collection", ".", "map", "(", ":delete", ")", ".", "count", "end" ]
Deletes the records matching +conditions+ by instantiating each record and calling its +delete+ method. ==== Parameters * +conditions+ - A string, array, or hash that specifies which records to destroy. If omitted, all records are destroyed. ==== Examples PersonMock.destroy_all(status: "inactive") PersonMock.where(age: 0..18).destroy_all If a limit scope is supplied, +delete_all+ raises an ActiveMocker error: Post.limit(100).delete_all # => ActiveMocker::Error: delete_all doesn't support limit scope
[ "Deletes", "the", "records", "matching", "+", "conditions", "+", "by", "instantiating", "each", "record", "and", "calling", "its", "+", "delete", "+", "method", "." ]
bb03387df80708817de2f4d7fc9ca2d3f4b161c3
https://github.com/zeisler/active_mocker/blob/bb03387df80708817de2f4d7fc9ca2d3f4b161c3/lib/active_mocker/mock/queries.rb#L62-L67
train
zeisler/active_mocker
lib/active_mocker/mock/queries.rb
ActiveMocker.Queries.find_by
def find_by(conditions = {}) to_a.detect do |record| Find.new(record).is_of(conditions) end end
ruby
def find_by(conditions = {}) to_a.detect do |record| Find.new(record).is_of(conditions) end end
[ "def", "find_by", "(", "conditions", "=", "{", "}", ")", "to_a", ".", "detect", "do", "|", "record", "|", "Find", ".", "new", "(", "record", ")", ".", "is_of", "(", "conditions", ")", "end", "end" ]
Finds the first record matching the specified conditions. There is no implied ordering so if order matters, you should specify it yourself. If no record is found, returns <tt>nil</tt>. Post.find_by name: 'Spartacus', rating: 4
[ "Finds", "the", "first", "record", "matching", "the", "specified", "conditions", ".", "There", "is", "no", "implied", "ordering", "so", "if", "order", "matters", "you", "should", "specify", "it", "yourself", "." ]
bb03387df80708817de2f4d7fc9ca2d3f4b161c3
https://github.com/zeisler/active_mocker/blob/bb03387df80708817de2f4d7fc9ca2d3f4b161c3/lib/active_mocker/mock/queries.rb#L192-L196
train
zeisler/active_mocker
lib/active_mocker/mock/queries.rb
ActiveMocker.Queries.limit
def limit(num) relation = __new_relation__(all.take(num)) relation.send(:set_from_limit) relation end
ruby
def limit(num) relation = __new_relation__(all.take(num)) relation.send(:set_from_limit) relation end
[ "def", "limit", "(", "num", ")", "relation", "=", "__new_relation__", "(", "all", ".", "take", "(", "num", ")", ")", "relation", ".", "send", "(", ":set_from_limit", ")", "relation", "end" ]
Specifies a limit for the number of records to retrieve. User.limit(10)
[ "Specifies", "a", "limit", "for", "the", "number", "of", "records", "to", "retrieve", "." ]
bb03387df80708817de2f4d7fc9ca2d3f4b161c3
https://github.com/zeisler/active_mocker/blob/bb03387df80708817de2f4d7fc9ca2d3f4b161c3/lib/active_mocker/mock/queries.rb#L268-L272
train
zeisler/active_mocker
lib/active_mocker/mock/queries.rb
ActiveMocker.Queries.sum
def sum(key) values = values_by_key(key) values.inject(0) do |sum, n| sum + (n || 0) end end
ruby
def sum(key) values = values_by_key(key) values.inject(0) do |sum, n| sum + (n || 0) end end
[ "def", "sum", "(", "key", ")", "values", "=", "values_by_key", "(", "key", ")", "values", ".", "inject", "(", "0", ")", "do", "|", "sum", ",", "n", "|", "sum", "+", "(", "n", "||", "0", ")", "end", "end" ]
Calculates the sum of values on a given column. The value is returned with the same data type of the column, 0 if there's no row. Person.sum(:age) # => 4562
[ "Calculates", "the", "sum", "of", "values", "on", "a", "given", "column", ".", "The", "value", "is", "returned", "with", "the", "same", "data", "type", "of", "the", "column", "0", "if", "there", "s", "no", "row", "." ]
bb03387df80708817de2f4d7fc9ca2d3f4b161c3
https://github.com/zeisler/active_mocker/blob/bb03387df80708817de2f4d7fc9ca2d3f4b161c3/lib/active_mocker/mock/queries.rb#L278-L283
train
zeisler/active_mocker
lib/active_mocker/mock/queries.rb
ActiveMocker.Queries.average
def average(key) values = values_by_key(key) total = values.inject { |sum, n| sum + n } BigDecimal.new(total) / BigDecimal.new(values.count) end
ruby
def average(key) values = values_by_key(key) total = values.inject { |sum, n| sum + n } BigDecimal.new(total) / BigDecimal.new(values.count) end
[ "def", "average", "(", "key", ")", "values", "=", "values_by_key", "(", "key", ")", "total", "=", "values", ".", "inject", "{", "|", "sum", ",", "n", "|", "sum", "+", "n", "}", "BigDecimal", ".", "new", "(", "total", ")", "/", "BigDecimal", ".", "new", "(", "values", ".", "count", ")", "end" ]
Calculates the average value on a given column. Returns +nil+ if there's no row. PersonMock.average(:age) # => 35.8
[ "Calculates", "the", "average", "value", "on", "a", "given", "column", ".", "Returns", "+", "nil", "+", "if", "there", "s", "no", "row", "." ]
bb03387df80708817de2f4d7fc9ca2d3f4b161c3
https://github.com/zeisler/active_mocker/blob/bb03387df80708817de2f4d7fc9ca2d3f4b161c3/lib/active_mocker/mock/queries.rb#L289-L293
train
zeisler/active_mocker
lib/active_mocker/mock/base.rb
ActiveMocker.Base.slice
def slice(*methods) Hash[methods.map! { |method| [method, public_send(method)] }].with_indifferent_access end
ruby
def slice(*methods) Hash[methods.map! { |method| [method, public_send(method)] }].with_indifferent_access end
[ "def", "slice", "(", "*", "methods", ")", "Hash", "[", "methods", ".", "map!", "{", "|", "method", "|", "[", "method", ",", "public_send", "(", "method", ")", "]", "}", "]", ".", "with_indifferent_access", "end" ]
Returns a hash of the given methods with their names as keys and returned values as values.
[ "Returns", "a", "hash", "of", "the", "given", "methods", "with", "their", "names", "as", "keys", "and", "returned", "values", "as", "values", "." ]
bb03387df80708817de2f4d7fc9ca2d3f4b161c3
https://github.com/zeisler/active_mocker/blob/bb03387df80708817de2f4d7fc9ca2d3f4b161c3/lib/active_mocker/mock/base.rb#L322-L324
train
diogot/danger-xcode_summary
lib/xcode_summary/plugin.rb
Danger.DangerXcodeSummary.warning_error_count
def warning_error_count(file_path) if File.file?(file_path) xcode_summary = JSON.parse(File.read(file_path), symbolize_names: true) warning_count = warnings(xcode_summary).count error_count = errors(xcode_summary).count result = { warnings: warning_count, errors: error_count } result.to_json else fail 'summary file not found' end end
ruby
def warning_error_count(file_path) if File.file?(file_path) xcode_summary = JSON.parse(File.read(file_path), symbolize_names: true) warning_count = warnings(xcode_summary).count error_count = errors(xcode_summary).count result = { warnings: warning_count, errors: error_count } result.to_json else fail 'summary file not found' end end
[ "def", "warning_error_count", "(", "file_path", ")", "if", "File", ".", "file?", "(", "file_path", ")", "xcode_summary", "=", "JSON", ".", "parse", "(", "File", ".", "read", "(", "file_path", ")", ",", "symbolize_names", ":", "true", ")", "warning_count", "=", "warnings", "(", "xcode_summary", ")", ".", "count", "error_count", "=", "errors", "(", "xcode_summary", ")", ".", "count", "result", "=", "{", "warnings", ":", "warning_count", ",", "errors", ":", "error_count", "}", "result", ".", "to_json", "else", "fail", "'summary file not found'", "end", "end" ]
Reads a file with JSON Xcode summary and reports its warning and error count. @param [String] file_path Path for Xcode summary in JSON format. @return [String] JSON string with warningCount and errorCount
[ "Reads", "a", "file", "with", "JSON", "Xcode", "summary", "and", "reports", "its", "warning", "and", "error", "count", "." ]
661bd0318e4dc719267422331def569088dde7bd
https://github.com/diogot/danger-xcode_summary/blob/661bd0318e4dc719267422331def569088dde7bd/lib/xcode_summary/plugin.rb#L118-L128
train
tom-lord/regexp-examples
lib/regexp-examples/groups.rb
RegexpExamples.MultiGroup.result
def result strings = @groups.map { |repeater| repeater.public_send(__callee__) } RegexpExamples.permutations_of_strings(strings).map do |result| GroupResult.new(result, group_id) end end
ruby
def result strings = @groups.map { |repeater| repeater.public_send(__callee__) } RegexpExamples.permutations_of_strings(strings).map do |result| GroupResult.new(result, group_id) end end
[ "def", "result", "strings", "=", "@groups", ".", "map", "{", "|", "repeater", "|", "repeater", ".", "public_send", "(", "__callee__", ")", "}", "RegexpExamples", ".", "permutations_of_strings", "(", "strings", ")", ".", "map", "do", "|", "result", "|", "GroupResult", ".", "new", "(", "result", ",", "group_id", ")", "end", "end" ]
Generates the result of each contained group and adds the filled group of each result to itself
[ "Generates", "the", "result", "of", "each", "contained", "group", "and", "adds", "the", "filled", "group", "of", "each", "result", "to", "itself" ]
90229731daf8a40bf34b739a12e403d2bc45d272
https://github.com/tom-lord/regexp-examples/blob/90229731daf8a40bf34b739a12e403d2bc45d272/lib/regexp-examples/groups.rb#L127-L132
train
Fullscreen/bh
lib/bh/helpers/button_helper.rb
Bh.Helpers.button
def button(*args, &block) button = Bh::Button.new(self, *args, &block) button.extract! :context, :size, :layout button.append_class! :btn button.append_class! button.context_class button.append_class! button.size_class button.append_class! button.layout_class button.render_tag :button end
ruby
def button(*args, &block) button = Bh::Button.new(self, *args, &block) button.extract! :context, :size, :layout button.append_class! :btn button.append_class! button.context_class button.append_class! button.size_class button.append_class! button.layout_class button.render_tag :button end
[ "def", "button", "(", "*", "args", ",", "&", "block", ")", "button", "=", "Bh", "::", "Button", ".", "new", "(", "self", ",", "args", ",", "block", ")", "button", ".", "extract!", ":context", ",", ":size", ",", ":layout", "button", ".", "append_class!", ":btn", "button", ".", "append_class!", "button", ".", "context_class", "button", ".", "append_class!", "button", ".", "size_class", "button", ".", "append_class!", "button", ".", "layout_class", "button", ".", "render_tag", ":button", "end" ]
Displays a Bootstrap-styled button. @see http://getbootstrap.com/css/#buttons @return [String] the HTML to display a Bootstrap-styled button. @overload button(caption, options = {}) @param [#to_s] caption the caption to display in the button. @param [Hash] options the options for the button. Any option not listed below is passed as an HTML attribute to the `<button>` tag. @option options [#to_s] :context (:default) the contextual alternative to apply to the button. Can be `:danger`, `:info`, `:link`, `:primary`, `:success` or `:warning`. @option options [#to_s] :size the size of the button. Can be `:extra_small` (alias `:xs`), `:large` (alias `:lg`) or `:small` (alias `:sm`). @option options [#to_s] :layout if set to `:block`, span the button for the full width of the parent. @example Display a button styled as a link. button 'Click here', context: :link @overload button(options = {}, &block) @param [Hash] options the options for the button (see above). @yieldreturn [#to_s] the caption to display in the button. @example Display a button with an HTML caption. button do content_tag :strong, 'Click here' end
[ "Displays", "a", "Bootstrap", "-", "styled", "button", "." ]
b9ad77bf9435dfbc4522958ea9a81415418433e6
https://github.com/Fullscreen/bh/blob/b9ad77bf9435dfbc4522958ea9a81415418433e6/lib/bh/helpers/button_helper.rb#L29-L38
train
Fullscreen/bh
lib/bh/helpers/panel_row_helper.rb
Bh.Helpers.panel_row
def panel_row(options = {}, &block) panel_row = Bh::PanelRow.new self, options, &block panel_row.extract! :column_class panel_row.append_class! :row panel_row.render_tag :div end
ruby
def panel_row(options = {}, &block) panel_row = Bh::PanelRow.new self, options, &block panel_row.extract! :column_class panel_row.append_class! :row panel_row.render_tag :div end
[ "def", "panel_row", "(", "options", "=", "{", "}", ",", "&", "block", ")", "panel_row", "=", "Bh", "::", "PanelRow", ".", "new", "self", ",", "options", ",", "block", "panel_row", ".", "extract!", ":column_class", "panel_row", ".", "append_class!", ":row", "panel_row", ".", "render_tag", ":div", "end" ]
Wraps a set of Bootstrap-styled panels in a row. @see http://getbootstrap.com/components/#panels @see http://getbootstrap.com/css/#grid @return [String] the HTML to display a row of Bootstrap-styled panels. @param [Hash] options the options for the row. Any option not listed below is passed as an HTML attribute to the row’s `<div>`. @option options [#to_s] :column_class the class to wrap each panel with. Useful to specify a grid size for the column such as 'col-sm-4' to indicate how many columns of the row each panel should occupy. @yieldreturn [#to_s] the panels to display in a row. @example Display a row of two panels with the same width. panel_row column_class: 'col-sm-6' do panel 'Panel #1', context: :success panel 'Panel #2', context: :info end
[ "Wraps", "a", "set", "of", "Bootstrap", "-", "styled", "panels", "in", "a", "row", "." ]
b9ad77bf9435dfbc4522958ea9a81415418433e6
https://github.com/Fullscreen/bh/blob/b9ad77bf9435dfbc4522958ea9a81415418433e6/lib/bh/helpers/panel_row_helper.rb#L20-L26
train
Fullscreen/bh
lib/bh/helpers/panel_helper.rb
Bh.Helpers.panel
def panel(*args, &block) panel = Bh::Panel.new self, *args, &block panel.extract! :body, :context, :title, :heading, :tag panel.append_class! :panel panel.append_class! panel.context_class panel.merge_html! panel.body panel.prepend_html! panel.heading if panel_row = Bh::Stack.find(Bh::PanelRow) container = Bh::Base.new(self) { panel.content_tag panel.tag } container.append_class! panel_row.column_class container.render_tag :div else panel.render_tag panel.tag end end
ruby
def panel(*args, &block) panel = Bh::Panel.new self, *args, &block panel.extract! :body, :context, :title, :heading, :tag panel.append_class! :panel panel.append_class! panel.context_class panel.merge_html! panel.body panel.prepend_html! panel.heading if panel_row = Bh::Stack.find(Bh::PanelRow) container = Bh::Base.new(self) { panel.content_tag panel.tag } container.append_class! panel_row.column_class container.render_tag :div else panel.render_tag panel.tag end end
[ "def", "panel", "(", "*", "args", ",", "&", "block", ")", "panel", "=", "Bh", "::", "Panel", ".", "new", "self", ",", "args", ",", "block", "panel", ".", "extract!", ":body", ",", ":context", ",", ":title", ",", ":heading", ",", ":tag", "panel", ".", "append_class!", ":panel", "panel", ".", "append_class!", "panel", ".", "context_class", "panel", ".", "merge_html!", "panel", ".", "body", "panel", ".", "prepend_html!", "panel", ".", "heading", "if", "panel_row", "=", "Bh", "::", "Stack", ".", "find", "(", "Bh", "::", "PanelRow", ")", "container", "=", "Bh", "::", "Base", ".", "new", "(", "self", ")", "{", "panel", ".", "content_tag", "panel", ".", "tag", "}", "container", ".", "append_class!", "panel_row", ".", "column_class", "container", ".", "render_tag", ":div", "else", "panel", ".", "render_tag", "panel", ".", "tag", "end", "end" ]
Displays a Bootstrap-styled panel. @see http://getbootstrap.com/components/#panels @return [String] the HTML to display a Bootstrap-styled panel. @overload panel(body, options = {}) @param [#to_s] body the content to display as the panel body. @param [Hash] options the options for the panel. Any option not listed below is passed as an HTML attribute to the panel’s `<div>`. @option options [#to_s] :title the text to display as the panel title. @option options [#to_s] :heading the text to display as the panel heading. @option options [#to_s] :body the text to display as the panel body. Using this option is equivalent to passing the body as an argument. @option options [#to_s] :context (#to_s) (:default) the contextual alternative to apply to the panel heading and border. Can be `:danger`, `:info`, `:primary`, `:success` or `:warning`. @option options [#to_s] :tag (#to_s) (:div) the HTML tag to wrap the panel into. @example Display an informative panel with plain-text content. panel 'You accepted the Terms of service.', context: :success @overload panel(options = {}, &block) @param [Hash] options the options for the panel (see above). @yieldreturn [#to_s] the content to display in the panel. @example Display a panel with HTML content. panel title: 'Thanks' do content_tag :div, class: 'panel-body' do content_tag :em, 'ou accepted the Terms of service.' end end
[ "Displays", "a", "Bootstrap", "-", "styled", "panel", "." ]
b9ad77bf9435dfbc4522958ea9a81415418433e6
https://github.com/Fullscreen/bh/blob/b9ad77bf9435dfbc4522958ea9a81415418433e6/lib/bh/helpers/panel_helper.rb#L35-L51
train
Fullscreen/bh
lib/bh/helpers/modal_helper.rb
Bh.Helpers.modal
def modal(*args, &block) modal = Bh::Modal.new self, *args, &block modal.extract! :button, :size, :body, :title, :id modal.extract_from :button, [:context, :size, :layout, :caption] modal.append_class_to! :button, :btn modal.append_class_to! :button, modal.button_context_class modal.append_class_to! :button, modal.button_size_class modal.merge! button: {caption: modal.caption} modal.append_class_to! :div, :'modal-dialog' modal.append_class_to! :div, modal.dialog_size_class modal.merge! div: {title: modal.title, id: modal.id} modal.render_partial 'modal' end
ruby
def modal(*args, &block) modal = Bh::Modal.new self, *args, &block modal.extract! :button, :size, :body, :title, :id modal.extract_from :button, [:context, :size, :layout, :caption] modal.append_class_to! :button, :btn modal.append_class_to! :button, modal.button_context_class modal.append_class_to! :button, modal.button_size_class modal.merge! button: {caption: modal.caption} modal.append_class_to! :div, :'modal-dialog' modal.append_class_to! :div, modal.dialog_size_class modal.merge! div: {title: modal.title, id: modal.id} modal.render_partial 'modal' end
[ "def", "modal", "(", "*", "args", ",", "&", "block", ")", "modal", "=", "Bh", "::", "Modal", ".", "new", "self", ",", "args", ",", "block", "modal", ".", "extract!", ":button", ",", ":size", ",", ":body", ",", ":title", ",", ":id", "modal", ".", "extract_from", ":button", ",", "[", ":context", ",", ":size", ",", ":layout", ",", ":caption", "]", "modal", ".", "append_class_to!", ":button", ",", ":btn", "modal", ".", "append_class_to!", ":button", ",", "modal", ".", "button_context_class", "modal", ".", "append_class_to!", ":button", ",", "modal", ".", "button_size_class", "modal", ".", "merge!", "button", ":", "{", "caption", ":", "modal", ".", "caption", "}", "modal", ".", "append_class_to!", ":div", ",", ":'", "'", "modal", ".", "append_class_to!", ":div", ",", "modal", ".", "dialog_size_class", "modal", ".", "merge!", "div", ":", "{", "title", ":", "modal", ".", "title", ",", "id", ":", "modal", ".", "id", "}", "modal", ".", "render_partial", "'modal'", "end" ]
Displays a Bootstrap-styled modal. @see http://getbootstrap.com/javascript/#modals @return [String] the HTML to display a Bootstrap-styled modal. @overload modal(body, options = {}) @param [#to_s] body the content to display as the modal body. @param [Hash] options the options for the modal. Any option not listed below is ignored, except for `:id` which is passed as an HTML attribute to the modal’s `<div>`. @option options [#to_s] :title ('Modal') the title of the modal. @option options [#to_s] :body the content to display as the modal body. Using this option is equivalent to passing the body as an argument. @option options [#to_s] :size the size of the modal. Can be `:large` (alias `:lg`) or `:small` (alias `:sm`). @option options [Hash] :button the options for the toggle button. * :caption (#to_s) ('Modal') the caption of the toggle button. * :context (#to_s) (:default) the contextual alternative to apply to the toggle button. Can be `:danger`, `:info`, `:link`, `:primary`, `:success` or `:warning`. * :size (#to_s) the size of the toggle button. Can be `:extra_small` (alias `:xs`), `:large` (alias `:lg`) or `:small` (alias `:sm`). * :layout (#to_s) if set to `:block`, span the button for the full width of the parent. @example Display a simple modal toggled by a blue button. modal 'You clicked me!', title: 'Click me', button: {context: :info} @overload modal(options = {}, &block) @param [Hash] options the options for the modal (see above). @yieldreturn [#to_s] the content to display in the modal. @example Display a modal with HTML content. modal title: 'Click me' do content_tag :div, class: 'modal-body' do content_tag :em, 'You clicked me!' end end
[ "Displays", "a", "Bootstrap", "-", "styled", "modal", "." ]
b9ad77bf9435dfbc4522958ea9a81415418433e6
https://github.com/Fullscreen/bh/blob/b9ad77bf9435dfbc4522958ea9a81415418433e6/lib/bh/helpers/modal_helper.rb#L38-L53
train
Fullscreen/bh
lib/bh/helpers/nav_helper.rb
Bh.Helpers.nav
def nav(options = {}, &block) nav = Bh::Nav.new(self, options, &block) nav.extract! :as, :layout nav.append_class! :nav if Bh::Stack.find(Bh::Navbar) nav.append_class! :'navbar-nav' else nav.merge! role: :tablist nav.append_class! nav.style_class nav.append_class! nav.layout_class end nav.render_tag :ul end
ruby
def nav(options = {}, &block) nav = Bh::Nav.new(self, options, &block) nav.extract! :as, :layout nav.append_class! :nav if Bh::Stack.find(Bh::Navbar) nav.append_class! :'navbar-nav' else nav.merge! role: :tablist nav.append_class! nav.style_class nav.append_class! nav.layout_class end nav.render_tag :ul end
[ "def", "nav", "(", "options", "=", "{", "}", ",", "&", "block", ")", "nav", "=", "Bh", "::", "Nav", ".", "new", "(", "self", ",", "options", ",", "block", ")", "nav", ".", "extract!", ":as", ",", ":layout", "nav", ".", "append_class!", ":nav", "if", "Bh", "::", "Stack", ".", "find", "(", "Bh", "::", "Navbar", ")", "nav", ".", "append_class!", ":'", "'", "else", "nav", ".", "merge!", "role", ":", ":tablist", "nav", ".", "append_class!", "nav", ".", "style_class", "nav", ".", "append_class!", "nav", ".", "layout_class", "end", "nav", ".", "render_tag", ":ul", "end" ]
Displays a Bootstrap-styled nav. @see http://getbootstrap.com/components/#nav @return [String] the HTML to display a Bootstrap-styled nav. @param [Hash] options the options for the nav. Any option not listed below is passed as an HTML attribute to the alert’s `<ul>`. @option options [#to_s] :as (:tabs) the style of the nav. Can be `:tabs` or `:pills`. @option options [#to_s] :layout the layout of the nav. Can be `:justified` or `:stacked`. @yieldreturn [#to_s] the content to display in the nav. @example Display a pills-styled nav with a link. nav as: :pills do link_to 'Home', '/' end
[ "Displays", "a", "Bootstrap", "-", "styled", "nav", "." ]
b9ad77bf9435dfbc4522958ea9a81415418433e6
https://github.com/Fullscreen/bh/blob/b9ad77bf9435dfbc4522958ea9a81415418433e6/lib/bh/helpers/nav_helper.rb#L20-L34
train
Fullscreen/bh
lib/bh/helpers/horizontal_helper.rb
Bh.Helpers.horizontal
def horizontal(*args, &block) if navbar = Bh::Stack.find(Bh::Navbar) horizontal = Bh::Base.new self, *args, &block horizontal.append_class! :'collapse navbar-collapse' horizontal.merge! id: navbar.id horizontal.render_tag :div end end
ruby
def horizontal(*args, &block) if navbar = Bh::Stack.find(Bh::Navbar) horizontal = Bh::Base.new self, *args, &block horizontal.append_class! :'collapse navbar-collapse' horizontal.merge! id: navbar.id horizontal.render_tag :div end end
[ "def", "horizontal", "(", "*", "args", ",", "&", "block", ")", "if", "navbar", "=", "Bh", "::", "Stack", ".", "find", "(", "Bh", "::", "Navbar", ")", "horizontal", "=", "Bh", "::", "Base", ".", "new", "self", ",", "args", ",", "block", "horizontal", ".", "append_class!", ":'", "'", "horizontal", ".", "merge!", "id", ":", "navbar", ".", "id", "horizontal", ".", "render_tag", ":div", "end", "end" ]
Displays the collapsable portion of a Bootstrap-styled navbar. @see http://getbootstrap.com/components/#navbar @return [String] the HTML to display the collapsable portion of a Bootstrap-styled navbar. @overload horizontal(content, options = {}) @param [#to_s] content the collapsable content to display in the navbar. @param [Hash] options the options to pass to the wrapping `<div>`. Note that the `:id` option is ignored since the id must generated by the navbar in order to match with the target of the toggle button. @overload horizontal(options = {}, &block) @param [Hash] options the options to pass to the wrapping `<div>`. @yieldreturn [#to_s] the collapsable content to display in the navbar. @example Display a navbar with two collapsable links. navbar do horizontal do nav do link_to 'Home', '/' link_to 'Profile', '/profile' end end end
[ "Displays", "the", "collapsable", "portion", "of", "a", "Bootstrap", "-", "styled", "navbar", "." ]
b9ad77bf9435dfbc4522958ea9a81415418433e6
https://github.com/Fullscreen/bh/blob/b9ad77bf9435dfbc4522958ea9a81415418433e6/lib/bh/helpers/horizontal_helper.rb#L26-L33
train
Fullscreen/bh
lib/bh/helpers/icon_helper.rb
Bh.Helpers.icon
def icon(name = nil, options = {}) icon = Bh::Icon.new self, nil, options.merge(name: name) icon.extract! :library, :name icon.append_class! icon.library_class icon.append_class! icon.name_class icon.render_tag :span end
ruby
def icon(name = nil, options = {}) icon = Bh::Icon.new self, nil, options.merge(name: name) icon.extract! :library, :name icon.append_class! icon.library_class icon.append_class! icon.name_class icon.render_tag :span end
[ "def", "icon", "(", "name", "=", "nil", ",", "options", "=", "{", "}", ")", "icon", "=", "Bh", "::", "Icon", ".", "new", "self", ",", "nil", ",", "options", ".", "merge", "(", "name", ":", "name", ")", "icon", ".", "extract!", ":library", ",", ":name", "icon", ".", "append_class!", "icon", ".", "library_class", "icon", ".", "append_class!", "icon", ".", "name_class", "icon", ".", "render_tag", ":span", "end" ]
Displays a Bootstrap-styled vector icon. @see http://getbootstrap.com/components/#glyphicons @see http://fortawesome.github.io/Font-Awesome/examples/#bootstrap @return [String] the HTML to display a vector (font) icon. @param [#to_s] name the name of the icon to display, with either dashes or underscores to separate multiple words. @param [Hash] options the options for the icon tag. Any option not listed below is passed as an HTML attribute to the icon’s `<span>`. @option options [#to_s] :library (:glyphicons) the vector icon library to use. Valid values are 'glyphicon', 'glyphicons' (for Glyphicons), 'font-awesome', 'font_awesome' and 'fa' (for Font Awesome). @example Display the "fire" font awesome icon with a title icon 'fire', library: :font_awesome, title: 'Hot'
[ "Displays", "a", "Bootstrap", "-", "styled", "vector", "icon", "." ]
b9ad77bf9435dfbc4522958ea9a81415418433e6
https://github.com/Fullscreen/bh/blob/b9ad77bf9435dfbc4522958ea9a81415418433e6/lib/bh/helpers/icon_helper.rb#L18-L25
train
Fullscreen/bh
lib/bh/helpers/vertical_helper.rb
Bh.Helpers.vertical
def vertical(*args, &block) if navbar = Bh::Stack.find(Bh::Navbar) vertical = Bh::Vertical.new self, *args, &block vertical.append_class! :'navbar-header' vertical.prepend_html! vertical.toggle_button(navbar.id) vertical.render_tag :div end end
ruby
def vertical(*args, &block) if navbar = Bh::Stack.find(Bh::Navbar) vertical = Bh::Vertical.new self, *args, &block vertical.append_class! :'navbar-header' vertical.prepend_html! vertical.toggle_button(navbar.id) vertical.render_tag :div end end
[ "def", "vertical", "(", "*", "args", ",", "&", "block", ")", "if", "navbar", "=", "Bh", "::", "Stack", ".", "find", "(", "Bh", "::", "Navbar", ")", "vertical", "=", "Bh", "::", "Vertical", ".", "new", "self", ",", "args", ",", "block", "vertical", ".", "append_class!", ":'", "'", "vertical", ".", "prepend_html!", "vertical", ".", "toggle_button", "(", "navbar", ".", "id", ")", "vertical", ".", "render_tag", ":div", "end", "end" ]
Displays the non-collapsable portion of a Bootstrap-styled navbar. @see http://getbootstrap.com/components/#navbar @return [String] the HTML to display the non-collapsable portion of a Bootstrap-styled navbar. @overload vertical(content, options = {}) @param [#to_s] content the non-collapsable content to display in the navbar. @param [Hash] options the options to pass to the wrapping `<div>`. @overload vertical(options = {}, &block) @param [Hash] options the options to pass to the wrapping `<div>`. @yieldreturn [#to_s] the non-collapsable content to display in the navbar. @example Display a navbar a non-collapsable links. navbar do vertical do link_to 'Home', '/' end end
[ "Displays", "the", "non", "-", "collapsable", "portion", "of", "a", "Bootstrap", "-", "styled", "navbar", "." ]
b9ad77bf9435dfbc4522958ea9a81415418433e6
https://github.com/Fullscreen/bh/blob/b9ad77bf9435dfbc4522958ea9a81415418433e6/lib/bh/helpers/vertical_helper.rb#L24-L31
train
Fullscreen/bh
lib/bh/helpers/progress_bar_helper.rb
Bh.Helpers.progress_bar
def progress_bar(args = nil, container_options = {}) progress_bars = Array.wrap(args).map do |options| progress_bar = Bh::ProgressBar.new self, nil, options progress_bar.extract! :percentage, :context, :striped, :animated, :label progress_bar.merge! progress_bar.aria_values progress_bar.append_class! :'progress-bar' progress_bar.append_class! progress_bar.context_class progress_bar.append_class! progress_bar.striped_class progress_bar.append_class! progress_bar.animated_class progress_bar.merge! progress_bar.values progress_bar.prepend_html! progress_bar.label progress_bar end container = Bh::Base.new self, progress_bars, container_options container.append_class! :progress container.render_tag :div end
ruby
def progress_bar(args = nil, container_options = {}) progress_bars = Array.wrap(args).map do |options| progress_bar = Bh::ProgressBar.new self, nil, options progress_bar.extract! :percentage, :context, :striped, :animated, :label progress_bar.merge! progress_bar.aria_values progress_bar.append_class! :'progress-bar' progress_bar.append_class! progress_bar.context_class progress_bar.append_class! progress_bar.striped_class progress_bar.append_class! progress_bar.animated_class progress_bar.merge! progress_bar.values progress_bar.prepend_html! progress_bar.label progress_bar end container = Bh::Base.new self, progress_bars, container_options container.append_class! :progress container.render_tag :div end
[ "def", "progress_bar", "(", "args", "=", "nil", ",", "container_options", "=", "{", "}", ")", "progress_bars", "=", "Array", ".", "wrap", "(", "args", ")", ".", "map", "do", "|", "options", "|", "progress_bar", "=", "Bh", "::", "ProgressBar", ".", "new", "self", ",", "nil", ",", "options", "progress_bar", ".", "extract!", ":percentage", ",", ":context", ",", ":striped", ",", ":animated", ",", ":label", "progress_bar", ".", "merge!", "progress_bar", ".", "aria_values", "progress_bar", ".", "append_class!", ":'", "'", "progress_bar", ".", "append_class!", "progress_bar", ".", "context_class", "progress_bar", ".", "append_class!", "progress_bar", ".", "striped_class", "progress_bar", ".", "append_class!", "progress_bar", ".", "animated_class", "progress_bar", ".", "merge!", "progress_bar", ".", "values", "progress_bar", ".", "prepend_html!", "progress_bar", ".", "label", "progress_bar", "end", "container", "=", "Bh", "::", "Base", ".", "new", "self", ",", "progress_bars", ",", "container_options", "container", ".", "append_class!", ":progress", "container", ".", "render_tag", ":div", "end" ]
Displays one or more Bootstrap-styled progress bars. @see http://getbootstrap.com/components/#progress @return [String] the HTML to display Bootstrap-styled progress bars. @overload progress_bar(bar_options = {}, container_options = {}) @param [Hash] bar_options the options to display a single progress bar. Any option not listed below is passed as an HTML attribute to the bar’s `<div>`. @option bar_options [Boolean, #to_s] :label (false) the label to display on top of the progress bar. If set to false, the label is hidden. If set to true, the label is generated from the percentage value. Any other provided value is used directly as the label. @option bar_options [Boolean] :striped (false) whether to display a striped version of the progress bar (rather than solid color). @option bar_options [Boolean] :animated (false) whether to display an animated version of the progress bar (rather than solid color). @option bar_options [#to_s] :context (:default) the contextual alternative to apply to the progress bar. Can be `:success`, `:info`, `:warning` or `:danger`. @param [Hash] container_options the options to pass as HTML attributes to the container’s `<div>`. @example Display a 30% warning progress bar. progress_bar percentage: 30, context: :warning @overload progress_bar(stacked_bars_options = [], container_options = {}) @param [Hash] stacked_bars_options an array of bar_options (see above). When an array is provided, a group of stacked progress bars is displayed, each one matching the corresponding bar options. @param [Hash] container_options the options to pass as HTML attributes to the container’s `<div>`. @example Display two stacked progress bars. progress_bar [{percentage: 30, context: :warning}, {percentage: 20}]
[ "Displays", "one", "or", "more", "Bootstrap", "-", "styled", "progress", "bars", "." ]
b9ad77bf9435dfbc4522958ea9a81415418433e6
https://github.com/Fullscreen/bh/blob/b9ad77bf9435dfbc4522958ea9a81415418433e6/lib/bh/helpers/progress_bar_helper.rb#L35-L53
train
Fullscreen/bh
lib/bh/helpers/navbar_helper.rb
Bh.Helpers.navbar
def navbar(options = {}, &block) navbar = Bh::Navbar.new(self, options, &block) navbar.extract! :inverted, :position, :padding, :fluid, :id navbar.append_class_to! :navigation, :navbar navbar.append_class_to! :navigation, navbar.style_class navbar.append_class_to! :navigation, navbar.position_class navbar.append_class_to! :div, navbar.layout_class navbar.prepend_html! navbar.body_padding_style navbar.render_partial 'navbar' end
ruby
def navbar(options = {}, &block) navbar = Bh::Navbar.new(self, options, &block) navbar.extract! :inverted, :position, :padding, :fluid, :id navbar.append_class_to! :navigation, :navbar navbar.append_class_to! :navigation, navbar.style_class navbar.append_class_to! :navigation, navbar.position_class navbar.append_class_to! :div, navbar.layout_class navbar.prepend_html! navbar.body_padding_style navbar.render_partial 'navbar' end
[ "def", "navbar", "(", "options", "=", "{", "}", ",", "&", "block", ")", "navbar", "=", "Bh", "::", "Navbar", ".", "new", "(", "self", ",", "options", ",", "block", ")", "navbar", ".", "extract!", ":inverted", ",", ":position", ",", ":padding", ",", ":fluid", ",", ":id", "navbar", ".", "append_class_to!", ":navigation", ",", ":navbar", "navbar", ".", "append_class_to!", ":navigation", ",", "navbar", ".", "style_class", "navbar", ".", "append_class_to!", ":navigation", ",", "navbar", ".", "position_class", "navbar", ".", "append_class_to!", ":div", ",", "navbar", ".", "layout_class", "navbar", ".", "prepend_html!", "navbar", ".", "body_padding_style", "navbar", ".", "render_partial", "'navbar'", "end" ]
Displays a Bootstrap-styled navbar. @see http://getbootstrap.com/components/#navbar @return [String] the HTML to display a Bootstrap-styled navbar. @param [Hash] options the options for the navbar. Any option not listed below is ignored, except for `:id` which is passed as an HTML attribute to the navbar’s collapsable `<div>`. @option options [Boolean] :fluid (false) whether to use a fluid container to surround the navbar content. @option options [Boolean] :inverted (false) whether to use an inverted palette of colors. @option options [#to_s] :position the position of the navbar. Can be `:top` (alias `:fixed_top`), `:bottom` (alias `:fixed_bottom`) or `:static` (alias `:static_top`). @option options [#to_s] :padding (70) if position is set to :top or :bottom, the padding to at the top (or bottom) of <body> to prevent the navbar from overlaying the content. @yieldreturn [#to_s] the content to display in the navbar. @example Display an inverted navbar with three links. navbar inverted: true do vertical do image_tag('logo') end horizontal do nav do link_to 'Home', '/' link_to 'Profile', '/profile' end end end
[ "Displays", "a", "Bootstrap", "-", "styled", "navbar", "." ]
b9ad77bf9435dfbc4522958ea9a81415418433e6
https://github.com/Fullscreen/bh/blob/b9ad77bf9435dfbc4522958ea9a81415418433e6/lib/bh/helpers/navbar_helper.rb#L35-L46
train
Fullscreen/bh
lib/bh/helpers/link_to_helper.rb
Bh.Helpers.link_to
def link_to(*args, &block) link_to = Bh::LinkTo.new self, *args, &block link_to.append_class! :'alert-link' if Bh::Stack.find(Bh::AlertBox) link_to.append_class! :'navbar-brand' if Bh::Stack.find(Bh::Vertical) link_to.merge! role: :menuitem if Bh::Stack.find(Bh::Dropdown) link_to.merge! tabindex: -1 if Bh::Stack.find(Bh::Dropdown) html = super link_to.content, link_to.url, link_to.attributes, &nil if Bh::Stack.find(Bh::Dropdown) container = Bh::Base.new(self) { html } container.merge! role: :presentation container.render_tag :li elsif Bh::Stack.find(Bh::Nav) container = Bh::Base.new(self) { html } container.append_class! :active if link_to.current_page? container.render_tag :li else html end end
ruby
def link_to(*args, &block) link_to = Bh::LinkTo.new self, *args, &block link_to.append_class! :'alert-link' if Bh::Stack.find(Bh::AlertBox) link_to.append_class! :'navbar-brand' if Bh::Stack.find(Bh::Vertical) link_to.merge! role: :menuitem if Bh::Stack.find(Bh::Dropdown) link_to.merge! tabindex: -1 if Bh::Stack.find(Bh::Dropdown) html = super link_to.content, link_to.url, link_to.attributes, &nil if Bh::Stack.find(Bh::Dropdown) container = Bh::Base.new(self) { html } container.merge! role: :presentation container.render_tag :li elsif Bh::Stack.find(Bh::Nav) container = Bh::Base.new(self) { html } container.append_class! :active if link_to.current_page? container.render_tag :li else html end end
[ "def", "link_to", "(", "*", "args", ",", "&", "block", ")", "link_to", "=", "Bh", "::", "LinkTo", ".", "new", "self", ",", "args", ",", "block", "link_to", ".", "append_class!", ":'", "'", "if", "Bh", "::", "Stack", ".", "find", "(", "Bh", "::", "AlertBox", ")", "link_to", ".", "append_class!", ":'", "'", "if", "Bh", "::", "Stack", ".", "find", "(", "Bh", "::", "Vertical", ")", "link_to", ".", "merge!", "role", ":", ":menuitem", "if", "Bh", "::", "Stack", ".", "find", "(", "Bh", "::", "Dropdown", ")", "link_to", ".", "merge!", "tabindex", ":", "-", "1", "if", "Bh", "::", "Stack", ".", "find", "(", "Bh", "::", "Dropdown", ")", "html", "=", "super", "link_to", ".", "content", ",", "link_to", ".", "url", ",", "link_to", ".", "attributes", ",", "nil", "if", "Bh", "::", "Stack", ".", "find", "(", "Bh", "::", "Dropdown", ")", "container", "=", "Bh", "::", "Base", ".", "new", "(", "self", ")", "{", "html", "}", "container", ".", "merge!", "role", ":", ":presentation", "container", ".", "render_tag", ":li", "elsif", "Bh", "::", "Stack", ".", "find", "(", "Bh", "::", "Nav", ")", "container", "=", "Bh", "::", "Base", ".", "new", "(", "self", ")", "{", "html", "}", "container", ".", "append_class!", ":active", "if", "link_to", ".", "current_page?", "container", ".", "render_tag", ":li", "else", "html", "end", "end" ]
Overrides `link_to` to display a Bootstrap-styled link. Can only be used in Ruby frameworks that provide the `link_to` method. @see http://getbootstrap.com/components/#dropdowns @see http://getbootstrap.com/components/#nav @see http://getbootstrap.com/components/#navbar-brand-image @see http://getbootstrap.com/components/#navbar-links @see http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to @see http://www.rubydoc.info/github/padrino/padrino-framework/Padrino/Helpers/AssetTagHelpers#link_to-instance_method @return [String] the HTML to display a Bootstrap-styled link. @overload link_to(caption, url, options = {}) @param [#to_s] caption the caption to display in the link. @param [#to_s] url the URL to link to. @param [Hash] options the options for the original `link_to` method. @example Display a plain-text link inside an alert-box. alert_box do link_to 'Check the terms and conditions', '/#terms' end @overload button_to(url, options = {}, &block) @param [#to_s] url the URL to link to (see above). @param [Hash] options the options for the original `link_to` method. @yieldreturn [#to_s] the caption to display in the link. @example Display a link with HTML inside a dropdown. dropdown 'Menu' do link_to '/#terms' do content_tag :strong, 'Check the terms and conditions' end end
[ "Overrides", "link_to", "to", "display", "a", "Bootstrap", "-", "styled", "link", ".", "Can", "only", "be", "used", "in", "Ruby", "frameworks", "that", "provide", "the", "link_to", "method", "." ]
b9ad77bf9435dfbc4522958ea9a81415418433e6
https://github.com/Fullscreen/bh/blob/b9ad77bf9435dfbc4522958ea9a81415418433e6/lib/bh/helpers/link_to_helper.rb#L37-L57
train
Fullscreen/bh
lib/bh/helpers/alert_box_helper.rb
Bh.Helpers.alert_box
def alert_box(*args, &block) alert_box = Bh::AlertBox.new(self, *args, &block) alert_box.extract! :context, :priority, :dismissible alert_box.append_class! :alert alert_box.append_class! alert_box.context_class alert_box.merge! role: :alert alert_box.prepend_html! alert_box.dismissible_button alert_box.render_tag :div end
ruby
def alert_box(*args, &block) alert_box = Bh::AlertBox.new(self, *args, &block) alert_box.extract! :context, :priority, :dismissible alert_box.append_class! :alert alert_box.append_class! alert_box.context_class alert_box.merge! role: :alert alert_box.prepend_html! alert_box.dismissible_button alert_box.render_tag :div end
[ "def", "alert_box", "(", "*", "args", ",", "&", "block", ")", "alert_box", "=", "Bh", "::", "AlertBox", ".", "new", "(", "self", ",", "args", ",", "block", ")", "alert_box", ".", "extract!", ":context", ",", ":priority", ",", ":dismissible", "alert_box", ".", "append_class!", ":alert", "alert_box", ".", "append_class!", "alert_box", ".", "context_class", "alert_box", ".", "merge!", "role", ":", ":alert", "alert_box", ".", "prepend_html!", "alert_box", ".", "dismissible_button", "alert_box", ".", "render_tag", ":div", "end" ]
Displays a Bootstrap-styled alert message. @see http://getbootstrap.com/components/#alerts @return [String] the HTML to display a Bootstrap-styled alert message. @overload alert_box(content, options = {}) @param [#to_s] content the content to display in the alert. @param [Hash] options the options for the alert box. Any option not listed below is passed as an HTML attribute to the alert’s `<div>`. @option options [Boolean] :dismissible (false) whether to display an '×' to the right of the box that can be clicked to dismiss the alert. @option options [#to_s] :context (:info) the contextual alternative to apply to the alert. Can be `:danger`, `:info`, `:success` or `:warning`. @option options [#to_s] :priority if set to one of the priority levels of Rails flash contents, determines the context of the alert box. Can be :alert or :notice. @example Display a dismissible alert box with a plain-text content. alert_box 'User updated successfully', dismissible: true @overload alert_box(options = {}, &block) @param [Hash] options the options for the alert box (see above). @yieldreturn [#to_s] the content to display in the alert. @example Display a success alert box with an HTML content. alert_box context: :success do content_tag :strong, 'User updated successfully' end
[ "Displays", "a", "Bootstrap", "-", "styled", "alert", "message", "." ]
b9ad77bf9435dfbc4522958ea9a81415418433e6
https://github.com/Fullscreen/bh/blob/b9ad77bf9435dfbc4522958ea9a81415418433e6/lib/bh/helpers/alert_box_helper.rb#L29-L38
train
jekyll-octopod/jekyll-octopod
lib/jekyll/octopod_filters.rb
Jekyll.OctopodFilters.otherwise
def otherwise(first, second) first = first.to_s first.empty? ? second : first end
ruby
def otherwise(first, second) first = first.to_s first.empty? ? second : first end
[ "def", "otherwise", "(", "first", ",", "second", ")", "first", "=", "first", ".", "to_s", "first", ".", "empty?", "?", "second", ":", "first", "end" ]
Returns the first argument if it's not nil or empty otherwise it returns the second one. {{ post.author | otherwise:site.author }}
[ "Returns", "the", "first", "argument", "if", "it", "s", "not", "nil", "or", "empty", "otherwise", "it", "returns", "the", "second", "one", "." ]
bc01a6b1d0b809dbd458bc7cec762c453a7a9be5
https://github.com/jekyll-octopod/jekyll-octopod/blob/bc01a6b1d0b809dbd458bc7cec762c453a7a9be5/lib/jekyll/octopod_filters.rb#L47-L50
train
jekyll-octopod/jekyll-octopod
lib/jekyll/octopod_filters.rb
Jekyll.OctopodFilters.audio
def audio(hsh, key = nil) if !hsh.nil? && hsh.length if key.nil? hsh['mp3'] ? hsh['mp3'] : hsh['m4a'] ? hsh['m4a'] : hsh['ogg'] ? hsh['ogg'] : hsh['opus'] ? hsh['opus'] : hsh.values.first else hsh[key] end end end
ruby
def audio(hsh, key = nil) if !hsh.nil? && hsh.length if key.nil? hsh['mp3'] ? hsh['mp3'] : hsh['m4a'] ? hsh['m4a'] : hsh['ogg'] ? hsh['ogg'] : hsh['opus'] ? hsh['opus'] : hsh.values.first else hsh[key] end end end
[ "def", "audio", "(", "hsh", ",", "key", "=", "nil", ")", "if", "!", "hsh", ".", "nil?", "&&", "hsh", ".", "length", "if", "key", ".", "nil?", "hsh", "[", "'mp3'", "]", "?", "hsh", "[", "'mp3'", "]", ":", "hsh", "[", "'m4a'", "]", "?", "hsh", "[", "'m4a'", "]", ":", "hsh", "[", "'ogg'", "]", "?", "hsh", "[", "'ogg'", "]", ":", "hsh", "[", "'opus'", "]", "?", "hsh", "[", "'opus'", "]", ":", "hsh", ".", "values", ".", "first", "else", "hsh", "[", "key", "]", "end", "end", "end" ]
Returns the audio file name of a given hash. Is no key as second parameter given, it trys first "mp3", than "m4a" and than it will return a more or less random value. {{ post.audio | audio:"m4a" }} => "my-episode.m4a"
[ "Returns", "the", "audio", "file", "name", "of", "a", "given", "hash", ".", "Is", "no", "key", "as", "second", "parameter", "given", "it", "trys", "first", "mp3", "than", "m4a", "and", "than", "it", "will", "return", "a", "more", "or", "less", "random", "value", "." ]
bc01a6b1d0b809dbd458bc7cec762c453a7a9be5
https://github.com/jekyll-octopod/jekyll-octopod/blob/bc01a6b1d0b809dbd458bc7cec762c453a7a9be5/lib/jekyll/octopod_filters.rb#L57-L65
train
jekyll-octopod/jekyll-octopod
lib/jekyll/octopod_filters.rb
Jekyll.OctopodFilters.audio_type
def audio_type(hsh) if !hsh.nil? && hsh.length hsh['mp3'] ? mime_type('mp3') : hsh['m4a'] ? mime_type('m4a') : hsh['ogg'] ? mime_type('ogg') : mime_type('opus') end end
ruby
def audio_type(hsh) if !hsh.nil? && hsh.length hsh['mp3'] ? mime_type('mp3') : hsh['m4a'] ? mime_type('m4a') : hsh['ogg'] ? mime_type('ogg') : mime_type('opus') end end
[ "def", "audio_type", "(", "hsh", ")", "if", "!", "hsh", ".", "nil?", "&&", "hsh", ".", "length", "hsh", "[", "'mp3'", "]", "?", "mime_type", "(", "'mp3'", ")", ":", "hsh", "[", "'m4a'", "]", "?", "mime_type", "(", "'m4a'", ")", ":", "hsh", "[", "'ogg'", "]", "?", "mime_type", "(", "'ogg'", ")", ":", "mime_type", "(", "'opus'", ")", "end", "end" ]
Returns the audio-type of a given hash. Is no key as second parameter given, it trys first "mp3", than "m4a" and than it will return a more or less random value. {{ post.audio | audiotype }} => "my-episode.m4a"
[ "Returns", "the", "audio", "-", "type", "of", "a", "given", "hash", ".", "Is", "no", "key", "as", "second", "parameter", "given", "it", "trys", "first", "mp3", "than", "m4a", "and", "than", "it", "will", "return", "a", "more", "or", "less", "random", "value", "." ]
bc01a6b1d0b809dbd458bc7cec762c453a7a9be5
https://github.com/jekyll-octopod/jekyll-octopod/blob/bc01a6b1d0b809dbd458bc7cec762c453a7a9be5/lib/jekyll/octopod_filters.rb#L73-L77
train
jekyll-octopod/jekyll-octopod
lib/jekyll/octopod_filters.rb
Jekyll.OctopodFilters.split_chapter
def split_chapter(chapter_str, attribute = nil) attributes = chapter_str.split(/ /, 2) return nil unless attributes.first.match(/\A(\d|:|\.)+\z/) if attribute.nil? { 'start' => attributes.first, 'title' => attributes.last } else attribute == 'start' ? attributes.first : attributes.last end end
ruby
def split_chapter(chapter_str, attribute = nil) attributes = chapter_str.split(/ /, 2) return nil unless attributes.first.match(/\A(\d|:|\.)+\z/) if attribute.nil? { 'start' => attributes.first, 'title' => attributes.last } else attribute == 'start' ? attributes.first : attributes.last end end
[ "def", "split_chapter", "(", "chapter_str", ",", "attribute", "=", "nil", ")", "attributes", "=", "chapter_str", ".", "split", "(", "/", "/", ",", "2", ")", "return", "nil", "unless", "attributes", ".", "first", ".", "match", "(", "/", "\\A", "\\d", "\\.", "\\z", "/", ")", "if", "attribute", ".", "nil?", "{", "'start'", "=>", "attributes", ".", "first", ",", "'title'", "=>", "attributes", ".", "last", "}", "else", "attribute", "==", "'start'", "?", "attributes", ".", "first", ":", "attributes", ".", "last", "end", "end" ]
Splits a chapter, like it is written to the post YAML front matter into the components 'start' which refers to a single point in time relative to the beginning of the media file nad 'title' which defines the text to be the title of the chapter. {{ '00:00:00.000 Welcome to Octopod!' | split_chapter }} => { 'start' => '00:00:00.000', 'title' => 'Welcome to Octopod!' } {{ '00:00:00.000 Welcome to Octopod!' | split_chapter:'title' }} => 'Welcome to Octopod!' {{ '00:00:00.000 Welcome to Octopod!' | split_chapter:'start' }} => '00:00:00.000'
[ "Splits", "a", "chapter", "like", "it", "is", "written", "to", "the", "post", "YAML", "front", "matter", "into", "the", "components", "start", "which", "refers", "to", "a", "single", "point", "in", "time", "relative", "to", "the", "beginning", "of", "the", "media", "file", "nad", "title", "which", "defines", "the", "text", "to", "be", "the", "title", "of", "the", "chapter", "." ]
bc01a6b1d0b809dbd458bc7cec762c453a7a9be5
https://github.com/jekyll-octopod/jekyll-octopod/blob/bc01a6b1d0b809dbd458bc7cec762c453a7a9be5/lib/jekyll/octopod_filters.rb#L147-L156
train
jekyll-octopod/jekyll-octopod
lib/jekyll/octopod_filters.rb
Jekyll.OctopodFilters.string_of_size
def string_of_size(bytes) bytes = bytes.to_i.to_f out = '0' return out if bytes == 0.0 jedec = %w[b K M G] [3, 2, 1, 0].each { |i| if bytes > 1024 ** i out = "%.1f#{jedec[i]}" % (bytes / 1024 ** i) break end } return out end
ruby
def string_of_size(bytes) bytes = bytes.to_i.to_f out = '0' return out if bytes == 0.0 jedec = %w[b K M G] [3, 2, 1, 0].each { |i| if bytes > 1024 ** i out = "%.1f#{jedec[i]}" % (bytes / 1024 ** i) break end } return out end
[ "def", "string_of_size", "(", "bytes", ")", "bytes", "=", "bytes", ".", "to_i", ".", "to_f", "out", "=", "'0'", "return", "out", "if", "bytes", "==", "0.0", "jedec", "=", "%w[", "b", "K", "M", "G", "]", "[", "3", ",", "2", ",", "1", ",", "0", "]", ".", "each", "{", "|", "i", "|", "if", "bytes", ">", "1024", "**", "i", "out", "=", "\"%.1f#{jedec[i]}\"", "%", "(", "bytes", "/", "1024", "**", "i", ")", "break", "end", "}", "return", "out", "end" ]
Gets a number of bytes and returns an human readable string of it. {{ 1252251 | string_of_size }} => "1.19M"
[ "Gets", "a", "number", "of", "bytes", "and", "returns", "an", "human", "readable", "string", "of", "it", "." ]
bc01a6b1d0b809dbd458bc7cec762c453a7a9be5
https://github.com/jekyll-octopod/jekyll-octopod/blob/bc01a6b1d0b809dbd458bc7cec762c453a7a9be5/lib/jekyll/octopod_filters.rb#L174-L188
train
jekyll-octopod/jekyll-octopod
lib/jekyll/octopod_filters.rb
Jekyll.OctopodFilters.disqus_config
def disqus_config(site, page = nil) if page disqus_vars = { 'disqus_identifier' => page['url'], 'disqus_url' => "#{site['url']}#{page['url']}", 'disqus_category_id' => page['disqus_category_id'] || site['disqus_category_id'], 'disqus_title' => j(page['title'] || site['site']) } else disqus_vars = { 'disqus_developer' => site['disqus_developer'], 'disqus_shortname' => site['disqus_shortname'] } end disqus_vars.delete_if { |_, v| v.nil? } disqus_vars.map { |k, v| "var #{k} = '#{v}';" }.compact.join("\n") end
ruby
def disqus_config(site, page = nil) if page disqus_vars = { 'disqus_identifier' => page['url'], 'disqus_url' => "#{site['url']}#{page['url']}", 'disqus_category_id' => page['disqus_category_id'] || site['disqus_category_id'], 'disqus_title' => j(page['title'] || site['site']) } else disqus_vars = { 'disqus_developer' => site['disqus_developer'], 'disqus_shortname' => site['disqus_shortname'] } end disqus_vars.delete_if { |_, v| v.nil? } disqus_vars.map { |k, v| "var #{k} = '#{v}';" }.compact.join("\n") end
[ "def", "disqus_config", "(", "site", ",", "page", "=", "nil", ")", "if", "page", "disqus_vars", "=", "{", "'disqus_identifier'", "=>", "page", "[", "'url'", "]", ",", "'disqus_url'", "=>", "\"#{site['url']}#{page['url']}\"", ",", "'disqus_category_id'", "=>", "page", "[", "'disqus_category_id'", "]", "||", "site", "[", "'disqus_category_id'", "]", ",", "'disqus_title'", "=>", "j", "(", "page", "[", "'title'", "]", "||", "site", "[", "'site'", "]", ")", "}", "else", "disqus_vars", "=", "{", "'disqus_developer'", "=>", "site", "[", "'disqus_developer'", "]", ",", "'disqus_shortname'", "=>", "site", "[", "'disqus_shortname'", "]", "}", "end", "disqus_vars", ".", "delete_if", "{", "|", "_", ",", "v", "|", "v", ".", "nil?", "}", "disqus_vars", ".", "map", "{", "|", "k", ",", "v", "|", "\"var #{k} = '#{v}';\"", "}", ".", "compact", ".", "join", "(", "\"\\n\"", ")", "end" ]
Generates the config for disqus integration If a page object is given, it generates the config variables only for this page. Otherwise it generate only the global config variables. {{ site | disqus_config }} {{ site | disqus_config:page }}
[ "Generates", "the", "config", "for", "disqus", "integration", "If", "a", "page", "object", "is", "given", "it", "generates", "the", "config", "variables", "only", "for", "this", "page", ".", "Otherwise", "it", "generate", "only", "the", "global", "config", "variables", "." ]
bc01a6b1d0b809dbd458bc7cec762c453a7a9be5
https://github.com/jekyll-octopod/jekyll-octopod/blob/bc01a6b1d0b809dbd458bc7cec762c453a7a9be5/lib/jekyll/octopod_filters.rb#L203-L220
train
jekyll-octopod/jekyll-octopod
lib/jekyll/octopod_filters.rb
Jekyll.OctopodFilters.sha1
def sha1(str, lenght = 8) sha1 = Digest::SHA1.hexdigest(str) sha1[0, lenght.to_i] end
ruby
def sha1(str, lenght = 8) sha1 = Digest::SHA1.hexdigest(str) sha1[0, lenght.to_i] end
[ "def", "sha1", "(", "str", ",", "lenght", "=", "8", ")", "sha1", "=", "Digest", "::", "SHA1", ".", "hexdigest", "(", "str", ")", "sha1", "[", "0", ",", "lenght", ".", "to_i", "]", "end" ]
Returns the hex-encoded hash value of a given string. The optional second argument defines the length of the returned string. {{ "Octopod" | sha1 }} => "8b20a59c" {{ "Octopod" | sha1:23 }} => "8b20a59c8e2dcb5e1f845ba"
[ "Returns", "the", "hex", "-", "encoded", "hash", "value", "of", "a", "given", "string", ".", "The", "optional", "second", "argument", "defines", "the", "length", "of", "the", "returned", "string", "." ]
bc01a6b1d0b809dbd458bc7cec762c453a7a9be5
https://github.com/jekyll-octopod/jekyll-octopod/blob/bc01a6b1d0b809dbd458bc7cec762c453a7a9be5/lib/jekyll/octopod_filters.rb#L227-L230
train
jekyll-octopod/jekyll-octopod
lib/jekyll/date_de.rb
Jekyll.DateDe.format_date
def format_date(date, format) date = datetime(date) if format.nil? || format.empty? || format == "ordinal" date_formatted = ordinalize(date) else format.gsub!(/%a/, ABBR_DAYNAMES_DE[date.wday]) format.gsub!(/%A/, DAYNAMES_DE[date.wday]) format.gsub!(/%b/, ABBR_MONTHNAMES_DE[date.mon]) format.gsub!(/%B/, MONTHNAMES_DE[date.mon]) date_formatted = date.strftime(format) end date_formatted end
ruby
def format_date(date, format) date = datetime(date) if format.nil? || format.empty? || format == "ordinal" date_formatted = ordinalize(date) else format.gsub!(/%a/, ABBR_DAYNAMES_DE[date.wday]) format.gsub!(/%A/, DAYNAMES_DE[date.wday]) format.gsub!(/%b/, ABBR_MONTHNAMES_DE[date.mon]) format.gsub!(/%B/, MONTHNAMES_DE[date.mon]) date_formatted = date.strftime(format) end date_formatted end
[ "def", "format_date", "(", "date", ",", "format", ")", "date", "=", "datetime", "(", "date", ")", "if", "format", ".", "nil?", "||", "format", ".", "empty?", "||", "format", "==", "\"ordinal\"", "date_formatted", "=", "ordinalize", "(", "date", ")", "else", "format", ".", "gsub!", "(", "/", "/", ",", "ABBR_DAYNAMES_DE", "[", "date", ".", "wday", "]", ")", "format", ".", "gsub!", "(", "/", "/", ",", "DAYNAMES_DE", "[", "date", ".", "wday", "]", ")", "format", ".", "gsub!", "(", "/", "/", ",", "ABBR_MONTHNAMES_DE", "[", "date", ".", "mon", "]", ")", "format", ".", "gsub!", "(", "/", "/", ",", "MONTHNAMES_DE", "[", "date", ".", "mon", "]", ")", "date_formatted", "=", "date", ".", "strftime", "(", "format", ")", "end", "date_formatted", "end" ]
Formats date by given date format
[ "Formats", "date", "by", "given", "date", "format" ]
bc01a6b1d0b809dbd458bc7cec762c453a7a9be5
https://github.com/jekyll-octopod/jekyll-octopod/blob/bc01a6b1d0b809dbd458bc7cec762c453a7a9be5/lib/jekyll/date_de.rb#L32-L44
train
jekyll-octopod/jekyll-octopod
lib/jekyll/flattr_filters.rb
Jekyll.FlattrFilters.flattr_loader_options
def flattr_loader_options(site) return if site['flattr_uid'].nil? keys = %w[mode https popout uid button language category] options = flattr_options(site, nil, keys).delete_if { |_, v| v.to_s.empty? } options.map { |k, v| "#{k}=#{ERB::Util.url_encode(v)}" }.join('&') end
ruby
def flattr_loader_options(site) return if site['flattr_uid'].nil? keys = %w[mode https popout uid button language category] options = flattr_options(site, nil, keys).delete_if { |_, v| v.to_s.empty? } options.map { |k, v| "#{k}=#{ERB::Util.url_encode(v)}" }.join('&') end
[ "def", "flattr_loader_options", "(", "site", ")", "return", "if", "site", "[", "'flattr_uid'", "]", ".", "nil?", "keys", "=", "%w[", "mode", "https", "popout", "uid", "button", "language", "category", "]", "options", "=", "flattr_options", "(", "site", ",", "nil", ",", "keys", ")", ".", "delete_if", "{", "|", "_", ",", "v", "|", "v", ".", "to_s", ".", "empty?", "}", "options", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{k}=#{ERB::Util.url_encode(v)}\"", "}", ".", "join", "(", "'&'", ")", "end" ]
Generates the query string part for the flattr load.js from the configurations in _config.yml {{ site | flattr_loader_options }}
[ "Generates", "the", "query", "string", "part", "for", "the", "flattr", "load", ".", "js", "from", "the", "configurations", "in", "_config", ".", "yml" ]
bc01a6b1d0b809dbd458bc7cec762c453a7a9be5
https://github.com/jekyll-octopod/jekyll-octopod/blob/bc01a6b1d0b809dbd458bc7cec762c453a7a9be5/lib/jekyll/flattr_filters.rb#L9-L15
train
jekyll-octopod/jekyll-octopod
lib/jekyll/flattr_filters.rb
Jekyll.FlattrFilters.flattr_button
def flattr_button(site, page = nil) return if site['flattr_uid'].nil? keys = %w[url title description uid popout button category language tags] options = flattr_options(site, page, keys) button = '<a class="FlattrButton" style="display:none;" ' button << %Q{title="#{options.delete('title')}" href="#{options.delete('url')}" } button << options.map { |k, v| %Q{data-flattr-#{k}="#{v}"} unless k == 'description' }.join(' ') button << ">\n\n#{options['description'].gsub(/<\/?[^>]*>/, "")}\n</a>" end
ruby
def flattr_button(site, page = nil) return if site['flattr_uid'].nil? keys = %w[url title description uid popout button category language tags] options = flattr_options(site, page, keys) button = '<a class="FlattrButton" style="display:none;" ' button << %Q{title="#{options.delete('title')}" href="#{options.delete('url')}" } button << options.map { |k, v| %Q{data-flattr-#{k}="#{v}"} unless k == 'description' }.join(' ') button << ">\n\n#{options['description'].gsub(/<\/?[^>]*>/, "")}\n</a>" end
[ "def", "flattr_button", "(", "site", ",", "page", "=", "nil", ")", "return", "if", "site", "[", "'flattr_uid'", "]", ".", "nil?", "keys", "=", "%w[", "url", "title", "description", "uid", "popout", "button", "category", "language", "tags", "]", "options", "=", "flattr_options", "(", "site", ",", "page", ",", "keys", ")", "button", "=", "'<a class=\"FlattrButton\" style=\"display:none;\" '", "button", "<<", "%Q{title=\"#{options.delete('title')}\" href=\"#{options.delete('url')}\" }", "button", "<<", "options", ".", "map", "{", "|", "k", ",", "v", "|", "%Q{data-flattr-#{k}=\"#{v}\"}", "unless", "k", "==", "'description'", "}", ".", "join", "(", "' '", ")", "button", "<<", "\">\\n\\n#{options['description'].gsub(/<\\/?[^>]*>/, \"\")}\\n</a>\"", "end" ]
Returns a flattr button {{ site | flattr_button:page }}
[ "Returns", "a", "flattr", "button" ]
bc01a6b1d0b809dbd458bc7cec762c453a7a9be5
https://github.com/jekyll-octopod/jekyll-octopod/blob/bc01a6b1d0b809dbd458bc7cec762c453a7a9be5/lib/jekyll/flattr_filters.rb#L20-L32
train
jekyll-octopod/jekyll-octopod
lib/jekyll/flattr_filters.rb
Jekyll.FlattrFilters.flattrize
def flattrize(hsh) config = {} hsh.to_hash.each { |k, v| if new_key = k.to_s.match(/\Aflattr_(.*)\z/) config[new_key[1]] = v else config[k] = v end } config end
ruby
def flattrize(hsh) config = {} hsh.to_hash.each { |k, v| if new_key = k.to_s.match(/\Aflattr_(.*)\z/) config[new_key[1]] = v else config[k] = v end } config end
[ "def", "flattrize", "(", "hsh", ")", "config", "=", "{", "}", "hsh", ".", "to_hash", ".", "each", "{", "|", "k", ",", "v", "|", "if", "new_key", "=", "k", ".", "to_s", ".", "match", "(", "/", "\\A", "\\z", "/", ")", "config", "[", "new_key", "[", "1", "]", "]", "=", "v", "else", "config", "[", "k", "]", "=", "v", "end", "}", "config", "end" ]
Removes all leading "flattr_" from the keys of the given hash. flattrize({ 'octopod' => 'awesome', 'flattr_uid' => 'pattex' }) => { "octopod" => "awesome", "uid" => "pattex" }
[ "Removes", "all", "leading", "flattr_", "from", "the", "keys", "of", "the", "given", "hash", "." ]
bc01a6b1d0b809dbd458bc7cec762c453a7a9be5
https://github.com/jekyll-octopod/jekyll-octopod/blob/bc01a6b1d0b809dbd458bc7cec762c453a7a9be5/lib/jekyll/flattr_filters.rb#L56-L67
train
gocardless/prius
lib/prius/registry.rb
Prius.Registry.load
def load(name, options = {}) env_var = options.fetch(:env_var, name.to_s.upcase) type = options.fetch(:type, :string) required = options.fetch(:required, true) @registry[name] = case type when :string then load_string(env_var, required) when :int then load_int(env_var, required) when :bool then load_bool(env_var, required) else raise ArgumentError, "Invalid type #{type}" end end
ruby
def load(name, options = {}) env_var = options.fetch(:env_var, name.to_s.upcase) type = options.fetch(:type, :string) required = options.fetch(:required, true) @registry[name] = case type when :string then load_string(env_var, required) when :int then load_int(env_var, required) when :bool then load_bool(env_var, required) else raise ArgumentError, "Invalid type #{type}" end end
[ "def", "load", "(", "name", ",", "options", "=", "{", "}", ")", "env_var", "=", "options", ".", "fetch", "(", ":env_var", ",", "name", ".", "to_s", ".", "upcase", ")", "type", "=", "options", ".", "fetch", "(", ":type", ",", ":string", ")", "required", "=", "options", ".", "fetch", "(", ":required", ",", "true", ")", "@registry", "[", "name", "]", "=", "case", "type", "when", ":string", "then", "load_string", "(", "env_var", ",", "required", ")", "when", ":int", "then", "load_int", "(", "env_var", ",", "required", ")", "when", ":bool", "then", "load_bool", "(", "env_var", ",", "required", ")", "else", "raise", "ArgumentError", ",", "\"Invalid type #{type}\"", "end", "end" ]
Initialise a Registry. env - A Hash used as a source for environment variables. Usually, ENV will be used. See Prius.load for documentation.
[ "Initialise", "a", "Registry", "." ]
786656cc97ca6d8b613e4f41495715296290d07f
https://github.com/gocardless/prius/blob/786656cc97ca6d8b613e4f41495715296290d07f/lib/prius/registry.rb#L15-L25
train
airbnb/interferon
lib/interferon.rb
Interferon.Interferon.run
def run start_time = Time.new.to_f Signal.trap('TERM') do log.info('SIGTERM received. shutting down gracefully...') @request_shutdown = true end run_desc = @dry_run ? 'dry run' : 'run' log.info("beginning alerts #{run_desc}") alerts = read_alerts(@alert_sources) groups = read_groups(@group_sources) hosts = read_hosts(@host_sources) @destinations.each do |dest| dest['options'] ||= {} dest['options']['dry_run'] = true if @dry_run end update_alerts(@destinations, hosts, alerts, groups) run_time = Time.new.to_f - start_time if @request_shutdown log.info("interferon #{run_desc} shut down by SIGTERM") else statsd.gauge('run_time', run_time) log.info("interferon #{run_desc} complete in %.2f seconds" % run_time) end end
ruby
def run start_time = Time.new.to_f Signal.trap('TERM') do log.info('SIGTERM received. shutting down gracefully...') @request_shutdown = true end run_desc = @dry_run ? 'dry run' : 'run' log.info("beginning alerts #{run_desc}") alerts = read_alerts(@alert_sources) groups = read_groups(@group_sources) hosts = read_hosts(@host_sources) @destinations.each do |dest| dest['options'] ||= {} dest['options']['dry_run'] = true if @dry_run end update_alerts(@destinations, hosts, alerts, groups) run_time = Time.new.to_f - start_time if @request_shutdown log.info("interferon #{run_desc} shut down by SIGTERM") else statsd.gauge('run_time', run_time) log.info("interferon #{run_desc} complete in %.2f seconds" % run_time) end end
[ "def", "run", "start_time", "=", "Time", ".", "new", ".", "to_f", "Signal", ".", "trap", "(", "'TERM'", ")", "do", "log", ".", "info", "(", "'SIGTERM received. shutting down gracefully...'", ")", "@request_shutdown", "=", "true", "end", "run_desc", "=", "@dry_run", "?", "'dry run'", ":", "'run'", "log", ".", "info", "(", "\"beginning alerts #{run_desc}\"", ")", "alerts", "=", "read_alerts", "(", "@alert_sources", ")", "groups", "=", "read_groups", "(", "@group_sources", ")", "hosts", "=", "read_hosts", "(", "@host_sources", ")", "@destinations", ".", "each", "do", "|", "dest", "|", "dest", "[", "'options'", "]", "||=", "{", "}", "dest", "[", "'options'", "]", "[", "'dry_run'", "]", "=", "true", "if", "@dry_run", "end", "update_alerts", "(", "@destinations", ",", "hosts", ",", "alerts", ",", "groups", ")", "run_time", "=", "Time", ".", "new", ".", "to_f", "-", "start_time", "if", "@request_shutdown", "log", ".", "info", "(", "\"interferon #{run_desc} shut down by SIGTERM\"", ")", "else", "statsd", ".", "gauge", "(", "'run_time'", ",", "run_time", ")", "log", ".", "info", "(", "\"interferon #{run_desc} complete in %.2f seconds\"", "%", "run_time", ")", "end", "end" ]
groups_sources is a hash from type => options for each group source host_sources is a hash from type => options for each host source destinations is a similar hash from type => options for each alerter
[ "groups_sources", "is", "a", "hash", "from", "type", "=", ">", "options", "for", "each", "group", "source", "host_sources", "is", "a", "hash", "from", "type", "=", ">", "options", "for", "each", "host", "source", "destinations", "is", "a", "similar", "hash", "from", "type", "=", ">", "options", "for", "each", "alerter" ]
4f91dc782ce1b818e2cd35146d565847fe4e023d
https://github.com/airbnb/interferon/blob/4f91dc782ce1b818e2cd35146d565847fe4e023d/lib/interferon.rb#L39-L66
train
airbnb/interferon
lib/interferon/host_sources/aws_rds.rb
Interferon::HostSources.AwsRds.account_number
def account_number return @account_number if @account_number begin my_arn = AWS::IAM.new( access_key_id: @access_key_id, secret_access_key: @secret_access_key ).client.get_user[:user][:arn] rescue AWS::IAM::Errors::AccessDenied => e my_arn = e.message.split[1] end @account_number = my_arn.split(':')[4] end
ruby
def account_number return @account_number if @account_number begin my_arn = AWS::IAM.new( access_key_id: @access_key_id, secret_access_key: @secret_access_key ).client.get_user[:user][:arn] rescue AWS::IAM::Errors::AccessDenied => e my_arn = e.message.split[1] end @account_number = my_arn.split(':')[4] end
[ "def", "account_number", "return", "@account_number", "if", "@account_number", "begin", "my_arn", "=", "AWS", "::", "IAM", ".", "new", "(", "access_key_id", ":", "@access_key_id", ",", "secret_access_key", ":", "@secret_access_key", ")", ".", "client", ".", "get_user", "[", ":user", "]", "[", ":arn", "]", "rescue", "AWS", "::", "IAM", "::", "Errors", "::", "AccessDenied", "=>", "e", "my_arn", "=", "e", ".", "message", ".", "split", "[", "1", "]", "end", "@account_number", "=", "my_arn", ".", "split", "(", "':'", ")", "[", "4", "]", "end" ]
unfortunately, this appears to be the only way to get your account number
[ "unfortunately", "this", "appears", "to", "be", "the", "only", "way", "to", "get", "your", "account", "number" ]
4f91dc782ce1b818e2cd35146d565847fe4e023d
https://github.com/airbnb/interferon/blob/4f91dc782ce1b818e2cd35146d565847fe4e023d/lib/interferon/host_sources/aws_rds.rb#L78-L91
train
zverok/time_math2
lib/time_math/op.rb
TimeMath.Op.call
def call(*tms) unless @arguments.empty? tms.empty? or raise(ArgumentError, 'Op arguments is already set, use call()') tms = @arguments end res = [*tms].flatten.map(&method(:perform)) tms.count == 1 && Util.timey?(tms.first) ? res.first : res end
ruby
def call(*tms) unless @arguments.empty? tms.empty? or raise(ArgumentError, 'Op arguments is already set, use call()') tms = @arguments end res = [*tms].flatten.map(&method(:perform)) tms.count == 1 && Util.timey?(tms.first) ? res.first : res end
[ "def", "call", "(", "*", "tms", ")", "unless", "@arguments", ".", "empty?", "tms", ".", "empty?", "or", "raise", "(", "ArgumentError", ",", "'Op arguments is already set, use call()'", ")", "tms", "=", "@arguments", "end", "res", "=", "[", "tms", "]", ".", "flatten", ".", "map", "(", "method", "(", ":perform", ")", ")", "tms", ".", "count", "==", "1", "&&", "Util", ".", "timey?", "(", "tms", ".", "first", ")", "?", "res", ".", "first", ":", "res", "end" ]
Performs op. If an Op was created with arguments, just performs all operations on them and returns the result. If it was created without arguments, performs all operations on arguments provided to `call`. @param tms one, or several, or an array of time-y values; should not be passed if Op was created with arguments. @return [Time,Date,DateTime,Array] one, or an array of processed arguments
[ "Performs", "op", ".", "If", "an", "Op", "was", "created", "with", "arguments", "just", "performs", "all", "operations", "on", "them", "and", "returns", "the", "result", ".", "If", "it", "was", "created", "without", "arguments", "performs", "all", "operations", "on", "arguments", "provided", "to", "call", "." ]
e9a3eef689f85f8711b49eebe3dad494eb2489dc
https://github.com/zverok/time_math2/blob/e9a3eef689f85f8711b49eebe3dad494eb2489dc/lib/time_math/op.rb#L177-L184
train
karmi/retire
lib/tire/alias.rb
Tire.Alias.indices
def indices(*names) names = Array(names).flatten names.compact.empty? ? @attributes[:indices] : (names.each { |n| @attributes[:indices].push(n) } and return self) end
ruby
def indices(*names) names = Array(names).flatten names.compact.empty? ? @attributes[:indices] : (names.each { |n| @attributes[:indices].push(n) } and return self) end
[ "def", "indices", "(", "*", "names", ")", "names", "=", "Array", "(", "names", ")", ".", "flatten", "names", ".", "compact", ".", "empty?", "?", "@attributes", "[", ":indices", "]", ":", "(", "names", ".", "each", "{", "|", "n", "|", "@attributes", "[", ":indices", "]", ".", "push", "(", "n", ")", "}", "and", "return", "self", ")", "end" ]
Get or set the alias indices
[ "Get", "or", "set", "the", "alias", "indices" ]
1016449cd5bcfd52853f1728452e26962c18790e
https://github.com/karmi/retire/blob/1016449cd5bcfd52853f1728452e26962c18790e/lib/tire/alias.rb#L142-L145
train
karmi/retire
lib/tire/alias.rb
Tire.Alias.filter
def filter(type=nil, *options) type ? (@attributes[:filter] = Search::Filter.new(type, *options).to_hash and return self ) : @attributes[:filter] end
ruby
def filter(type=nil, *options) type ? (@attributes[:filter] = Search::Filter.new(type, *options).to_hash and return self ) : @attributes[:filter] end
[ "def", "filter", "(", "type", "=", "nil", ",", "*", "options", ")", "type", "?", "(", "@attributes", "[", ":filter", "]", "=", "Search", "::", "Filter", ".", "new", "(", "type", ",", "options", ")", ".", "to_hash", "and", "return", "self", ")", ":", "@attributes", "[", ":filter", "]", "end" ]
Get or set the alias routing
[ "Get", "or", "set", "the", "alias", "routing" ]
1016449cd5bcfd52853f1728452e26962c18790e
https://github.com/karmi/retire/blob/1016449cd5bcfd52853f1728452e26962c18790e/lib/tire/alias.rb#L155-L157
train
karmi/retire
lib/tire/alias.rb
Tire.Alias.as_json
def as_json(options=nil) actions = [] indices.add_indices.each do |index| operation = { :index => index, :alias => name } operation.update( { :routing => routing } ) if respond_to?(:routing) and routing operation.update( { :filter => filter } ) if respond_to?(:filter) and filter actions.push( { :add => operation } ) end indices.remove_indices.each do |index| operation = { :index => index, :alias => name } actions.push( { :remove => operation } ) end { :actions => actions } end
ruby
def as_json(options=nil) actions = [] indices.add_indices.each do |index| operation = { :index => index, :alias => name } operation.update( { :routing => routing } ) if respond_to?(:routing) and routing operation.update( { :filter => filter } ) if respond_to?(:filter) and filter actions.push( { :add => operation } ) end indices.remove_indices.each do |index| operation = { :index => index, :alias => name } actions.push( { :remove => operation } ) end { :actions => actions } end
[ "def", "as_json", "(", "options", "=", "nil", ")", "actions", "=", "[", "]", "indices", ".", "add_indices", ".", "each", "do", "|", "index", "|", "operation", "=", "{", ":index", "=>", "index", ",", ":alias", "=>", "name", "}", "operation", ".", "update", "(", "{", ":routing", "=>", "routing", "}", ")", "if", "respond_to?", "(", ":routing", ")", "and", "routing", "operation", ".", "update", "(", "{", ":filter", "=>", "filter", "}", ")", "if", "respond_to?", "(", ":filter", ")", "and", "filter", "actions", ".", "push", "(", "{", ":add", "=>", "operation", "}", ")", "end", "indices", ".", "remove_indices", ".", "each", "do", "|", "index", "|", "operation", "=", "{", ":index", "=>", "index", ",", ":alias", "=>", "name", "}", "actions", ".", "push", "(", "{", ":remove", "=>", "operation", "}", ")", "end", "{", ":actions", "=>", "actions", "}", "end" ]
Return a Hash suitable for JSON serialization
[ "Return", "a", "Hash", "suitable", "for", "JSON", "serialization" ]
1016449cd5bcfd52853f1728452e26962c18790e
https://github.com/karmi/retire/blob/1016449cd5bcfd52853f1728452e26962c18790e/lib/tire/alias.rb#L170-L185
train
karmi/retire
lib/tire/index.rb
Tire.Index.mapping!
def mapping!(*args) mapping(*args) raise RuntimeError, response.body unless response.success? end
ruby
def mapping!(*args) mapping(*args) raise RuntimeError, response.body unless response.success? end
[ "def", "mapping!", "(", "*", "args", ")", "mapping", "(", "args", ")", "raise", "RuntimeError", ",", "response", ".", "body", "unless", "response", ".", "success?", "end" ]
Raises an exception for unsuccessful responses
[ "Raises", "an", "exception", "for", "unsuccessful", "responses" ]
1016449cd5bcfd52853f1728452e26962c18790e
https://github.com/karmi/retire/blob/1016449cd5bcfd52853f1728452e26962c18790e/lib/tire/index.rb#L75-L78
train
optoro/amazon_seller_central
lib/amazon_seller_central/inventory_page.rb
AmazonSellerCentral.InventoryPage.listing_row_to_object
def listing_row_to_object(row) l = Listing.new row.css('td').each_with_index do |td, i| txt = td.text.strip # yes, slightly slower to do this here, but I type less. case i when 4 l.sku = txt when 5 l.asin = txt when 6 l.product_name = txt when 7 l.created_at = parse_amazon_time(txt) when 8 l.quantity = (inputs = td.css('input')).any? ? inputs.first['value'].to_i : txt.to_i when 10 l.price = get_price(td) when 11 l.condition = txt when 12 l.low_price = get_low_price(td) when 3 l.status = txt end end l end
ruby
def listing_row_to_object(row) l = Listing.new row.css('td').each_with_index do |td, i| txt = td.text.strip # yes, slightly slower to do this here, but I type less. case i when 4 l.sku = txt when 5 l.asin = txt when 6 l.product_name = txt when 7 l.created_at = parse_amazon_time(txt) when 8 l.quantity = (inputs = td.css('input')).any? ? inputs.first['value'].to_i : txt.to_i when 10 l.price = get_price(td) when 11 l.condition = txt when 12 l.low_price = get_low_price(td) when 3 l.status = txt end end l end
[ "def", "listing_row_to_object", "(", "row", ")", "l", "=", "Listing", ".", "new", "row", ".", "css", "(", "'td'", ")", ".", "each_with_index", "do", "|", "td", ",", "i", "|", "txt", "=", "td", ".", "text", ".", "strip", "# yes, slightly slower to do this here, but I type less.", "case", "i", "when", "4", "l", ".", "sku", "=", "txt", "when", "5", "l", ".", "asin", "=", "txt", "when", "6", "l", ".", "product_name", "=", "txt", "when", "7", "l", ".", "created_at", "=", "parse_amazon_time", "(", "txt", ")", "when", "8", "l", ".", "quantity", "=", "(", "inputs", "=", "td", ".", "css", "(", "'input'", ")", ")", ".", "any?", "?", "inputs", ".", "first", "[", "'value'", "]", ".", "to_i", ":", "txt", ".", "to_i", "when", "10", "l", ".", "price", "=", "get_price", "(", "td", ")", "when", "11", "l", ".", "condition", "=", "txt", "when", "12", "l", ".", "low_price", "=", "get_low_price", "(", "td", ")", "when", "3", "l", ".", "status", "=", "txt", "end", "end", "l", "end" ]
0 - hidden input of sku 1 - checkbox itemOffer 2 - actions 3 - status 4 - sku 5 - asin 6 - product name 7 - date created 8 - qty 9 - your price 10 - condition 11 - low price 12 - buy-box price 13 - fulfilled by
[ "0", "-", "hidden", "input", "of", "sku", "1", "-", "checkbox", "itemOffer", "2", "-", "actions", "3", "-", "status", "4", "-", "sku", "5", "-", "asin", "6", "-", "product", "name", "7", "-", "date", "created", "8", "-", "qty", "9", "-", "your", "price", "10", "-", "condition", "11", "-", "low", "price", "12", "-", "buy", "-", "box", "price", "13", "-", "fulfilled", "by" ]
8e994034b797d73745731991903c574ce36a5b39
https://github.com/optoro/amazon_seller_central/blob/8e994034b797d73745731991903c574ce36a5b39/lib/amazon_seller_central/inventory_page.rb#L82-L110
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.theme=
def theme=(options) reset_themes defaults = { :colors => %w(black white), :additional_line_colors => [], :marker_color => 'white', :marker_shadow_color => nil, :font_color => 'black', :background_colors => nil, :background_image => nil } @theme_options = defaults.merge options @colors = @theme_options[:colors] @marker_color = @theme_options[:marker_color] @marker_shadow_color = @theme_options[:marker_shadow_color] @font_color = @theme_options[:font_color] || @marker_color @additional_line_colors = @theme_options[:additional_line_colors] render_background end
ruby
def theme=(options) reset_themes defaults = { :colors => %w(black white), :additional_line_colors => [], :marker_color => 'white', :marker_shadow_color => nil, :font_color => 'black', :background_colors => nil, :background_image => nil } @theme_options = defaults.merge options @colors = @theme_options[:colors] @marker_color = @theme_options[:marker_color] @marker_shadow_color = @theme_options[:marker_shadow_color] @font_color = @theme_options[:font_color] || @marker_color @additional_line_colors = @theme_options[:additional_line_colors] render_background end
[ "def", "theme", "=", "(", "options", ")", "reset_themes", "defaults", "=", "{", ":colors", "=>", "%w(", "black", "white", ")", ",", ":additional_line_colors", "=>", "[", "]", ",", ":marker_color", "=>", "'white'", ",", ":marker_shadow_color", "=>", "nil", ",", ":font_color", "=>", "'black'", ",", ":background_colors", "=>", "nil", ",", ":background_image", "=>", "nil", "}", "@theme_options", "=", "defaults", ".", "merge", "options", "@colors", "=", "@theme_options", "[", ":colors", "]", "@marker_color", "=", "@theme_options", "[", ":marker_color", "]", "@marker_shadow_color", "=", "@theme_options", "[", ":marker_shadow_color", "]", "@font_color", "=", "@theme_options", "[", ":font_color", "]", "||", "@marker_color", "@additional_line_colors", "=", "@theme_options", "[", ":additional_line_colors", "]", "render_background", "end" ]
You can set a theme manually. Assign a hash to this method before you send your data. graph.theme = { :colors => %w(orange purple green white red), :marker_color => 'blue', :background_colors => ['black', 'grey', :top_bottom] } :background_image => 'squirrel.png' is also possible. (Or hopefully something better looking than that.)
[ "You", "can", "set", "a", "theme", "manually", ".", "Assign", "a", "hash", "to", "this", "method", "before", "you", "send", "your", "data", "." ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L347-L368
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.data
def data(name, data_points=[], color=nil) data_points = Array(data_points) # make sure it's an array @data << [name, data_points, color] # Set column count if this is larger than previous counts @column_count = (data_points.length > @column_count) ? data_points.length : @column_count # Pre-normalize data_points.each do |data_point| next if data_point.nil? # Setup max/min so spread starts at the low end of the data points if @maximum_value.nil? && @minimum_value.nil? @maximum_value = @minimum_value = data_point end # TODO Doesn't work with stacked bar graphs # Original: @maximum_value = larger_than_max?(data_point, index) ? max(data_point, index) : @maximum_value @maximum_value = larger_than_max?(data_point) ? data_point : @maximum_value @has_data = true if @maximum_value >= 0 @minimum_value = less_than_min?(data_point) ? data_point : @minimum_value @has_data = true if @minimum_value < 0 end end
ruby
def data(name, data_points=[], color=nil) data_points = Array(data_points) # make sure it's an array @data << [name, data_points, color] # Set column count if this is larger than previous counts @column_count = (data_points.length > @column_count) ? data_points.length : @column_count # Pre-normalize data_points.each do |data_point| next if data_point.nil? # Setup max/min so spread starts at the low end of the data points if @maximum_value.nil? && @minimum_value.nil? @maximum_value = @minimum_value = data_point end # TODO Doesn't work with stacked bar graphs # Original: @maximum_value = larger_than_max?(data_point, index) ? max(data_point, index) : @maximum_value @maximum_value = larger_than_max?(data_point) ? data_point : @maximum_value @has_data = true if @maximum_value >= 0 @minimum_value = less_than_min?(data_point) ? data_point : @minimum_value @has_data = true if @minimum_value < 0 end end
[ "def", "data", "(", "name", ",", "data_points", "=", "[", "]", ",", "color", "=", "nil", ")", "data_points", "=", "Array", "(", "data_points", ")", "# make sure it's an array", "@data", "<<", "[", "name", ",", "data_points", ",", "color", "]", "# Set column count if this is larger than previous counts", "@column_count", "=", "(", "data_points", ".", "length", ">", "@column_count", ")", "?", "data_points", ".", "length", ":", "@column_count", "# Pre-normalize", "data_points", ".", "each", "do", "|", "data_point", "|", "next", "if", "data_point", ".", "nil?", "# Setup max/min so spread starts at the low end of the data points", "if", "@maximum_value", ".", "nil?", "&&", "@minimum_value", ".", "nil?", "@maximum_value", "=", "@minimum_value", "=", "data_point", "end", "# TODO Doesn't work with stacked bar graphs", "# Original: @maximum_value = larger_than_max?(data_point, index) ? max(data_point, index) : @maximum_value", "@maximum_value", "=", "larger_than_max?", "(", "data_point", ")", "?", "data_point", ":", "@maximum_value", "@has_data", "=", "true", "if", "@maximum_value", ">=", "0", "@minimum_value", "=", "less_than_min?", "(", "data_point", ")", "?", "data_point", ":", "@minimum_value", "@has_data", "=", "true", "if", "@minimum_value", "<", "0", "end", "end" ]
Parameters are an array where the first element is the name of the dataset and the value is an array of values to plot. Can be called multiple times with different datasets for a multi-valued graph. If the color argument is nil, the next color from the default theme will be used. NOTE: If you want to use a preset theme, you must set it before calling data(). Example: data("Bart S.", [95, 45, 78, 89, 88, 76], '#ffcc00')
[ "Parameters", "are", "an", "array", "where", "the", "first", "element", "is", "the", "name", "of", "the", "dataset", "and", "the", "value", "is", "an", "array", "of", "values", "to", "plot", "." ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L408-L431
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.draw
def draw # Maybe should be done in one of the following functions for more granularity. unless @has_data draw_no_data return end setup_data setup_drawing debug { # Outer margin @d.rectangle(@left_margin, @top_margin, @raw_columns - @right_margin, @raw_rows - @bottom_margin) # Graph area box @d.rectangle(@graph_left, @graph_top, @graph_right, @graph_bottom) } draw_legend draw_line_markers draw_axis_labels draw_title end
ruby
def draw # Maybe should be done in one of the following functions for more granularity. unless @has_data draw_no_data return end setup_data setup_drawing debug { # Outer margin @d.rectangle(@left_margin, @top_margin, @raw_columns - @right_margin, @raw_rows - @bottom_margin) # Graph area box @d.rectangle(@graph_left, @graph_top, @graph_right, @graph_bottom) } draw_legend draw_line_markers draw_axis_labels draw_title end
[ "def", "draw", "# Maybe should be done in one of the following functions for more granularity.", "unless", "@has_data", "draw_no_data", "return", "end", "setup_data", "setup_drawing", "debug", "{", "# Outer margin", "@d", ".", "rectangle", "(", "@left_margin", ",", "@top_margin", ",", "@raw_columns", "-", "@right_margin", ",", "@raw_rows", "-", "@bottom_margin", ")", "# Graph area box", "@d", ".", "rectangle", "(", "@graph_left", ",", "@graph_top", ",", "@graph_right", ",", "@graph_bottom", ")", "}", "draw_legend", "draw_line_markers", "draw_axis_labels", "draw_title", "end" ]
Overridden by subclasses to do the actual plotting of the graph. Subclasses should start by calling super() for this method.
[ "Overridden", "by", "subclasses", "to", "do", "the", "actual", "plotting", "of", "the", "graph", "." ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L456-L478
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.normalize
def normalize(force=false) if @norm_data.nil? || force @norm_data = [] return unless @has_data @data.each do |data_row| norm_data_points = [] data_row[DATA_VALUES_INDEX].each do |data_point| if data_point.nil? norm_data_points << nil else norm_data_points << ((data_point.to_f - @minimum_value.to_f) / @spread) end end if @show_labels_for_bar_values @norm_data << [data_row[DATA_LABEL_INDEX], norm_data_points, data_row[DATA_COLOR_INDEX], data_row[DATA_VALUES_INDEX]] else @norm_data << [data_row[DATA_LABEL_INDEX], norm_data_points, data_row[DATA_COLOR_INDEX]] end end end end
ruby
def normalize(force=false) if @norm_data.nil? || force @norm_data = [] return unless @has_data @data.each do |data_row| norm_data_points = [] data_row[DATA_VALUES_INDEX].each do |data_point| if data_point.nil? norm_data_points << nil else norm_data_points << ((data_point.to_f - @minimum_value.to_f) / @spread) end end if @show_labels_for_bar_values @norm_data << [data_row[DATA_LABEL_INDEX], norm_data_points, data_row[DATA_COLOR_INDEX], data_row[DATA_VALUES_INDEX]] else @norm_data << [data_row[DATA_LABEL_INDEX], norm_data_points, data_row[DATA_COLOR_INDEX]] end end end end
[ "def", "normalize", "(", "force", "=", "false", ")", "if", "@norm_data", ".", "nil?", "||", "force", "@norm_data", "=", "[", "]", "return", "unless", "@has_data", "@data", ".", "each", "do", "|", "data_row", "|", "norm_data_points", "=", "[", "]", "data_row", "[", "DATA_VALUES_INDEX", "]", ".", "each", "do", "|", "data_point", "|", "if", "data_point", ".", "nil?", "norm_data_points", "<<", "nil", "else", "norm_data_points", "<<", "(", "(", "data_point", ".", "to_f", "-", "@minimum_value", ".", "to_f", ")", "/", "@spread", ")", "end", "end", "if", "@show_labels_for_bar_values", "@norm_data", "<<", "[", "data_row", "[", "DATA_LABEL_INDEX", "]", ",", "norm_data_points", ",", "data_row", "[", "DATA_COLOR_INDEX", "]", ",", "data_row", "[", "DATA_VALUES_INDEX", "]", "]", "else", "@norm_data", "<<", "[", "data_row", "[", "DATA_LABEL_INDEX", "]", ",", "norm_data_points", ",", "data_row", "[", "DATA_COLOR_INDEX", "]", "]", "end", "end", "end", "end" ]
Make copy of data with values scaled between 0-100
[ "Make", "copy", "of", "data", "with", "values", "scaled", "between", "0", "-", "100" ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L504-L525
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.setup_graph_measurements
def setup_graph_measurements @marker_caps_height = @hide_line_markers ? 0 : calculate_caps_height(@marker_font_size) @title_caps_height = (@hide_title || @title.nil?) ? 0 : calculate_caps_height(@title_font_size) * @title.lines.to_a.size @legend_caps_height = @hide_legend ? 0 : calculate_caps_height(@legend_font_size) if @hide_line_markers (@graph_left, @graph_right_margin, @graph_bottom_margin) = [@left_margin, @right_margin, @bottom_margin] else if @has_left_labels longest_left_label_width = calculate_width(@marker_font_size, labels.values.inject('') { |value, memo| (value.to_s.length > memo.to_s.length) ? value : memo }) * 1.25 else longest_left_label_width = calculate_width(@marker_font_size, label(@maximum_value.to_f, @increment)) end # Shift graph if left line numbers are hidden line_number_width = @hide_line_numbers && !@has_left_labels ? 0.0 : (longest_left_label_width + LABEL_MARGIN * 2) @graph_left = @left_margin + line_number_width + (@y_axis_label.nil? ? 0.0 : @marker_caps_height + LABEL_MARGIN * 2) # Make space for half the width of the rightmost column label. # Might be greater than the number of columns if between-style bar markers are used. last_label = @labels.keys.sort.last.to_i extra_room_for_long_label = (last_label >= (@column_count-1) && @center_labels_over_point) ? calculate_width(@marker_font_size, @labels[last_label]) / 2.0 : 0 @graph_right_margin = @right_margin + extra_room_for_long_label @graph_bottom_margin = @bottom_margin + @marker_caps_height + LABEL_MARGIN end @graph_right = @raw_columns - @graph_right_margin @graph_width = @raw_columns - @graph_left - @graph_right_margin # When @hide title, leave a title_margin space for aesthetics. # Same with @hide_legend @graph_top = @legend_at_bottom ? @top_margin : (@top_margin + (@hide_title ? title_margin : @title_caps_height + title_margin) + (@hide_legend ? legend_margin : @legend_caps_height + legend_margin)) x_axis_label_height = @x_axis_label.nil? ? 0.0 : @marker_caps_height + LABEL_MARGIN # FIXME: Consider chart types other than bar @graph_bottom = @raw_rows - @graph_bottom_margin - x_axis_label_height - @label_stagger_height @graph_height = @graph_bottom - @graph_top end
ruby
def setup_graph_measurements @marker_caps_height = @hide_line_markers ? 0 : calculate_caps_height(@marker_font_size) @title_caps_height = (@hide_title || @title.nil?) ? 0 : calculate_caps_height(@title_font_size) * @title.lines.to_a.size @legend_caps_height = @hide_legend ? 0 : calculate_caps_height(@legend_font_size) if @hide_line_markers (@graph_left, @graph_right_margin, @graph_bottom_margin) = [@left_margin, @right_margin, @bottom_margin] else if @has_left_labels longest_left_label_width = calculate_width(@marker_font_size, labels.values.inject('') { |value, memo| (value.to_s.length > memo.to_s.length) ? value : memo }) * 1.25 else longest_left_label_width = calculate_width(@marker_font_size, label(@maximum_value.to_f, @increment)) end # Shift graph if left line numbers are hidden line_number_width = @hide_line_numbers && !@has_left_labels ? 0.0 : (longest_left_label_width + LABEL_MARGIN * 2) @graph_left = @left_margin + line_number_width + (@y_axis_label.nil? ? 0.0 : @marker_caps_height + LABEL_MARGIN * 2) # Make space for half the width of the rightmost column label. # Might be greater than the number of columns if between-style bar markers are used. last_label = @labels.keys.sort.last.to_i extra_room_for_long_label = (last_label >= (@column_count-1) && @center_labels_over_point) ? calculate_width(@marker_font_size, @labels[last_label]) / 2.0 : 0 @graph_right_margin = @right_margin + extra_room_for_long_label @graph_bottom_margin = @bottom_margin + @marker_caps_height + LABEL_MARGIN end @graph_right = @raw_columns - @graph_right_margin @graph_width = @raw_columns - @graph_left - @graph_right_margin # When @hide title, leave a title_margin space for aesthetics. # Same with @hide_legend @graph_top = @legend_at_bottom ? @top_margin : (@top_margin + (@hide_title ? title_margin : @title_caps_height + title_margin) + (@hide_legend ? legend_margin : @legend_caps_height + legend_margin)) x_axis_label_height = @x_axis_label.nil? ? 0.0 : @marker_caps_height + LABEL_MARGIN # FIXME: Consider chart types other than bar @graph_bottom = @raw_rows - @graph_bottom_margin - x_axis_label_height - @label_stagger_height @graph_height = @graph_bottom - @graph_top end
[ "def", "setup_graph_measurements", "@marker_caps_height", "=", "@hide_line_markers", "?", "0", ":", "calculate_caps_height", "(", "@marker_font_size", ")", "@title_caps_height", "=", "(", "@hide_title", "||", "@title", ".", "nil?", ")", "?", "0", ":", "calculate_caps_height", "(", "@title_font_size", ")", "*", "@title", ".", "lines", ".", "to_a", ".", "size", "@legend_caps_height", "=", "@hide_legend", "?", "0", ":", "calculate_caps_height", "(", "@legend_font_size", ")", "if", "@hide_line_markers", "(", "@graph_left", ",", "@graph_right_margin", ",", "@graph_bottom_margin", ")", "=", "[", "@left_margin", ",", "@right_margin", ",", "@bottom_margin", "]", "else", "if", "@has_left_labels", "longest_left_label_width", "=", "calculate_width", "(", "@marker_font_size", ",", "labels", ".", "values", ".", "inject", "(", "''", ")", "{", "|", "value", ",", "memo", "|", "(", "value", ".", "to_s", ".", "length", ">", "memo", ".", "to_s", ".", "length", ")", "?", "value", ":", "memo", "}", ")", "*", "1.25", "else", "longest_left_label_width", "=", "calculate_width", "(", "@marker_font_size", ",", "label", "(", "@maximum_value", ".", "to_f", ",", "@increment", ")", ")", "end", "# Shift graph if left line numbers are hidden", "line_number_width", "=", "@hide_line_numbers", "&&", "!", "@has_left_labels", "?", "0.0", ":", "(", "longest_left_label_width", "+", "LABEL_MARGIN", "*", "2", ")", "@graph_left", "=", "@left_margin", "+", "line_number_width", "+", "(", "@y_axis_label", ".", "nil?", "?", "0.0", ":", "@marker_caps_height", "+", "LABEL_MARGIN", "*", "2", ")", "# Make space for half the width of the rightmost column label.", "# Might be greater than the number of columns if between-style bar markers are used.", "last_label", "=", "@labels", ".", "keys", ".", "sort", ".", "last", ".", "to_i", "extra_room_for_long_label", "=", "(", "last_label", ">=", "(", "@column_count", "-", "1", ")", "&&", "@center_labels_over_point", ")", "?", "calculate_width", "(", "@marker_font_size", ",", "@labels", "[", "last_label", "]", ")", "/", "2.0", ":", "0", "@graph_right_margin", "=", "@right_margin", "+", "extra_room_for_long_label", "@graph_bottom_margin", "=", "@bottom_margin", "+", "@marker_caps_height", "+", "LABEL_MARGIN", "end", "@graph_right", "=", "@raw_columns", "-", "@graph_right_margin", "@graph_width", "=", "@raw_columns", "-", "@graph_left", "-", "@graph_right_margin", "# When @hide title, leave a title_margin space for aesthetics.", "# Same with @hide_legend", "@graph_top", "=", "@legend_at_bottom", "?", "@top_margin", ":", "(", "@top_margin", "+", "(", "@hide_title", "?", "title_margin", ":", "@title_caps_height", "+", "title_margin", ")", "+", "(", "@hide_legend", "?", "legend_margin", ":", "@legend_caps_height", "+", "legend_margin", ")", ")", "x_axis_label_height", "=", "@x_axis_label", ".", "nil?", "?", "0.0", ":", "@marker_caps_height", "+", "LABEL_MARGIN", "# FIXME: Consider chart types other than bar", "@graph_bottom", "=", "@raw_rows", "-", "@graph_bottom_margin", "-", "x_axis_label_height", "-", "@label_stagger_height", "@graph_height", "=", "@graph_bottom", "-", "@graph_top", "end" ]
Calculates size of drawable area, general font dimensions, etc.
[ "Calculates", "size", "of", "drawable", "area", "general", "font", "dimensions", "etc", "." ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L535-L591
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.draw_axis_labels
def draw_axis_labels unless @x_axis_label.nil? # X Axis # Centered vertically and horizontally by setting the # height to 1.0 and the width to the width of the graph. x_axis_label_y_coordinate = @graph_bottom + LABEL_MARGIN * 2 + @marker_caps_height # TODO Center between graph area @d.fill = @font_color @d.font = @font if @font @d.stroke('transparent') @d.pointsize = scale_fontsize(@marker_font_size) @d.gravity = NorthGravity @d = @d.annotate_scaled(@base_image, @raw_columns, 1.0, 0.0, x_axis_label_y_coordinate, @x_axis_label, @scale) debug { @d.line 0.0, x_axis_label_y_coordinate, @raw_columns, x_axis_label_y_coordinate } end unless @y_axis_label.nil? # Y Axis, rotated vertically @d.rotation = -90.0 @d.gravity = CenterGravity @d = @d.annotate_scaled(@base_image, 1.0, @raw_rows, @left_margin + @marker_caps_height / 2.0, 0.0, @y_axis_label, @scale) @d.rotation = 90.0 end end
ruby
def draw_axis_labels unless @x_axis_label.nil? # X Axis # Centered vertically and horizontally by setting the # height to 1.0 and the width to the width of the graph. x_axis_label_y_coordinate = @graph_bottom + LABEL_MARGIN * 2 + @marker_caps_height # TODO Center between graph area @d.fill = @font_color @d.font = @font if @font @d.stroke('transparent') @d.pointsize = scale_fontsize(@marker_font_size) @d.gravity = NorthGravity @d = @d.annotate_scaled(@base_image, @raw_columns, 1.0, 0.0, x_axis_label_y_coordinate, @x_axis_label, @scale) debug { @d.line 0.0, x_axis_label_y_coordinate, @raw_columns, x_axis_label_y_coordinate } end unless @y_axis_label.nil? # Y Axis, rotated vertically @d.rotation = -90.0 @d.gravity = CenterGravity @d = @d.annotate_scaled(@base_image, 1.0, @raw_rows, @left_margin + @marker_caps_height / 2.0, 0.0, @y_axis_label, @scale) @d.rotation = 90.0 end end
[ "def", "draw_axis_labels", "unless", "@x_axis_label", ".", "nil?", "# X Axis", "# Centered vertically and horizontally by setting the", "# height to 1.0 and the width to the width of the graph.", "x_axis_label_y_coordinate", "=", "@graph_bottom", "+", "LABEL_MARGIN", "*", "2", "+", "@marker_caps_height", "# TODO Center between graph area", "@d", ".", "fill", "=", "@font_color", "@d", ".", "font", "=", "@font", "if", "@font", "@d", ".", "stroke", "(", "'transparent'", ")", "@d", ".", "pointsize", "=", "scale_fontsize", "(", "@marker_font_size", ")", "@d", ".", "gravity", "=", "NorthGravity", "@d", "=", "@d", ".", "annotate_scaled", "(", "@base_image", ",", "@raw_columns", ",", "1.0", ",", "0.0", ",", "x_axis_label_y_coordinate", ",", "@x_axis_label", ",", "@scale", ")", "debug", "{", "@d", ".", "line", "0.0", ",", "x_axis_label_y_coordinate", ",", "@raw_columns", ",", "x_axis_label_y_coordinate", "}", "end", "unless", "@y_axis_label", ".", "nil?", "# Y Axis, rotated vertically", "@d", ".", "rotation", "=", "-", "90.0", "@d", ".", "gravity", "=", "CenterGravity", "@d", "=", "@d", ".", "annotate_scaled", "(", "@base_image", ",", "1.0", ",", "@raw_rows", ",", "@left_margin", "+", "@marker_caps_height", "/", "2.0", ",", "0.0", ",", "@y_axis_label", ",", "@scale", ")", "@d", ".", "rotation", "=", "90.0", "end", "end" ]
Draw the optional labels for the x axis and y axis.
[ "Draw", "the", "optional", "labels", "for", "the", "x", "axis", "and", "y", "axis", "." ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L594-L624
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.draw_line_markers
def draw_line_markers return if @hide_line_markers @d = @d.stroke_antialias false if @y_axis_increment.nil? # Try to use a number of horizontal lines that will come out even. # # TODO Do the same for larger numbers...100, 75, 50, 25 if @marker_count.nil? (3..7).each do |lines| if @spread % lines == 0.0 @marker_count = lines break end end @marker_count ||= 4 end @increment = (@spread > 0 && @marker_count > 0) ? significant(@spread / @marker_count) : 1 else # TODO Make this work for negative values @marker_count = (@spread / @y_axis_increment).to_i @increment = @y_axis_increment end @increment_scaled = @graph_height.to_f / (@spread / @increment) # Draw horizontal line markers and annotate with numbers (0..@marker_count).each do |index| y = @graph_top + @graph_height - index.to_f * @increment_scaled @d = @d.fill(@marker_color) # FIXME(uwe): Workaround for Issue #66 # https://github.com/topfunky/gruff/issues/66 # https://github.com/rmagick/rmagick/issues/82 # Remove if the issue gets fixed. y += 0.001 unless defined?(JRUBY_VERSION) # EMXIF @d = @d.line(@graph_left, y, @graph_right, y) #If the user specified a marker shadow color, draw a shadow just below it unless @marker_shadow_color.nil? @d = @d.fill(@marker_shadow_color) @d = @d.line(@graph_left, y + 1, @graph_right, y + 1) end marker_label = BigDecimal(index.to_s) * BigDecimal(@increment.to_s) + BigDecimal(@minimum_value.to_s) unless @hide_line_numbers @d.fill = @font_color @d.font = @font if @font @d.stroke('transparent') @d.pointsize = scale_fontsize(@marker_font_size) @d.gravity = EastGravity # Vertically center with 1.0 for the height @d = @d.annotate_scaled(@base_image, @graph_left - LABEL_MARGIN, 1.0, 0.0, y, label(marker_label, @increment), @scale) end end # # Submitted by a contibutor...the utility escapes me # i = 0 # @additional_line_values.each do |value| # @increment_scaled = @graph_height.to_f / (@maximum_value.to_f / value) # # y = @graph_top + @graph_height - @increment_scaled # # @d = @d.stroke(@additional_line_colors[i]) # @d = @d.line(@graph_left, y, @graph_right, y) # # # @d.fill = @additional_line_colors[i] # @d.font = @font if @font # @d.stroke('transparent') # @d.pointsize = scale_fontsize(@marker_font_size) # @d.gravity = EastGravity # @d = @d.annotate_scaled( @base_image, # 100, 20, # -10, y - (@marker_font_size/2.0), # "", @scale) # i += 1 # end @d = @d.stroke_antialias true end
ruby
def draw_line_markers return if @hide_line_markers @d = @d.stroke_antialias false if @y_axis_increment.nil? # Try to use a number of horizontal lines that will come out even. # # TODO Do the same for larger numbers...100, 75, 50, 25 if @marker_count.nil? (3..7).each do |lines| if @spread % lines == 0.0 @marker_count = lines break end end @marker_count ||= 4 end @increment = (@spread > 0 && @marker_count > 0) ? significant(@spread / @marker_count) : 1 else # TODO Make this work for negative values @marker_count = (@spread / @y_axis_increment).to_i @increment = @y_axis_increment end @increment_scaled = @graph_height.to_f / (@spread / @increment) # Draw horizontal line markers and annotate with numbers (0..@marker_count).each do |index| y = @graph_top + @graph_height - index.to_f * @increment_scaled @d = @d.fill(@marker_color) # FIXME(uwe): Workaround for Issue #66 # https://github.com/topfunky/gruff/issues/66 # https://github.com/rmagick/rmagick/issues/82 # Remove if the issue gets fixed. y += 0.001 unless defined?(JRUBY_VERSION) # EMXIF @d = @d.line(@graph_left, y, @graph_right, y) #If the user specified a marker shadow color, draw a shadow just below it unless @marker_shadow_color.nil? @d = @d.fill(@marker_shadow_color) @d = @d.line(@graph_left, y + 1, @graph_right, y + 1) end marker_label = BigDecimal(index.to_s) * BigDecimal(@increment.to_s) + BigDecimal(@minimum_value.to_s) unless @hide_line_numbers @d.fill = @font_color @d.font = @font if @font @d.stroke('transparent') @d.pointsize = scale_fontsize(@marker_font_size) @d.gravity = EastGravity # Vertically center with 1.0 for the height @d = @d.annotate_scaled(@base_image, @graph_left - LABEL_MARGIN, 1.0, 0.0, y, label(marker_label, @increment), @scale) end end # # Submitted by a contibutor...the utility escapes me # i = 0 # @additional_line_values.each do |value| # @increment_scaled = @graph_height.to_f / (@maximum_value.to_f / value) # # y = @graph_top + @graph_height - @increment_scaled # # @d = @d.stroke(@additional_line_colors[i]) # @d = @d.line(@graph_left, y, @graph_right, y) # # # @d.fill = @additional_line_colors[i] # @d.font = @font if @font # @d.stroke('transparent') # @d.pointsize = scale_fontsize(@marker_font_size) # @d.gravity = EastGravity # @d = @d.annotate_scaled( @base_image, # 100, 20, # -10, y - (@marker_font_size/2.0), # "", @scale) # i += 1 # end @d = @d.stroke_antialias true end
[ "def", "draw_line_markers", "return", "if", "@hide_line_markers", "@d", "=", "@d", ".", "stroke_antialias", "false", "if", "@y_axis_increment", ".", "nil?", "# Try to use a number of horizontal lines that will come out even.", "#", "# TODO Do the same for larger numbers...100, 75, 50, 25", "if", "@marker_count", ".", "nil?", "(", "3", "..", "7", ")", ".", "each", "do", "|", "lines", "|", "if", "@spread", "%", "lines", "==", "0.0", "@marker_count", "=", "lines", "break", "end", "end", "@marker_count", "||=", "4", "end", "@increment", "=", "(", "@spread", ">", "0", "&&", "@marker_count", ">", "0", ")", "?", "significant", "(", "@spread", "/", "@marker_count", ")", ":", "1", "else", "# TODO Make this work for negative values", "@marker_count", "=", "(", "@spread", "/", "@y_axis_increment", ")", ".", "to_i", "@increment", "=", "@y_axis_increment", "end", "@increment_scaled", "=", "@graph_height", ".", "to_f", "/", "(", "@spread", "/", "@increment", ")", "# Draw horizontal line markers and annotate with numbers", "(", "0", "..", "@marker_count", ")", ".", "each", "do", "|", "index", "|", "y", "=", "@graph_top", "+", "@graph_height", "-", "index", ".", "to_f", "*", "@increment_scaled", "@d", "=", "@d", ".", "fill", "(", "@marker_color", ")", "# FIXME(uwe): Workaround for Issue #66", "# https://github.com/topfunky/gruff/issues/66", "# https://github.com/rmagick/rmagick/issues/82", "# Remove if the issue gets fixed.", "y", "+=", "0.001", "unless", "defined?", "(", "JRUBY_VERSION", ")", "# EMXIF", "@d", "=", "@d", ".", "line", "(", "@graph_left", ",", "y", ",", "@graph_right", ",", "y", ")", "#If the user specified a marker shadow color, draw a shadow just below it", "unless", "@marker_shadow_color", ".", "nil?", "@d", "=", "@d", ".", "fill", "(", "@marker_shadow_color", ")", "@d", "=", "@d", ".", "line", "(", "@graph_left", ",", "y", "+", "1", ",", "@graph_right", ",", "y", "+", "1", ")", "end", "marker_label", "=", "BigDecimal", "(", "index", ".", "to_s", ")", "*", "BigDecimal", "(", "@increment", ".", "to_s", ")", "+", "BigDecimal", "(", "@minimum_value", ".", "to_s", ")", "unless", "@hide_line_numbers", "@d", ".", "fill", "=", "@font_color", "@d", ".", "font", "=", "@font", "if", "@font", "@d", ".", "stroke", "(", "'transparent'", ")", "@d", ".", "pointsize", "=", "scale_fontsize", "(", "@marker_font_size", ")", "@d", ".", "gravity", "=", "EastGravity", "# Vertically center with 1.0 for the height", "@d", "=", "@d", ".", "annotate_scaled", "(", "@base_image", ",", "@graph_left", "-", "LABEL_MARGIN", ",", "1.0", ",", "0.0", ",", "y", ",", "label", "(", "marker_label", ",", "@increment", ")", ",", "@scale", ")", "end", "end", "# # Submitted by a contibutor...the utility escapes me", "# i = 0", "# @additional_line_values.each do |value|", "# @increment_scaled = @graph_height.to_f / (@maximum_value.to_f / value)", "#", "# y = @graph_top + @graph_height - @increment_scaled", "#", "# @d = @d.stroke(@additional_line_colors[i])", "# @d = @d.line(@graph_left, y, @graph_right, y)", "#", "#", "# @d.fill = @additional_line_colors[i]", "# @d.font = @font if @font", "# @d.stroke('transparent')", "# @d.pointsize = scale_fontsize(@marker_font_size)", "# @d.gravity = EastGravity", "# @d = @d.annotate_scaled( @base_image,", "# 100, 20,", "# -10, y - (@marker_font_size/2.0),", "# \"\", @scale)", "# i += 1", "# end", "@d", "=", "@d", ".", "stroke_antialias", "true", "end" ]
Draws horizontal background lines and labels
[ "Draws", "horizontal", "background", "lines", "and", "labels" ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L627-L715
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.draw_legend
def draw_legend return if @hide_legend @legend_labels = @data.collect { |item| item[DATA_LABEL_INDEX] } legend_square_width = @legend_box_size # small square with color of this item # May fix legend drawing problem at small sizes @d.font = @font if @font @d.pointsize = @legend_font_size label_widths = [[]] # Used to calculate line wrap @legend_labels.each do |label| metrics = @d.get_type_metrics(@base_image, label.to_s) label_width = metrics.width + legend_square_width * 2.7 label_widths.last.push label_width if sum(label_widths.last) > (@raw_columns * 0.9) label_widths.push [label_widths.last.pop] end end current_x_offset = center(sum(label_widths.first)) current_y_offset = @legend_at_bottom ? @graph_height + title_margin : (@hide_title ? @top_margin + title_margin : @top_margin + title_margin + @title_caps_height) @legend_labels.each_with_index do |legend_label, index| # Draw label @d.fill = @font_color @d.font = @font if @font @d.pointsize = scale_fontsize(@legend_font_size) @d.stroke('transparent') @d.font_weight = NormalWeight @d.gravity = WestGravity @d = @d.annotate_scaled(@base_image, @raw_columns, 1.0, current_x_offset + (legend_square_width * 1.7), current_y_offset, legend_label.to_s, @scale) # Now draw box with color of this dataset @d = @d.stroke('transparent') @d = @d.fill @data[index][DATA_COLOR_INDEX] @d = @d.rectangle(current_x_offset, current_y_offset - legend_square_width / 2.0, current_x_offset + legend_square_width, current_y_offset + legend_square_width / 2.0) @d.pointsize = @legend_font_size metrics = @d.get_type_metrics(@base_image, legend_label.to_s) current_string_offset = metrics.width + (legend_square_width * 2.7) # Handle wrapping label_widths.first.shift if label_widths.first.empty? debug { @d.line 0.0, current_y_offset, @raw_columns, current_y_offset } label_widths.shift current_x_offset = center(sum(label_widths.first)) unless label_widths.empty? line_height = [@legend_caps_height, legend_square_width].max + legend_margin if label_widths.length > 0 # Wrap to next line and shrink available graph dimensions current_y_offset += line_height @graph_top += line_height @graph_height = @graph_bottom - @graph_top end else current_x_offset += current_string_offset end end @color_index = 0 end
ruby
def draw_legend return if @hide_legend @legend_labels = @data.collect { |item| item[DATA_LABEL_INDEX] } legend_square_width = @legend_box_size # small square with color of this item # May fix legend drawing problem at small sizes @d.font = @font if @font @d.pointsize = @legend_font_size label_widths = [[]] # Used to calculate line wrap @legend_labels.each do |label| metrics = @d.get_type_metrics(@base_image, label.to_s) label_width = metrics.width + legend_square_width * 2.7 label_widths.last.push label_width if sum(label_widths.last) > (@raw_columns * 0.9) label_widths.push [label_widths.last.pop] end end current_x_offset = center(sum(label_widths.first)) current_y_offset = @legend_at_bottom ? @graph_height + title_margin : (@hide_title ? @top_margin + title_margin : @top_margin + title_margin + @title_caps_height) @legend_labels.each_with_index do |legend_label, index| # Draw label @d.fill = @font_color @d.font = @font if @font @d.pointsize = scale_fontsize(@legend_font_size) @d.stroke('transparent') @d.font_weight = NormalWeight @d.gravity = WestGravity @d = @d.annotate_scaled(@base_image, @raw_columns, 1.0, current_x_offset + (legend_square_width * 1.7), current_y_offset, legend_label.to_s, @scale) # Now draw box with color of this dataset @d = @d.stroke('transparent') @d = @d.fill @data[index][DATA_COLOR_INDEX] @d = @d.rectangle(current_x_offset, current_y_offset - legend_square_width / 2.0, current_x_offset + legend_square_width, current_y_offset + legend_square_width / 2.0) @d.pointsize = @legend_font_size metrics = @d.get_type_metrics(@base_image, legend_label.to_s) current_string_offset = metrics.width + (legend_square_width * 2.7) # Handle wrapping label_widths.first.shift if label_widths.first.empty? debug { @d.line 0.0, current_y_offset, @raw_columns, current_y_offset } label_widths.shift current_x_offset = center(sum(label_widths.first)) unless label_widths.empty? line_height = [@legend_caps_height, legend_square_width].max + legend_margin if label_widths.length > 0 # Wrap to next line and shrink available graph dimensions current_y_offset += line_height @graph_top += line_height @graph_height = @graph_bottom - @graph_top end else current_x_offset += current_string_offset end end @color_index = 0 end
[ "def", "draw_legend", "return", "if", "@hide_legend", "@legend_labels", "=", "@data", ".", "collect", "{", "|", "item", "|", "item", "[", "DATA_LABEL_INDEX", "]", "}", "legend_square_width", "=", "@legend_box_size", "# small square with color of this item", "# May fix legend drawing problem at small sizes", "@d", ".", "font", "=", "@font", "if", "@font", "@d", ".", "pointsize", "=", "@legend_font_size", "label_widths", "=", "[", "[", "]", "]", "# Used to calculate line wrap", "@legend_labels", ".", "each", "do", "|", "label", "|", "metrics", "=", "@d", ".", "get_type_metrics", "(", "@base_image", ",", "label", ".", "to_s", ")", "label_width", "=", "metrics", ".", "width", "+", "legend_square_width", "*", "2.7", "label_widths", ".", "last", ".", "push", "label_width", "if", "sum", "(", "label_widths", ".", "last", ")", ">", "(", "@raw_columns", "*", "0.9", ")", "label_widths", ".", "push", "[", "label_widths", ".", "last", ".", "pop", "]", "end", "end", "current_x_offset", "=", "center", "(", "sum", "(", "label_widths", ".", "first", ")", ")", "current_y_offset", "=", "@legend_at_bottom", "?", "@graph_height", "+", "title_margin", ":", "(", "@hide_title", "?", "@top_margin", "+", "title_margin", ":", "@top_margin", "+", "title_margin", "+", "@title_caps_height", ")", "@legend_labels", ".", "each_with_index", "do", "|", "legend_label", ",", "index", "|", "# Draw label", "@d", ".", "fill", "=", "@font_color", "@d", ".", "font", "=", "@font", "if", "@font", "@d", ".", "pointsize", "=", "scale_fontsize", "(", "@legend_font_size", ")", "@d", ".", "stroke", "(", "'transparent'", ")", "@d", ".", "font_weight", "=", "NormalWeight", "@d", ".", "gravity", "=", "WestGravity", "@d", "=", "@d", ".", "annotate_scaled", "(", "@base_image", ",", "@raw_columns", ",", "1.0", ",", "current_x_offset", "+", "(", "legend_square_width", "*", "1.7", ")", ",", "current_y_offset", ",", "legend_label", ".", "to_s", ",", "@scale", ")", "# Now draw box with color of this dataset", "@d", "=", "@d", ".", "stroke", "(", "'transparent'", ")", "@d", "=", "@d", ".", "fill", "@data", "[", "index", "]", "[", "DATA_COLOR_INDEX", "]", "@d", "=", "@d", ".", "rectangle", "(", "current_x_offset", ",", "current_y_offset", "-", "legend_square_width", "/", "2.0", ",", "current_x_offset", "+", "legend_square_width", ",", "current_y_offset", "+", "legend_square_width", "/", "2.0", ")", "@d", ".", "pointsize", "=", "@legend_font_size", "metrics", "=", "@d", ".", "get_type_metrics", "(", "@base_image", ",", "legend_label", ".", "to_s", ")", "current_string_offset", "=", "metrics", ".", "width", "+", "(", "legend_square_width", "*", "2.7", ")", "# Handle wrapping", "label_widths", ".", "first", ".", "shift", "if", "label_widths", ".", "first", ".", "empty?", "debug", "{", "@d", ".", "line", "0.0", ",", "current_y_offset", ",", "@raw_columns", ",", "current_y_offset", "}", "label_widths", ".", "shift", "current_x_offset", "=", "center", "(", "sum", "(", "label_widths", ".", "first", ")", ")", "unless", "label_widths", ".", "empty?", "line_height", "=", "[", "@legend_caps_height", ",", "legend_square_width", "]", ".", "max", "+", "legend_margin", "if", "label_widths", ".", "length", ">", "0", "# Wrap to next line and shrink available graph dimensions", "current_y_offset", "+=", "line_height", "@graph_top", "+=", "line_height", "@graph_height", "=", "@graph_bottom", "-", "@graph_top", "end", "else", "current_x_offset", "+=", "current_string_offset", "end", "end", "@color_index", "=", "0", "end" ]
Draws a legend with the names of the datasets matched to the colors used to draw them.
[ "Draws", "a", "legend", "with", "the", "names", "of", "the", "datasets", "matched", "to", "the", "colors", "used", "to", "draw", "them", "." ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L737-L809
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.draw_title
def draw_title return if (@hide_title || @title.nil?) @d.fill = @font_color @d.font = @title_font || @font if @title_font || @font @d.stroke('transparent') @d.pointsize = scale_fontsize(@title_font_size) @d.font_weight = if @bold_title then BoldWeight else NormalWeight end @d.gravity = NorthGravity @d = @d.annotate_scaled(@base_image, @raw_columns, 1.0, 0, @top_margin, @title, @scale) end
ruby
def draw_title return if (@hide_title || @title.nil?) @d.fill = @font_color @d.font = @title_font || @font if @title_font || @font @d.stroke('transparent') @d.pointsize = scale_fontsize(@title_font_size) @d.font_weight = if @bold_title then BoldWeight else NormalWeight end @d.gravity = NorthGravity @d = @d.annotate_scaled(@base_image, @raw_columns, 1.0, 0, @top_margin, @title, @scale) end
[ "def", "draw_title", "return", "if", "(", "@hide_title", "||", "@title", ".", "nil?", ")", "@d", ".", "fill", "=", "@font_color", "@d", ".", "font", "=", "@title_font", "||", "@font", "if", "@title_font", "||", "@font", "@d", ".", "stroke", "(", "'transparent'", ")", "@d", ".", "pointsize", "=", "scale_fontsize", "(", "@title_font_size", ")", "@d", ".", "font_weight", "=", "if", "@bold_title", "then", "BoldWeight", "else", "NormalWeight", "end", "@d", ".", "gravity", "=", "NorthGravity", "@d", "=", "@d", ".", "annotate_scaled", "(", "@base_image", ",", "@raw_columns", ",", "1.0", ",", "0", ",", "@top_margin", ",", "@title", ",", "@scale", ")", "end" ]
Draws a title on the graph.
[ "Draws", "a", "title", "on", "the", "graph", "." ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L812-L825
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.draw_value_label
def draw_value_label(x_offset, y_offset, data_point, bar_value=false) return if @hide_line_markers && !bar_value #y_offset = @graph_bottom + LABEL_MARGIN @d.fill = @font_color @d.font = @font if @font @d.stroke('transparent') @d.font_weight = NormalWeight @d.pointsize = scale_fontsize(@marker_font_size) @d.gravity = NorthGravity @d = @d.annotate_scaled(@base_image, 1.0, 1.0, x_offset, y_offset, data_point.to_s, @scale) debug { @d.line 0.0, y_offset, @raw_columns, y_offset } end
ruby
def draw_value_label(x_offset, y_offset, data_point, bar_value=false) return if @hide_line_markers && !bar_value #y_offset = @graph_bottom + LABEL_MARGIN @d.fill = @font_color @d.font = @font if @font @d.stroke('transparent') @d.font_weight = NormalWeight @d.pointsize = scale_fontsize(@marker_font_size) @d.gravity = NorthGravity @d = @d.annotate_scaled(@base_image, 1.0, 1.0, x_offset, y_offset, data_point.to_s, @scale) debug { @d.line 0.0, y_offset, @raw_columns, y_offset } end
[ "def", "draw_value_label", "(", "x_offset", ",", "y_offset", ",", "data_point", ",", "bar_value", "=", "false", ")", "return", "if", "@hide_line_markers", "&&", "!", "bar_value", "#y_offset = @graph_bottom + LABEL_MARGIN", "@d", ".", "fill", "=", "@font_color", "@d", ".", "font", "=", "@font", "if", "@font", "@d", ".", "stroke", "(", "'transparent'", ")", "@d", ".", "font_weight", "=", "NormalWeight", "@d", ".", "pointsize", "=", "scale_fontsize", "(", "@marker_font_size", ")", "@d", ".", "gravity", "=", "NorthGravity", "@d", "=", "@d", ".", "annotate_scaled", "(", "@base_image", ",", "1.0", ",", "1.0", ",", "x_offset", ",", "y_offset", ",", "data_point", ".", "to_s", ",", "@scale", ")", "debug", "{", "@d", ".", "line", "0.0", ",", "y_offset", ",", "@raw_columns", ",", "y_offset", "}", "end" ]
Draws the data value over the data point in bar graphs
[ "Draws", "the", "data", "value", "over", "the", "data", "point", "in", "bar", "graphs" ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L875-L892
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.draw_no_data
def draw_no_data @d.fill = @font_color @d.font = @font if @font @d.stroke('transparent') @d.font_weight = NormalWeight @d.pointsize = scale_fontsize(80) @d.gravity = CenterGravity @d = @d.annotate_scaled(@base_image, @raw_columns, @raw_rows/2.0, 0, 10, @no_data_message, @scale) end
ruby
def draw_no_data @d.fill = @font_color @d.font = @font if @font @d.stroke('transparent') @d.font_weight = NormalWeight @d.pointsize = scale_fontsize(80) @d.gravity = CenterGravity @d = @d.annotate_scaled(@base_image, @raw_columns, @raw_rows/2.0, 0, 10, @no_data_message, @scale) end
[ "def", "draw_no_data", "@d", ".", "fill", "=", "@font_color", "@d", ".", "font", "=", "@font", "if", "@font", "@d", ".", "stroke", "(", "'transparent'", ")", "@d", ".", "font_weight", "=", "NormalWeight", "@d", ".", "pointsize", "=", "scale_fontsize", "(", "80", ")", "@d", ".", "gravity", "=", "CenterGravity", "@d", "=", "@d", ".", "annotate_scaled", "(", "@base_image", ",", "@raw_columns", ",", "@raw_rows", "/", "2.0", ",", "0", ",", "10", ",", "@no_data_message", ",", "@scale", ")", "end" ]
Shows an error message because you have no data.
[ "Shows", "an", "error", "message", "because", "you", "have", "no", "data", "." ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L895-L906
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.render_gradiated_background
def render_gradiated_background(top_color, bottom_color, direct = :top_bottom) case direct when :bottom_top gradient_fill = GradientFill.new(0, 0, 100, 0, bottom_color, top_color) when :left_right gradient_fill = GradientFill.new(0, 0, 0, 100, top_color, bottom_color) when :right_left gradient_fill = GradientFill.new(0, 0, 0, 100, bottom_color, top_color) when :topleft_bottomright gradient_fill = GradientFill.new(0, 100, 100, 0, top_color, bottom_color) when :topright_bottomleft gradient_fill = GradientFill.new(0, 0, 100, 100, bottom_color, top_color) else gradient_fill = GradientFill.new(0, 0, 100, 0, top_color, bottom_color) end Image.new(@columns, @rows, gradient_fill) end
ruby
def render_gradiated_background(top_color, bottom_color, direct = :top_bottom) case direct when :bottom_top gradient_fill = GradientFill.new(0, 0, 100, 0, bottom_color, top_color) when :left_right gradient_fill = GradientFill.new(0, 0, 0, 100, top_color, bottom_color) when :right_left gradient_fill = GradientFill.new(0, 0, 0, 100, bottom_color, top_color) when :topleft_bottomright gradient_fill = GradientFill.new(0, 100, 100, 0, top_color, bottom_color) when :topright_bottomleft gradient_fill = GradientFill.new(0, 0, 100, 100, bottom_color, top_color) else gradient_fill = GradientFill.new(0, 0, 100, 0, top_color, bottom_color) end Image.new(@columns, @rows, gradient_fill) end
[ "def", "render_gradiated_background", "(", "top_color", ",", "bottom_color", ",", "direct", "=", ":top_bottom", ")", "case", "direct", "when", ":bottom_top", "gradient_fill", "=", "GradientFill", ".", "new", "(", "0", ",", "0", ",", "100", ",", "0", ",", "bottom_color", ",", "top_color", ")", "when", ":left_right", "gradient_fill", "=", "GradientFill", ".", "new", "(", "0", ",", "0", ",", "0", ",", "100", ",", "top_color", ",", "bottom_color", ")", "when", ":right_left", "gradient_fill", "=", "GradientFill", ".", "new", "(", "0", ",", "0", ",", "0", ",", "100", ",", "bottom_color", ",", "top_color", ")", "when", ":topleft_bottomright", "gradient_fill", "=", "GradientFill", ".", "new", "(", "0", ",", "100", ",", "100", ",", "0", ",", "top_color", ",", "bottom_color", ")", "when", ":topright_bottomleft", "gradient_fill", "=", "GradientFill", ".", "new", "(", "0", ",", "0", ",", "100", ",", "100", ",", "bottom_color", ",", "top_color", ")", "else", "gradient_fill", "=", "GradientFill", ".", "new", "(", "0", ",", "0", ",", "100", ",", "0", ",", "top_color", ",", "bottom_color", ")", "end", "Image", ".", "new", "(", "@columns", ",", "@rows", ",", "gradient_fill", ")", "end" ]
Use with a theme definition method to draw a gradiated background.
[ "Use", "with", "a", "theme", "definition", "method", "to", "draw", "a", "gradiated", "background", "." ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L930-L946
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.sort_data
def sort_data @data = @data.sort_by { |a| -a[DATA_VALUES_INDEX].inject(0) { |sum, num| sum + num.to_f } } end
ruby
def sort_data @data = @data.sort_by { |a| -a[DATA_VALUES_INDEX].inject(0) { |sum, num| sum + num.to_f } } end
[ "def", "sort_data", "@data", "=", "@data", ".", "sort_by", "{", "|", "a", "|", "-", "a", "[", "DATA_VALUES_INDEX", "]", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "num", "|", "sum", "+", "num", ".", "to_f", "}", "}", "end" ]
Sort with largest overall summed value at front of array.
[ "Sort", "with", "largest", "overall", "summed", "value", "at", "front", "of", "array", "." ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L1020-L1022
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.sort_norm_data
def sort_norm_data @norm_data = @norm_data.sort_by { |a| -a[DATA_VALUES_INDEX].inject(0) { |sum, num| sum + num.to_f } } end
ruby
def sort_norm_data @norm_data = @norm_data.sort_by { |a| -a[DATA_VALUES_INDEX].inject(0) { |sum, num| sum + num.to_f } } end
[ "def", "sort_norm_data", "@norm_data", "=", "@norm_data", ".", "sort_by", "{", "|", "a", "|", "-", "a", "[", "DATA_VALUES_INDEX", "]", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "num", "|", "sum", "+", "num", ".", "to_f", "}", "}", "end" ]
Sort with largest overall summed value at front of array so it shows up correctly in the drawn graph.
[ "Sort", "with", "largest", "overall", "summed", "value", "at", "front", "of", "array", "so", "it", "shows", "up", "correctly", "in", "the", "drawn", "graph", "." ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L1031-L1034
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.get_maximum_by_stack
def get_maximum_by_stack # Get sum of each stack max_hash = {} @data.each do |data_set| data_set[DATA_VALUES_INDEX].each_with_index do |data_point, i| max_hash[i] = 0.0 unless max_hash[i] max_hash[i] += data_point.to_f end end # @maximum_value = 0 max_hash.keys.each do |key| @maximum_value = max_hash[key] if max_hash[key] > @maximum_value end @minimum_value = 0 end
ruby
def get_maximum_by_stack # Get sum of each stack max_hash = {} @data.each do |data_set| data_set[DATA_VALUES_INDEX].each_with_index do |data_point, i| max_hash[i] = 0.0 unless max_hash[i] max_hash[i] += data_point.to_f end end # @maximum_value = 0 max_hash.keys.each do |key| @maximum_value = max_hash[key] if max_hash[key] > @maximum_value end @minimum_value = 0 end
[ "def", "get_maximum_by_stack", "# Get sum of each stack", "max_hash", "=", "{", "}", "@data", ".", "each", "do", "|", "data_set", "|", "data_set", "[", "DATA_VALUES_INDEX", "]", ".", "each_with_index", "do", "|", "data_point", ",", "i", "|", "max_hash", "[", "i", "]", "=", "0.0", "unless", "max_hash", "[", "i", "]", "max_hash", "[", "i", "]", "+=", "data_point", ".", "to_f", "end", "end", "# @maximum_value = 0", "max_hash", ".", "keys", ".", "each", "do", "|", "key", "|", "@maximum_value", "=", "max_hash", "[", "key", "]", "if", "max_hash", "[", "key", "]", ">", "@maximum_value", "end", "@minimum_value", "=", "0", "end" ]
Used by StackedBar and child classes. May need to be moved to the StackedBar class.
[ "Used", "by", "StackedBar", "and", "child", "classes", "." ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L1039-L1054
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.label
def label(value, increment) label = if increment if increment >= 10 || (increment * 1) == (increment * 1).to_i.to_f sprintf('%0i', value) elsif increment >= 1.0 || (increment * 10) == (increment * 10).to_i.to_f sprintf('%0.1f', value) elsif increment >= 0.1 || (increment * 100) == (increment * 100).to_i.to_f sprintf('%0.2f', value) elsif increment >= 0.01 || (increment * 1000) == (increment * 1000).to_i.to_f sprintf('%0.3f', value) elsif increment >= 0.001 || (increment * 10000) == (increment * 10000).to_i.to_f sprintf('%0.4f', value) else value.to_s end elsif (@spread.to_f % (@marker_count.to_f==0 ? 1 : @marker_count.to_f) == 0) || !@y_axis_increment.nil? value.to_i.to_s elsif @spread > 10.0 sprintf('%0i', value) elsif @spread >= 3.0 sprintf('%0.2f', value) else value.to_s end parts = label.split('.') parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{THOUSAND_SEPARATOR}") parts.join('.') end
ruby
def label(value, increment) label = if increment if increment >= 10 || (increment * 1) == (increment * 1).to_i.to_f sprintf('%0i', value) elsif increment >= 1.0 || (increment * 10) == (increment * 10).to_i.to_f sprintf('%0.1f', value) elsif increment >= 0.1 || (increment * 100) == (increment * 100).to_i.to_f sprintf('%0.2f', value) elsif increment >= 0.01 || (increment * 1000) == (increment * 1000).to_i.to_f sprintf('%0.3f', value) elsif increment >= 0.001 || (increment * 10000) == (increment * 10000).to_i.to_f sprintf('%0.4f', value) else value.to_s end elsif (@spread.to_f % (@marker_count.to_f==0 ? 1 : @marker_count.to_f) == 0) || !@y_axis_increment.nil? value.to_i.to_s elsif @spread > 10.0 sprintf('%0i', value) elsif @spread >= 3.0 sprintf('%0.2f', value) else value.to_s end parts = label.split('.') parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{THOUSAND_SEPARATOR}") parts.join('.') end
[ "def", "label", "(", "value", ",", "increment", ")", "label", "=", "if", "increment", "if", "increment", ">=", "10", "||", "(", "increment", "*", "1", ")", "==", "(", "increment", "*", "1", ")", ".", "to_i", ".", "to_f", "sprintf", "(", "'%0i'", ",", "value", ")", "elsif", "increment", ">=", "1.0", "||", "(", "increment", "*", "10", ")", "==", "(", "increment", "*", "10", ")", ".", "to_i", ".", "to_f", "sprintf", "(", "'%0.1f'", ",", "value", ")", "elsif", "increment", ">=", "0.1", "||", "(", "increment", "*", "100", ")", "==", "(", "increment", "*", "100", ")", ".", "to_i", ".", "to_f", "sprintf", "(", "'%0.2f'", ",", "value", ")", "elsif", "increment", ">=", "0.01", "||", "(", "increment", "*", "1000", ")", "==", "(", "increment", "*", "1000", ")", ".", "to_i", ".", "to_f", "sprintf", "(", "'%0.3f'", ",", "value", ")", "elsif", "increment", ">=", "0.001", "||", "(", "increment", "*", "10000", ")", "==", "(", "increment", "*", "10000", ")", ".", "to_i", ".", "to_f", "sprintf", "(", "'%0.4f'", ",", "value", ")", "else", "value", ".", "to_s", "end", "elsif", "(", "@spread", ".", "to_f", "%", "(", "@marker_count", ".", "to_f", "==", "0", "?", "1", ":", "@marker_count", ".", "to_f", ")", "==", "0", ")", "||", "!", "@y_axis_increment", ".", "nil?", "value", ".", "to_i", ".", "to_s", "elsif", "@spread", ">", "10.0", "sprintf", "(", "'%0i'", ",", "value", ")", "elsif", "@spread", ">=", "3.0", "sprintf", "(", "'%0.2f'", ",", "value", ")", "else", "value", ".", "to_s", "end", "parts", "=", "label", ".", "split", "(", "'.'", ")", "parts", "[", "0", "]", ".", "gsub!", "(", "/", "\\d", "\\d", "\\d", "\\d", "\\d", "/", ",", "\"\\\\1#{THOUSAND_SEPARATOR}\"", ")", "parts", ".", "join", "(", "'.'", ")", "end" ]
Return a formatted string representing a number value that should be printed as a label.
[ "Return", "a", "formatted", "string", "representing", "a", "number", "value", "that", "should", "be", "printed", "as", "a", "label", "." ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L1088-L1116
train
topfunky/gruff
lib/gruff/base.rb
Gruff.Base.calculate_width
def calculate_width(font_size, text) return 0 if text.nil? @d.pointsize = font_size @d.font = @font if @font @d.get_type_metrics(@base_image, text.to_s).width end
ruby
def calculate_width(font_size, text) return 0 if text.nil? @d.pointsize = font_size @d.font = @font if @font @d.get_type_metrics(@base_image, text.to_s).width end
[ "def", "calculate_width", "(", "font_size", ",", "text", ")", "return", "0", "if", "text", ".", "nil?", "@d", ".", "pointsize", "=", "font_size", "@d", ".", "font", "=", "@font", "if", "@font", "@d", ".", "get_type_metrics", "(", "@base_image", ",", "text", ".", "to_s", ")", ".", "width", "end" ]
Returns the width of a string at this pointsize. Not scaled since it deals with dimensions that the regular scaling will handle.
[ "Returns", "the", "width", "of", "a", "string", "at", "this", "pointsize", "." ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L1133-L1138
train
topfunky/gruff
lib/gruff/base.rb
Magick.Draw.annotate_scaled
def annotate_scaled(img, width, height, x, y, text, scale) scaled_width = (width * scale) >= 1 ? (width * scale) : 1 scaled_height = (height * scale) >= 1 ? (height * scale) : 1 self.annotate(img, scaled_width, scaled_height, x * scale, y * scale, text.gsub('%', '%%')) end
ruby
def annotate_scaled(img, width, height, x, y, text, scale) scaled_width = (width * scale) >= 1 ? (width * scale) : 1 scaled_height = (height * scale) >= 1 ? (height * scale) : 1 self.annotate(img, scaled_width, scaled_height, x * scale, y * scale, text.gsub('%', '%%')) end
[ "def", "annotate_scaled", "(", "img", ",", "width", ",", "height", ",", "x", ",", "y", ",", "text", ",", "scale", ")", "scaled_width", "=", "(", "width", "*", "scale", ")", ">=", "1", "?", "(", "width", "*", "scale", ")", ":", "1", "scaled_height", "=", "(", "height", "*", "scale", ")", ">=", "1", "?", "(", "height", "*", "scale", ")", ":", "1", "self", ".", "annotate", "(", "img", ",", "scaled_width", ",", "scaled_height", ",", "x", "*", "scale", ",", "y", "*", "scale", ",", "text", ".", "gsub", "(", "'%'", ",", "'%%'", ")", ")", "end" ]
Additional method to scale annotation text since Draw.scale doesn't.
[ "Additional", "method", "to", "scale", "annotation", "text", "since", "Draw", ".", "scale", "doesn", "t", "." ]
0625ec81f37908d519e6a725a3140a42fb9aa2ee
https://github.com/topfunky/gruff/blob/0625ec81f37908d519e6a725a3140a42fb9aa2ee/lib/gruff/base.rb#L1157-L1165
train
coinbase/traffic_jam
lib/traffic_jam/configuration.rb
TrafficJam.Configuration.limits
def limits(action) @limits ||= {} limits = @limits[action.to_sym] raise TrafficJam::LimitNotFound.new(action) if limits.nil? limits end
ruby
def limits(action) @limits ||= {} limits = @limits[action.to_sym] raise TrafficJam::LimitNotFound.new(action) if limits.nil? limits end
[ "def", "limits", "(", "action", ")", "@limits", "||=", "{", "}", "limits", "=", "@limits", "[", "action", ".", "to_sym", "]", "raise", "TrafficJam", "::", "LimitNotFound", ".", "new", "(", "action", ")", "if", "limits", ".", "nil?", "limits", "end" ]
Get registered limit parameters for an action. @see #register @param action [Symbol] action name @return [Hash] max and period parameters in a hash @raise [TrafficJam::LimitNotFound] if action is not registered
[ "Get", "registered", "limit", "parameters", "for", "an", "action", "." ]
2b90aa596fdb384086a5a39a203effed14a01756
https://github.com/coinbase/traffic_jam/blob/2b90aa596fdb384086a5a39a203effed14a01756/lib/traffic_jam/configuration.rb#L56-L61
train
coinbase/traffic_jam
lib/traffic_jam/limit_group.rb
TrafficJam.LimitGroup.increment
def increment(amount = 1, time: Time.now) exceeded_index = limits.find_index do |limit| !limit.increment(amount, time: time) end if exceeded_index limits[0...exceeded_index].each do |limit| limit.decrement(amount, time: time) end end exceeded_index.nil? end
ruby
def increment(amount = 1, time: Time.now) exceeded_index = limits.find_index do |limit| !limit.increment(amount, time: time) end if exceeded_index limits[0...exceeded_index].each do |limit| limit.decrement(amount, time: time) end end exceeded_index.nil? end
[ "def", "increment", "(", "amount", "=", "1", ",", "time", ":", "Time", ".", "now", ")", "exceeded_index", "=", "limits", ".", "find_index", "do", "|", "limit", "|", "!", "limit", ".", "increment", "(", "amount", ",", "time", ":", "time", ")", "end", "if", "exceeded_index", "limits", "[", "0", "...", "exceeded_index", "]", ".", "each", "do", "|", "limit", "|", "limit", ".", "decrement", "(", "amount", ",", "time", ":", "time", ")", "end", "end", "exceeded_index", ".", "nil?", "end" ]
Attempt to increment the limits by the given amount. Does not increment if incrementing would exceed any limit. @param amount [Integer] amount to increment by @param time [Time] optional time of increment @return [Boolean] whether increment operation was successful
[ "Attempt", "to", "increment", "the", "limits", "by", "the", "given", "amount", ".", "Does", "not", "increment", "if", "incrementing", "would", "exceed", "any", "limit", "." ]
2b90aa596fdb384086a5a39a203effed14a01756
https://github.com/coinbase/traffic_jam/blob/2b90aa596fdb384086a5a39a203effed14a01756/lib/traffic_jam/limit_group.rb#L39-L49
train
coinbase/traffic_jam
lib/traffic_jam/limit_group.rb
TrafficJam.LimitGroup.increment!
def increment!(amount = 1, time: Time.now) exception = nil exceeded_index = limits.find_index do |limit| begin limit.increment!(amount, time: time) rescue TrafficJam::LimitExceededError => e exception = e true end end if exceeded_index limits[0...exceeded_index].each do |limit| limit.decrement(amount, time: time) end raise exception end end
ruby
def increment!(amount = 1, time: Time.now) exception = nil exceeded_index = limits.find_index do |limit| begin limit.increment!(amount, time: time) rescue TrafficJam::LimitExceededError => e exception = e true end end if exceeded_index limits[0...exceeded_index].each do |limit| limit.decrement(amount, time: time) end raise exception end end
[ "def", "increment!", "(", "amount", "=", "1", ",", "time", ":", "Time", ".", "now", ")", "exception", "=", "nil", "exceeded_index", "=", "limits", ".", "find_index", "do", "|", "limit", "|", "begin", "limit", ".", "increment!", "(", "amount", ",", "time", ":", "time", ")", "rescue", "TrafficJam", "::", "LimitExceededError", "=>", "e", "exception", "=", "e", "true", "end", "end", "if", "exceeded_index", "limits", "[", "0", "...", "exceeded_index", "]", ".", "each", "do", "|", "limit", "|", "limit", ".", "decrement", "(", "amount", ",", "time", ":", "time", ")", "end", "raise", "exception", "end", "end" ]
Increment the limits by the given amount. Raises an error and does not increment if doing so would exceed any limit. @param amount [Integer] amount to increment by @param time [Time] optional time of increment @return [nil] @raise [TrafficJam::LimitExceededError] if increment would exceed any limits
[ "Increment", "the", "limits", "by", "the", "given", "amount", ".", "Raises", "an", "error", "and", "does", "not", "increment", "if", "doing", "so", "would", "exceed", "any", "limit", "." ]
2b90aa596fdb384086a5a39a203effed14a01756
https://github.com/coinbase/traffic_jam/blob/2b90aa596fdb384086a5a39a203effed14a01756/lib/traffic_jam/limit_group.rb#L59-L75
train
coinbase/traffic_jam
lib/traffic_jam/limit_group.rb
TrafficJam.LimitGroup.decrement
def decrement(amount = 1, time: Time.now) limits.all? { |limit| limit.decrement(amount, time: time) } end
ruby
def decrement(amount = 1, time: Time.now) limits.all? { |limit| limit.decrement(amount, time: time) } end
[ "def", "decrement", "(", "amount", "=", "1", ",", "time", ":", "Time", ".", "now", ")", "limits", ".", "all?", "{", "|", "limit", "|", "limit", ".", "decrement", "(", "amount", ",", "time", ":", "time", ")", "}", "end" ]
Decrement the limits by the given amount. @param amount [Integer] amount to decrement by @param time [Time] optional time of decrement @return [true]
[ "Decrement", "the", "limits", "by", "the", "given", "amount", "." ]
2b90aa596fdb384086a5a39a203effed14a01756
https://github.com/coinbase/traffic_jam/blob/2b90aa596fdb384086a5a39a203effed14a01756/lib/traffic_jam/limit_group.rb#L82-L84
train
coinbase/traffic_jam
lib/traffic_jam/limit_group.rb
TrafficJam.LimitGroup.limit_exceeded
def limit_exceeded(amount = 1) limits.each do |limit| limit_exceeded = limit.limit_exceeded(amount) return limit_exceeded if limit_exceeded end nil end
ruby
def limit_exceeded(amount = 1) limits.each do |limit| limit_exceeded = limit.limit_exceeded(amount) return limit_exceeded if limit_exceeded end nil end
[ "def", "limit_exceeded", "(", "amount", "=", "1", ")", "limits", ".", "each", "do", "|", "limit", "|", "limit_exceeded", "=", "limit", ".", "limit_exceeded", "(", "amount", ")", "return", "limit_exceeded", "if", "limit_exceeded", "end", "nil", "end" ]
Return the first limit to be exceeded if incrementing by the given amount, or nil otherwise. Does not change amount used for any limit. @param amount [Integer] @return [TrafficJam::Limit, nil]
[ "Return", "the", "first", "limit", "to", "be", "exceeded", "if", "incrementing", "by", "the", "given", "amount", "or", "nil", "otherwise", ".", "Does", "not", "change", "amount", "used", "for", "any", "limit", "." ]
2b90aa596fdb384086a5a39a203effed14a01756
https://github.com/coinbase/traffic_jam/blob/2b90aa596fdb384086a5a39a203effed14a01756/lib/traffic_jam/limit_group.rb#L100-L106
train
coinbase/traffic_jam
lib/traffic_jam/gcra_limit.rb
TrafficJam.GCRALimit.increment
def increment(amount = 1, time: Time.now) return true if amount == 0 return false if max == 0 raise ArgumentError.new("Amount must be positive") if amount < 0 if amount != amount.to_i raise ArgumentError.new("Amount must be an integer") end return false if amount > max incrby = (period * 1000 * amount / max).to_i argv = [incrby, period * 1000] result = begin redis.evalsha( Scripts::INCREMENT_GCRA_HASH, keys: [key], argv: argv) rescue Redis::CommandError redis.eval(Scripts::INCREMENT_GCRA, keys: [key], argv: argv) end case result when 0 return true when -1 raise Errors::InvalidKeyError, "Redis key #{key} has no expire time set" when -2 return false else raise Errors::UnknownReturnValue, "Received unexpected return value #{result} from " \ "increment_gcra eval" end end
ruby
def increment(amount = 1, time: Time.now) return true if amount == 0 return false if max == 0 raise ArgumentError.new("Amount must be positive") if amount < 0 if amount != amount.to_i raise ArgumentError.new("Amount must be an integer") end return false if amount > max incrby = (period * 1000 * amount / max).to_i argv = [incrby, period * 1000] result = begin redis.evalsha( Scripts::INCREMENT_GCRA_HASH, keys: [key], argv: argv) rescue Redis::CommandError redis.eval(Scripts::INCREMENT_GCRA, keys: [key], argv: argv) end case result when 0 return true when -1 raise Errors::InvalidKeyError, "Redis key #{key} has no expire time set" when -2 return false else raise Errors::UnknownReturnValue, "Received unexpected return value #{result} from " \ "increment_gcra eval" end end
[ "def", "increment", "(", "amount", "=", "1", ",", "time", ":", "Time", ".", "now", ")", "return", "true", "if", "amount", "==", "0", "return", "false", "if", "max", "==", "0", "raise", "ArgumentError", ".", "new", "(", "\"Amount must be positive\"", ")", "if", "amount", "<", "0", "if", "amount", "!=", "amount", ".", "to_i", "raise", "ArgumentError", ".", "new", "(", "\"Amount must be an integer\"", ")", "end", "return", "false", "if", "amount", ">", "max", "incrby", "=", "(", "period", "*", "1000", "*", "amount", "/", "max", ")", ".", "to_i", "argv", "=", "[", "incrby", ",", "period", "*", "1000", "]", "result", "=", "begin", "redis", ".", "evalsha", "(", "Scripts", "::", "INCREMENT_GCRA_HASH", ",", "keys", ":", "[", "key", "]", ",", "argv", ":", "argv", ")", "rescue", "Redis", "::", "CommandError", "redis", ".", "eval", "(", "Scripts", "::", "INCREMENT_GCRA", ",", "keys", ":", "[", "key", "]", ",", "argv", ":", "argv", ")", "end", "case", "result", "when", "0", "return", "true", "when", "-", "1", "raise", "Errors", "::", "InvalidKeyError", ",", "\"Redis key #{key} has no expire time set\"", "when", "-", "2", "return", "false", "else", "raise", "Errors", "::", "UnknownReturnValue", ",", "\"Received unexpected return value #{result} from \"", "\"increment_gcra eval\"", "end", "end" ]
Increment the amount used by the given number. Does not perform increment if the operation would exceed the limit. Returns whether the operation was successful. @param amount [Integer] amount to increment by @param time [Time] time is ignored @return [Boolean] true if increment succeded and false if incrementing would exceed the limit
[ "Increment", "the", "amount", "used", "by", "the", "given", "number", ".", "Does", "not", "perform", "increment", "if", "the", "operation", "would", "exceed", "the", "limit", ".", "Returns", "whether", "the", "operation", "was", "successful", "." ]
2b90aa596fdb384086a5a39a203effed14a01756
https://github.com/coinbase/traffic_jam/blob/2b90aa596fdb384086a5a39a203effed14a01756/lib/traffic_jam/gcra_limit.rb#L35-L69
train
coinbase/traffic_jam
lib/traffic_jam/limit.rb
TrafficJam.Limit.increment
def increment(amount = 1, time: Time.now) return amount <= 0 if max.zero? if amount != amount.to_i raise ArgumentError.new("Amount must be an integer") end timestamp = (time.to_f * 1000).to_i argv = [timestamp, amount.to_i, max, period * 1000] result = begin redis.evalsha( Scripts::INCREMENT_SCRIPT_HASH, keys: [key], argv: argv) rescue Redis::CommandError redis.eval(Scripts::INCREMENT_SCRIPT, keys: [key], argv: argv) end !!result end
ruby
def increment(amount = 1, time: Time.now) return amount <= 0 if max.zero? if amount != amount.to_i raise ArgumentError.new("Amount must be an integer") end timestamp = (time.to_f * 1000).to_i argv = [timestamp, amount.to_i, max, period * 1000] result = begin redis.evalsha( Scripts::INCREMENT_SCRIPT_HASH, keys: [key], argv: argv) rescue Redis::CommandError redis.eval(Scripts::INCREMENT_SCRIPT, keys: [key], argv: argv) end !!result end
[ "def", "increment", "(", "amount", "=", "1", ",", "time", ":", "Time", ".", "now", ")", "return", "amount", "<=", "0", "if", "max", ".", "zero?", "if", "amount", "!=", "amount", ".", "to_i", "raise", "ArgumentError", ".", "new", "(", "\"Amount must be an integer\"", ")", "end", "timestamp", "=", "(", "time", ".", "to_f", "*", "1000", ")", ".", "to_i", "argv", "=", "[", "timestamp", ",", "amount", ".", "to_i", ",", "max", ",", "period", "*", "1000", "]", "result", "=", "begin", "redis", ".", "evalsha", "(", "Scripts", "::", "INCREMENT_SCRIPT_HASH", ",", "keys", ":", "[", "key", "]", ",", "argv", ":", "argv", ")", "rescue", "Redis", "::", "CommandError", "redis", ".", "eval", "(", "Scripts", "::", "INCREMENT_SCRIPT", ",", "keys", ":", "[", "key", "]", ",", "argv", ":", "argv", ")", "end", "!", "!", "result", "end" ]
Increment the amount used by the given number. Does not perform increment if the operation would exceed the limit. Returns whether the operation was successful. Time of increment can be specified optionally with a keyword argument, which is useful for rolling back with a decrement. @param amount [Integer] amount to increment by @param time [Time] time when increment occurs @return [Boolean] true if increment succeded and false if incrementing would exceed the limit
[ "Increment", "the", "amount", "used", "by", "the", "given", "number", ".", "Does", "not", "perform", "increment", "if", "the", "operation", "would", "exceed", "the", "limit", ".", "Returns", "whether", "the", "operation", "was", "successful", ".", "Time", "of", "increment", "can", "be", "specified", "optionally", "with", "a", "keyword", "argument", "which", "is", "useful", "for", "rolling", "back", "with", "a", "decrement", "." ]
2b90aa596fdb384086a5a39a203effed14a01756
https://github.com/coinbase/traffic_jam/blob/2b90aa596fdb384086a5a39a203effed14a01756/lib/traffic_jam/limit.rb#L67-L86
train
coinbase/traffic_jam
lib/traffic_jam/lifetime_limit.rb
TrafficJam.LifetimeLimit.used
def used return 0 if max.zero? amount = redis.get(key) || 0 [amount.to_i, max].min end
ruby
def used return 0 if max.zero? amount = redis.get(key) || 0 [amount.to_i, max].min end
[ "def", "used", "return", "0", "if", "max", ".", "zero?", "amount", "=", "redis", ".", "get", "(", "key", ")", "||", "0", "[", "amount", ".", "to_i", ",", "max", "]", ".", "min", "end" ]
Return amount of limit used @return [Integer] amount used
[ "Return", "amount", "of", "limit", "used" ]
2b90aa596fdb384086a5a39a203effed14a01756
https://github.com/coinbase/traffic_jam/blob/2b90aa596fdb384086a5a39a203effed14a01756/lib/traffic_jam/lifetime_limit.rb#L36-L40
train
voltrb/volt
lib/volt/tasks/dispatcher.rb
Volt.Dispatcher.dispatch
def dispatch(channel, message) # Dispatch the task in the worker pool. Pas in the meta data @worker_pool.post do begin dispatch_in_thread(channel, message) rescue => e err = "Worker Thread Exception for #{message}\n" err += e.inspect err += e.backtrace.join("\n") if e.respond_to?(:backtrace) Volt.logger.error(err) end end end
ruby
def dispatch(channel, message) # Dispatch the task in the worker pool. Pas in the meta data @worker_pool.post do begin dispatch_in_thread(channel, message) rescue => e err = "Worker Thread Exception for #{message}\n" err += e.inspect err += e.backtrace.join("\n") if e.respond_to?(:backtrace) Volt.logger.error(err) end end end
[ "def", "dispatch", "(", "channel", ",", "message", ")", "# Dispatch the task in the worker pool. Pas in the meta data", "@worker_pool", ".", "post", "do", "begin", "dispatch_in_thread", "(", "channel", ",", "message", ")", "rescue", "=>", "e", "err", "=", "\"Worker Thread Exception for #{message}\\n\"", "err", "+=", "e", ".", "inspect", "err", "+=", "e", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", "if", "e", ".", "respond_to?", "(", ":backtrace", ")", "Volt", ".", "logger", ".", "error", "(", "err", ")", "end", "end", "end" ]
Dispatch takes an incoming Task from the client and runs it on the server, returning the result to the client. Tasks returning a promise will wait to return.
[ "Dispatch", "takes", "an", "incoming", "Task", "from", "the", "client", "and", "runs", "it", "on", "the", "server", "returning", "the", "result", "to", "the", "client", ".", "Tasks", "returning", "a", "promise", "will", "wait", "to", "return", "." ]
f942b92385adbc894ee4a37903ee6a9c1a65e9a4
https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/tasks/dispatcher.rb#L53-L66
train
voltrb/volt
lib/volt/tasks/dispatcher.rb
Volt.Dispatcher.safe_method?
def safe_method?(klass, method_name) # Make sure the class being called is a Task. return false unless klass.ancestors.include?(Task) # Make sure the method is defined on the klass we're using and not up the hiearchy. # ^ This check prevents methods like #send, #eval, #instance_eval, #class_eval, etc... klass.ancestors.each do |ancestor_klass| if ancestor_klass.instance_methods(false).include?(method_name) return true elsif ancestor_klass == Task # We made it to Task and didn't find the method, that means it # was defined above Task, so we reject the call. return false end end false end
ruby
def safe_method?(klass, method_name) # Make sure the class being called is a Task. return false unless klass.ancestors.include?(Task) # Make sure the method is defined on the klass we're using and not up the hiearchy. # ^ This check prevents methods like #send, #eval, #instance_eval, #class_eval, etc... klass.ancestors.each do |ancestor_klass| if ancestor_klass.instance_methods(false).include?(method_name) return true elsif ancestor_klass == Task # We made it to Task and didn't find the method, that means it # was defined above Task, so we reject the call. return false end end false end
[ "def", "safe_method?", "(", "klass", ",", "method_name", ")", "# Make sure the class being called is a Task.", "return", "false", "unless", "klass", ".", "ancestors", ".", "include?", "(", "Task", ")", "# Make sure the method is defined on the klass we're using and not up the hiearchy.", "# ^ This check prevents methods like #send, #eval, #instance_eval, #class_eval, etc...", "klass", ".", "ancestors", ".", "each", "do", "|", "ancestor_klass", "|", "if", "ancestor_klass", ".", "instance_methods", "(", "false", ")", ".", "include?", "(", "method_name", ")", "return", "true", "elsif", "ancestor_klass", "==", "Task", "# We made it to Task and didn't find the method, that means it", "# was defined above Task, so we reject the call.", "return", "false", "end", "end", "false", "end" ]
Check if it is safe to use this method
[ "Check", "if", "it", "is", "safe", "to", "use", "this", "method" ]
f942b92385adbc894ee4a37903ee6a9c1a65e9a4
https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/tasks/dispatcher.rb#L70-L87
train
voltrb/volt
lib/volt/tasks/dispatcher.rb
Volt.Dispatcher.dispatch_in_thread
def dispatch_in_thread(channel, message) callback_id, class_name, method_name, meta_data, *args = message method_name = method_name.to_sym # Get the class klass = Object.send(:const_get, class_name) promise = Promise.new cookies = nil start_time = Time.now.to_f # Check that we are calling on a Task class and a method provide at # Task or above in the ancestor chain. (so no :send or anything) if safe_method?(klass, method_name) promise.resolve(nil) # Init and send the method promise = promise.then do result = nil Timeout.timeout(klass.__timeout || @worker_timeout) do Thread.current['meta'] = meta_data begin klass_inst = klass.new(@volt_app, channel, self) result = klass_inst.send(method_name, *args) cookies = klass_inst.fetch_cookies ensure Thread.current['meta'] = nil end end result end else # Unsafe method promise.reject(RuntimeError.new("unsafe method: #{method_name}")) end # Called after task runs or fails finish = proc do |error| if error.is_a?(Timeout::Error) # re-raise with a message error = Timeout::Error.new("Task Timed Out after #{@worker_timeout} seconds: #{message}") end run_time = ((Time.now.to_f - start_time) * 1000).round(3) Volt.logger.log_dispatch(class_name, method_name, run_time, args, error) end # Run the promise and pass the return value/error back to the client promise.then do |result| reply = EJSON.stringify(['response', callback_id, result, nil, cookies]) channel.send_string_message(reply) finish.call end.fail do |error| begin finish.call(error) begin # Try to send, handle error if we can't convert the result to EJSON reply = EJSON.stringify(['response', callback_id, nil, error, cookies]) # use send_string_message, since we stringify here, not on the other # side of Drb. channel.send_string_message(reply) rescue EJSON::NonEjsonType => e # Convert the error into a string so it can be serialized to # something. error = "#{error.class.to_s}: #{error.to_s}" channel.send_message('response', callback_id, nil, error, cookies) end rescue => e Volt.logger.error "Error in fail dispatch: #{e.inspect}" Volt.logger.error(e.backtrace.join("\n")) if e.respond_to?(:backtrace) raise end end end
ruby
def dispatch_in_thread(channel, message) callback_id, class_name, method_name, meta_data, *args = message method_name = method_name.to_sym # Get the class klass = Object.send(:const_get, class_name) promise = Promise.new cookies = nil start_time = Time.now.to_f # Check that we are calling on a Task class and a method provide at # Task or above in the ancestor chain. (so no :send or anything) if safe_method?(klass, method_name) promise.resolve(nil) # Init and send the method promise = promise.then do result = nil Timeout.timeout(klass.__timeout || @worker_timeout) do Thread.current['meta'] = meta_data begin klass_inst = klass.new(@volt_app, channel, self) result = klass_inst.send(method_name, *args) cookies = klass_inst.fetch_cookies ensure Thread.current['meta'] = nil end end result end else # Unsafe method promise.reject(RuntimeError.new("unsafe method: #{method_name}")) end # Called after task runs or fails finish = proc do |error| if error.is_a?(Timeout::Error) # re-raise with a message error = Timeout::Error.new("Task Timed Out after #{@worker_timeout} seconds: #{message}") end run_time = ((Time.now.to_f - start_time) * 1000).round(3) Volt.logger.log_dispatch(class_name, method_name, run_time, args, error) end # Run the promise and pass the return value/error back to the client promise.then do |result| reply = EJSON.stringify(['response', callback_id, result, nil, cookies]) channel.send_string_message(reply) finish.call end.fail do |error| begin finish.call(error) begin # Try to send, handle error if we can't convert the result to EJSON reply = EJSON.stringify(['response', callback_id, nil, error, cookies]) # use send_string_message, since we stringify here, not on the other # side of Drb. channel.send_string_message(reply) rescue EJSON::NonEjsonType => e # Convert the error into a string so it can be serialized to # something. error = "#{error.class.to_s}: #{error.to_s}" channel.send_message('response', callback_id, nil, error, cookies) end rescue => e Volt.logger.error "Error in fail dispatch: #{e.inspect}" Volt.logger.error(e.backtrace.join("\n")) if e.respond_to?(:backtrace) raise end end end
[ "def", "dispatch_in_thread", "(", "channel", ",", "message", ")", "callback_id", ",", "class_name", ",", "method_name", ",", "meta_data", ",", "*", "args", "=", "message", "method_name", "=", "method_name", ".", "to_sym", "# Get the class", "klass", "=", "Object", ".", "send", "(", ":const_get", ",", "class_name", ")", "promise", "=", "Promise", ".", "new", "cookies", "=", "nil", "start_time", "=", "Time", ".", "now", ".", "to_f", "# Check that we are calling on a Task class and a method provide at", "# Task or above in the ancestor chain. (so no :send or anything)", "if", "safe_method?", "(", "klass", ",", "method_name", ")", "promise", ".", "resolve", "(", "nil", ")", "# Init and send the method", "promise", "=", "promise", ".", "then", "do", "result", "=", "nil", "Timeout", ".", "timeout", "(", "klass", ".", "__timeout", "||", "@worker_timeout", ")", "do", "Thread", ".", "current", "[", "'meta'", "]", "=", "meta_data", "begin", "klass_inst", "=", "klass", ".", "new", "(", "@volt_app", ",", "channel", ",", "self", ")", "result", "=", "klass_inst", ".", "send", "(", "method_name", ",", "args", ")", "cookies", "=", "klass_inst", ".", "fetch_cookies", "ensure", "Thread", ".", "current", "[", "'meta'", "]", "=", "nil", "end", "end", "result", "end", "else", "# Unsafe method", "promise", ".", "reject", "(", "RuntimeError", ".", "new", "(", "\"unsafe method: #{method_name}\"", ")", ")", "end", "# Called after task runs or fails", "finish", "=", "proc", "do", "|", "error", "|", "if", "error", ".", "is_a?", "(", "Timeout", "::", "Error", ")", "# re-raise with a message", "error", "=", "Timeout", "::", "Error", ".", "new", "(", "\"Task Timed Out after #{@worker_timeout} seconds: #{message}\"", ")", "end", "run_time", "=", "(", "(", "Time", ".", "now", ".", "to_f", "-", "start_time", ")", "*", "1000", ")", ".", "round", "(", "3", ")", "Volt", ".", "logger", ".", "log_dispatch", "(", "class_name", ",", "method_name", ",", "run_time", ",", "args", ",", "error", ")", "end", "# Run the promise and pass the return value/error back to the client", "promise", ".", "then", "do", "|", "result", "|", "reply", "=", "EJSON", ".", "stringify", "(", "[", "'response'", ",", "callback_id", ",", "result", ",", "nil", ",", "cookies", "]", ")", "channel", ".", "send_string_message", "(", "reply", ")", "finish", ".", "call", "end", ".", "fail", "do", "|", "error", "|", "begin", "finish", ".", "call", "(", "error", ")", "begin", "# Try to send, handle error if we can't convert the result to EJSON", "reply", "=", "EJSON", ".", "stringify", "(", "[", "'response'", ",", "callback_id", ",", "nil", ",", "error", ",", "cookies", "]", ")", "# use send_string_message, since we stringify here, not on the other", "# side of Drb.", "channel", ".", "send_string_message", "(", "reply", ")", "rescue", "EJSON", "::", "NonEjsonType", "=>", "e", "# Convert the error into a string so it can be serialized to", "# something.", "error", "=", "\"#{error.class.to_s}: #{error.to_s}\"", "channel", ".", "send_message", "(", "'response'", ",", "callback_id", ",", "nil", ",", "error", ",", "cookies", ")", "end", "rescue", "=>", "e", "Volt", ".", "logger", ".", "error", "\"Error in fail dispatch: #{e.inspect}\"", "Volt", ".", "logger", ".", "error", "(", "e", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", ")", "if", "e", ".", "respond_to?", "(", ":backtrace", ")", "raise", "end", "end", "end" ]
Do the actual dispatching, should be running inside of a worker thread at this point.
[ "Do", "the", "actual", "dispatching", "should", "be", "running", "inside", "of", "a", "worker", "thread", "at", "this", "point", "." ]
f942b92385adbc894ee4a37903ee6a9c1a65e9a4
https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/tasks/dispatcher.rb#L97-L178
train
voltrb/volt
lib/volt/models/validations/validations.rb
Volt.Validations.validate
def validate(field_name = nil, options = nil, &block) if block # Setup a custom validation inside of the current validations block. if field_name || options fail 'validate should be passed a field name and options or a block, not both.' end @instance_custom_validations << block else @instance_validations[field_name] ||= {} @instance_validations[field_name].merge!(options) end end
ruby
def validate(field_name = nil, options = nil, &block) if block # Setup a custom validation inside of the current validations block. if field_name || options fail 'validate should be passed a field name and options or a block, not both.' end @instance_custom_validations << block else @instance_validations[field_name] ||= {} @instance_validations[field_name].merge!(options) end end
[ "def", "validate", "(", "field_name", "=", "nil", ",", "options", "=", "nil", ",", "&", "block", ")", "if", "block", "# Setup a custom validation inside of the current validations block.", "if", "field_name", "||", "options", "fail", "'validate should be passed a field name and options or a block, not both.'", "end", "@instance_custom_validations", "<<", "block", "else", "@instance_validations", "[", "field_name", "]", "||=", "{", "}", "@instance_validations", "[", "field_name", "]", ".", "merge!", "(", "options", ")", "end", "end" ]
Called on the model inside of a validations block. Allows the user to control if validations should be run.
[ "Called", "on", "the", "model", "inside", "of", "a", "validations", "block", ".", "Allows", "the", "user", "to", "control", "if", "validations", "should", "be", "run", "." ]
f942b92385adbc894ee4a37903ee6a9c1a65e9a4
https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/validations/validations.rb#L64-L75
train
voltrb/volt
lib/volt/models/validations/validations.rb
Volt.Validations.mark_all_fields!
def mark_all_fields! # TODO: We can use a Set here, but set was having issues. Check in a # later version of opal. fields_to_mark = [] # Look at each validation validations = self.class.validations_to_run if validations fields_to_mark += validations.keys end # Also include any current fields fields_to_mark += attributes.keys fields_to_mark.each do |key| mark_field!(key.to_sym) end end
ruby
def mark_all_fields! # TODO: We can use a Set here, but set was having issues. Check in a # later version of opal. fields_to_mark = [] # Look at each validation validations = self.class.validations_to_run if validations fields_to_mark += validations.keys end # Also include any current fields fields_to_mark += attributes.keys fields_to_mark.each do |key| mark_field!(key.to_sym) end end
[ "def", "mark_all_fields!", "# TODO: We can use a Set here, but set was having issues. Check in a", "# later version of opal.", "fields_to_mark", "=", "[", "]", "# Look at each validation", "validations", "=", "self", ".", "class", ".", "validations_to_run", "if", "validations", "fields_to_mark", "+=", "validations", ".", "keys", "end", "# Also include any current fields", "fields_to_mark", "+=", "attributes", ".", "keys", "fields_to_mark", ".", "each", "do", "|", "key", "|", "mark_field!", "(", "key", ".", "to_sym", ")", "end", "end" ]
Marks all fields, useful for when a model saves.
[ "Marks", "all", "fields", "useful", "for", "when", "a", "model", "saves", "." ]
f942b92385adbc894ee4a37903ee6a9c1a65e9a4
https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/validations/validations.rb#L93-L110
train
voltrb/volt
lib/volt/models/validations/validations.rb
Volt.Validations.error_in_changed_attributes?
def error_in_changed_attributes? errs = errors changed_attributes.each_pair do |key, _| # If any of the fields with errors are also the ones that were return true if errs[key] end false end
ruby
def error_in_changed_attributes? errs = errors changed_attributes.each_pair do |key, _| # If any of the fields with errors are also the ones that were return true if errs[key] end false end
[ "def", "error_in_changed_attributes?", "errs", "=", "errors", "changed_attributes", ".", "each_pair", "do", "|", "key", ",", "_", "|", "# If any of the fields with errors are also the ones that were", "return", "true", "if", "errs", "[", "key", "]", "end", "false", "end" ]
Returns true if any of the changed fields now has an error @return [Boolean] true if one of the changed fields has an error.
[ "Returns", "true", "if", "any", "of", "the", "changed", "fields", "now", "has", "an", "error" ]
f942b92385adbc894ee4a37903ee6a9c1a65e9a4
https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/validations/validations.rb#L161-L170
train
voltrb/volt
lib/volt/models/validations/validations.rb
Volt.Validations.run_validations
def run_validations(validations = nil) # Default to running the class level validations validations ||= self.class.validations_to_run promise = Promise.new.resolve(nil) if validations # Run through each validation validations.each_pair do |field_name, options| promise = promise.then { run_validation(field_name, options) } end end promise end
ruby
def run_validations(validations = nil) # Default to running the class level validations validations ||= self.class.validations_to_run promise = Promise.new.resolve(nil) if validations # Run through each validation validations.each_pair do |field_name, options| promise = promise.then { run_validation(field_name, options) } end end promise end
[ "def", "run_validations", "(", "validations", "=", "nil", ")", "# Default to running the class level validations", "validations", "||=", "self", ".", "class", ".", "validations_to_run", "promise", "=", "Promise", ".", "new", ".", "resolve", "(", "nil", ")", "if", "validations", "# Run through each validation", "validations", ".", "each_pair", "do", "|", "field_name", ",", "options", "|", "promise", "=", "promise", ".", "then", "{", "run_validation", "(", "field_name", ",", "options", ")", "}", "end", "end", "promise", "end" ]
Runs through each of the normal validations. @param [Array] An array of validations to run @return [Promise] a promsie to run all validations
[ "Runs", "through", "each", "of", "the", "normal", "validations", "." ]
f942b92385adbc894ee4a37903ee6a9c1a65e9a4
https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/validations/validations.rb#L177-L191
train
voltrb/volt
lib/volt/models/validations/validations.rb
Volt.Validations.run_validation
def run_validation(field_name, options) promise = Promise.new.resolve(nil) options.each_pair do |validation, args| # Call the specific validator, then merge the results back # into one large errors hash. klass = validation_class(validation, args) if klass # Chain on the promises promise = promise.then do klass.validate(self, field_name, args) end.then do |errs| errors.merge!(errs) end else fail "validation type #{validation} is not specified." end end promise end
ruby
def run_validation(field_name, options) promise = Promise.new.resolve(nil) options.each_pair do |validation, args| # Call the specific validator, then merge the results back # into one large errors hash. klass = validation_class(validation, args) if klass # Chain on the promises promise = promise.then do klass.validate(self, field_name, args) end.then do |errs| errors.merge!(errs) end else fail "validation type #{validation} is not specified." end end promise end
[ "def", "run_validation", "(", "field_name", ",", "options", ")", "promise", "=", "Promise", ".", "new", ".", "resolve", "(", "nil", ")", "options", ".", "each_pair", "do", "|", "validation", ",", "args", "|", "# Call the specific validator, then merge the results back", "# into one large errors hash.", "klass", "=", "validation_class", "(", "validation", ",", "args", ")", "if", "klass", "# Chain on the promises", "promise", "=", "promise", ".", "then", "do", "klass", ".", "validate", "(", "self", ",", "field_name", ",", "args", ")", "end", ".", "then", "do", "|", "errs", "|", "errors", ".", "merge!", "(", "errs", ")", "end", "else", "fail", "\"validation type #{validation} is not specified.\"", "end", "end", "promise", "end" ]
Runs an individual validation @returns [Promise]
[ "Runs", "an", "individual", "validation" ]
f942b92385adbc894ee4a37903ee6a9c1a65e9a4
https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/validations/validations.rb#L195-L215
train
voltrb/volt
lib/volt/reactive/reactive_array.rb
Volt.ReactiveArray.__clear
def __clear old_size = @array.size deps = @array_deps @array_deps = [] # Trigger remove for each cell old_size.times do |index| trigger_removed!(old_size - index - 1) end # Trigger on each cell since we are clearing out the array if deps deps.each do |dep| dep.changed! if dep end end # clear the array @array = [] end
ruby
def __clear old_size = @array.size deps = @array_deps @array_deps = [] # Trigger remove for each cell old_size.times do |index| trigger_removed!(old_size - index - 1) end # Trigger on each cell since we are clearing out the array if deps deps.each do |dep| dep.changed! if dep end end # clear the array @array = [] end
[ "def", "__clear", "old_size", "=", "@array", ".", "size", "deps", "=", "@array_deps", "@array_deps", "=", "[", "]", "# Trigger remove for each cell", "old_size", ".", "times", "do", "|", "index", "|", "trigger_removed!", "(", "old_size", "-", "index", "-", "1", ")", "end", "# Trigger on each cell since we are clearing out the array", "if", "deps", "deps", ".", "each", "do", "|", "dep", "|", "dep", ".", "changed!", "if", "dep", "end", "end", "# clear the array", "@array", "=", "[", "]", "end" ]
used internally, clears out the array, triggers the change events, but does not call clear on the persistors. Used when models are updated externally.
[ "used", "internally", "clears", "out", "the", "array", "triggers", "the", "change", "events", "but", "does", "not", "call", "clear", "on", "the", "persistors", ".", "Used", "when", "models", "are", "updated", "externally", "." ]
f942b92385adbc894ee4a37903ee6a9c1a65e9a4
https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/reactive/reactive_array.rb#L248-L268
train
voltrb/volt
lib/volt/models/buffer.rb
Volt.Buffer.promise_for_errors
def promise_for_errors(errors) mark_all_fields! # Wrap in an Errors class unless it already is one errors = errors.is_a?(Errors) ? errors : Errors.new(errors) Promise.new.reject(errors) end
ruby
def promise_for_errors(errors) mark_all_fields! # Wrap in an Errors class unless it already is one errors = errors.is_a?(Errors) ? errors : Errors.new(errors) Promise.new.reject(errors) end
[ "def", "promise_for_errors", "(", "errors", ")", "mark_all_fields!", "# Wrap in an Errors class unless it already is one", "errors", "=", "errors", ".", "is_a?", "(", "Errors", ")", "?", "errors", ":", "Errors", ".", "new", "(", "errors", ")", "Promise", ".", "new", ".", "reject", "(", "errors", ")", "end" ]
When errors come in, we mark all fields and return a rejected promise.
[ "When", "errors", "come", "in", "we", "mark", "all", "fields", "and", "return", "a", "rejected", "promise", "." ]
f942b92385adbc894ee4a37903ee6a9c1a65e9a4
https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/buffer.rb#L75-L82
train
voltrb/volt
lib/volt/models/buffer.rb
Volt.Buffer.buffer
def buffer model_path = options[:path] model_klass = self.class new_options = options.merge(path: model_path, save_to: self, buffer: true).reject { |k, _| k.to_sym == :persistor } model = nil Volt::Model.no_validate do model = model_klass.new(attributes, new_options, :loaded) model.instance_variable_set('@new', @new) end model end
ruby
def buffer model_path = options[:path] model_klass = self.class new_options = options.merge(path: model_path, save_to: self, buffer: true).reject { |k, _| k.to_sym == :persistor } model = nil Volt::Model.no_validate do model = model_klass.new(attributes, new_options, :loaded) model.instance_variable_set('@new', @new) end model end
[ "def", "buffer", "model_path", "=", "options", "[", ":path", "]", "model_klass", "=", "self", ".", "class", "new_options", "=", "options", ".", "merge", "(", "path", ":", "model_path", ",", "save_to", ":", "self", ",", "buffer", ":", "true", ")", ".", "reject", "{", "|", "k", ",", "_", "|", "k", ".", "to_sym", "==", ":persistor", "}", "model", "=", "nil", "Volt", "::", "Model", ".", "no_validate", "do", "model", "=", "model_klass", ".", "new", "(", "attributes", ",", "new_options", ",", ":loaded", ")", "model", ".", "instance_variable_set", "(", "'@new'", ",", "@new", ")", "end", "model", "end" ]
Returns a buffered version of the model
[ "Returns", "a", "buffered", "version", "of", "the", "model" ]
f942b92385adbc894ee4a37903ee6a9c1a65e9a4
https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/buffer.rb#L89-L104
train