id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
18,300
piotrmurach/tty-command
lib/tty/command.rb
TTY.Command.run
def run(*args, &block) cmd = command(*args) result = execute_command(cmd, &block) if result && result.failure? raise ExitError.new(cmd.to_command, result) end result end
ruby
def run(*args, &block) cmd = command(*args) result = execute_command(cmd, &block) if result && result.failure? raise ExitError.new(cmd.to_command, result) end result end
[ "def", "run", "(", "*", "args", ",", "&", "block", ")", "cmd", "=", "command", "(", "args", ")", "result", "=", "execute_command", "(", "cmd", ",", "block", ")", "if", "result", "&&", "result", ".", "failure?", "raise", "ExitError", ".", "new", "(", "cmd", ".", "to_command", ",", "result", ")", "end", "result", "end" ]
Initialize a Command object @param [Hash] options @option options [IO] :output the stream to which printer prints, defaults to stdout @option options [Symbol] :printer the printer to use for output logging, defaults to :pretty @option options [Symbol] :dry_run the mode for executing command @api public Start external executable in a child process @example cmd.run(command, [argv1, ..., argvN], [options]) @example cmd.run(command, ...) do |result| ... end @param [String] command the command to run @param [Array[String]] argv an array of string arguments @param [Hash] options hash of operations to perform @option options [String] :chdir The current directory. @option options [Integer] :timeout Maximum number of seconds to allow the process to run before aborting with a TimeoutExceeded exception. @option options [Symbol] :signal Signal used on timeout, SIGKILL by default @yield [out, err] Yields stdout and stderr output whenever available @raise [ExitError] raised when command exits with non-zero code @api public
[ "Initialize", "a", "Command", "object" ]
10910b0279a08de3652433d8627e2090cd8b9087
https://github.com/piotrmurach/tty-command/blob/10910b0279a08de3652433d8627e2090cd8b9087/lib/tty/command.rb#L102-L109
18,301
piotrmurach/tty-command
lib/tty/command.rb
TTY.Command.ruby
def ruby(*args, &block) options = args.last.is_a?(Hash) ? args.pop : {} if args.length > 1 run(*([RUBY] + args + [options]), &block) else run("#{RUBY} #{args.first}", options, &block) end end
ruby
def ruby(*args, &block) options = args.last.is_a?(Hash) ? args.pop : {} if args.length > 1 run(*([RUBY] + args + [options]), &block) else run("#{RUBY} #{args.first}", options, &block) end end
[ "def", "ruby", "(", "*", "args", ",", "&", "block", ")", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "if", "args", ".", "length", ">", "1", "run", "(", "(", "[", "RUBY", "]", "+", "args", "+", "[", "options", "]", ")", ",", "block", ")", "else", "run", "(", "\"#{RUBY} #{args.first}\"", ",", "options", ",", "block", ")", "end", "end" ]
Run Ruby interperter with the given arguments @example ruby %q{-e "puts 'Hello world'"} @api public
[ "Run", "Ruby", "interperter", "with", "the", "given", "arguments" ]
10910b0279a08de3652433d8627e2090cd8b9087
https://github.com/piotrmurach/tty-command/blob/10910b0279a08de3652433d8627e2090cd8b9087/lib/tty/command.rb#L154-L161
18,302
piotrmurach/tty-command
lib/tty/command.rb
TTY.Command.find_printer_class
def find_printer_class(name) const_name = name.to_s.split('_').map(&:capitalize).join.to_sym if const_name.empty? || !TTY::Command::Printers.const_defined?(const_name) raise ArgumentError, %(Unknown printer type "#{name}") end TTY::Command::Printers.const_get(const_name) end
ruby
def find_printer_class(name) const_name = name.to_s.split('_').map(&:capitalize).join.to_sym if const_name.empty? || !TTY::Command::Printers.const_defined?(const_name) raise ArgumentError, %(Unknown printer type "#{name}") end TTY::Command::Printers.const_get(const_name) end
[ "def", "find_printer_class", "(", "name", ")", "const_name", "=", "name", ".", "to_s", ".", "split", "(", "'_'", ")", ".", "map", "(", ":capitalize", ")", ".", "join", ".", "to_sym", "if", "const_name", ".", "empty?", "||", "!", "TTY", "::", "Command", "::", "Printers", ".", "const_defined?", "(", "const_name", ")", "raise", "ArgumentError", ",", "%(Unknown printer type \"#{name}\")", "end", "TTY", "::", "Command", "::", "Printers", ".", "const_get", "(", "const_name", ")", "end" ]
Find printer class or fail @raise [ArgumentError] @api private
[ "Find", "printer", "class", "or", "fail" ]
10910b0279a08de3652433d8627e2090cd8b9087
https://github.com/piotrmurach/tty-command/blob/10910b0279a08de3652433d8627e2090cd8b9087/lib/tty/command.rb#L206-L212
18,303
heroku/hatchet
lib/hatchet/config.rb
Hatchet.Config.init_config!
def init_config!(config) set_internal_config!(config) config.each do |(directory, git_repos)| git_repos.each do |git_repo| git_repo = git_repo.include?("github.com") ? git_repo : "https://github.com/#{git_repo}.git" repo_name = name_from_git_repo(git_repo) repo_path = File.join(repo_directory_path, directory, repo_name) if repos.key? repo_name puts " warning duplicate repo found: #{repo_name.inspect}" repos[repo_name] = false else repos[repo_name] = repo_path end dirs[repo_path] = git_repo end end end
ruby
def init_config!(config) set_internal_config!(config) config.each do |(directory, git_repos)| git_repos.each do |git_repo| git_repo = git_repo.include?("github.com") ? git_repo : "https://github.com/#{git_repo}.git" repo_name = name_from_git_repo(git_repo) repo_path = File.join(repo_directory_path, directory, repo_name) if repos.key? repo_name puts " warning duplicate repo found: #{repo_name.inspect}" repos[repo_name] = false else repos[repo_name] = repo_path end dirs[repo_path] = git_repo end end end
[ "def", "init_config!", "(", "config", ")", "set_internal_config!", "(", "config", ")", "config", ".", "each", "do", "|", "(", "directory", ",", "git_repos", ")", "|", "git_repos", ".", "each", "do", "|", "git_repo", "|", "git_repo", "=", "git_repo", ".", "include?", "(", "\"github.com\"", ")", "?", "git_repo", ":", "\"https://github.com/#{git_repo}.git\"", "repo_name", "=", "name_from_git_repo", "(", "git_repo", ")", "repo_path", "=", "File", ".", "join", "(", "repo_directory_path", ",", "directory", ",", "repo_name", ")", "if", "repos", ".", "key?", "repo_name", "puts", "\" warning duplicate repo found: #{repo_name.inspect}\"", "repos", "[", "repo_name", "]", "=", "false", "else", "repos", "[", "repo_name", "]", "=", "repo_path", "end", "dirs", "[", "repo_path", "]", "=", "git_repo", "end", "end", "end" ]
pulls out config and makes easy to use hashes dirs has the repo paths as keys and the git_repos as values repos has repo names as keys and the paths as values
[ "pulls", "out", "config", "and", "makes", "easy", "to", "use", "hashes", "dirs", "has", "the", "repo", "paths", "as", "keys", "and", "the", "git_repos", "as", "values", "repos", "has", "repo", "names", "as", "keys", "and", "the", "paths", "as", "values" ]
12815a5255419442b4b528f06ed59c96e5859e4e
https://github.com/heroku/hatchet/blob/12815a5255419442b4b528f06ed59c96e5859e4e/lib/hatchet/config.rb#L71-L87
18,304
heroku/hatchet
lib/hatchet/app.rb
Hatchet.App.setup!
def setup! return self if @app_is_setup puts "Hatchet setup: #{name.inspect} for #{repo_name.inspect}" create_git_repo! unless is_git_repo? create_app set_labs! buildpack_list = @buildpacks.map { |pack| { buildpack: pack } } api_rate_limit.call.buildpack_installation.update(name, updates: buildpack_list) set_config @app_config call_before_deploy @app_is_setup = true self end
ruby
def setup! return self if @app_is_setup puts "Hatchet setup: #{name.inspect} for #{repo_name.inspect}" create_git_repo! unless is_git_repo? create_app set_labs! buildpack_list = @buildpacks.map { |pack| { buildpack: pack } } api_rate_limit.call.buildpack_installation.update(name, updates: buildpack_list) set_config @app_config call_before_deploy @app_is_setup = true self end
[ "def", "setup!", "return", "self", "if", "@app_is_setup", "puts", "\"Hatchet setup: #{name.inspect} for #{repo_name.inspect}\"", "create_git_repo!", "unless", "is_git_repo?", "create_app", "set_labs!", "buildpack_list", "=", "@buildpacks", ".", "map", "{", "|", "pack", "|", "{", "buildpack", ":", "pack", "}", "}", "api_rate_limit", ".", "call", ".", "buildpack_installation", ".", "update", "(", "name", ",", "updates", ":", "buildpack_list", ")", "set_config", "@app_config", "call_before_deploy", "@app_is_setup", "=", "true", "self", "end" ]
creates a new heroku app via the API
[ "creates", "a", "new", "heroku", "app", "via", "the", "API" ]
12815a5255419442b4b528f06ed59c96e5859e4e
https://github.com/heroku/hatchet/blob/12815a5255419442b4b528f06ed59c96e5859e4e/lib/hatchet/app.rb#L164-L177
18,305
heroku/hatchet
lib/hatchet/reaper.rb
Hatchet.Reaper.get_apps
def get_apps apps = @api_rate_limit.call.app.list.sort_by { |app| DateTime.parse(app["created_at"]) }.reverse @app_count = apps.count @hatchet_apps = apps.select {|app| app["name"].match(@regex) } end
ruby
def get_apps apps = @api_rate_limit.call.app.list.sort_by { |app| DateTime.parse(app["created_at"]) }.reverse @app_count = apps.count @hatchet_apps = apps.select {|app| app["name"].match(@regex) } end
[ "def", "get_apps", "apps", "=", "@api_rate_limit", ".", "call", ".", "app", ".", "list", ".", "sort_by", "{", "|", "app", "|", "DateTime", ".", "parse", "(", "app", "[", "\"created_at\"", "]", ")", "}", ".", "reverse", "@app_count", "=", "apps", ".", "count", "@hatchet_apps", "=", "apps", ".", "select", "{", "|", "app", "|", "app", "[", "\"name\"", "]", ".", "match", "(", "@regex", ")", "}", "end" ]
Ascending order, oldest is last
[ "Ascending", "order", "oldest", "is", "last" ]
12815a5255419442b4b528f06ed59c96e5859e4e
https://github.com/heroku/hatchet/blob/12815a5255419442b4b528f06ed59c96e5859e4e/lib/hatchet/reaper.rb#L21-L25
18,306
hammackj/uirusu
lib/uirusu/vtresult.rb
Uirusu.VTResult.to_stdout
def to_stdout result_string = String.new hashes = Array.new @results.sort_by {|k| k[:scanner] }.each do |result| unless hashes.include? result[:hash].downcase result_string << "#{result[:hash]}:\n" hashes << result[:hash].downcase end result_string << "#{result[:scanner]}: ".rjust(25) + "#{result[:result]}\n" end if @results != nil result_string end
ruby
def to_stdout result_string = String.new hashes = Array.new @results.sort_by {|k| k[:scanner] }.each do |result| unless hashes.include? result[:hash].downcase result_string << "#{result[:hash]}:\n" hashes << result[:hash].downcase end result_string << "#{result[:scanner]}: ".rjust(25) + "#{result[:result]}\n" end if @results != nil result_string end
[ "def", "to_stdout", "result_string", "=", "String", ".", "new", "hashes", "=", "Array", ".", "new", "@results", ".", "sort_by", "{", "|", "k", "|", "k", "[", ":scanner", "]", "}", ".", "each", "do", "|", "result", "|", "unless", "hashes", ".", "include?", "result", "[", ":hash", "]", ".", "downcase", "result_string", "<<", "\"#{result[:hash]}:\\n\"", "hashes", "<<", "result", "[", ":hash", "]", ".", "downcase", "end", "result_string", "<<", "\"#{result[:scanner]}: \"", ".", "rjust", "(", "25", ")", "+", "\"#{result[:result]}\\n\"", "end", "if", "@results", "!=", "nil", "result_string", "end" ]
Builds a VTResult object based on the hash and results passed to it @param hash, Cryptographic hash that was searched @param results, Results of the search on Virustotal.com Outputs the result to STDOUT @return [String] Pretty text printable representation of the result
[ "Builds", "a", "VTResult", "object", "based", "on", "the", "hash", "and", "results", "passed", "to", "it" ]
1f9e46d505416bc6c006f4e6ae334bc7a93e3402
https://github.com/hammackj/uirusu/blob/1f9e46d505416bc6c006f4e6ae334bc7a93e3402/lib/uirusu/vtresult.rb#L108-L121
18,307
hammackj/uirusu
lib/uirusu/vtresult.rb
Uirusu.VTResult.to_xml
def to_xml result_string = String.new result_string << "<results>\n" @results.each do |result| result_string << "\t<vtresult>\n" RESULT_FIELDS.each{|field| result_string << "\t\t<#{field.to_s}>#{result[field]}</#{field.to_s}>\n" unless field == :permalink and result['permalink'].nil? } result_string << "\t</vtresult>\n" end if @results != nil result_string << "</results>\n" result_string end
ruby
def to_xml result_string = String.new result_string << "<results>\n" @results.each do |result| result_string << "\t<vtresult>\n" RESULT_FIELDS.each{|field| result_string << "\t\t<#{field.to_s}>#{result[field]}</#{field.to_s}>\n" unless field == :permalink and result['permalink'].nil? } result_string << "\t</vtresult>\n" end if @results != nil result_string << "</results>\n" result_string end
[ "def", "to_xml", "result_string", "=", "String", ".", "new", "result_string", "<<", "\"<results>\\n\"", "@results", ".", "each", "do", "|", "result", "|", "result_string", "<<", "\"\\t<vtresult>\\n\"", "RESULT_FIELDS", ".", "each", "{", "|", "field", "|", "result_string", "<<", "\"\\t\\t<#{field.to_s}>#{result[field]}</#{field.to_s}>\\n\"", "unless", "field", "==", ":permalink", "and", "result", "[", "'permalink'", "]", ".", "nil?", "}", "result_string", "<<", "\"\\t</vtresult>\\n\"", "end", "if", "@results", "!=", "nil", "result_string", "<<", "\"</results>\\n\"", "result_string", "end" ]
Outputs the result to XML @return [String] XML representation of the result
[ "Outputs", "the", "result", "to", "XML" ]
1f9e46d505416bc6c006f4e6ae334bc7a93e3402
https://github.com/hammackj/uirusu/blob/1f9e46d505416bc6c006f4e6ae334bc7a93e3402/lib/uirusu/vtresult.rb#L140-L153
18,308
netbe/Babelish
lib/babelish/strings2csv.rb
Babelish.Strings2CSV.load_strings
def load_strings(strings_filename) strings = {} comments = {} # genstrings uses utf16, so that's what we expect. utf8 should not be impact file = File.open(strings_filename, "r:utf-16:utf-8") begin contents = file.read if RUBY_VERSION == "1.9.2" # fixes conversion, see http://po-ru.com/diary/fixing-invalid-utf-8-in-ruby-revisited/ require 'iconv' ic = Iconv.new('UTF-8//IGNORE', 'UTF-8') contents = ic.iconv(contents + ' ')[0..-2] end rescue Encoding::InvalidByteSequenceError => e # silent error # faults back to utf8 contents = File.open(strings_filename, "r:utf-8") end previous_comment = nil contents.each_line do |line| key, value = self.parse_dotstrings_line(line) if key strings.merge!({key => value}) comments[key] = previous_comment if previous_comment else previous_comment = self.parse_comment_line(line) end end [strings, comments] end
ruby
def load_strings(strings_filename) strings = {} comments = {} # genstrings uses utf16, so that's what we expect. utf8 should not be impact file = File.open(strings_filename, "r:utf-16:utf-8") begin contents = file.read if RUBY_VERSION == "1.9.2" # fixes conversion, see http://po-ru.com/diary/fixing-invalid-utf-8-in-ruby-revisited/ require 'iconv' ic = Iconv.new('UTF-8//IGNORE', 'UTF-8') contents = ic.iconv(contents + ' ')[0..-2] end rescue Encoding::InvalidByteSequenceError => e # silent error # faults back to utf8 contents = File.open(strings_filename, "r:utf-8") end previous_comment = nil contents.each_line do |line| key, value = self.parse_dotstrings_line(line) if key strings.merge!({key => value}) comments[key] = previous_comment if previous_comment else previous_comment = self.parse_comment_line(line) end end [strings, comments] end
[ "def", "load_strings", "(", "strings_filename", ")", "strings", "=", "{", "}", "comments", "=", "{", "}", "# genstrings uses utf16, so that's what we expect. utf8 should not be impact", "file", "=", "File", ".", "open", "(", "strings_filename", ",", "\"r:utf-16:utf-8\"", ")", "begin", "contents", "=", "file", ".", "read", "if", "RUBY_VERSION", "==", "\"1.9.2\"", "# fixes conversion, see http://po-ru.com/diary/fixing-invalid-utf-8-in-ruby-revisited/", "require", "'iconv'", "ic", "=", "Iconv", ".", "new", "(", "'UTF-8//IGNORE'", ",", "'UTF-8'", ")", "contents", "=", "ic", ".", "iconv", "(", "contents", "+", "' '", ")", "[", "0", "..", "-", "2", "]", "end", "rescue", "Encoding", "::", "InvalidByteSequenceError", "=>", "e", "# silent error", "# faults back to utf8", "contents", "=", "File", ".", "open", "(", "strings_filename", ",", "\"r:utf-8\"", ")", "end", "previous_comment", "=", "nil", "contents", ".", "each_line", "do", "|", "line", "|", "key", ",", "value", "=", "self", ".", "parse_dotstrings_line", "(", "line", ")", "if", "key", "strings", ".", "merge!", "(", "{", "key", "=>", "value", "}", ")", "comments", "[", "key", "]", "=", "previous_comment", "if", "previous_comment", "else", "previous_comment", "=", "self", ".", "parse_comment_line", "(", "line", ")", "end", "end", "[", "strings", ",", "comments", "]", "end" ]
Load all strings of a given file
[ "Load", "all", "strings", "of", "a", "given", "file" ]
1fd8488322b3422f038bd440d6e6b06d8b1ea202
https://github.com/netbe/Babelish/blob/1fd8488322b3422f038bd440d6e6b06d8b1ea202/lib/babelish/strings2csv.rb#L28-L58
18,309
netbe/Babelish
lib/babelish/csv2base.rb
Babelish.Csv2Base.convert
def convert(name = @csv_filename) rowIndex = 0 excludedCols = [] defaultCol = 0 CSV.foreach(name, :quote_char => '"', :col_sep => @csv_separator, :row_sep => :auto) do |row| if rowIndex == 0 #check there's at least two columns return unless row.count > 1 else #skip empty lines (or sections) next if row == nil or row[@keys_column].nil? end # go through columns row.size.times do |i| next if excludedCols.include? i #header if rowIndex == 0 # defaultCol can be the keyValue defaultCol = i if self.default_lang == row[i] # ignore all headers not listed in langs to create files (excludedCols << i and next) unless @langs.has_key?(row[i]) language = Language.new(row[i]) if @langs[row[i]].is_a?(Array) @langs[row[i]].each do |id| language.add_language_id(id.to_s) end else language.add_language_id(@langs[row[i]].to_s) end @languages[i] = language elsif !@state_column || (row[@state_column].nil? || row[@state_column] == '' || !@excluded_states.include?(row[@state_column])) key = row[@keys_column] comment = @comments_column ? row[@comments_column] : nil key.strip! if @stripping default_value = self.default_lang ? row[defaultCol] : nil value = self.process_value(row[i], default_value) @comments[key] = comment @languages[i].add_content_pair(key, value) end end rowIndex += 1 end write_content end
ruby
def convert(name = @csv_filename) rowIndex = 0 excludedCols = [] defaultCol = 0 CSV.foreach(name, :quote_char => '"', :col_sep => @csv_separator, :row_sep => :auto) do |row| if rowIndex == 0 #check there's at least two columns return unless row.count > 1 else #skip empty lines (or sections) next if row == nil or row[@keys_column].nil? end # go through columns row.size.times do |i| next if excludedCols.include? i #header if rowIndex == 0 # defaultCol can be the keyValue defaultCol = i if self.default_lang == row[i] # ignore all headers not listed in langs to create files (excludedCols << i and next) unless @langs.has_key?(row[i]) language = Language.new(row[i]) if @langs[row[i]].is_a?(Array) @langs[row[i]].each do |id| language.add_language_id(id.to_s) end else language.add_language_id(@langs[row[i]].to_s) end @languages[i] = language elsif !@state_column || (row[@state_column].nil? || row[@state_column] == '' || !@excluded_states.include?(row[@state_column])) key = row[@keys_column] comment = @comments_column ? row[@comments_column] : nil key.strip! if @stripping default_value = self.default_lang ? row[defaultCol] : nil value = self.process_value(row[i], default_value) @comments[key] = comment @languages[i].add_content_pair(key, value) end end rowIndex += 1 end write_content end
[ "def", "convert", "(", "name", "=", "@csv_filename", ")", "rowIndex", "=", "0", "excludedCols", "=", "[", "]", "defaultCol", "=", "0", "CSV", ".", "foreach", "(", "name", ",", ":quote_char", "=>", "'\"'", ",", ":col_sep", "=>", "@csv_separator", ",", ":row_sep", "=>", ":auto", ")", "do", "|", "row", "|", "if", "rowIndex", "==", "0", "#check there's at least two columns", "return", "unless", "row", ".", "count", ">", "1", "else", "#skip empty lines (or sections)", "next", "if", "row", "==", "nil", "or", "row", "[", "@keys_column", "]", ".", "nil?", "end", "# go through columns", "row", ".", "size", ".", "times", "do", "|", "i", "|", "next", "if", "excludedCols", ".", "include?", "i", "#header", "if", "rowIndex", "==", "0", "# defaultCol can be the keyValue", "defaultCol", "=", "i", "if", "self", ".", "default_lang", "==", "row", "[", "i", "]", "# ignore all headers not listed in langs to create files", "(", "excludedCols", "<<", "i", "and", "next", ")", "unless", "@langs", ".", "has_key?", "(", "row", "[", "i", "]", ")", "language", "=", "Language", ".", "new", "(", "row", "[", "i", "]", ")", "if", "@langs", "[", "row", "[", "i", "]", "]", ".", "is_a?", "(", "Array", ")", "@langs", "[", "row", "[", "i", "]", "]", ".", "each", "do", "|", "id", "|", "language", ".", "add_language_id", "(", "id", ".", "to_s", ")", "end", "else", "language", ".", "add_language_id", "(", "@langs", "[", "row", "[", "i", "]", "]", ".", "to_s", ")", "end", "@languages", "[", "i", "]", "=", "language", "elsif", "!", "@state_column", "||", "(", "row", "[", "@state_column", "]", ".", "nil?", "||", "row", "[", "@state_column", "]", "==", "''", "||", "!", "@excluded_states", ".", "include?", "(", "row", "[", "@state_column", "]", ")", ")", "key", "=", "row", "[", "@keys_column", "]", "comment", "=", "@comments_column", "?", "row", "[", "@comments_column", "]", ":", "nil", "key", ".", "strip!", "if", "@stripping", "default_value", "=", "self", ".", "default_lang", "?", "row", "[", "defaultCol", "]", ":", "nil", "value", "=", "self", ".", "process_value", "(", "row", "[", "i", "]", ",", "default_value", ")", "@comments", "[", "key", "]", "=", "comment", "@languages", "[", "i", "]", ".", "add_content_pair", "(", "key", ",", "value", ")", "end", "end", "rowIndex", "+=", "1", "end", "write_content", "end" ]
Convert csv file to multiple Localizable.strings files for each column
[ "Convert", "csv", "file", "to", "multiple", "Localizable", ".", "strings", "files", "for", "each", "column" ]
1fd8488322b3422f038bd440d6e6b06d8b1ea202
https://github.com/netbe/Babelish/blob/1fd8488322b3422f038bd440d6e6b06d8b1ea202/lib/babelish/csv2base.rb#L97-L147
18,310
netbe/Babelish
lib/babelish/base2csv.rb
Babelish.Base2Csv.convert
def convert(write_to_file = true) strings = {} keys = nil comments = {} @filenames.each do |fname| header = fname strings[header], file_comments = load_strings(fname) keys ||= strings[header].keys comments.merge!(file_comments) unless file_comments.nil? end if write_to_file # Create csv file puts "Creating #{@csv_filename}" create_csv_file(keys, strings, comments) else return keys, strings end end
ruby
def convert(write_to_file = true) strings = {} keys = nil comments = {} @filenames.each do |fname| header = fname strings[header], file_comments = load_strings(fname) keys ||= strings[header].keys comments.merge!(file_comments) unless file_comments.nil? end if write_to_file # Create csv file puts "Creating #{@csv_filename}" create_csv_file(keys, strings, comments) else return keys, strings end end
[ "def", "convert", "(", "write_to_file", "=", "true", ")", "strings", "=", "{", "}", "keys", "=", "nil", "comments", "=", "{", "}", "@filenames", ".", "each", "do", "|", "fname", "|", "header", "=", "fname", "strings", "[", "header", "]", ",", "file_comments", "=", "load_strings", "(", "fname", ")", "keys", "||=", "strings", "[", "header", "]", ".", "keys", "comments", ".", "merge!", "(", "file_comments", ")", "unless", "file_comments", ".", "nil?", "end", "if", "write_to_file", "# Create csv file", "puts", "\"Creating #{@csv_filename}\"", "create_csv_file", "(", "keys", ",", "strings", ",", "comments", ")", "else", "return", "keys", ",", "strings", "end", "end" ]
Process files and create csv @param [Boolean] write_to_file create or not the csv file @return [Hash] the translations formatted if write_to_file
[ "Process", "files", "and", "create", "csv" ]
1fd8488322b3422f038bd440d6e6b06d8b1ea202
https://github.com/netbe/Babelish/blob/1fd8488322b3422f038bd440d6e6b06d8b1ea202/lib/babelish/base2csv.rb#L24-L43
18,311
netbe/Babelish
lib/babelish/base2csv.rb
Babelish.Base2Csv.basename
def basename(file_path) filename = File.basename(file_path) return filename.split('.')[0].to_sym if file_path end
ruby
def basename(file_path) filename = File.basename(file_path) return filename.split('.')[0].to_sym if file_path end
[ "def", "basename", "(", "file_path", ")", "filename", "=", "File", ".", "basename", "(", "file_path", ")", "return", "filename", ".", "split", "(", "'.'", ")", "[", "0", "]", ".", "to_sym", "if", "file_path", "end" ]
Basename of given file @param [String, #read] file_path @return [String] basename
[ "Basename", "of", "given", "file" ]
1fd8488322b3422f038bd440d6e6b06d8b1ea202
https://github.com/netbe/Babelish/blob/1fd8488322b3422f038bd440d6e6b06d8b1ea202/lib/babelish/base2csv.rb#L71-L74
18,312
netbe/Babelish
lib/babelish/base2csv.rb
Babelish.Base2Csv.create_csv_file
def create_csv_file(keys, strings, comments = nil) raise "csv_filename must not be nil" unless @csv_filename CSV.open(@csv_filename, "wb") do |csv| @headers << "Comments" if !comments.nil? && !comments.empty? csv << @headers keys.each do |key| line = [key] default_val = strings[@default_lang][key] if strings[@default_lang] @filenames.each do |fname| lang = fname current_val = (lang != default_lang && strings[lang][key] == default_val) ? '' : strings[lang][key] line << current_val end line << comments[key] if comments && comments[key] csv << line end puts "Done" end end
ruby
def create_csv_file(keys, strings, comments = nil) raise "csv_filename must not be nil" unless @csv_filename CSV.open(@csv_filename, "wb") do |csv| @headers << "Comments" if !comments.nil? && !comments.empty? csv << @headers keys.each do |key| line = [key] default_val = strings[@default_lang][key] if strings[@default_lang] @filenames.each do |fname| lang = fname current_val = (lang != default_lang && strings[lang][key] == default_val) ? '' : strings[lang][key] line << current_val end line << comments[key] if comments && comments[key] csv << line end puts "Done" end end
[ "def", "create_csv_file", "(", "keys", ",", "strings", ",", "comments", "=", "nil", ")", "raise", "\"csv_filename must not be nil\"", "unless", "@csv_filename", "CSV", ".", "open", "(", "@csv_filename", ",", "\"wb\"", ")", "do", "|", "csv", "|", "@headers", "<<", "\"Comments\"", "if", "!", "comments", ".", "nil?", "&&", "!", "comments", ".", "empty?", "csv", "<<", "@headers", "keys", ".", "each", "do", "|", "key", "|", "line", "=", "[", "key", "]", "default_val", "=", "strings", "[", "@default_lang", "]", "[", "key", "]", "if", "strings", "[", "@default_lang", "]", "@filenames", ".", "each", "do", "|", "fname", "|", "lang", "=", "fname", "current_val", "=", "(", "lang", "!=", "default_lang", "&&", "strings", "[", "lang", "]", "[", "key", "]", "==", "default_val", ")", "?", "''", ":", "strings", "[", "lang", "]", "[", "key", "]", "line", "<<", "current_val", "end", "line", "<<", "comments", "[", "key", "]", "if", "comments", "&&", "comments", "[", "key", "]", "csv", "<<", "line", "end", "puts", "\"Done\"", "end", "end" ]
Create the resulting file @param [Array] keys references of all translations @param [Array] strings translations of all languages @param [Hash] comments hash containing keys, comments related to each keys, describe the translation
[ "Create", "the", "resulting", "file" ]
1fd8488322b3422f038bd440d6e6b06d8b1ea202
https://github.com/netbe/Babelish/blob/1fd8488322b3422f038bd440d6e6b06d8b1ea202/lib/babelish/base2csv.rb#L83-L101
18,313
janlelis/clipboard
lib/clipboard/utils.rb
Clipboard.Utils.popen
def popen(cmd, data, read_output_stream = false) Open3.popen2(cmd) { |input, output, waiter_thread| output_thread = Thread.new { output.read } if read_output_stream begin input.write data rescue Errno::EPIPE end input.close output_thread.value if read_output_stream waiter_thread.value } end
ruby
def popen(cmd, data, read_output_stream = false) Open3.popen2(cmd) { |input, output, waiter_thread| output_thread = Thread.new { output.read } if read_output_stream begin input.write data rescue Errno::EPIPE end input.close output_thread.value if read_output_stream waiter_thread.value } end
[ "def", "popen", "(", "cmd", ",", "data", ",", "read_output_stream", "=", "false", ")", "Open3", ".", "popen2", "(", "cmd", ")", "{", "|", "input", ",", "output", ",", "waiter_thread", "|", "output_thread", "=", "Thread", ".", "new", "{", "output", ".", "read", "}", "if", "read_output_stream", "begin", "input", ".", "write", "data", "rescue", "Errno", "::", "EPIPE", "end", "input", ".", "close", "output_thread", ".", "value", "if", "read_output_stream", "waiter_thread", ".", "value", "}", "end" ]
Utility to call external command - pure .popen2 becomes messy with xsel when not reading the output stream - xclip doesn't like to have output stream read
[ "Utility", "to", "call", "external", "command", "-", "pure", ".", "popen2", "becomes", "messy", "with", "xsel", "when", "not", "reading", "the", "output", "stream", "-", "xclip", "doesn", "t", "like", "to", "have", "output", "stream", "read" ]
a2d406dd9f93d304e11059176c9c1dc978bfc87b
https://github.com/janlelis/clipboard/blob/a2d406dd9f93d304e11059176c9c1dc978bfc87b/lib/clipboard/utils.rb#L18-L31
18,314
neovim/neovim-ruby
lib/neovim/executable.rb
Neovim.Executable.version
def version @version ||= IO.popen([@path, "--version"]) do |io| io.gets[VERSION_PATTERN, 1] end rescue => e raise Error, "Couldn't load #{@path}: #{e}" end
ruby
def version @version ||= IO.popen([@path, "--version"]) do |io| io.gets[VERSION_PATTERN, 1] end rescue => e raise Error, "Couldn't load #{@path}: #{e}" end
[ "def", "version", "@version", "||=", "IO", ".", "popen", "(", "[", "@path", ",", "\"--version\"", "]", ")", "do", "|", "io", "|", "io", ".", "gets", "[", "VERSION_PATTERN", ",", "1", "]", "end", "rescue", "=>", "e", "raise", "Error", ",", "\"Couldn't load #{@path}: #{e}\"", "end" ]
Fetch the +nvim+ version. @return [String]
[ "Fetch", "the", "+", "nvim", "+", "version", "." ]
3c58db971226219b9f373a8abb359be3f26b3b52
https://github.com/neovim/neovim-ruby/blob/3c58db971226219b9f373a8abb359be3f26b3b52/lib/neovim/executable.rb#L26-L32
18,315
neovim/neovim-ruby
lib/neovim/api.rb
Neovim.API.functions
def functions @functions ||= @api_info.fetch("functions").inject({}) do |acc, func| function = Function.new(func) acc.merge(function.name => function) end end
ruby
def functions @functions ||= @api_info.fetch("functions").inject({}) do |acc, func| function = Function.new(func) acc.merge(function.name => function) end end
[ "def", "functions", "@functions", "||=", "@api_info", ".", "fetch", "(", "\"functions\"", ")", ".", "inject", "(", "{", "}", ")", "do", "|", "acc", ",", "func", "|", "function", "=", "Function", ".", "new", "(", "func", ")", "acc", ".", "merge", "(", "function", ".", "name", "=>", "function", ")", "end", "end" ]
Return all functions defined by the API.
[ "Return", "all", "functions", "defined", "by", "the", "API", "." ]
3c58db971226219b9f373a8abb359be3f26b3b52
https://github.com/neovim/neovim-ruby/blob/3c58db971226219b9f373a8abb359be3f26b3b52/lib/neovim/api.rb#L11-L16
18,316
neovim/neovim-ruby
lib/neovim/window.rb
Neovim.Window.cursor=
def cursor=(coords) x, y = coords x = [x, 1].max y = [y, 0].max + 1 @session.request(:nvim_eval, "cursor(#{x}, #{y})") end
ruby
def cursor=(coords) x, y = coords x = [x, 1].max y = [y, 0].max + 1 @session.request(:nvim_eval, "cursor(#{x}, #{y})") end
[ "def", "cursor", "=", "(", "coords", ")", "x", ",", "y", "=", "coords", "x", "=", "[", "x", ",", "1", "]", ".", "max", "y", "=", "[", "y", ",", "0", "]", ".", "max", "+", "1", "@session", ".", "request", "(", ":nvim_eval", ",", "\"cursor(#{x}, #{y})\"", ")", "end" ]
Set the cursor coodinates @param coords [Array(Integer, Integer)] @return [Array(Integer, Integer)]
[ "Set", "the", "cursor", "coodinates" ]
3c58db971226219b9f373a8abb359be3f26b3b52
https://github.com/neovim/neovim-ruby/blob/3c58db971226219b9f373a8abb359be3f26b3b52/lib/neovim/window.rb#L58-L63
18,317
neovim/neovim-ruby
lib/neovim/line_range.rb
Neovim.LineRange.each
def each(&block) (0...@buffer.count).each_slice(5000) do |linenos| start, stop = linenos[0], linenos[-1] + 1 @buffer.get_lines(start, stop, true).each(&block) end end
ruby
def each(&block) (0...@buffer.count).each_slice(5000) do |linenos| start, stop = linenos[0], linenos[-1] + 1 @buffer.get_lines(start, stop, true).each(&block) end end
[ "def", "each", "(", "&", "block", ")", "(", "0", "...", "@buffer", ".", "count", ")", ".", "each_slice", "(", "5000", ")", "do", "|", "linenos", "|", "start", ",", "stop", "=", "linenos", "[", "0", "]", ",", "linenos", "[", "-", "1", "]", "+", "1", "@buffer", ".", "get_lines", "(", "start", ",", "stop", ",", "true", ")", ".", "each", "(", "block", ")", "end", "end" ]
Satisfy the +Enumerable+ interface by yielding each line. @yieldparam line [String]
[ "Satisfy", "the", "+", "Enumerable", "+", "interface", "by", "yielding", "each", "line", "." ]
3c58db971226219b9f373a8abb359be3f26b3b52
https://github.com/neovim/neovim-ruby/blob/3c58db971226219b9f373a8abb359be3f26b3b52/lib/neovim/line_range.rb#L13-L18
18,318
neovim/neovim-ruby
lib/neovim/line_range.rb
Neovim.LineRange.[]=
def []=(*args) *target, val = args pos, len = target if pos.is_a?(Range) @buffer.set_lines(*range_indices(pos), true, Array(val)) else start, stop = length_indices(pos, len || 1) @buffer.set_lines(start, stop, true, Array(val)) end end
ruby
def []=(*args) *target, val = args pos, len = target if pos.is_a?(Range) @buffer.set_lines(*range_indices(pos), true, Array(val)) else start, stop = length_indices(pos, len || 1) @buffer.set_lines(start, stop, true, Array(val)) end end
[ "def", "[]=", "(", "*", "args", ")", "*", "target", ",", "val", "=", "args", "pos", ",", "len", "=", "target", "if", "pos", ".", "is_a?", "(", "Range", ")", "@buffer", ".", "set_lines", "(", "range_indices", "(", "pos", ")", ",", "true", ",", "Array", "(", "val", ")", ")", "else", "start", ",", "stop", "=", "length_indices", "(", "pos", ",", "len", "||", "1", ")", "@buffer", ".", "set_lines", "(", "start", ",", "stop", ",", "true", ",", "Array", "(", "val", ")", ")", "end", "end" ]
Set a line or line range. @overload []=(index, string) @param index [Integer] @param string [String] @overload []=(index, length, strings) @param index [Integer] @param length [Integer] @param strings [Array<String>] @overload []=(range, strings) @param range [Range] @param strings [Array<String>] @example Replace the first line using an index line_range[0] = "first" @example Replace the first two lines using a +Range+ line_range[0..1] = ["first", "second"] @example Replace the first two lines using an index and length line_range[0, 2] = ["first", "second"]
[ "Set", "a", "line", "or", "line", "range", "." ]
3c58db971226219b9f373a8abb359be3f26b3b52
https://github.com/neovim/neovim-ruby/blob/3c58db971226219b9f373a8abb359be3f26b3b52/lib/neovim/line_range.rb#L84-L94
18,319
neovim/neovim-ruby
lib/neovim/session.rb
Neovim.Session.request
def request(method, *args) main_thread_only do @request_id += 1 blocking = Fiber.current == @main_fiber log(:debug) do { method_name: method, request_id: @request_id, blocking: blocking, arguments: args } end @event_loop.request(@request_id, method, *args) response = blocking ? blocking_response : yielding_response raise(Exited) if response.nil? raise(response.error) if response.error response.value end end
ruby
def request(method, *args) main_thread_only do @request_id += 1 blocking = Fiber.current == @main_fiber log(:debug) do { method_name: method, request_id: @request_id, blocking: blocking, arguments: args } end @event_loop.request(@request_id, method, *args) response = blocking ? blocking_response : yielding_response raise(Exited) if response.nil? raise(response.error) if response.error response.value end end
[ "def", "request", "(", "method", ",", "*", "args", ")", "main_thread_only", "do", "@request_id", "+=", "1", "blocking", "=", "Fiber", ".", "current", "==", "@main_fiber", "log", "(", ":debug", ")", "do", "{", "method_name", ":", "method", ",", "request_id", ":", "@request_id", ",", "blocking", ":", "blocking", ",", "arguments", ":", "args", "}", "end", "@event_loop", ".", "request", "(", "@request_id", ",", "method", ",", "args", ")", "response", "=", "blocking", "?", "blocking_response", ":", "yielding_response", "raise", "(", "Exited", ")", "if", "response", ".", "nil?", "raise", "(", "response", ".", "error", ")", "if", "response", ".", "error", "response", ".", "value", "end", "end" ]
Make an RPC request and return its response. If this method is called inside a callback, we are already inside a +Fiber+ handler. In that case, we write to the stream and yield the +Fiber+. Once the response is received, resume the +Fiber+ and return the result. If this method is called outside a callback, write to the stream and run the event loop until a response is received. Messages received in the meantime are enqueued to be handled later.
[ "Make", "an", "RPC", "request", "and", "return", "its", "response", "." ]
3c58db971226219b9f373a8abb359be3f26b3b52
https://github.com/neovim/neovim-ruby/blob/3c58db971226219b9f373a8abb359be3f26b3b52/lib/neovim/session.rb#L54-L75
18,320
onfido/tzu_mock
lib/tzu_mock/mocker.rb
TzuMock.Mocker.mock_proc
def mock_proc(klass, methods, success, result, type) Proc.new do methods.each do |method| allow(klass).to receive(method) do |&block| outcome = Tzu::Outcome.new(success, result, type) outcome.handle(&block) if block outcome end end end end
ruby
def mock_proc(klass, methods, success, result, type) Proc.new do methods.each do |method| allow(klass).to receive(method) do |&block| outcome = Tzu::Outcome.new(success, result, type) outcome.handle(&block) if block outcome end end end end
[ "def", "mock_proc", "(", "klass", ",", "methods", ",", "success", ",", "result", ",", "type", ")", "Proc", ".", "new", "do", "methods", ".", "each", "do", "|", "method", "|", "allow", "(", "klass", ")", ".", "to", "receive", "(", "method", ")", "do", "|", "&", "block", "|", "outcome", "=", "Tzu", "::", "Outcome", ".", "new", "(", "success", ",", "result", ",", "type", ")", "outcome", ".", "handle", "(", "block", ")", "if", "block", "outcome", "end", "end", "end", "end" ]
Need to pass variables in explicity to give the Proc access to them
[ "Need", "to", "pass", "variables", "in", "explicity", "to", "give", "the", "Proc", "access", "to", "them" ]
6fd135b825cdce664e6ca2427cb93f08a8621651
https://github.com/onfido/tzu_mock/blob/6fd135b825cdce664e6ca2427cb93f08a8621651/lib/tzu_mock/mocker.rb#L21-L31
18,321
chef/dep-selector
lib/dep_selector/selector.rb
DepSelector.Selector.find_solution
def find_solution(solution_constraints, valid_packages = nil) # this is a performance optimization so that packages that are # completely unreachable by the solution constraints don't get # added to the CSP packages_to_include_in_solve = trim_unreachable_packages(dep_graph, solution_constraints) begin # first, try to solve the whole set of constraints solve(dep_graph.clone, solution_constraints, valid_packages, packages_to_include_in_solve) rescue Exceptions::NoSolutionFound, Exceptions::TimeBoundExceededNoSolution # since we're here, solving the whole system failed, so add # the solution_constraints one-by-one and try to solve in # order to find the constraint that breaks the system in order # to give helpful debugging info # # TODO [cw,2010/11/28]: for an efficiency gain, instead of # continually re-building the problem and looking for a # solution, turn solution_constraints into a Generator and # iteratively add and solve in order to re-use # propagations. This will require separating setting up the # constraints from searching for the solution. Timeout::timeout(@time_bound, Exceptions::TimeBoundExceededNoSolution) do solution_constraints.each_index do |idx| workspace = dep_graph.clone begin solve(workspace, solution_constraints[0..idx], valid_packages, packages_to_include_in_solve) rescue Exceptions::NoSolutionFound => nsf disabled_packages = packages_to_include_in_solve.inject([]) do |acc, elt| pkg = workspace.package(elt.name) acc << pkg if nsf.unsatisfiable_problem.is_package_disabled?(pkg.gecode_package_id) acc end # disambiguate between packages disabled becuase they # don't exist and those that have otherwise problematic # constraints disabled_non_existent_packages = [] disabled_most_constrained_packages = [] disabled_packages.each do |disabled_pkg| disabled_collection = if disabled_pkg.valid? || (valid_packages && valid_packages.include?(disabled_pkg)) disabled_most_constrained_packages else disabled_non_existent_packages end disabled_collection << disabled_pkg end # Pick the first non-existent or most-constrained package # that was required or the package whose constraints had # to be disabled in order to find a solution and generate # feedback for it. We only report feedback for one # package, because it is in fact actionable and dispalying # feedback for every disabled package would probably be # too long. The full set of disabled packages is # accessible in the NoSolutionExists exception. disabled_package_to_report_on = disabled_non_existent_packages.first || disabled_most_constrained_packages.first feedback = error_reporter.give_feedback(dep_graph, solution_constraints, idx, disabled_package_to_report_on) raise Exceptions::NoSolutionExists.new(feedback, solution_constraints[idx], disabled_non_existent_packages, disabled_most_constrained_packages) end end end end end
ruby
def find_solution(solution_constraints, valid_packages = nil) # this is a performance optimization so that packages that are # completely unreachable by the solution constraints don't get # added to the CSP packages_to_include_in_solve = trim_unreachable_packages(dep_graph, solution_constraints) begin # first, try to solve the whole set of constraints solve(dep_graph.clone, solution_constraints, valid_packages, packages_to_include_in_solve) rescue Exceptions::NoSolutionFound, Exceptions::TimeBoundExceededNoSolution # since we're here, solving the whole system failed, so add # the solution_constraints one-by-one and try to solve in # order to find the constraint that breaks the system in order # to give helpful debugging info # # TODO [cw,2010/11/28]: for an efficiency gain, instead of # continually re-building the problem and looking for a # solution, turn solution_constraints into a Generator and # iteratively add and solve in order to re-use # propagations. This will require separating setting up the # constraints from searching for the solution. Timeout::timeout(@time_bound, Exceptions::TimeBoundExceededNoSolution) do solution_constraints.each_index do |idx| workspace = dep_graph.clone begin solve(workspace, solution_constraints[0..idx], valid_packages, packages_to_include_in_solve) rescue Exceptions::NoSolutionFound => nsf disabled_packages = packages_to_include_in_solve.inject([]) do |acc, elt| pkg = workspace.package(elt.name) acc << pkg if nsf.unsatisfiable_problem.is_package_disabled?(pkg.gecode_package_id) acc end # disambiguate between packages disabled becuase they # don't exist and those that have otherwise problematic # constraints disabled_non_existent_packages = [] disabled_most_constrained_packages = [] disabled_packages.each do |disabled_pkg| disabled_collection = if disabled_pkg.valid? || (valid_packages && valid_packages.include?(disabled_pkg)) disabled_most_constrained_packages else disabled_non_existent_packages end disabled_collection << disabled_pkg end # Pick the first non-existent or most-constrained package # that was required or the package whose constraints had # to be disabled in order to find a solution and generate # feedback for it. We only report feedback for one # package, because it is in fact actionable and dispalying # feedback for every disabled package would probably be # too long. The full set of disabled packages is # accessible in the NoSolutionExists exception. disabled_package_to_report_on = disabled_non_existent_packages.first || disabled_most_constrained_packages.first feedback = error_reporter.give_feedback(dep_graph, solution_constraints, idx, disabled_package_to_report_on) raise Exceptions::NoSolutionExists.new(feedback, solution_constraints[idx], disabled_non_existent_packages, disabled_most_constrained_packages) end end end end end
[ "def", "find_solution", "(", "solution_constraints", ",", "valid_packages", "=", "nil", ")", "# this is a performance optimization so that packages that are", "# completely unreachable by the solution constraints don't get", "# added to the CSP", "packages_to_include_in_solve", "=", "trim_unreachable_packages", "(", "dep_graph", ",", "solution_constraints", ")", "begin", "# first, try to solve the whole set of constraints", "solve", "(", "dep_graph", ".", "clone", ",", "solution_constraints", ",", "valid_packages", ",", "packages_to_include_in_solve", ")", "rescue", "Exceptions", "::", "NoSolutionFound", ",", "Exceptions", "::", "TimeBoundExceededNoSolution", "# since we're here, solving the whole system failed, so add", "# the solution_constraints one-by-one and try to solve in", "# order to find the constraint that breaks the system in order", "# to give helpful debugging info", "#", "# TODO [cw,2010/11/28]: for an efficiency gain, instead of", "# continually re-building the problem and looking for a", "# solution, turn solution_constraints into a Generator and", "# iteratively add and solve in order to re-use", "# propagations. This will require separating setting up the", "# constraints from searching for the solution.", "Timeout", "::", "timeout", "(", "@time_bound", ",", "Exceptions", "::", "TimeBoundExceededNoSolution", ")", "do", "solution_constraints", ".", "each_index", "do", "|", "idx", "|", "workspace", "=", "dep_graph", ".", "clone", "begin", "solve", "(", "workspace", ",", "solution_constraints", "[", "0", "..", "idx", "]", ",", "valid_packages", ",", "packages_to_include_in_solve", ")", "rescue", "Exceptions", "::", "NoSolutionFound", "=>", "nsf", "disabled_packages", "=", "packages_to_include_in_solve", ".", "inject", "(", "[", "]", ")", "do", "|", "acc", ",", "elt", "|", "pkg", "=", "workspace", ".", "package", "(", "elt", ".", "name", ")", "acc", "<<", "pkg", "if", "nsf", ".", "unsatisfiable_problem", ".", "is_package_disabled?", "(", "pkg", ".", "gecode_package_id", ")", "acc", "end", "# disambiguate between packages disabled becuase they", "# don't exist and those that have otherwise problematic", "# constraints", "disabled_non_existent_packages", "=", "[", "]", "disabled_most_constrained_packages", "=", "[", "]", "disabled_packages", ".", "each", "do", "|", "disabled_pkg", "|", "disabled_collection", "=", "if", "disabled_pkg", ".", "valid?", "||", "(", "valid_packages", "&&", "valid_packages", ".", "include?", "(", "disabled_pkg", ")", ")", "disabled_most_constrained_packages", "else", "disabled_non_existent_packages", "end", "disabled_collection", "<<", "disabled_pkg", "end", "# Pick the first non-existent or most-constrained package", "# that was required or the package whose constraints had", "# to be disabled in order to find a solution and generate", "# feedback for it. We only report feedback for one", "# package, because it is in fact actionable and dispalying", "# feedback for every disabled package would probably be", "# too long. The full set of disabled packages is", "# accessible in the NoSolutionExists exception.", "disabled_package_to_report_on", "=", "disabled_non_existent_packages", ".", "first", "||", "disabled_most_constrained_packages", ".", "first", "feedback", "=", "error_reporter", ".", "give_feedback", "(", "dep_graph", ",", "solution_constraints", ",", "idx", ",", "disabled_package_to_report_on", ")", "raise", "Exceptions", "::", "NoSolutionExists", ".", "new", "(", "feedback", ",", "solution_constraints", "[", "idx", "]", ",", "disabled_non_existent_packages", ",", "disabled_most_constrained_packages", ")", "end", "end", "end", "end", "end" ]
Based on solution_constraints, this method tries to find an assignment of PackageVersions that is compatible with the DependencyGraph. If one cannot be found, the constraints are added one at a time until the first unsatisfiable constraint is detected. Once the unsatisfiable solution constraint is identified, required non-existent packages and the most constrained packages are identified and thrown in a NoSolutionExists exception. If a solution constraint refers to a package that doesn't exist or the constraint matches no versions, it is considered invalid. All invalid solution constraints are collected and raised in an InvalidSolutionConstraints exception. If valid_packages is non-nil, it is considered the authoritative list of extant Packages; otherwise, Package#valid? is used. This is useful if the dependency graph represents an already filtered set of packages such that a Package actually exists in your domain but is added to the dependency graph with no versions, in which case Package#valid? would return false even though we don't want to report that the package is non-existent.
[ "Based", "on", "solution_constraints", "this", "method", "tries", "to", "find", "an", "assignment", "of", "PackageVersions", "that", "is", "compatible", "with", "the", "DependencyGraph", ".", "If", "one", "cannot", "be", "found", "the", "constraints", "are", "added", "one", "at", "a", "time", "until", "the", "first", "unsatisfiable", "constraint", "is", "detected", ".", "Once", "the", "unsatisfiable", "solution", "constraint", "is", "identified", "required", "non", "-", "existent", "packages", "and", "the", "most", "constrained", "packages", "are", "identified", "and", "thrown", "in", "a", "NoSolutionExists", "exception", "." ]
48b05738be2c9ce28ca5ed83681291b9e0d87d6c
https://github.com/chef/dep-selector/blob/48b05738be2c9ce28ca5ed83681291b9e0d87d6c/lib/dep_selector/selector.rb#L63-L131
18,322
chef/dep-selector
lib/dep_selector/selector.rb
DepSelector.Selector.process_soln_constraints
def process_soln_constraints(workspace, solution_constraints, valid_packages) gecode = workspace.gecode_wrapper # create shadow package whose dependencies are the solution constraints soln_constraints_pkg_id = gecode.add_package(0, 0, 0) soln_constraints_on_non_existent_packages = [] soln_constraints_that_match_no_versions = [] # generate constraints imposed by solution_constraints solution_constraints.each do |soln_constraint| # look up the package in the cloned dep_graph that corresponds to soln_constraint pkg_name = soln_constraint.package.name pkg = workspace.package(pkg_name) constraint = soln_constraint.constraint # record invalid solution constraints and raise an exception # afterwards unless pkg.valid? || (valid_packages && valid_packages.include?(pkg)) soln_constraints_on_non_existent_packages << soln_constraint next end if pkg[constraint].empty? soln_constraints_that_match_no_versions << soln_constraint next end pkg_id = pkg.gecode_package_id gecode.mark_preferred_to_be_at_latest(pkg_id, 10) gecode.mark_required(pkg_id) if constraint acceptable_versions = pkg.densely_packed_versions[constraint] gecode.add_version_constraint(soln_constraints_pkg_id, 0, pkg_id, acceptable_versions.min, acceptable_versions.max) else # this restricts the domain of the variable to >= 0, which # means -1, the shadow package, cannot be assigned, meaning # the package must be bound to an actual version gecode.add_version_constraint(soln_constraints_pkg_id, 0, pkg_id, 0, pkg.densely_packed_versions.range.max) end end if soln_constraints_on_non_existent_packages.any? || soln_constraints_that_match_no_versions.any? raise Exceptions::InvalidSolutionConstraints.new(soln_constraints_on_non_existent_packages, soln_constraints_that_match_no_versions) end end
ruby
def process_soln_constraints(workspace, solution_constraints, valid_packages) gecode = workspace.gecode_wrapper # create shadow package whose dependencies are the solution constraints soln_constraints_pkg_id = gecode.add_package(0, 0, 0) soln_constraints_on_non_existent_packages = [] soln_constraints_that_match_no_versions = [] # generate constraints imposed by solution_constraints solution_constraints.each do |soln_constraint| # look up the package in the cloned dep_graph that corresponds to soln_constraint pkg_name = soln_constraint.package.name pkg = workspace.package(pkg_name) constraint = soln_constraint.constraint # record invalid solution constraints and raise an exception # afterwards unless pkg.valid? || (valid_packages && valid_packages.include?(pkg)) soln_constraints_on_non_existent_packages << soln_constraint next end if pkg[constraint].empty? soln_constraints_that_match_no_versions << soln_constraint next end pkg_id = pkg.gecode_package_id gecode.mark_preferred_to_be_at_latest(pkg_id, 10) gecode.mark_required(pkg_id) if constraint acceptable_versions = pkg.densely_packed_versions[constraint] gecode.add_version_constraint(soln_constraints_pkg_id, 0, pkg_id, acceptable_versions.min, acceptable_versions.max) else # this restricts the domain of the variable to >= 0, which # means -1, the shadow package, cannot be assigned, meaning # the package must be bound to an actual version gecode.add_version_constraint(soln_constraints_pkg_id, 0, pkg_id, 0, pkg.densely_packed_versions.range.max) end end if soln_constraints_on_non_existent_packages.any? || soln_constraints_that_match_no_versions.any? raise Exceptions::InvalidSolutionConstraints.new(soln_constraints_on_non_existent_packages, soln_constraints_that_match_no_versions) end end
[ "def", "process_soln_constraints", "(", "workspace", ",", "solution_constraints", ",", "valid_packages", ")", "gecode", "=", "workspace", ".", "gecode_wrapper", "# create shadow package whose dependencies are the solution constraints", "soln_constraints_pkg_id", "=", "gecode", ".", "add_package", "(", "0", ",", "0", ",", "0", ")", "soln_constraints_on_non_existent_packages", "=", "[", "]", "soln_constraints_that_match_no_versions", "=", "[", "]", "# generate constraints imposed by solution_constraints", "solution_constraints", ".", "each", "do", "|", "soln_constraint", "|", "# look up the package in the cloned dep_graph that corresponds to soln_constraint", "pkg_name", "=", "soln_constraint", ".", "package", ".", "name", "pkg", "=", "workspace", ".", "package", "(", "pkg_name", ")", "constraint", "=", "soln_constraint", ".", "constraint", "# record invalid solution constraints and raise an exception", "# afterwards", "unless", "pkg", ".", "valid?", "||", "(", "valid_packages", "&&", "valid_packages", ".", "include?", "(", "pkg", ")", ")", "soln_constraints_on_non_existent_packages", "<<", "soln_constraint", "next", "end", "if", "pkg", "[", "constraint", "]", ".", "empty?", "soln_constraints_that_match_no_versions", "<<", "soln_constraint", "next", "end", "pkg_id", "=", "pkg", ".", "gecode_package_id", "gecode", ".", "mark_preferred_to_be_at_latest", "(", "pkg_id", ",", "10", ")", "gecode", ".", "mark_required", "(", "pkg_id", ")", "if", "constraint", "acceptable_versions", "=", "pkg", ".", "densely_packed_versions", "[", "constraint", "]", "gecode", ".", "add_version_constraint", "(", "soln_constraints_pkg_id", ",", "0", ",", "pkg_id", ",", "acceptable_versions", ".", "min", ",", "acceptable_versions", ".", "max", ")", "else", "# this restricts the domain of the variable to >= 0, which", "# means -1, the shadow package, cannot be assigned, meaning", "# the package must be bound to an actual version", "gecode", ".", "add_version_constraint", "(", "soln_constraints_pkg_id", ",", "0", ",", "pkg_id", ",", "0", ",", "pkg", ".", "densely_packed_versions", ".", "range", ".", "max", ")", "end", "end", "if", "soln_constraints_on_non_existent_packages", ".", "any?", "||", "soln_constraints_that_match_no_versions", ".", "any?", "raise", "Exceptions", "::", "InvalidSolutionConstraints", ".", "new", "(", "soln_constraints_on_non_existent_packages", ",", "soln_constraints_that_match_no_versions", ")", "end", "end" ]
This method validates SolutionConstraints and adds their corresponding constraints to the workspace.
[ "This", "method", "validates", "SolutionConstraints", "and", "adds", "their", "corresponding", "constraints", "to", "the", "workspace", "." ]
48b05738be2c9ce28ca5ed83681291b9e0d87d6c
https://github.com/chef/dep-selector/blob/48b05738be2c9ce28ca5ed83681291b9e0d87d6c/lib/dep_selector/selector.rb#L156-L203
18,323
chef/dep-selector
lib/dep_selector/selector.rb
DepSelector.Selector.trim_solution
def trim_solution(soln_constraints, soln, workspace) trimmed_soln = {} soln_constraints.each do |soln_constraint| package = workspace.package(soln_constraint.package.name) expand_package(trimmed_soln, package, soln) end trimmed_soln end
ruby
def trim_solution(soln_constraints, soln, workspace) trimmed_soln = {} soln_constraints.each do |soln_constraint| package = workspace.package(soln_constraint.package.name) expand_package(trimmed_soln, package, soln) end trimmed_soln end
[ "def", "trim_solution", "(", "soln_constraints", ",", "soln", ",", "workspace", ")", "trimmed_soln", "=", "{", "}", "soln_constraints", ".", "each", "do", "|", "soln_constraint", "|", "package", "=", "workspace", ".", "package", "(", "soln_constraint", ".", "package", ".", "name", ")", "expand_package", "(", "trimmed_soln", ",", "package", ",", "soln", ")", "end", "trimmed_soln", "end" ]
Given an assignment of versions to packages, filter down to only the required assignments
[ "Given", "an", "assignment", "of", "versions", "to", "packages", "filter", "down", "to", "only", "the", "required", "assignments" ]
48b05738be2c9ce28ca5ed83681291b9e0d87d6c
https://github.com/chef/dep-selector/blob/48b05738be2c9ce28ca5ed83681291b9e0d87d6c/lib/dep_selector/selector.rb#L207-L217
18,324
chef/dep-selector
lib/dep_selector/selector.rb
DepSelector.Selector.trim_unreachable_packages
def trim_unreachable_packages(workspace, soln_constraints) reachable_packages = [] soln_constraints.each do |soln_constraint| find_reachable_packages(workspace, soln_constraint.package, soln_constraint.constraint, reachable_packages) end reachable_packages end
ruby
def trim_unreachable_packages(workspace, soln_constraints) reachable_packages = [] soln_constraints.each do |soln_constraint| find_reachable_packages(workspace, soln_constraint.package, soln_constraint.constraint, reachable_packages) end reachable_packages end
[ "def", "trim_unreachable_packages", "(", "workspace", ",", "soln_constraints", ")", "reachable_packages", "=", "[", "]", "soln_constraints", ".", "each", "do", "|", "soln_constraint", "|", "find_reachable_packages", "(", "workspace", ",", "soln_constraint", ".", "package", ",", "soln_constraint", ".", "constraint", ",", "reachable_packages", ")", "end", "reachable_packages", "end" ]
Given a workspace and solution constraints, this method returns an array that includes only packages that can be induced by the solution constraints.
[ "Given", "a", "workspace", "and", "solution", "constraints", "this", "method", "returns", "an", "array", "that", "includes", "only", "packages", "that", "can", "be", "induced", "by", "the", "solution", "constraints", "." ]
48b05738be2c9ce28ca5ed83681291b9e0d87d6c
https://github.com/chef/dep-selector/blob/48b05738be2c9ce28ca5ed83681291b9e0d87d6c/lib/dep_selector/selector.rb#L238-L248
18,325
janko/tus-ruby-server
lib/tus/server.rb
Tus.Server.validate_partial_uploads!
def validate_partial_uploads!(part_uids) input = Queue.new part_uids.each { |part_uid| input << part_uid } input.close results = Queue.new thread_count = storage.concurrency[:concatenation] if storage.respond_to?(:concurrency) thread_count ||= 10 threads = thread_count.times.map do Thread.new do begin loop do part_uid = input.pop or break part_info = storage.read_info(part_uid) results << Tus::Info.new(part_info) end nil rescue => error input.clear error end end end errors = threads.map(&:value).compact if errors.any? { |error| error.is_a?(Tus::NotFound) } error!(400, "One or more partial uploads were not found") elsif errors.any? fail errors.first end part_infos = Array.new(results.size) { results.pop } # convert Queue into an Array unless part_infos.all?(&:partial?) error!(400, "One or more uploads were not partial") end if max_size && part_infos.map(&:length).inject(0, :+) > max_size error!(400, "The sum of partial upload lengths exceed Tus-Max-Size") end end
ruby
def validate_partial_uploads!(part_uids) input = Queue.new part_uids.each { |part_uid| input << part_uid } input.close results = Queue.new thread_count = storage.concurrency[:concatenation] if storage.respond_to?(:concurrency) thread_count ||= 10 threads = thread_count.times.map do Thread.new do begin loop do part_uid = input.pop or break part_info = storage.read_info(part_uid) results << Tus::Info.new(part_info) end nil rescue => error input.clear error end end end errors = threads.map(&:value).compact if errors.any? { |error| error.is_a?(Tus::NotFound) } error!(400, "One or more partial uploads were not found") elsif errors.any? fail errors.first end part_infos = Array.new(results.size) { results.pop } # convert Queue into an Array unless part_infos.all?(&:partial?) error!(400, "One or more uploads were not partial") end if max_size && part_infos.map(&:length).inject(0, :+) > max_size error!(400, "The sum of partial upload lengths exceed Tus-Max-Size") end end
[ "def", "validate_partial_uploads!", "(", "part_uids", ")", "input", "=", "Queue", ".", "new", "part_uids", ".", "each", "{", "|", "part_uid", "|", "input", "<<", "part_uid", "}", "input", ".", "close", "results", "=", "Queue", ".", "new", "thread_count", "=", "storage", ".", "concurrency", "[", ":concatenation", "]", "if", "storage", ".", "respond_to?", "(", ":concurrency", ")", "thread_count", "||=", "10", "threads", "=", "thread_count", ".", "times", ".", "map", "do", "Thread", ".", "new", "do", "begin", "loop", "do", "part_uid", "=", "input", ".", "pop", "or", "break", "part_info", "=", "storage", ".", "read_info", "(", "part_uid", ")", "results", "<<", "Tus", "::", "Info", ".", "new", "(", "part_info", ")", "end", "nil", "rescue", "=>", "error", "input", ".", "clear", "error", "end", "end", "end", "errors", "=", "threads", ".", "map", "(", ":value", ")", ".", "compact", "if", "errors", ".", "any?", "{", "|", "error", "|", "error", ".", "is_a?", "(", "Tus", "::", "NotFound", ")", "}", "error!", "(", "400", ",", "\"One or more partial uploads were not found\"", ")", "elsif", "errors", ".", "any?", "fail", "errors", ".", "first", "end", "part_infos", "=", "Array", ".", "new", "(", "results", ".", "size", ")", "{", "results", ".", "pop", "}", "# convert Queue into an Array", "unless", "part_infos", ".", "all?", "(", ":partial?", ")", "error!", "(", "400", ",", "\"One or more uploads were not partial\"", ")", "end", "if", "max_size", "&&", "part_infos", ".", "map", "(", ":length", ")", ".", "inject", "(", "0", ",", ":+", ")", ">", "max_size", "error!", "(", "400", ",", "\"The sum of partial upload lengths exceed Tus-Max-Size\"", ")", "end", "end" ]
Validates that each partial upload exists and is marked as one.
[ "Validates", "that", "each", "partial", "upload", "exists", "and", "is", "marked", "as", "one", "." ]
8e8cb77a10a83c1e61263107b8bfd7934ac45638
https://github.com/janko/tus-ruby-server/blob/8e8cb77a10a83c1e61263107b8bfd7934ac45638/lib/tus/server.rb#L309-L352
18,326
wvanbergen/chunky_png
lib/chunky_png/image.rb
ChunkyPNG.Image.metadata_chunks
def metadata_chunks metadata.map do |key, value| if value.length >= METADATA_COMPRESSION_TRESHOLD ChunkyPNG::Chunk::CompressedText.new(key, value) else ChunkyPNG::Chunk::Text.new(key, value) end end end
ruby
def metadata_chunks metadata.map do |key, value| if value.length >= METADATA_COMPRESSION_TRESHOLD ChunkyPNG::Chunk::CompressedText.new(key, value) else ChunkyPNG::Chunk::Text.new(key, value) end end end
[ "def", "metadata_chunks", "metadata", ".", "map", "do", "|", "key", ",", "value", "|", "if", "value", ".", "length", ">=", "METADATA_COMPRESSION_TRESHOLD", "ChunkyPNG", "::", "Chunk", "::", "CompressedText", ".", "new", "(", "key", ",", "value", ")", "else", "ChunkyPNG", "::", "Chunk", "::", "Text", ".", "new", "(", "key", ",", "value", ")", "end", "end", "end" ]
Returns the metadata for this image as PNG chunks. Chunks will either be of the {ChunkyPNG::Chunk::Text} type for small values (in bytes), or of the {ChunkyPNG::Chunk::CompressedText} type for values that are larger in size. @return [Array<ChunkyPNG::Chunk>] An array of metadata chunks. @see ChunkyPNG::Image::METADATA_COMPRESSION_TRESHOLD
[ "Returns", "the", "metadata", "for", "this", "image", "as", "PNG", "chunks", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/image.rb#L41-L49
18,327
wvanbergen/chunky_png
lib/chunky_png/rmagick.rb
ChunkyPNG.RMagick.import
def import(image) pixels = image.export_pixels_to_str(0, 0, image.columns, image.rows, "RGBA") ChunkyPNG::Canvas.from_rgba_stream(image.columns, image.rows, pixels) end
ruby
def import(image) pixels = image.export_pixels_to_str(0, 0, image.columns, image.rows, "RGBA") ChunkyPNG::Canvas.from_rgba_stream(image.columns, image.rows, pixels) end
[ "def", "import", "(", "image", ")", "pixels", "=", "image", ".", "export_pixels_to_str", "(", "0", ",", "0", ",", "image", ".", "columns", ",", "image", ".", "rows", ",", "\"RGBA\"", ")", "ChunkyPNG", "::", "Canvas", ".", "from_rgba_stream", "(", "image", ".", "columns", ",", "image", ".", "rows", ",", "pixels", ")", "end" ]
Imports an RMagick image as Canvas object. @param [Magick::Image] image The image to import @return [ChunkyPNG::Canvas] The canvas, constructed from the RMagick image.
[ "Imports", "an", "RMagick", "image", "as", "Canvas", "object", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/rmagick.rb#L27-L30
18,328
wvanbergen/chunky_png
lib/chunky_png/rmagick.rb
ChunkyPNG.RMagick.export
def export(canvas) image = Magick::Image.new(canvas.width, canvas.height) image.import_pixels(0, 0, canvas.width, canvas.height, "RGBA", canvas.pixels.pack("N*")) image end
ruby
def export(canvas) image = Magick::Image.new(canvas.width, canvas.height) image.import_pixels(0, 0, canvas.width, canvas.height, "RGBA", canvas.pixels.pack("N*")) image end
[ "def", "export", "(", "canvas", ")", "image", "=", "Magick", "::", "Image", ".", "new", "(", "canvas", ".", "width", ",", "canvas", ".", "height", ")", "image", ".", "import_pixels", "(", "0", ",", "0", ",", "canvas", ".", "width", ",", "canvas", ".", "height", ",", "\"RGBA\"", ",", "canvas", ".", "pixels", ".", "pack", "(", "\"N*\"", ")", ")", "image", "end" ]
Exports a Canvas as RMagick image instance. @param [ChunkyPNG::Canvas] canvas The canvas to export. @return [Magick::Image] The RMagick image constructed from the Canvas instance.
[ "Exports", "a", "Canvas", "as", "RMagick", "image", "instance", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/rmagick.rb#L35-L39
18,329
wvanbergen/chunky_png
lib/chunky_png/vector.rb
ChunkyPNG.Vector.each_edge
def each_edge(close = true) raise ChunkyPNG::ExpectationFailed, "Not enough points in this path to draw an edge!" if length < 2 points.each_cons(2) { |a, b| yield(a, b) } yield(points.last, points.first) if close end
ruby
def each_edge(close = true) raise ChunkyPNG::ExpectationFailed, "Not enough points in this path to draw an edge!" if length < 2 points.each_cons(2) { |a, b| yield(a, b) } yield(points.last, points.first) if close end
[ "def", "each_edge", "(", "close", "=", "true", ")", "raise", "ChunkyPNG", "::", "ExpectationFailed", ",", "\"Not enough points in this path to draw an edge!\"", "if", "length", "<", "2", "points", ".", "each_cons", "(", "2", ")", "{", "|", "a", ",", "b", "|", "yield", "(", "a", ",", "b", ")", "}", "yield", "(", "points", ".", "last", ",", "points", ".", "first", ")", "if", "close", "end" ]
Initializes a vector based on a list of Point instances. You usually do not want to use this method directly, but call {ChunkyPNG.Vector} instead. @param [Array<ChunkyPNG::Point>] points @see ChunkyPNG.Vector Iterates over all the edges in this vector. An edge is a combination of two subsequent points in the vector. Together, they will form a path from the first point to the last point @param [true, false] close Whether to close the path, i.e. return an edge that connects the last point in the vector back to the first point. @return [void] @raise [ChunkyPNG::ExpectationFailed] if the vector contains less than two points. @see #edges
[ "Initializes", "a", "vector", "based", "on", "a", "list", "of", "Point", "instances", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/vector.rb#L58-L62
18,330
wvanbergen/chunky_png
lib/chunky_png/datastream.rb
ChunkyPNG.Datastream.to_blob
def to_blob str = StringIO.new str.set_encoding("ASCII-8BIT") write(str) str.string end
ruby
def to_blob str = StringIO.new str.set_encoding("ASCII-8BIT") write(str) str.string end
[ "def", "to_blob", "str", "=", "StringIO", ".", "new", "str", ".", "set_encoding", "(", "\"ASCII-8BIT\"", ")", "write", "(", "str", ")", "str", ".", "string", "end" ]
Encodes this datastream into a string. @return [String] The encoded PNG datastream.
[ "Encodes", "this", "datastream", "into", "a", "string", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/datastream.rb#L180-L185
18,331
wvanbergen/chunky_png
lib/chunky_png/dimension.rb
ChunkyPNG.Dimension.include?
def include?(*point_like) point = ChunkyPNG::Point(*point_like) point.x >= 0 && point.x < width && point.y >= 0 && point.y < height end
ruby
def include?(*point_like) point = ChunkyPNG::Point(*point_like) point.x >= 0 && point.x < width && point.y >= 0 && point.y < height end
[ "def", "include?", "(", "*", "point_like", ")", "point", "=", "ChunkyPNG", "::", "Point", "(", "point_like", ")", "point", ".", "x", ">=", "0", "&&", "point", ".", "x", "<", "width", "&&", "point", ".", "y", ">=", "0", "&&", "point", ".", "y", "<", "height", "end" ]
Checks whether a point is within bounds of this dimension. @param [ChunkyPNG::Point, ...] point_like A point-like to bounds-check. @return [true, false] True iff the x and y coordinate fall in this dimension. @see ChunkyPNG.Point
[ "Checks", "whether", "a", "point", "is", "within", "bounds", "of", "this", "dimension", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/dimension.rb#L94-L97
18,332
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.parse
def parse(source) return source if source.is_a?(Integer) case source.to_s when /^\d+$/ then source.to_s.to_i when HEX3_COLOR_REGEXP, HEX6_COLOR_REGEXP then from_hex(source.to_s) when HTML_COLOR_REGEXP then html_color(source.to_s) else raise ArgumentError, "Don't know how to create a color from #{source.inspect}!" end end
ruby
def parse(source) return source if source.is_a?(Integer) case source.to_s when /^\d+$/ then source.to_s.to_i when HEX3_COLOR_REGEXP, HEX6_COLOR_REGEXP then from_hex(source.to_s) when HTML_COLOR_REGEXP then html_color(source.to_s) else raise ArgumentError, "Don't know how to create a color from #{source.inspect}!" end end
[ "def", "parse", "(", "source", ")", "return", "source", "if", "source", ".", "is_a?", "(", "Integer", ")", "case", "source", ".", "to_s", "when", "/", "\\d", "/", "then", "source", ".", "to_s", ".", "to_i", "when", "HEX3_COLOR_REGEXP", ",", "HEX6_COLOR_REGEXP", "then", "from_hex", "(", "source", ".", "to_s", ")", "when", "HTML_COLOR_REGEXP", "then", "html_color", "(", "source", ".", "to_s", ")", "else", "raise", "ArgumentError", ",", "\"Don't know how to create a color from #{source.inspect}!\"", "end", "end" ]
CONSTRUCTING COLOR VALUES Parses a color value given a numeric or string argument. It supports color numbers, colors in hex notation and named HTML colors. @param [Integer, String] source The color value. @return [Integer] The color value, with the opacity applied if one was given.
[ "CONSTRUCTING", "COLOR", "VALUES" ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L84-L92
18,333
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.from_hex
def from_hex(hex_value, opacity = nil) base_color = case hex_value when HEX3_COLOR_REGEXP $1.gsub(/([0-9a-f])/i, '\1\1').hex << 8 when HEX6_COLOR_REGEXP $1.hex << 8 else raise ArgumentError, "Not a valid hex color notation: #{hex_value.inspect}!" end opacity ||= $2 ? $2.hex : 0xff base_color | opacity end
ruby
def from_hex(hex_value, opacity = nil) base_color = case hex_value when HEX3_COLOR_REGEXP $1.gsub(/([0-9a-f])/i, '\1\1').hex << 8 when HEX6_COLOR_REGEXP $1.hex << 8 else raise ArgumentError, "Not a valid hex color notation: #{hex_value.inspect}!" end opacity ||= $2 ? $2.hex : 0xff base_color | opacity end
[ "def", "from_hex", "(", "hex_value", ",", "opacity", "=", "nil", ")", "base_color", "=", "case", "hex_value", "when", "HEX3_COLOR_REGEXP", "$1", ".", "gsub", "(", "/", "/i", ",", "'\\1\\1'", ")", ".", "hex", "<<", "8", "when", "HEX6_COLOR_REGEXP", "$1", ".", "hex", "<<", "8", "else", "raise", "ArgumentError", ",", "\"Not a valid hex color notation: #{hex_value.inspect}!\"", "end", "opacity", "||=", "$2", "?", "$2", ".", "hex", ":", "0xff", "base_color", "|", "opacity", "end" ]
Creates a color by converting it from a string in hex notation. It supports colors with (#rrggbbaa) or without (#rrggbb) alpha channel as well as the 3-digit short format (#rgb) for those without. Color strings may include the prefix "0x" or "#". @param [String] hex_value The color in hex notation. @param [Integer] opacity The opacity value for the color. Overrides any opacity value given in the hex value if given. @return [Integer] The color value. @raise [ArgumentError] if the value given is not a hex color notation.
[ "Creates", "a", "color", "by", "converting", "it", "from", "a", "string", "in", "hex", "notation", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L165-L176
18,334
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.from_hsv
def from_hsv(hue, saturation, value, alpha = 255) raise ArgumentError, "Hue must be between 0 and 360" unless (0..360).cover?(hue) raise ArgumentError, "Saturation must be between 0 and 1" unless (0..1).cover?(saturation) raise ArgumentError, "Value/brightness must be between 0 and 1" unless (0..1).cover?(value) chroma = value * saturation rgb = cylindrical_to_cubic(hue, saturation, value, chroma) rgb.map! { |component| ((component + value - chroma) * 255).to_i } rgb << alpha rgba(*rgb) end
ruby
def from_hsv(hue, saturation, value, alpha = 255) raise ArgumentError, "Hue must be between 0 and 360" unless (0..360).cover?(hue) raise ArgumentError, "Saturation must be between 0 and 1" unless (0..1).cover?(saturation) raise ArgumentError, "Value/brightness must be between 0 and 1" unless (0..1).cover?(value) chroma = value * saturation rgb = cylindrical_to_cubic(hue, saturation, value, chroma) rgb.map! { |component| ((component + value - chroma) * 255).to_i } rgb << alpha rgba(*rgb) end
[ "def", "from_hsv", "(", "hue", ",", "saturation", ",", "value", ",", "alpha", "=", "255", ")", "raise", "ArgumentError", ",", "\"Hue must be between 0 and 360\"", "unless", "(", "0", "..", "360", ")", ".", "cover?", "(", "hue", ")", "raise", "ArgumentError", ",", "\"Saturation must be between 0 and 1\"", "unless", "(", "0", "..", "1", ")", ".", "cover?", "(", "saturation", ")", "raise", "ArgumentError", ",", "\"Value/brightness must be between 0 and 1\"", "unless", "(", "0", "..", "1", ")", ".", "cover?", "(", "value", ")", "chroma", "=", "value", "*", "saturation", "rgb", "=", "cylindrical_to_cubic", "(", "hue", ",", "saturation", ",", "value", ",", "chroma", ")", "rgb", ".", "map!", "{", "|", "component", "|", "(", "(", "component", "+", "value", "-", "chroma", ")", "*", "255", ")", ".", "to_i", "}", "rgb", "<<", "alpha", "rgba", "(", "rgb", ")", "end" ]
Creates a new color from an HSV triple. Create a new color using an HSV (sometimes also called HSB) triple. The words `value` and `brightness` are used interchangeably and synonymously in descriptions of this colorspace. This implementation follows the modern convention of 0 degrees hue indicating red. @param [Fixnum] hue The hue component (0-360) @param [Fixnum] saturation The saturation component (0-1) @param [Fixnum] value The value (brightness) component (0-1) @param [Fixnum] alpha Defaults to opaque (255). @return [Integer] The newly constructed color value. @raise [ArgumentError] if the hsv triple is invalid. @see http://en.wikipedia.org/wiki/HSL_and_HSV
[ "Creates", "a", "new", "color", "from", "an", "HSV", "triple", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L192-L202
18,335
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.from_hsl
def from_hsl(hue, saturation, lightness, alpha = 255) raise ArgumentError, "Hue #{hue} was not between 0 and 360" unless (0..360).cover?(hue) raise ArgumentError, "Saturation #{saturation} was not between 0 and 1" unless (0..1).cover?(saturation) raise ArgumentError, "Lightness #{lightness} was not between 0 and 1" unless (0..1).cover?(lightness) chroma = (1 - (2 * lightness - 1).abs) * saturation rgb = cylindrical_to_cubic(hue, saturation, lightness, chroma) rgb.map! { |component| ((component + lightness - 0.5 * chroma) * 255).to_i } rgb << alpha rgba(*rgb) end
ruby
def from_hsl(hue, saturation, lightness, alpha = 255) raise ArgumentError, "Hue #{hue} was not between 0 and 360" unless (0..360).cover?(hue) raise ArgumentError, "Saturation #{saturation} was not between 0 and 1" unless (0..1).cover?(saturation) raise ArgumentError, "Lightness #{lightness} was not between 0 and 1" unless (0..1).cover?(lightness) chroma = (1 - (2 * lightness - 1).abs) * saturation rgb = cylindrical_to_cubic(hue, saturation, lightness, chroma) rgb.map! { |component| ((component + lightness - 0.5 * chroma) * 255).to_i } rgb << alpha rgba(*rgb) end
[ "def", "from_hsl", "(", "hue", ",", "saturation", ",", "lightness", ",", "alpha", "=", "255", ")", "raise", "ArgumentError", ",", "\"Hue #{hue} was not between 0 and 360\"", "unless", "(", "0", "..", "360", ")", ".", "cover?", "(", "hue", ")", "raise", "ArgumentError", ",", "\"Saturation #{saturation} was not between 0 and 1\"", "unless", "(", "0", "..", "1", ")", ".", "cover?", "(", "saturation", ")", "raise", "ArgumentError", ",", "\"Lightness #{lightness} was not between 0 and 1\"", "unless", "(", "0", "..", "1", ")", ".", "cover?", "(", "lightness", ")", "chroma", "=", "(", "1", "-", "(", "2", "*", "lightness", "-", "1", ")", ".", "abs", ")", "*", "saturation", "rgb", "=", "cylindrical_to_cubic", "(", "hue", ",", "saturation", ",", "lightness", ",", "chroma", ")", "rgb", ".", "map!", "{", "|", "component", "|", "(", "(", "component", "+", "lightness", "-", "0.5", "*", "chroma", ")", "*", "255", ")", ".", "to_i", "}", "rgb", "<<", "alpha", "rgba", "(", "rgb", ")", "end" ]
Creates a new color from an HSL triple. This implementation follows the modern convention of 0 degrees hue indicating red. @param [Fixnum] hue The hue component (0-360) @param [Fixnum] saturation The saturation component (0-1) @param [Fixnum] lightness The lightness component (0-1) @param [Fixnum] alpha Defaults to opaque (255). @return [Integer] The newly constructed color value. @raise [ArgumentError] if the hsl triple is invalid. @see http://en.wikipedia.org/wiki/HSL_and_HSV
[ "Creates", "a", "new", "color", "from", "an", "HSL", "triple", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L218-L228
18,336
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.cylindrical_to_cubic
def cylindrical_to_cubic(hue, saturation, y_component, chroma) hue_prime = hue.fdiv(60) x = chroma * (1 - (hue_prime % 2 - 1).abs) case hue_prime when (0...1) then [chroma, x, 0] when (1...2) then [x, chroma, 0] when (2...3) then [0, chroma, x] when (3...4) then [0, x, chroma] when (4...5) then [x, 0, chroma] when (5..6) then [chroma, 0, x] end end
ruby
def cylindrical_to_cubic(hue, saturation, y_component, chroma) hue_prime = hue.fdiv(60) x = chroma * (1 - (hue_prime % 2 - 1).abs) case hue_prime when (0...1) then [chroma, x, 0] when (1...2) then [x, chroma, 0] when (2...3) then [0, chroma, x] when (3...4) then [0, x, chroma] when (4...5) then [x, 0, chroma] when (5..6) then [chroma, 0, x] end end
[ "def", "cylindrical_to_cubic", "(", "hue", ",", "saturation", ",", "y_component", ",", "chroma", ")", "hue_prime", "=", "hue", ".", "fdiv", "(", "60", ")", "x", "=", "chroma", "*", "(", "1", "-", "(", "hue_prime", "%", "2", "-", "1", ")", ".", "abs", ")", "case", "hue_prime", "when", "(", "0", "...", "1", ")", "then", "[", "chroma", ",", "x", ",", "0", "]", "when", "(", "1", "...", "2", ")", "then", "[", "x", ",", "chroma", ",", "0", "]", "when", "(", "2", "...", "3", ")", "then", "[", "0", ",", "chroma", ",", "x", "]", "when", "(", "3", "...", "4", ")", "then", "[", "0", ",", "x", ",", "chroma", "]", "when", "(", "4", "...", "5", ")", "then", "[", "x", ",", "0", ",", "chroma", "]", "when", "(", "5", "..", "6", ")", "then", "[", "chroma", ",", "0", ",", "x", "]", "end", "end" ]
Convert one HSL or HSV triple and associated chroma to a scaled rgb triple This method encapsulates the shared mathematical operations needed to convert coordinates from a cylindrical colorspace such as HSL or HSV into coordinates of the RGB colorspace. Even though chroma values are derived from the other three coordinates, the formula for calculating chroma differs for each colorspace. Since it is calculated differently for each colorspace, it must be passed in as a parameter. @param [Fixnum] hue The hue-component (0-360) @param [Fixnum] saturation The saturation-component (0-1) @param [Fixnum] y_component The y_component can represent either lightness or brightness/value (0-1) depending on which scheme (HSV/HSL) is being used. @param [Fixnum] chroma The associated chroma value. @return [Array<Fixnum>] A scaled r,g,b triple. Scheme-dependent adjustments are still needed to reach the true r,g,b values. @see http://en.wikipedia.org/wiki/HSL_and_HSV @see http://www.tomjewett.com/colors/hsb.html @private
[ "Convert", "one", "HSL", "or", "HSV", "triple", "and", "associated", "chroma", "to", "a", "scaled", "rgb", "triple" ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L251-L263
18,337
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.grayscale?
def grayscale?(value) r(value) == b(value) && b(value) == g(value) end
ruby
def grayscale?(value) r(value) == b(value) && b(value) == g(value) end
[ "def", "grayscale?", "(", "value", ")", "r", "(", "value", ")", "==", "b", "(", "value", ")", "&&", "b", "(", "value", ")", "==", "g", "(", "value", ")", "end" ]
Returns true if this color is fully transparent. @param [Integer] value The color to test. @return [true, false] True if the r, g and b component are equal.
[ "Returns", "true", "if", "this", "color", "is", "fully", "transparent", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L321-L323
18,338
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.compose_quick
def compose_quick(fg, bg) return fg if opaque?(fg) || fully_transparent?(bg) return bg if fully_transparent?(fg) a_com = int8_mult(0xff - a(fg), a(bg)) new_r = int8_mult(a(fg), r(fg)) + int8_mult(a_com, r(bg)) new_g = int8_mult(a(fg), g(fg)) + int8_mult(a_com, g(bg)) new_b = int8_mult(a(fg), b(fg)) + int8_mult(a_com, b(bg)) new_a = a(fg) + a_com rgba(new_r, new_g, new_b, new_a) end
ruby
def compose_quick(fg, bg) return fg if opaque?(fg) || fully_transparent?(bg) return bg if fully_transparent?(fg) a_com = int8_mult(0xff - a(fg), a(bg)) new_r = int8_mult(a(fg), r(fg)) + int8_mult(a_com, r(bg)) new_g = int8_mult(a(fg), g(fg)) + int8_mult(a_com, g(bg)) new_b = int8_mult(a(fg), b(fg)) + int8_mult(a_com, b(bg)) new_a = a(fg) + a_com rgba(new_r, new_g, new_b, new_a) end
[ "def", "compose_quick", "(", "fg", ",", "bg", ")", "return", "fg", "if", "opaque?", "(", "fg", ")", "||", "fully_transparent?", "(", "bg", ")", "return", "bg", "if", "fully_transparent?", "(", "fg", ")", "a_com", "=", "int8_mult", "(", "0xff", "-", "a", "(", "fg", ")", ",", "a", "(", "bg", ")", ")", "new_r", "=", "int8_mult", "(", "a", "(", "fg", ")", ",", "r", "(", "fg", ")", ")", "+", "int8_mult", "(", "a_com", ",", "r", "(", "bg", ")", ")", "new_g", "=", "int8_mult", "(", "a", "(", "fg", ")", ",", "g", "(", "fg", ")", ")", "+", "int8_mult", "(", "a_com", ",", "g", "(", "bg", ")", ")", "new_b", "=", "int8_mult", "(", "a", "(", "fg", ")", ",", "b", "(", "fg", ")", ")", "+", "int8_mult", "(", "a_com", ",", "b", "(", "bg", ")", ")", "new_a", "=", "a", "(", "fg", ")", "+", "a_com", "rgba", "(", "new_r", ",", "new_g", ",", "new_b", ",", "new_a", ")", "end" ]
Composes two colors with an alpha channel using integer math. This version is faster than the version based on floating point math, so this compositing function is used by default. @param [Integer] fg The foreground color. @param [Integer] bg The background color. @return [Integer] The composited color. @see ChunkyPNG::Color#compose_precise
[ "Composes", "two", "colors", "with", "an", "alpha", "channel", "using", "integer", "math", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L360-L370
18,339
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.compose_precise
def compose_precise(fg, bg) return fg if opaque?(fg) || fully_transparent?(bg) return bg if fully_transparent?(fg) fg_a = a(fg).to_f / MAX bg_a = a(bg).to_f / MAX a_com = (1.0 - fg_a) * bg_a new_r = (fg_a * r(fg) + a_com * r(bg)).round new_g = (fg_a * g(fg) + a_com * g(bg)).round new_b = (fg_a * b(fg) + a_com * b(bg)).round new_a = ((fg_a + a_com) * MAX).round rgba(new_r, new_g, new_b, new_a) end
ruby
def compose_precise(fg, bg) return fg if opaque?(fg) || fully_transparent?(bg) return bg if fully_transparent?(fg) fg_a = a(fg).to_f / MAX bg_a = a(bg).to_f / MAX a_com = (1.0 - fg_a) * bg_a new_r = (fg_a * r(fg) + a_com * r(bg)).round new_g = (fg_a * g(fg) + a_com * g(bg)).round new_b = (fg_a * b(fg) + a_com * b(bg)).round new_a = ((fg_a + a_com) * MAX).round rgba(new_r, new_g, new_b, new_a) end
[ "def", "compose_precise", "(", "fg", ",", "bg", ")", "return", "fg", "if", "opaque?", "(", "fg", ")", "||", "fully_transparent?", "(", "bg", ")", "return", "bg", "if", "fully_transparent?", "(", "fg", ")", "fg_a", "=", "a", "(", "fg", ")", ".", "to_f", "/", "MAX", "bg_a", "=", "a", "(", "bg", ")", ".", "to_f", "/", "MAX", "a_com", "=", "(", "1.0", "-", "fg_a", ")", "*", "bg_a", "new_r", "=", "(", "fg_a", "*", "r", "(", "fg", ")", "+", "a_com", "*", "r", "(", "bg", ")", ")", ".", "round", "new_g", "=", "(", "fg_a", "*", "g", "(", "fg", ")", "+", "a_com", "*", "g", "(", "bg", ")", ")", ".", "round", "new_b", "=", "(", "fg_a", "*", "b", "(", "fg", ")", "+", "a_com", "*", "b", "(", "bg", ")", ")", ".", "round", "new_a", "=", "(", "(", "fg_a", "+", "a_com", ")", "*", "MAX", ")", ".", "round", "rgba", "(", "new_r", ",", "new_g", ",", "new_b", ",", "new_a", ")", "end" ]
Composes two colors with an alpha channel using floating point math. This method uses more precise floating point math, but this precision is lost when the result is converted back to an integer. Because it is slower than the version based on integer math, that version is preferred. @param [Integer] fg The foreground color. @param [Integer] bg The background color. @return [Integer] The composited color. @see ChunkyPNG::Color#compose_quick
[ "Composes", "two", "colors", "with", "an", "alpha", "channel", "using", "floating", "point", "math", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L382-L395
18,340
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.interpolate_quick
def interpolate_quick(fg, bg, alpha) return fg if alpha >= 255 return bg if alpha <= 0 alpha_com = 255 - alpha new_r = int8_mult(alpha, r(fg)) + int8_mult(alpha_com, r(bg)) new_g = int8_mult(alpha, g(fg)) + int8_mult(alpha_com, g(bg)) new_b = int8_mult(alpha, b(fg)) + int8_mult(alpha_com, b(bg)) new_a = int8_mult(alpha, a(fg)) + int8_mult(alpha_com, a(bg)) rgba(new_r, new_g, new_b, new_a) end
ruby
def interpolate_quick(fg, bg, alpha) return fg if alpha >= 255 return bg if alpha <= 0 alpha_com = 255 - alpha new_r = int8_mult(alpha, r(fg)) + int8_mult(alpha_com, r(bg)) new_g = int8_mult(alpha, g(fg)) + int8_mult(alpha_com, g(bg)) new_b = int8_mult(alpha, b(fg)) + int8_mult(alpha_com, b(bg)) new_a = int8_mult(alpha, a(fg)) + int8_mult(alpha_com, a(bg)) rgba(new_r, new_g, new_b, new_a) end
[ "def", "interpolate_quick", "(", "fg", ",", "bg", ",", "alpha", ")", "return", "fg", "if", "alpha", ">=", "255", "return", "bg", "if", "alpha", "<=", "0", "alpha_com", "=", "255", "-", "alpha", "new_r", "=", "int8_mult", "(", "alpha", ",", "r", "(", "fg", ")", ")", "+", "int8_mult", "(", "alpha_com", ",", "r", "(", "bg", ")", ")", "new_g", "=", "int8_mult", "(", "alpha", ",", "g", "(", "fg", ")", ")", "+", "int8_mult", "(", "alpha_com", ",", "g", "(", "bg", ")", ")", "new_b", "=", "int8_mult", "(", "alpha", ",", "b", "(", "fg", ")", ")", "+", "int8_mult", "(", "alpha_com", ",", "b", "(", "bg", ")", ")", "new_a", "=", "int8_mult", "(", "alpha", ",", "a", "(", "fg", ")", ")", "+", "int8_mult", "(", "alpha_com", ",", "a", "(", "bg", ")", ")", "rgba", "(", "new_r", ",", "new_g", ",", "new_b", ",", "new_a", ")", "end" ]
Interpolates the foreground and background colors by the given alpha value. This also blends the alpha channels themselves. A blending factor of 255 will give entirely the foreground, while a blending factor of 0 will give the background. @param [Integer] fg The foreground color. @param [Integer] bg The background color. @param [Integer] alpha The blending factor (fixed 8bit) @return [Integer] The interpolated color.
[ "Interpolates", "the", "foreground", "and", "background", "colors", "by", "the", "given", "alpha", "value", ".", "This", "also", "blends", "the", "alpha", "channels", "themselves", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L419-L431
18,341
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.fade
def fade(color, factor) new_alpha = int8_mult(a(color), factor) (color & 0xffffff00) | new_alpha end
ruby
def fade(color, factor) new_alpha = int8_mult(a(color), factor) (color & 0xffffff00) | new_alpha end
[ "def", "fade", "(", "color", ",", "factor", ")", "new_alpha", "=", "int8_mult", "(", "a", "(", "color", ")", ",", "factor", ")", "(", "color", "&", "0xffffff00", ")", "|", "new_alpha", "end" ]
Lowers the intensity of a color, by lowering its alpha by a given factor. @param [Integer] color The color to adjust. @param [Integer] factor Fade factor as an integer between 0 and 255. @return [Integer] The faded color.
[ "Lowers", "the", "intensity", "of", "a", "color", "by", "lowering", "its", "alpha", "by", "a", "given", "factor", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L460-L463
18,342
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.decompose_color
def decompose_color(color, mask, bg, tolerance = 1) if alpha_decomposable?(color, mask, bg, tolerance) mask & 0xffffff00 | decompose_alpha(color, mask, bg) else mask & 0xffffff00 end end
ruby
def decompose_color(color, mask, bg, tolerance = 1) if alpha_decomposable?(color, mask, bg, tolerance) mask & 0xffffff00 | decompose_alpha(color, mask, bg) else mask & 0xffffff00 end end
[ "def", "decompose_color", "(", "color", ",", "mask", ",", "bg", ",", "tolerance", "=", "1", ")", "if", "alpha_decomposable?", "(", "color", ",", "mask", ",", "bg", ",", "tolerance", ")", "mask", "&", "0xffffff00", "|", "decompose_alpha", "(", "color", ",", "mask", ",", "bg", ")", "else", "mask", "&", "0xffffff00", "end", "end" ]
Decomposes a color, given a color, a mask color and a background color. The returned color will be a variant of the mask color, with the alpha channel set to the best fitting value. This basically is the reverse operation if alpha composition. If the color cannot be decomposed, this method will return the fully transparent variant of the mask color. @param [Integer] color The color that was the result of compositing. @param [Integer] mask The opaque variant of the color that was being composed @param [Integer] bg The background color on which the color was composed. @param [Integer] tolerance The decomposition tolerance level, a value between 0 and 255. @return [Integer] The decomposed color, a variant of the masked color with the alpha channel set to an appropriate value.
[ "Decomposes", "a", "color", "given", "a", "color", "a", "mask", "color", "and", "a", "background", "color", ".", "The", "returned", "color", "will", "be", "a", "variant", "of", "the", "mask", "color", "with", "the", "alpha", "channel", "set", "to", "the", "best", "fitting", "value", ".", "This", "basically", "is", "the", "reverse", "operation", "if", "alpha", "composition", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L481-L487
18,343
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.alpha_decomposable?
def alpha_decomposable?(color, mask, bg, tolerance = 1) components = decompose_alpha_components(color, mask, bg) sum = components.inject(0) { |a, b| a + b } max = components.max * 3 components.max <= 255 && components.min >= 0 && (sum + tolerance * 3) >= max end
ruby
def alpha_decomposable?(color, mask, bg, tolerance = 1) components = decompose_alpha_components(color, mask, bg) sum = components.inject(0) { |a, b| a + b } max = components.max * 3 components.max <= 255 && components.min >= 0 && (sum + tolerance * 3) >= max end
[ "def", "alpha_decomposable?", "(", "color", ",", "mask", ",", "bg", ",", "tolerance", "=", "1", ")", "components", "=", "decompose_alpha_components", "(", "color", ",", "mask", ",", "bg", ")", "sum", "=", "components", ".", "inject", "(", "0", ")", "{", "|", "a", ",", "b", "|", "a", "+", "b", "}", "max", "=", "components", ".", "max", "*", "3", "components", ".", "max", "<=", "255", "&&", "components", ".", "min", ">=", "0", "&&", "(", "sum", "+", "tolerance", "*", "3", ")", ">=", "max", "end" ]
Checks whether an alpha channel value can successfully be composed given the resulting color, the mask color and a background color, all of which should be opaque. @param [Integer] color The color that was the result of compositing. @param [Integer] mask The opaque variant of the color that was being composed @param [Integer] bg The background color on which the color was composed. @param [Integer] tolerance The decomposition tolerance level, a value between 0 and 255. @return [Boolean] True if the alpha component can be decomposed successfully. @see #decompose_alpha
[ "Checks", "whether", "an", "alpha", "channel", "value", "can", "successfully", "be", "composed", "given", "the", "resulting", "color", "the", "mask", "color", "and", "a", "background", "color", "all", "of", "which", "should", "be", "opaque", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L502-L507
18,344
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.decompose_alpha
def decompose_alpha(color, mask, bg) components = decompose_alpha_components(color, mask, bg) (components.inject(0) { |a, b| a + b } / 3.0).round end
ruby
def decompose_alpha(color, mask, bg) components = decompose_alpha_components(color, mask, bg) (components.inject(0) { |a, b| a + b } / 3.0).round end
[ "def", "decompose_alpha", "(", "color", ",", "mask", ",", "bg", ")", "components", "=", "decompose_alpha_components", "(", "color", ",", "mask", ",", "bg", ")", "(", "components", ".", "inject", "(", "0", ")", "{", "|", "a", ",", "b", "|", "a", "+", "b", "}", "/", "3.0", ")", ".", "round", "end" ]
Decomposes the alpha channel value given the resulting color, the mask color and a background color, all of which should be opaque. Make sure to call {#alpha_decomposable?} first to see if the alpha channel value can successfully decomposed with a given tolerance, otherwise the return value of this method is undefined. @param [Integer] color The color that was the result of compositing. @param [Integer] mask The opaque variant of the color that was being composed @param [Integer] bg The background color on which the color was composed. @return [Integer] The best fitting alpha channel, a value between 0 and 255. @see #alpha_decomposable?
[ "Decomposes", "the", "alpha", "channel", "value", "given", "the", "resulting", "color", "the", "mask", "color", "and", "a", "background", "color", "all", "of", "which", "should", "be", "opaque", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L523-L526
18,345
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.decompose_alpha_component
def decompose_alpha_component(channel, color, mask, bg) cc, mc, bc = send(channel, color), send(channel, mask), send(channel, bg) return 0x00 if bc == cc return 0xff if bc == mc return 0xff if cc == mc (((bc - cc).to_f / (bc - mc).to_f) * MAX).round end
ruby
def decompose_alpha_component(channel, color, mask, bg) cc, mc, bc = send(channel, color), send(channel, mask), send(channel, bg) return 0x00 if bc == cc return 0xff if bc == mc return 0xff if cc == mc (((bc - cc).to_f / (bc - mc).to_f) * MAX).round end
[ "def", "decompose_alpha_component", "(", "channel", ",", "color", ",", "mask", ",", "bg", ")", "cc", ",", "mc", ",", "bc", "=", "send", "(", "channel", ",", "color", ")", ",", "send", "(", "channel", ",", "mask", ")", ",", "send", "(", "channel", ",", "bg", ")", "return", "0x00", "if", "bc", "==", "cc", "return", "0xff", "if", "bc", "==", "mc", "return", "0xff", "if", "cc", "==", "mc", "(", "(", "(", "bc", "-", "cc", ")", ".", "to_f", "/", "(", "bc", "-", "mc", ")", ".", "to_f", ")", "*", "MAX", ")", ".", "round", "end" ]
Decomposes an alpha channel for either the r, g or b color channel. @param [:r, :g, :b] channel The channel to decompose the alpha channel from. @param [Integer] color The color that was the result of compositing. @param [Integer] mask The opaque variant of the color that was being composed @param [Integer] bg The background color on which the color was composed. @return [Integer] The decomposed alpha value for the channel.
[ "Decomposes", "an", "alpha", "channel", "for", "either", "the", "r", "g", "or", "b", "color", "channel", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L536-L544
18,346
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.decompose_alpha_components
def decompose_alpha_components(color, mask, bg) [ decompose_alpha_component(:r, color, mask, bg), decompose_alpha_component(:g, color, mask, bg), decompose_alpha_component(:b, color, mask, bg), ] end
ruby
def decompose_alpha_components(color, mask, bg) [ decompose_alpha_component(:r, color, mask, bg), decompose_alpha_component(:g, color, mask, bg), decompose_alpha_component(:b, color, mask, bg), ] end
[ "def", "decompose_alpha_components", "(", "color", ",", "mask", ",", "bg", ")", "[", "decompose_alpha_component", "(", ":r", ",", "color", ",", "mask", ",", "bg", ")", ",", "decompose_alpha_component", "(", ":g", ",", "color", ",", "mask", ",", "bg", ")", ",", "decompose_alpha_component", "(", ":b", ",", "color", ",", "mask", ",", "bg", ")", ",", "]", "end" ]
Decomposes the alpha channels for the r, g and b color channel. @param [Integer] color The color that was the result of compositing. @param [Integer] mask The opaque variant of the color that was being composed @param [Integer] bg The background color on which the color was composed. @return [Array<Integer>] The decomposed alpha values for the r, g and b channels.
[ "Decomposes", "the", "alpha", "channels", "for", "the", "r", "g", "and", "b", "color", "channel", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L553-L559
18,347
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.to_hsv
def to_hsv(color, include_alpha = false) hue, chroma, max, _ = hue_and_chroma(color) value = max saturation = chroma.zero? ? 0.0 : chroma.fdiv(value) include_alpha ? [hue, saturation, value, a(color)] : [hue, saturation, value] end
ruby
def to_hsv(color, include_alpha = false) hue, chroma, max, _ = hue_and_chroma(color) value = max saturation = chroma.zero? ? 0.0 : chroma.fdiv(value) include_alpha ? [hue, saturation, value, a(color)] : [hue, saturation, value] end
[ "def", "to_hsv", "(", "color", ",", "include_alpha", "=", "false", ")", "hue", ",", "chroma", ",", "max", ",", "_", "=", "hue_and_chroma", "(", "color", ")", "value", "=", "max", "saturation", "=", "chroma", ".", "zero?", "?", "0.0", ":", "chroma", ".", "fdiv", "(", "value", ")", "include_alpha", "?", "[", "hue", ",", "saturation", ",", "value", ",", "a", "(", "color", ")", "]", ":", "[", "hue", ",", "saturation", ",", "value", "]", "end" ]
Returns an array with the separate HSV components of a color. Because ChunkyPNG internally handles colors as Integers for performance reasons, some rounding occurs when importing or exporting HSV colors whose coordinates are float-based. Because of this rounding, #to_hsv and #from_hsv may not be perfect inverses. This implementation follows the modern convention of 0 degrees hue indicating red. @param [Integer] color The ChunkyPNG color to convert. @param [Boolean] include_alpha Flag indicates whether a fourth element representing alpha channel should be included in the returned array. @return [Array[0]] The hue of the color (0-360) @return [Array[1]] The saturation of the color (0-1) @return [Array[2]] The value of the color (0-1) @return [Array[3]] Optional fourth element for alpha, included if include_alpha=true (0-255) @see http://en.wikipedia.org/wiki/HSL_and_HSV
[ "Returns", "an", "array", "with", "the", "separate", "HSV", "components", "of", "a", "color", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L594-L601
18,348
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.to_hsl
def to_hsl(color, include_alpha = false) hue, chroma, max, min = hue_and_chroma(color) lightness = 0.5 * (max + min) saturation = chroma.zero? ? 0.0 : chroma.fdiv(1 - (2 * lightness - 1).abs) include_alpha ? [hue, saturation, lightness, a(color)] : [hue, saturation, lightness] end
ruby
def to_hsl(color, include_alpha = false) hue, chroma, max, min = hue_and_chroma(color) lightness = 0.5 * (max + min) saturation = chroma.zero? ? 0.0 : chroma.fdiv(1 - (2 * lightness - 1).abs) include_alpha ? [hue, saturation, lightness, a(color)] : [hue, saturation, lightness] end
[ "def", "to_hsl", "(", "color", ",", "include_alpha", "=", "false", ")", "hue", ",", "chroma", ",", "max", ",", "min", "=", "hue_and_chroma", "(", "color", ")", "lightness", "=", "0.5", "*", "(", "max", "+", "min", ")", "saturation", "=", "chroma", ".", "zero?", "?", "0.0", ":", "chroma", ".", "fdiv", "(", "1", "-", "(", "2", "*", "lightness", "-", "1", ")", ".", "abs", ")", "include_alpha", "?", "[", "hue", ",", "saturation", ",", "lightness", ",", "a", "(", "color", ")", "]", ":", "[", "hue", ",", "saturation", ",", "lightness", "]", "end" ]
Returns an array with the separate HSL components of a color. Because ChunkyPNG internally handles colors as Integers for performance reasons, some rounding occurs when importing or exporting HSL colors whose coordinates are float-based. Because of this rounding, #to_hsl and #from_hsl may not be perfect inverses. This implementation follows the modern convention of 0 degrees hue indicating red. @param [Integer] color The ChunkyPNG color to convert. @param [Boolean] include_alpha Flag indicates whether a fourth element representing alpha channel should be included in the returned array. @return [Array<Fixnum>[0]] The hue of the color (0-360) @return [Array<Fixnum>[1]] The saturation of the color (0-1) @return [Array<Fixnum>[2]] The lightness of the color (0-1) @return [Array<Fixnum>[3]] Optional fourth element for alpha, included if include_alpha=true (0-255) @see http://en.wikipedia.org/wiki/HSL_and_HSV
[ "Returns", "an", "array", "with", "the", "separate", "HSL", "components", "of", "a", "color", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L623-L630
18,349
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.to_truecolor_alpha_bytes
def to_truecolor_alpha_bytes(color) [r(color), g(color), b(color), a(color)] end
ruby
def to_truecolor_alpha_bytes(color) [r(color), g(color), b(color), a(color)] end
[ "def", "to_truecolor_alpha_bytes", "(", "color", ")", "[", "r", "(", "color", ")", ",", "g", "(", "color", ")", ",", "b", "(", "color", ")", ",", "a", "(", "color", ")", "]", "end" ]
Returns an array with the separate RGBA values for this color. @param [Integer] color The color to convert. @return [Array<Integer>] An array with 4 Integer elements.
[ "Returns", "an", "array", "with", "the", "separate", "RGBA", "values", "for", "this", "color", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L666-L668
18,350
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.html_color
def html_color(color_name, opacity = nil) if color_name.to_s =~ HTML_COLOR_REGEXP opacity ||= $2 ? ($2.to_f * 255.0).round : 0xff base_color_name = $1.gsub(/[^a-z]+/i, "").downcase.to_sym return PREDEFINED_COLORS[base_color_name] | opacity if PREDEFINED_COLORS.key?(base_color_name) end raise ArgumentError, "Unknown color name #{color_name}!" end
ruby
def html_color(color_name, opacity = nil) if color_name.to_s =~ HTML_COLOR_REGEXP opacity ||= $2 ? ($2.to_f * 255.0).round : 0xff base_color_name = $1.gsub(/[^a-z]+/i, "").downcase.to_sym return PREDEFINED_COLORS[base_color_name] | opacity if PREDEFINED_COLORS.key?(base_color_name) end raise ArgumentError, "Unknown color name #{color_name}!" end
[ "def", "html_color", "(", "color_name", ",", "opacity", "=", "nil", ")", "if", "color_name", ".", "to_s", "=~", "HTML_COLOR_REGEXP", "opacity", "||=", "$2", "?", "(", "$2", ".", "to_f", "*", "255.0", ")", ".", "round", ":", "0xff", "base_color_name", "=", "$1", ".", "gsub", "(", "/", "/i", ",", "\"\"", ")", ".", "downcase", ".", "to_sym", "return", "PREDEFINED_COLORS", "[", "base_color_name", "]", "|", "opacity", "if", "PREDEFINED_COLORS", ".", "key?", "(", "base_color_name", ")", "end", "raise", "ArgumentError", ",", "\"Unknown color name #{color_name}!\"", "end" ]
Gets a color value based on a HTML color name. The color name is flexible. E.g. <tt>'yellowgreen'</tt>, <tt>'Yellow green'</tt>, <tt>'YellowGreen'</tt>, <tt>'YELLOW_GREEN'</tt> and <tt>:yellow_green</tt> will all return the same color value. You can include a opacity level in the color name (e.g. <tt>'red @ 0.5'</tt>) or give an explicit opacity value as second argument. If no opacity value is given, the color will be fully opaque. @param [Symbol, String] color_name The color name. It may include an opacity specifier like <tt>@ 0.8</tt> to set the color's opacity. @param [Integer] opacity The opacity value for the color between 0 and 255. Overrides any opacity value given in the color name. @return [Integer] The color value. @raise [ChunkyPNG::Exception] If the color name was not recognized.
[ "Gets", "a", "color", "value", "based", "on", "a", "HTML", "color", "name", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L908-L915
18,351
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.samples_per_pixel
def samples_per_pixel(color_mode) case color_mode when ChunkyPNG::COLOR_INDEXED then 1 when ChunkyPNG::COLOR_TRUECOLOR then 3 when ChunkyPNG::COLOR_TRUECOLOR_ALPHA then 4 when ChunkyPNG::COLOR_GRAYSCALE then 1 when ChunkyPNG::COLOR_GRAYSCALE_ALPHA then 2 else raise ChunkyPNG::NotSupported, "Don't know the number of samples for this colormode: #{color_mode}!" end end
ruby
def samples_per_pixel(color_mode) case color_mode when ChunkyPNG::COLOR_INDEXED then 1 when ChunkyPNG::COLOR_TRUECOLOR then 3 when ChunkyPNG::COLOR_TRUECOLOR_ALPHA then 4 when ChunkyPNG::COLOR_GRAYSCALE then 1 when ChunkyPNG::COLOR_GRAYSCALE_ALPHA then 2 else raise ChunkyPNG::NotSupported, "Don't know the number of samples for this colormode: #{color_mode}!" end end
[ "def", "samples_per_pixel", "(", "color_mode", ")", "case", "color_mode", "when", "ChunkyPNG", "::", "COLOR_INDEXED", "then", "1", "when", "ChunkyPNG", "::", "COLOR_TRUECOLOR", "then", "3", "when", "ChunkyPNG", "::", "COLOR_TRUECOLOR_ALPHA", "then", "4", "when", "ChunkyPNG", "::", "COLOR_GRAYSCALE", "then", "1", "when", "ChunkyPNG", "::", "COLOR_GRAYSCALE_ALPHA", "then", "2", "else", "raise", "ChunkyPNG", "::", "NotSupported", ",", "\"Don't know the number of samples for this colormode: #{color_mode}!\"", "end", "end" ]
STATIC UTILITY METHODS Returns the number of sample values per pixel. @param [Integer] color_mode The color mode being used. @return [Integer] The number of sample values per pixel.
[ "STATIC", "UTILITY", "METHODS" ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L933-L942
18,352
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.pass_bytesize
def pass_bytesize(color_mode, depth, width, height) return 0 if width == 0 || height == 0 (scanline_bytesize(color_mode, depth, width) + 1) * height end
ruby
def pass_bytesize(color_mode, depth, width, height) return 0 if width == 0 || height == 0 (scanline_bytesize(color_mode, depth, width) + 1) * height end
[ "def", "pass_bytesize", "(", "color_mode", ",", "depth", ",", "width", ",", "height", ")", "return", "0", "if", "width", "==", "0", "||", "height", "==", "0", "(", "scanline_bytesize", "(", "color_mode", ",", "depth", ",", "width", ")", "+", "1", ")", "*", "height", "end" ]
Returns the number of bytes used for an image pass @param [Integer] color_mode The color mode in which the pixels are stored. @param [Integer] depth The color depth of the pixels. @param [Integer] width The width of the image pass. @param [Integer] height The height of the image pass. @return [Integer] The number of bytes used per scanline in a datastream.
[ "Returns", "the", "number", "of", "bytes", "used", "for", "an", "image", "pass" ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L983-L986
18,353
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.[]=
def []=(x, y, color) assert_xy!(x, y) @pixels[y * width + x] = ChunkyPNG::Color.parse(color) end
ruby
def []=(x, y, color) assert_xy!(x, y) @pixels[y * width + x] = ChunkyPNG::Color.parse(color) end
[ "def", "[]=", "(", "x", ",", "y", ",", "color", ")", "assert_xy!", "(", "x", ",", "y", ")", "@pixels", "[", "y", "*", "width", "+", "x", "]", "=", "ChunkyPNG", "::", "Color", ".", "parse", "(", "color", ")", "end" ]
Replaces a single pixel in this canvas. @param [Integer] x The x-coordinate of the pixel (column) @param [Integer] y The y-coordinate of the pixel (row) @param [Integer] color The new color for the provided coordinates. @return [Integer] The new color value for this pixel, i.e. <tt>color</tt>. @raise [ChunkyPNG::OutOfBounds] when the coordinates are outside of the image's dimensions. @see #set_pixel
[ "Replaces", "a", "single", "pixel", "in", "this", "canvas", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L133-L136
18,354
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.set_pixel_if_within_bounds
def set_pixel_if_within_bounds(x, y, color) return unless include_xy?(x, y) @pixels[y * width + x] = color end
ruby
def set_pixel_if_within_bounds(x, y, color) return unless include_xy?(x, y) @pixels[y * width + x] = color end
[ "def", "set_pixel_if_within_bounds", "(", "x", ",", "y", ",", "color", ")", "return", "unless", "include_xy?", "(", "x", ",", "y", ")", "@pixels", "[", "y", "*", "width", "+", "x", "]", "=", "color", "end" ]
Replaces a single pixel in this canvas, with bounds checking. It will do noting if the provided coordinates are out of bounds. @param [Integer] x The x-coordinate of the pixel (column) @param [Integer] y The y-coordinate of the pixel (row) @param [Integer] color The new color value for the provided coordinates. @return [Integer] The new color value for this pixel, i.e. <tt>color</tt>, or <tt>nil</tt> if the coordinates are out of bounds.
[ "Replaces", "a", "single", "pixel", "in", "this", "canvas", "with", "bounds", "checking", ".", "It", "will", "do", "noting", "if", "the", "provided", "coordinates", "are", "out", "of", "bounds", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L160-L163
18,355
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.column
def column(x) assert_x!(x) (0...height).inject([]) { |pixels, y| pixels << get_pixel(x, y) } end
ruby
def column(x) assert_x!(x) (0...height).inject([]) { |pixels, y| pixels << get_pixel(x, y) } end
[ "def", "column", "(", "x", ")", "assert_x!", "(", "x", ")", "(", "0", "...", "height", ")", ".", "inject", "(", "[", "]", ")", "{", "|", "pixels", ",", "y", "|", "pixels", "<<", "get_pixel", "(", "x", ",", "y", ")", "}", "end" ]
Returns an extracted column as vector of pixels. @param [Integer] x The 0-based column index. @return [Array<Integer>] The vector of pixels in the requested column.
[ "Returns", "an", "extracted", "column", "as", "vector", "of", "pixels", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L198-L201
18,356
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.replace_row!
def replace_row!(y, vector) assert_y!(y) && assert_width!(vector.length) pixels[y * width, width] = vector end
ruby
def replace_row!(y, vector) assert_y!(y) && assert_width!(vector.length) pixels[y * width, width] = vector end
[ "def", "replace_row!", "(", "y", ",", "vector", ")", "assert_y!", "(", "y", ")", "&&", "assert_width!", "(", "vector", ".", "length", ")", "pixels", "[", "y", "*", "width", ",", "width", "]", "=", "vector", "end" ]
Replaces a row of pixels on this canvas. @param [Integer] y The 0-based row index. @param [Array<Integer>] vector The vector of pixels to replace the row with. @return [void]
[ "Replaces", "a", "row", "of", "pixels", "on", "this", "canvas", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L208-L211
18,357
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.replace_column!
def replace_column!(x, vector) assert_x!(x) && assert_height!(vector.length) for y in 0...height do set_pixel(x, y, vector[y]) end end
ruby
def replace_column!(x, vector) assert_x!(x) && assert_height!(vector.length) for y in 0...height do set_pixel(x, y, vector[y]) end end
[ "def", "replace_column!", "(", "x", ",", "vector", ")", "assert_x!", "(", "x", ")", "&&", "assert_height!", "(", "vector", ".", "length", ")", "for", "y", "in", "0", "...", "height", "do", "set_pixel", "(", "x", ",", "y", ",", "vector", "[", "y", "]", ")", "end", "end" ]
Replaces a column of pixels on this canvas. @param [Integer] x The 0-based column index. @param [Array<Integer>] vector The vector of pixels to replace the column with. @return [void]
[ "Replaces", "a", "column", "of", "pixels", "on", "this", "canvas", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L218-L223
18,358
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.inspect
def inspect inspected = "<#{self.class.name} #{width}x#{height} [" for y in 0...height inspected << "\n\t[" << row(y).map { |p| ChunkyPNG::Color.to_hex(p) }.join(" ") << "]" end inspected << "\n]>" end
ruby
def inspect inspected = "<#{self.class.name} #{width}x#{height} [" for y in 0...height inspected << "\n\t[" << row(y).map { |p| ChunkyPNG::Color.to_hex(p) }.join(" ") << "]" end inspected << "\n]>" end
[ "def", "inspect", "inspected", "=", "\"<#{self.class.name} #{width}x#{height} [\"", "for", "y", "in", "0", "...", "height", "inspected", "<<", "\"\\n\\t[\"", "<<", "row", "(", "y", ")", ".", "map", "{", "|", "p", "|", "ChunkyPNG", "::", "Color", ".", "to_hex", "(", "p", ")", "}", ".", "join", "(", "\" \"", ")", "<<", "\"]\"", "end", "inspected", "<<", "\"\\n]>\"", "end" ]
Alternative implementation of the inspect method. @return [String] A nicely formatted string representation of this canvas. @private
[ "Alternative", "implementation", "of", "the", "inspect", "method", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L297-L303
18,359
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.replace_canvas!
def replace_canvas!(new_width, new_height, new_pixels) unless new_pixels.length == new_width * new_height raise ArgumentError, "The provided pixel array should have #{new_width * new_height} items" end @width, @height, @pixels = new_width, new_height, new_pixels self end
ruby
def replace_canvas!(new_width, new_height, new_pixels) unless new_pixels.length == new_width * new_height raise ArgumentError, "The provided pixel array should have #{new_width * new_height} items" end @width, @height, @pixels = new_width, new_height, new_pixels self end
[ "def", "replace_canvas!", "(", "new_width", ",", "new_height", ",", "new_pixels", ")", "unless", "new_pixels", ".", "length", "==", "new_width", "*", "new_height", "raise", "ArgumentError", ",", "\"The provided pixel array should have #{new_width * new_height} items\"", "end", "@width", ",", "@height", ",", "@pixels", "=", "new_width", ",", "new_height", ",", "new_pixels", "self", "end" ]
Replaces the image, given a new width, new height, and a new pixel array.
[ "Replaces", "the", "image", "given", "a", "new", "width", "new", "height", "and", "a", "new", "pixel", "array", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L308-L314
18,360
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.assert_xy!
def assert_xy!(x, y) unless include_xy?(x, y) raise ChunkyPNG::OutOfBounds, "Coordinates (#{x},#{y}) out of bounds!" end true end
ruby
def assert_xy!(x, y) unless include_xy?(x, y) raise ChunkyPNG::OutOfBounds, "Coordinates (#{x},#{y}) out of bounds!" end true end
[ "def", "assert_xy!", "(", "x", ",", "y", ")", "unless", "include_xy?", "(", "x", ",", "y", ")", "raise", "ChunkyPNG", "::", "OutOfBounds", ",", "\"Coordinates (#{x},#{y}) out of bounds!\"", "end", "true", "end" ]
Throws an exception if the x- or y-coordinate is out of bounds.
[ "Throws", "an", "exception", "if", "the", "x", "-", "or", "y", "-", "coordinate", "is", "out", "of", "bounds", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L333-L338
18,361
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.assert_size!
def assert_size!(matrix_width, matrix_height) if width != matrix_width raise ChunkyPNG::ExpectationFailed, "The width of the matrix does not match the canvas width!" end if height != matrix_height raise ChunkyPNG::ExpectationFailed, "The height of the matrix does not match the canvas height!" end true end
ruby
def assert_size!(matrix_width, matrix_height) if width != matrix_width raise ChunkyPNG::ExpectationFailed, "The width of the matrix does not match the canvas width!" end if height != matrix_height raise ChunkyPNG::ExpectationFailed, "The height of the matrix does not match the canvas height!" end true end
[ "def", "assert_size!", "(", "matrix_width", ",", "matrix_height", ")", "if", "width", "!=", "matrix_width", "raise", "ChunkyPNG", "::", "ExpectationFailed", ",", "\"The width of the matrix does not match the canvas width!\"", "end", "if", "height", "!=", "matrix_height", "raise", "ChunkyPNG", "::", "ExpectationFailed", ",", "\"The height of the matrix does not match the canvas height!\"", "end", "true", "end" ]
Throws an exception if the matrix width and height does not match this canvas' dimensions.
[ "Throws", "an", "exception", "if", "the", "matrix", "width", "and", "height", "does", "not", "match", "this", "canvas", "dimensions", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L361-L371
18,362
wvanbergen/chunky_png
lib/chunky_png/palette.rb
ChunkyPNG.Palette.to_trns_chunk
def to_trns_chunk ChunkyPNG::Chunk::Transparency.new("tRNS", map { |c| ChunkyPNG::Color.a(c) }.pack("C*")) end
ruby
def to_trns_chunk ChunkyPNG::Chunk::Transparency.new("tRNS", map { |c| ChunkyPNG::Color.a(c) }.pack("C*")) end
[ "def", "to_trns_chunk", "ChunkyPNG", "::", "Chunk", "::", "Transparency", ".", "new", "(", "\"tRNS\"", ",", "map", "{", "|", "c", "|", "ChunkyPNG", "::", "Color", ".", "a", "(", "c", ")", "}", ".", "pack", "(", "\"C*\"", ")", ")", "end" ]
Creates a tRNS chunk that corresponds with this palette to store the alpha channel of all colors. Note that this chunk can be left out of every color in the palette is opaque, and the image is encoded using indexed colors. @return [ChunkyPNG::Chunk::Transparency] The tRNS chunk.
[ "Creates", "a", "tRNS", "chunk", "that", "corresponds", "with", "this", "palette", "to", "store", "the", "alpha", "channel", "of", "all", "colors", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/palette.rb#L163-L165
18,363
wvanbergen/chunky_png
lib/chunky_png/palette.rb
ChunkyPNG.Palette.to_plte_chunk
def to_plte_chunk @encoding_map = {} colors = [] each_with_index do |color, index| @encoding_map[color] = index colors += ChunkyPNG::Color.to_truecolor_bytes(color) end ChunkyPNG::Chunk::Palette.new("PLTE", colors.pack("C*")) end
ruby
def to_plte_chunk @encoding_map = {} colors = [] each_with_index do |color, index| @encoding_map[color] = index colors += ChunkyPNG::Color.to_truecolor_bytes(color) end ChunkyPNG::Chunk::Palette.new("PLTE", colors.pack("C*")) end
[ "def", "to_plte_chunk", "@encoding_map", "=", "{", "}", "colors", "=", "[", "]", "each_with_index", "do", "|", "color", ",", "index", "|", "@encoding_map", "[", "color", "]", "=", "index", "colors", "+=", "ChunkyPNG", "::", "Color", ".", "to_truecolor_bytes", "(", "color", ")", "end", "ChunkyPNG", "::", "Chunk", "::", "Palette", ".", "new", "(", "\"PLTE\"", ",", "colors", ".", "pack", "(", "\"C*\"", ")", ")", "end" ]
Creates a PLTE chunk that corresponds with this palette to store the r, g, and b channels of all colors. @note A PLTE chunk should only be included if the image is encoded using index colors. After this chunk has been built, the palette becomes suitable for encoding an image. @return [ChunkyPNG::Chunk::Palette] The PLTE chunk. @see ChunkyPNG::Palette#can_encode?
[ "Creates", "a", "PLTE", "chunk", "that", "corresponds", "with", "this", "palette", "to", "store", "the", "r", "g", "and", "b", "channels", "of", "all", "colors", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/palette.rb#L176-L186
18,364
wvanbergen/chunky_png
lib/chunky_png/palette.rb
ChunkyPNG.Palette.best_color_settings
def best_color_settings if black_and_white? [ChunkyPNG::COLOR_GRAYSCALE, 1] elsif grayscale? if opaque? [ChunkyPNG::COLOR_GRAYSCALE, 8] else [ChunkyPNG::COLOR_GRAYSCALE_ALPHA, 8] end elsif indexable? [ChunkyPNG::COLOR_INDEXED, determine_bit_depth] elsif opaque? [ChunkyPNG::COLOR_TRUECOLOR, 8] else [ChunkyPNG::COLOR_TRUECOLOR_ALPHA, 8] end end
ruby
def best_color_settings if black_and_white? [ChunkyPNG::COLOR_GRAYSCALE, 1] elsif grayscale? if opaque? [ChunkyPNG::COLOR_GRAYSCALE, 8] else [ChunkyPNG::COLOR_GRAYSCALE_ALPHA, 8] end elsif indexable? [ChunkyPNG::COLOR_INDEXED, determine_bit_depth] elsif opaque? [ChunkyPNG::COLOR_TRUECOLOR, 8] else [ChunkyPNG::COLOR_TRUECOLOR_ALPHA, 8] end end
[ "def", "best_color_settings", "if", "black_and_white?", "[", "ChunkyPNG", "::", "COLOR_GRAYSCALE", ",", "1", "]", "elsif", "grayscale?", "if", "opaque?", "[", "ChunkyPNG", "::", "COLOR_GRAYSCALE", ",", "8", "]", "else", "[", "ChunkyPNG", "::", "COLOR_GRAYSCALE_ALPHA", ",", "8", "]", "end", "elsif", "indexable?", "[", "ChunkyPNG", "::", "COLOR_INDEXED", ",", "determine_bit_depth", "]", "elsif", "opaque?", "[", "ChunkyPNG", "::", "COLOR_TRUECOLOR", ",", "8", "]", "else", "[", "ChunkyPNG", "::", "COLOR_TRUECOLOR_ALPHA", ",", "8", "]", "end", "end" ]
Determines the most suitable colormode for this palette. @return [Integer] The colormode which would create the smallest possible file for images that use this exact palette.
[ "Determines", "the", "most", "suitable", "colormode", "for", "this", "palette", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/palette.rb#L191-L207
18,365
david942j/heapinfo
lib/heapinfo/arena.rb
HeapInfo.Fastbin.title
def title class_name = Helper.color(Helper.class_name(self), sev: :bin) size_str = index.nil? ? nil : "[#{Helper.color(format('%#x', idx_to_size))}]" "#{class_name}#{size_str}: " end
ruby
def title class_name = Helper.color(Helper.class_name(self), sev: :bin) size_str = index.nil? ? nil : "[#{Helper.color(format('%#x', idx_to_size))}]" "#{class_name}#{size_str}: " end
[ "def", "title", "class_name", "=", "Helper", ".", "color", "(", "Helper", ".", "class_name", "(", "self", ")", ",", "sev", ":", ":bin", ")", "size_str", "=", "index", ".", "nil?", "?", "nil", ":", "\"[#{Helper.color(format('%#x', idx_to_size))}]\"", "\"#{class_name}#{size_str}: \"", "end" ]
For pretty inspect. @return [String] Title with color codes.
[ "For", "pretty", "inspect", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/arena.rb#L103-L107
18,366
david942j/heapinfo
lib/heapinfo/arena.rb
HeapInfo.Fastbin.inspect
def inspect title + list.map do |ptr| next "(#{ptr})\n" if ptr.is_a?(Symbol) next " => (nil)\n" if ptr.nil? format(' => %s', Helper.color(format('%#x', ptr))) end.join end
ruby
def inspect title + list.map do |ptr| next "(#{ptr})\n" if ptr.is_a?(Symbol) next " => (nil)\n" if ptr.nil? format(' => %s', Helper.color(format('%#x', ptr))) end.join end
[ "def", "inspect", "title", "+", "list", ".", "map", "do", "|", "ptr", "|", "next", "\"(#{ptr})\\n\"", "if", "ptr", ".", "is_a?", "(", "Symbol", ")", "next", "\" => (nil)\\n\"", "if", "ptr", ".", "nil?", "format", "(", "' => %s'", ",", "Helper", ".", "color", "(", "format", "(", "'%#x'", ",", "ptr", ")", ")", ")", "end", ".", "join", "end" ]
Pretty inspect. @return [String] fastbin layouts wrapper with color codes.
[ "Pretty", "inspect", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/arena.rb#L111-L118
18,367
david942j/heapinfo
lib/heapinfo/arena.rb
HeapInfo.UnsortedBin.pretty_list
def pretty_list(list) center = nil list.map.with_index do |c, idx| next center = Helper.color('[self]', sev: :bin) if c == @base color_c = Helper.color(format('%#x', c)) fwd = fd_of(c) next "#{color_c}(invalid)" if fwd.nil? # invalid c bck = bk_of(c) if center.nil? # bk side format('%s%s', color_c, fwd == list[idx + 1] ? nil : Helper.color(format('(%#x)', fwd))) else # fd side format('%s%s', bck == list[idx - 1] ? nil : Helper.color(format('(%#x)', bck)), color_c) end end.join(' === ') end
ruby
def pretty_list(list) center = nil list.map.with_index do |c, idx| next center = Helper.color('[self]', sev: :bin) if c == @base color_c = Helper.color(format('%#x', c)) fwd = fd_of(c) next "#{color_c}(invalid)" if fwd.nil? # invalid c bck = bk_of(c) if center.nil? # bk side format('%s%s', color_c, fwd == list[idx + 1] ? nil : Helper.color(format('(%#x)', fwd))) else # fd side format('%s%s', bck == list[idx - 1] ? nil : Helper.color(format('(%#x)', bck)), color_c) end end.join(' === ') end
[ "def", "pretty_list", "(", "list", ")", "center", "=", "nil", "list", ".", "map", ".", "with_index", "do", "|", "c", ",", "idx", "|", "next", "center", "=", "Helper", ".", "color", "(", "'[self]'", ",", "sev", ":", ":bin", ")", "if", "c", "==", "@base", "color_c", "=", "Helper", ".", "color", "(", "format", "(", "'%#x'", ",", "c", ")", ")", "fwd", "=", "fd_of", "(", "c", ")", "next", "\"#{color_c}(invalid)\"", "if", "fwd", ".", "nil?", "# invalid c", "bck", "=", "bk_of", "(", "c", ")", "if", "center", ".", "nil?", "# bk side", "format", "(", "'%s%s'", ",", "color_c", ",", "fwd", "==", "list", "[", "idx", "+", "1", "]", "?", "nil", ":", "Helper", ".", "color", "(", "format", "(", "'(%#x)'", ",", "fwd", ")", ")", ")", "else", "# fd side", "format", "(", "'%s%s'", ",", "bck", "==", "list", "[", "idx", "-", "1", "]", "?", "nil", ":", "Helper", ".", "color", "(", "format", "(", "'(%#x)'", ",", "bck", ")", ")", ",", "color_c", ")", "end", "end", ".", "join", "(", "' === '", ")", "end" ]
Wrapper the doubly linked list with color codes. @param [Array<Integer>] list The list from {#link_list}. @return [String] Wrapper with color codes.
[ "Wrapper", "the", "doubly", "linked", "list", "with", "color", "codes", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/arena.rb#L188-L204
18,368
david942j/heapinfo
lib/heapinfo/arena.rb
HeapInfo.UnsortedBin.link_list
def link_list(expand_size) list = [@base] # fd work = proc do |ptr, nxt, append| sz = 0 dup = {} while ptr != @base && sz < expand_size append.call(ptr) break if ptr.nil? || dup[ptr] # invalid or duplicated pointer dup[ptr] = true ptr = __send__(nxt, ptr) sz += 1 end end work.call(@fd, :fd_of, ->(ptr) { list << ptr }) work.call(@bk, :bk_of, ->(ptr) { list.unshift(ptr) }) list end
ruby
def link_list(expand_size) list = [@base] # fd work = proc do |ptr, nxt, append| sz = 0 dup = {} while ptr != @base && sz < expand_size append.call(ptr) break if ptr.nil? || dup[ptr] # invalid or duplicated pointer dup[ptr] = true ptr = __send__(nxt, ptr) sz += 1 end end work.call(@fd, :fd_of, ->(ptr) { list << ptr }) work.call(@bk, :bk_of, ->(ptr) { list.unshift(ptr) }) list end
[ "def", "link_list", "(", "expand_size", ")", "list", "=", "[", "@base", "]", "# fd", "work", "=", "proc", "do", "|", "ptr", ",", "nxt", ",", "append", "|", "sz", "=", "0", "dup", "=", "{", "}", "while", "ptr", "!=", "@base", "&&", "sz", "<", "expand_size", "append", ".", "call", "(", "ptr", ")", "break", "if", "ptr", ".", "nil?", "||", "dup", "[", "ptr", "]", "# invalid or duplicated pointer", "dup", "[", "ptr", "]", "=", "true", "ptr", "=", "__send__", "(", "nxt", ",", "ptr", ")", "sz", "+=", "1", "end", "end", "work", ".", "call", "(", "@fd", ",", ":fd_of", ",", "->", "(", "ptr", ")", "{", "list", "<<", "ptr", "}", ")", "work", ".", "call", "(", "@bk", ",", ":bk_of", ",", "->", "(", "ptr", ")", "{", "list", ".", "unshift", "(", "ptr", ")", "}", ")", "list", "end" ]
Return the double link list with bin in the center. The list will like +[..., bk of bk, bk of bin, bin, fd of bin, fd of fd, ...]+. @param [Integer] expand_size At most expand size. For +size = 2+, the expand list would be <tt>bk, bk, bin, fd, fd</tt>. @return [Array<Integer>] The linked list.
[ "Return", "the", "double", "link", "list", "with", "bin", "in", "the", "center", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/arena.rb#L212-L230
18,369
david942j/heapinfo
lib/heapinfo/dumper.rb
HeapInfo.Dumper.x
def x(count, address) commands = [address, count * size_t] base = base_of(*commands) res = dump(*commands).unpack(size_t == 4 ? 'L*' : 'Q*') str = res.group_by.with_index { |_, i| i / (16 / size_t) }.map do |round, values| Helper.hex(base + round * 16) + ":\t" + values.map { |v| Helper.color(format("0x%0#{size_t * 2}x", v)) }.join("\t") end.join("\n") puts str end
ruby
def x(count, address) commands = [address, count * size_t] base = base_of(*commands) res = dump(*commands).unpack(size_t == 4 ? 'L*' : 'Q*') str = res.group_by.with_index { |_, i| i / (16 / size_t) }.map do |round, values| Helper.hex(base + round * 16) + ":\t" + values.map { |v| Helper.color(format("0x%0#{size_t * 2}x", v)) }.join("\t") end.join("\n") puts str end
[ "def", "x", "(", "count", ",", "address", ")", "commands", "=", "[", "address", ",", "count", "*", "size_t", "]", "base", "=", "base_of", "(", "commands", ")", "res", "=", "dump", "(", "commands", ")", ".", "unpack", "(", "size_t", "==", "4", "?", "'L*'", ":", "'Q*'", ")", "str", "=", "res", ".", "group_by", ".", "with_index", "{", "|", "_", ",", "i", "|", "i", "/", "(", "16", "/", "size_t", ")", "}", ".", "map", "do", "|", "round", ",", "values", "|", "Helper", ".", "hex", "(", "base", "+", "round", "*", "16", ")", "+", "\":\\t\"", "+", "values", ".", "map", "{", "|", "v", "|", "Helper", ".", "color", "(", "format", "(", "\"0x%0#{size_t * 2}x\"", ",", "v", ")", ")", "}", ".", "join", "(", "\"\\t\"", ")", "end", ".", "join", "(", "\"\\n\"", ")", "puts", "str", "end" ]
Show dump results like in gdb's command +x+. Details are in {HeapInfo::Process#x}. @param [Integer] count The number of result need to dump. @param [Symbol, String, Integer] address The base address to be dumped. @return [void] @example x 3, 0x400000 # 0x400000: 0x00010102464c457f 0x0000000000000000 # 0x400010: 0x00000001003e0002
[ "Show", "dump", "results", "like", "in", "gdb", "s", "command", "+", "x", "+", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/dumper.rb#L68-L77
18,370
david942j/heapinfo
lib/heapinfo/dumper.rb
HeapInfo.Dumper.cstring
def cstring(address) base = base_of(address) len = 1 cur = '' loop do cur << (dump(base + len - 1, len) || '') break if cur.index("\x00") len <<= 1 return cur if cur.size != len - 1 # reached undumpable memory end cur[0, cur.index("\x00")] end
ruby
def cstring(address) base = base_of(address) len = 1 cur = '' loop do cur << (dump(base + len - 1, len) || '') break if cur.index("\x00") len <<= 1 return cur if cur.size != len - 1 # reached undumpable memory end cur[0, cur.index("\x00")] end
[ "def", "cstring", "(", "address", ")", "base", "=", "base_of", "(", "address", ")", "len", "=", "1", "cur", "=", "''", "loop", "do", "cur", "<<", "(", "dump", "(", "base", "+", "len", "-", "1", ",", "len", ")", "||", "''", ")", "break", "if", "cur", ".", "index", "(", "\"\\x00\"", ")", "len", "<<=", "1", "return", "cur", "if", "cur", ".", "size", "!=", "len", "-", "1", "# reached undumpable memory", "end", "cur", "[", "0", ",", "cur", ".", "index", "(", "\"\\x00\"", ")", "]", "end" ]
Dump data from +address+ until reach null-byte. @return [String]
[ "Dump", "data", "from", "+", "address", "+", "until", "reach", "null", "-", "byte", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/dumper.rb#L82-L94
18,371
david942j/heapinfo
lib/heapinfo/dumper.rb
HeapInfo.Dumper.base_len_of
def base_len_of(arg, len = DUMP_BYTES) segments = @info.call(:segments) || {} segments = segments.each_with_object({}) do |(k, seg), memo| memo[k] = seg.base end base = case arg when Integer then arg when Symbol then segments[arg] when String then Helper.evaluate(arg, store: segments) end raise ArgumentError, "Invalid base: #{arg.inspect}" unless base.is_a?(Integer) # invalid usage [base, len] end
ruby
def base_len_of(arg, len = DUMP_BYTES) segments = @info.call(:segments) || {} segments = segments.each_with_object({}) do |(k, seg), memo| memo[k] = seg.base end base = case arg when Integer then arg when Symbol then segments[arg] when String then Helper.evaluate(arg, store: segments) end raise ArgumentError, "Invalid base: #{arg.inspect}" unless base.is_a?(Integer) # invalid usage [base, len] end
[ "def", "base_len_of", "(", "arg", ",", "len", "=", "DUMP_BYTES", ")", "segments", "=", "@info", ".", "call", "(", ":segments", ")", "||", "{", "}", "segments", "=", "segments", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "k", ",", "seg", ")", ",", "memo", "|", "memo", "[", "k", "]", "=", "seg", ".", "base", "end", "base", "=", "case", "arg", "when", "Integer", "then", "arg", "when", "Symbol", "then", "segments", "[", "arg", "]", "when", "String", "then", "Helper", ".", "evaluate", "(", "arg", ",", "store", ":", "segments", ")", "end", "raise", "ArgumentError", ",", "\"Invalid base: #{arg.inspect}\"", "unless", "base", ".", "is_a?", "(", "Integer", ")", "# invalid usage", "[", "base", ",", "len", "]", "end" ]
Get the base address and length. +@info+ will be used for getting the segment base, so we can support use symbol as base address. @param [Integer, Symbol, String] arg The base address, see examples. @param [Integer] len An integer. @example base_len_of(123, 321) #=> [123, 321] base_len_of(123) #=> [123, DUMP_BYTES] base_len_of(:heap, 10) #=> [0x603000, 10] # assume heap base @ 0x603000 base_len_of('heap+0x30', 10) #=> [0x603030, 10] base_len_of('elf+0x3*2-1') #=> [0x400005, DUMP_BYTES]
[ "Get", "the", "base", "address", "and", "length", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/dumper.rb#L174-L187
18,372
david942j/heapinfo
lib/heapinfo/process_info.rb
HeapInfo.ProcessInfo.segments
def segments EXPORT.map do |sym| seg = __send__(sym) [sym, seg] if seg.is_a?(Segment) end.compact.to_h end
ruby
def segments EXPORT.map do |sym| seg = __send__(sym) [sym, seg] if seg.is_a?(Segment) end.compact.to_h end
[ "def", "segments", "EXPORT", ".", "map", "do", "|", "sym", "|", "seg", "=", "__send__", "(", "sym", ")", "[", "sym", ",", "seg", "]", "if", "seg", ".", "is_a?", "(", "Segment", ")", "end", ".", "compact", ".", "to_h", "end" ]
Return segemnts load currently. @return [Hash{Symbol => Segment}] The segments in hash format.
[ "Return", "segemnts", "load", "currently", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/process_info.rb#L72-L77
18,373
david942j/heapinfo
lib/heapinfo/process_info.rb
HeapInfo.ProcessInfo.to_segment
def to_segment(sym) return nil unless EXPORT.include?(sym) seg = __send__(sym) return nil unless seg.is_a?(Segment) seg end
ruby
def to_segment(sym) return nil unless EXPORT.include?(sym) seg = __send__(sym) return nil unless seg.is_a?(Segment) seg end
[ "def", "to_segment", "(", "sym", ")", "return", "nil", "unless", "EXPORT", ".", "include?", "(", "sym", ")", "seg", "=", "__send__", "(", "sym", ")", "return", "nil", "unless", "seg", ".", "is_a?", "(", "Segment", ")", "seg", "end" ]
Convert symbol to segment. @return [HeapInfo::Segment?] The segment object.
[ "Convert", "symbol", "to", "segment", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/process_info.rb#L83-L90
18,374
david942j/heapinfo
lib/heapinfo/libc.rb
HeapInfo.Libc.main_arena
def main_arena return @main_arena.reload! if defined? @main_arena off = main_arena_offset return if off.nil? @main_arena = Arena.new(off + base, size_t, dumper) end
ruby
def main_arena return @main_arena.reload! if defined? @main_arena off = main_arena_offset return if off.nil? @main_arena = Arena.new(off + base, size_t, dumper) end
[ "def", "main_arena", "return", "@main_arena", ".", "reload!", "if", "defined?", "@main_arena", "off", "=", "main_arena_offset", "return", "if", "off", ".", "nil?", "@main_arena", "=", "Arena", ".", "new", "(", "off", "+", "base", ",", "size_t", ",", "dumper", ")", "end" ]
Get the +main_arena+ of libc. @return [HeapInfo::Arena]
[ "Get", "the", "+", "main_arena", "+", "of", "libc", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/libc.rb#L30-L37
18,375
david942j/heapinfo
lib/heapinfo/libc.rb
HeapInfo.Libc.info
def info return @info if defined? @info # Try to fetch from cache first. key = HeapInfo::Cache.key_libc_info(name) @info = HeapInfo::Cache.read(key) @info ||= execute_libc_info.tap { |i| HeapInfo::Cache.write(key, i) } end
ruby
def info return @info if defined? @info # Try to fetch from cache first. key = HeapInfo::Cache.key_libc_info(name) @info = HeapInfo::Cache.read(key) @info ||= execute_libc_info.tap { |i| HeapInfo::Cache.write(key, i) } end
[ "def", "info", "return", "@info", "if", "defined?", "@info", "# Try to fetch from cache first.", "key", "=", "HeapInfo", "::", "Cache", ".", "key_libc_info", "(", "name", ")", "@info", "=", "HeapInfo", "::", "Cache", ".", "read", "(", "key", ")", "@info", "||=", "execute_libc_info", ".", "tap", "{", "|", "i", "|", "HeapInfo", "::", "Cache", ".", "write", "(", "key", ",", "i", ")", "}", "end" ]
Get libc's info.
[ "Get", "libc", "s", "info", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/libc.rb#L79-L86
18,376
david942j/heapinfo
lib/heapinfo/nil.rb
HeapInfo.Nil.method_missing
def method_missing(method_sym, *args, &block) # rubocop:disable Style/MethodMissingSuper return nil.__send__(method_sym, *args, &block) if nil.respond_to?(method_sym) self end
ruby
def method_missing(method_sym, *args, &block) # rubocop:disable Style/MethodMissingSuper return nil.__send__(method_sym, *args, &block) if nil.respond_to?(method_sym) self end
[ "def", "method_missing", "(", "method_sym", ",", "*", "args", ",", "&", "block", ")", "# rubocop:disable Style/MethodMissingSuper", "return", "nil", ".", "__send__", "(", "method_sym", ",", "args", ",", "block", ")", "if", "nil", ".", "respond_to?", "(", "method_sym", ")", "self", "end" ]
Hook all missing methods @return [HeapInfo::Nil] return +self+ so that it can be a +nil+ chain. @example # h.dump would return Nil when process not found p h.dump(:heap)[8, 8].unpack('Q*') #=> nil
[ "Hook", "all", "missing", "methods" ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/nil.rb#L21-L25
18,377
david942j/heapinfo
lib/heapinfo/glibc/free.rb
HeapInfo.Glibc.invalid_pointer
def invalid_pointer(ptr, size) errmsg = "free(): invalid pointer\n" # unsigned compare malloc_assert(ptr <= ulong(-size)) { errmsg + format('ptr(0x%x) > -size(0x%x)', ptr, ulong(-size)) } malloc_assert((ptr % (size_t * 2)).zero?) { errmsg + format('ptr(0x%x) %% %d != 0', ptr, size_t * 2) } end
ruby
def invalid_pointer(ptr, size) errmsg = "free(): invalid pointer\n" # unsigned compare malloc_assert(ptr <= ulong(-size)) { errmsg + format('ptr(0x%x) > -size(0x%x)', ptr, ulong(-size)) } malloc_assert((ptr % (size_t * 2)).zero?) { errmsg + format('ptr(0x%x) %% %d != 0', ptr, size_t * 2) } end
[ "def", "invalid_pointer", "(", "ptr", ",", "size", ")", "errmsg", "=", "\"free(): invalid pointer\\n\"", "# unsigned compare", "malloc_assert", "(", "ptr", "<=", "ulong", "(", "-", "size", ")", ")", "{", "errmsg", "+", "format", "(", "'ptr(0x%x) > -size(0x%x)'", ",", "ptr", ",", "ulong", "(", "-", "size", ")", ")", "}", "malloc_assert", "(", "(", "ptr", "%", "(", "size_t", "*", "2", ")", ")", ".", "zero?", ")", "{", "errmsg", "+", "format", "(", "'ptr(0x%x) %% %d != 0'", ",", "ptr", ",", "size_t", "*", "2", ")", "}", "end" ]
Start of checkers
[ "Start", "of", "checkers" ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/glibc/free.rb#L67-L72
18,378
david942j/heapinfo
lib/heapinfo/chunk.rb
HeapInfo.Chunk.flags
def flags mask = @size - size flag = [] flag << :non_main_arena unless (mask & 4).zero? flag << :mmapped unless (mask & 2).zero? flag << :prev_inuse unless (mask & 1).zero? flag end
ruby
def flags mask = @size - size flag = [] flag << :non_main_arena unless (mask & 4).zero? flag << :mmapped unless (mask & 2).zero? flag << :prev_inuse unless (mask & 1).zero? flag end
[ "def", "flags", "mask", "=", "@size", "-", "size", "flag", "=", "[", "]", "flag", "<<", ":non_main_arena", "unless", "(", "mask", "&", "4", ")", ".", "zero?", "flag", "<<", ":mmapped", "unless", "(", "mask", "&", "2", ")", ".", "zero?", "flag", "<<", ":prev_inuse", "unless", "(", "mask", "&", "1", ")", ".", "zero?", "flag", "end" ]
The chunk flags record in low three bits of size @return [Array<Symbol>] flags of chunk @example c = [0, 0x25].pack("Q*").to_chunk c.flags # [:non_main_arena, :prev_inuse]
[ "The", "chunk", "flags", "record", "in", "low", "three", "bits", "of", "size" ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/chunk.rb#L61-L68
18,379
david942j/heapinfo
lib/heapinfo/process.rb
HeapInfo.Process.offset
def offset(addr, sym = nil) return unless load? segment = @info.to_segment(sym) if segment.nil? sym, segment = @info.segments .select { |_, seg| seg.base <= addr } .min_by { |_, seg| addr - seg } end return $stdout.puts "Invalid address #{Helper.hex(addr)}" if segment.nil? $stdout.puts Helper.color(Helper.hex(addr - segment)) + ' after ' + Helper.color(sym, sev: :sym) end
ruby
def offset(addr, sym = nil) return unless load? segment = @info.to_segment(sym) if segment.nil? sym, segment = @info.segments .select { |_, seg| seg.base <= addr } .min_by { |_, seg| addr - seg } end return $stdout.puts "Invalid address #{Helper.hex(addr)}" if segment.nil? $stdout.puts Helper.color(Helper.hex(addr - segment)) + ' after ' + Helper.color(sym, sev: :sym) end
[ "def", "offset", "(", "addr", ",", "sym", "=", "nil", ")", "return", "unless", "load?", "segment", "=", "@info", ".", "to_segment", "(", "sym", ")", "if", "segment", ".", "nil?", "sym", ",", "segment", "=", "@info", ".", "segments", ".", "select", "{", "|", "_", ",", "seg", "|", "seg", ".", "base", "<=", "addr", "}", ".", "min_by", "{", "|", "_", ",", "seg", "|", "addr", "-", "seg", "}", "end", "return", "$stdout", ".", "puts", "\"Invalid address #{Helper.hex(addr)}\"", "if", "segment", ".", "nil?", "$stdout", ".", "puts", "Helper", ".", "color", "(", "Helper", ".", "hex", "(", "addr", "-", "segment", ")", ")", "+", "' after '", "+", "Helper", ".", "color", "(", "sym", ",", "sev", ":", ":sym", ")", "end" ]
Show the offset in pretty way between the segment. Very useful in pwn when leak some address, see examples for more details. @param [Integer] addr The leaked address. @param [Symbol] sym The segement symbol to be calculated offset. If this parameter not given, will loop segments and find the most close one. See examples for more details. @return [void] Offset will show to stdout. @example h.offset(0x7f11f6ae1670, :libc) #=> 0xf6670 after libc h.offset(0x5559edc057a0, :heap) #=> 0x9637a0 after heap h.offset(0x7f11f6ae1670) #=> 0xf6670 after :libc h.offset(0x5559edc057a0) #=> 0x9637a0 after :heap
[ "Show", "the", "offset", "in", "pretty", "way", "between", "the", "segment", ".", "Very", "useful", "in", "pwn", "when", "leak", "some", "address", "see", "examples", "for", "more", "details", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/process.rb#L128-L140
18,380
david942j/heapinfo
lib/heapinfo/process.rb
HeapInfo.Process.find
def find(pattern, from, length = :unlimited, rel: false) return Nil.instance unless load? dumper.find(pattern, from, length, rel) end
ruby
def find(pattern, from, length = :unlimited, rel: false) return Nil.instance unless load? dumper.find(pattern, from, length, rel) end
[ "def", "find", "(", "pattern", ",", "from", ",", "length", "=", ":unlimited", ",", "rel", ":", "false", ")", "return", "Nil", ".", "instance", "unless", "load?", "dumper", ".", "find", "(", "pattern", ",", "from", ",", "length", ",", "rel", ")", "end" ]
Gdb-like command. Search a specific value/string/regexp in memory. @param [Integer, String, Regexp] pattern The desired search pattern, can be value(+Integer+), string, or regular expression. @param [Integer, String, Symbol] from Start address for searching, can be segment(+Symbol+) or segments with offset. See examples for more information. @param [Integer] length The search length limit, default is unlimited, which will search until pattern found or reach unreadable memory. @param [Boolean] rel To show relative offset of +from+ or absolute address. @return [Integer, nil] The first matched address, +nil+ is returned when no such pattern found. @example h.find(0xdeadbeef, 'heap+0x10', 0x1000) #=> 6299664 # 0x602010 h.find(/E.F/, 0x400000, 4) #=> 4194305 # 0x400001 h.find(/E.F/, 0x400000, 3) #=> nil sh_offset = h.find('/bin/sh', :libc) - h.libc #=> 1559771 # 0x17ccdb h.find('/bin/sh', :libc, rel: true) == h.find('/bin/sh', :libc) - h.libc #=> true
[ "Gdb", "-", "like", "command", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/process.rb#L208-L212
18,381
david942j/heapinfo
lib/heapinfo/process.rb
HeapInfo.Process.find_all
def find_all(pattern, segment = :all) return Nil.instance unless load? segments = segment == :all ? %i[elf heap libc ld stack] : Array(segment) result = findall_raw(pattern, segments).reject { |(_, _, ary)| ary.empty? } target = pattern.is_a?(Integer) ? Helper.hex(pattern) : pattern.inspect str = ["Searching #{Helper.color(target)}:\n"] str.concat(result.map do |(sym, base, ary)| "In #{Helper.color(sym, sev: :bin)} (#{Helper.color(Helper.hex(base))}):\n" + ary.map { |v| " #{Helper.color(sym, sev: :bin)}+#{Helper.color(Helper.hex(v))}\n" }.join end) $stdout.puts str end
ruby
def find_all(pattern, segment = :all) return Nil.instance unless load? segments = segment == :all ? %i[elf heap libc ld stack] : Array(segment) result = findall_raw(pattern, segments).reject { |(_, _, ary)| ary.empty? } target = pattern.is_a?(Integer) ? Helper.hex(pattern) : pattern.inspect str = ["Searching #{Helper.color(target)}:\n"] str.concat(result.map do |(sym, base, ary)| "In #{Helper.color(sym, sev: :bin)} (#{Helper.color(Helper.hex(base))}):\n" + ary.map { |v| " #{Helper.color(sym, sev: :bin)}+#{Helper.color(Helper.hex(v))}\n" }.join end) $stdout.puts str end
[ "def", "find_all", "(", "pattern", ",", "segment", "=", ":all", ")", "return", "Nil", ".", "instance", "unless", "load?", "segments", "=", "segment", "==", ":all", "?", "%i[", "elf", "heap", "libc", "ld", "stack", "]", ":", "Array", "(", "segment", ")", "result", "=", "findall_raw", "(", "pattern", ",", "segments", ")", ".", "reject", "{", "|", "(", "_", ",", "_", ",", "ary", ")", "|", "ary", ".", "empty?", "}", "target", "=", "pattern", ".", "is_a?", "(", "Integer", ")", "?", "Helper", ".", "hex", "(", "pattern", ")", ":", "pattern", ".", "inspect", "str", "=", "[", "\"Searching #{Helper.color(target)}:\\n\"", "]", "str", ".", "concat", "(", "result", ".", "map", "do", "|", "(", "sym", ",", "base", ",", "ary", ")", "|", "\"In #{Helper.color(sym, sev: :bin)} (#{Helper.color(Helper.hex(base))}):\\n\"", "+", "ary", ".", "map", "{", "|", "v", "|", "\" #{Helper.color(sym, sev: :bin)}+#{Helper.color(Helper.hex(v))}\\n\"", "}", ".", "join", "end", ")", "$stdout", ".", "puts", "str", "end" ]
Find pattern in all segments with pretty output. @param [Integer, String, Regexp] pattern The desired search pattern, can be value(+Integer+), string, or regular expression. @param [Symbol, Array<Symbol>] segment Only find pattern in these symbols. @return [void]
[ "Find", "pattern", "in", "all", "segments", "with", "pretty", "output", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/process.rb#L223-L235
18,382
david942j/heapinfo
lib/heapinfo/process.rb
HeapInfo.Process.to_s
def to_s return 'Process not found' unless load? "Program: #{Helper.color(program.name)} PID: #{Helper.color(pid)}\n" + program.to_s + heap.to_s + stack.to_s + libc.to_s + ld.to_s + format("%-28s\tvalue: #{Helper.color(format('%#x', canary), sev: :sym)}", Helper.color('canary', sev: :sym)) end
ruby
def to_s return 'Process not found' unless load? "Program: #{Helper.color(program.name)} PID: #{Helper.color(pid)}\n" + program.to_s + heap.to_s + stack.to_s + libc.to_s + ld.to_s + format("%-28s\tvalue: #{Helper.color(format('%#x', canary), sev: :sym)}", Helper.color('canary', sev: :sym)) end
[ "def", "to_s", "return", "'Process not found'", "unless", "load?", "\"Program: #{Helper.color(program.name)} PID: #{Helper.color(pid)}\\n\"", "+", "program", ".", "to_s", "+", "heap", ".", "to_s", "+", "stack", ".", "to_s", "+", "libc", ".", "to_s", "+", "ld", ".", "to_s", "+", "format", "(", "\"%-28s\\tvalue: #{Helper.color(format('%#x', canary), sev: :sym)}\"", ",", "Helper", ".", "color", "(", "'canary'", ",", "sev", ":", ":sym", ")", ")", "end" ]
Show simple information of target process. Contains program names, pid, and segments' info. @return [String] @example puts h
[ "Show", "simple", "information", "of", "target", "process", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/process.rb#L266-L276
18,383
david942j/heapinfo
lib/heapinfo/process.rb
HeapInfo.Process.canary
def canary return Nil.instance unless load? addr = @info.auxv[:random] Helper.unpack(bits / 8, @dumper.dump(addr, bits / 8)) & 0xffffffffffffff00 end
ruby
def canary return Nil.instance unless load? addr = @info.auxv[:random] Helper.unpack(bits / 8, @dumper.dump(addr, bits / 8)) & 0xffffffffffffff00 end
[ "def", "canary", "return", "Nil", ".", "instance", "unless", "load?", "addr", "=", "@info", ".", "auxv", "[", ":random", "]", "Helper", ".", "unpack", "(", "bits", "/", "8", ",", "@dumper", ".", "dump", "(", "addr", ",", "bits", "/", "8", ")", ")", "&", "0xffffffffffffff00", "end" ]
Get the value of stack guard. @return [Integer] @example h.canary #=> 11342701118118205184 # 0x9d695e921adc9700
[ "Get", "the", "value", "of", "stack", "guard", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/process.rb#L284-L289
18,384
infertux/bashcov
lib/bashcov/xtrace.rb
Bashcov.Xtrace.read
def read @field_stream.read = @read field_count = FIELDS.length fields = @field_stream.each( self.class.delimiter, field_count, PS4_START_REGEXP ) # +take(field_count)+ would be more natural here, but doesn't seem to # play nicely with +Enumerator+s backed by +IO+ objects. loop do break if (hit = (1..field_count).map { fields.next }).empty? parse_hit!(*hit) end @read.close unless @read.closed? @files end
ruby
def read @field_stream.read = @read field_count = FIELDS.length fields = @field_stream.each( self.class.delimiter, field_count, PS4_START_REGEXP ) # +take(field_count)+ would be more natural here, but doesn't seem to # play nicely with +Enumerator+s backed by +IO+ objects. loop do break if (hit = (1..field_count).map { fields.next }).empty? parse_hit!(*hit) end @read.close unless @read.closed? @files end
[ "def", "read", "@field_stream", ".", "read", "=", "@read", "field_count", "=", "FIELDS", ".", "length", "fields", "=", "@field_stream", ".", "each", "(", "self", ".", "class", ".", "delimiter", ",", "field_count", ",", "PS4_START_REGEXP", ")", "# +take(field_count)+ would be more natural here, but doesn't seem to", "# play nicely with +Enumerator+s backed by +IO+ objects.", "loop", "do", "break", "if", "(", "hit", "=", "(", "1", "..", "field_count", ")", ".", "map", "{", "fields", ".", "next", "}", ")", ".", "empty?", "parse_hit!", "(", "hit", ")", "end", "@read", ".", "close", "unless", "@read", ".", "closed?", "@files", "end" ]
Read fields extracted from Bash's debugging output @return [Hash<Pathname, Array<Integer, nil>>] A hash mapping Bash scripts to Simplecov-style coverage stats
[ "Read", "fields", "extracted", "from", "Bash", "s", "debugging", "output" ]
40730ae72b286e7508937e187fc000715d8a6892
https://github.com/infertux/bashcov/blob/40730ae72b286e7508937e187fc000715d8a6892/lib/bashcov/xtrace.rb#L84-L103
18,385
infertux/bashcov
lib/bashcov/xtrace.rb
Bashcov.Xtrace.update_wd_stacks!
def update_wd_stacks!(pwd, oldpwd) @pwd_stack[0] ||= pwd @oldpwd_stack[0] ||= oldpwd unless oldpwd.to_s.empty? # We haven't changed working directories; short-circuit. return if pwd == @pwd_stack[-1] # If the current +pwd+ is identical to the top of the +@oldpwd_stack+ and # the current +oldpwd+ is identical to the second-to-top entry, then a # previous cd/pushd has been undone. if pwd == @oldpwd_stack[-1] && oldpwd == @oldpwd_stack[-2] @pwd_stack.pop @oldpwd_stack.pop else # New cd/pushd @pwd_stack << pwd @oldpwd_stack << oldpwd end end
ruby
def update_wd_stacks!(pwd, oldpwd) @pwd_stack[0] ||= pwd @oldpwd_stack[0] ||= oldpwd unless oldpwd.to_s.empty? # We haven't changed working directories; short-circuit. return if pwd == @pwd_stack[-1] # If the current +pwd+ is identical to the top of the +@oldpwd_stack+ and # the current +oldpwd+ is identical to the second-to-top entry, then a # previous cd/pushd has been undone. if pwd == @oldpwd_stack[-1] && oldpwd == @oldpwd_stack[-2] @pwd_stack.pop @oldpwd_stack.pop else # New cd/pushd @pwd_stack << pwd @oldpwd_stack << oldpwd end end
[ "def", "update_wd_stacks!", "(", "pwd", ",", "oldpwd", ")", "@pwd_stack", "[", "0", "]", "||=", "pwd", "@oldpwd_stack", "[", "0", "]", "||=", "oldpwd", "unless", "oldpwd", ".", "to_s", ".", "empty?", "# We haven't changed working directories; short-circuit.", "return", "if", "pwd", "==", "@pwd_stack", "[", "-", "1", "]", "# If the current +pwd+ is identical to the top of the +@oldpwd_stack+ and", "# the current +oldpwd+ is identical to the second-to-top entry, then a", "# previous cd/pushd has been undone.", "if", "pwd", "==", "@oldpwd_stack", "[", "-", "1", "]", "&&", "oldpwd", "==", "@oldpwd_stack", "[", "-", "2", "]", "@pwd_stack", ".", "pop", "@oldpwd_stack", ".", "pop", "else", "# New cd/pushd", "@pwd_stack", "<<", "pwd", "@oldpwd_stack", "<<", "oldpwd", "end", "end" ]
Updates the stacks that track the history of values for +PWD+ and +OLDPWD+ @param [Pathname] pwd expanded +PWD+ @param [Pathname] oldpwd expanded +OLDPWD+ @return [void]
[ "Updates", "the", "stacks", "that", "track", "the", "history", "of", "values", "for", "+", "PWD", "+", "and", "+", "OLDPWD", "+" ]
40730ae72b286e7508937e187fc000715d8a6892
https://github.com/infertux/bashcov/blob/40730ae72b286e7508937e187fc000715d8a6892/lib/bashcov/xtrace.rb#L169-L186
18,386
infertux/bashcov
lib/bashcov/detective.rb
Bashcov.Detective.shellscript?
def shellscript?(filename) return false unless File.exist?(filename) && File.readable?(filename) \ && File.file?(File.realpath(filename)) shellscript_shebang?(filename) || \ (shellscript_extension?(filename) && shellscript_syntax?(filename)) end
ruby
def shellscript?(filename) return false unless File.exist?(filename) && File.readable?(filename) \ && File.file?(File.realpath(filename)) shellscript_shebang?(filename) || \ (shellscript_extension?(filename) && shellscript_syntax?(filename)) end
[ "def", "shellscript?", "(", "filename", ")", "return", "false", "unless", "File", ".", "exist?", "(", "filename", ")", "&&", "File", ".", "readable?", "(", "filename", ")", "&&", "File", ".", "file?", "(", "File", ".", "realpath", "(", "filename", ")", ")", "shellscript_shebang?", "(", "filename", ")", "||", "(", "shellscript_extension?", "(", "filename", ")", "&&", "shellscript_syntax?", "(", "filename", ")", ")", "end" ]
Create an object that can be used for inferring whether a file is or is not a shell script. @param [String] bash_path path to a Bash interpreter Checks whether the provided file refers to a shell script by determining whether the first line is a shebang that refers to a shell executable, or whether the file has a shellscript extension and contains valid shell syntax. @param [String,Pathname] filename the name of the file to be checked @return [Boolean] whether +filename+ refers to a shell script @note returns +false+ when +filename+ is not readable, even if +filename+ indeed refers to a shell script.
[ "Create", "an", "object", "that", "can", "be", "used", "for", "inferring", "whether", "a", "file", "is", "or", "is", "not", "a", "shell", "script", "." ]
40730ae72b286e7508937e187fc000715d8a6892
https://github.com/infertux/bashcov/blob/40730ae72b286e7508937e187fc000715d8a6892/lib/bashcov/detective.rb#L33-L39
18,387
infertux/bashcov
lib/bashcov/field_stream.rb
Bashcov.FieldStream.each
def each(delimiter, field_count, start_match) return enum_for(__method__, delimiter, field_count, start_match) unless block_given? chunked = each_field(delimiter).chunk(&chunk_matches(start_match)) yield_fields = lambda do |(_, chunk)| chunk.each { |e| yield e } (field_count - chunk.size).times { yield "" } end # Skip junk that might appear before the first start-of-fields match begin n, chunk = chunked.next yield_fields.call([n, chunk]) unless n.zero? rescue StopIteration return end chunked.each(&yield_fields) end
ruby
def each(delimiter, field_count, start_match) return enum_for(__method__, delimiter, field_count, start_match) unless block_given? chunked = each_field(delimiter).chunk(&chunk_matches(start_match)) yield_fields = lambda do |(_, chunk)| chunk.each { |e| yield e } (field_count - chunk.size).times { yield "" } end # Skip junk that might appear before the first start-of-fields match begin n, chunk = chunked.next yield_fields.call([n, chunk]) unless n.zero? rescue StopIteration return end chunked.each(&yield_fields) end
[ "def", "each", "(", "delimiter", ",", "field_count", ",", "start_match", ")", "return", "enum_for", "(", "__method__", ",", "delimiter", ",", "field_count", ",", "start_match", ")", "unless", "block_given?", "chunked", "=", "each_field", "(", "delimiter", ")", ".", "chunk", "(", "chunk_matches", "(", "start_match", ")", ")", "yield_fields", "=", "lambda", "do", "|", "(", "_", ",", "chunk", ")", "|", "chunk", ".", "each", "{", "|", "e", "|", "yield", "e", "}", "(", "field_count", "-", "chunk", ".", "size", ")", ".", "times", "{", "yield", "\"\"", "}", "end", "# Skip junk that might appear before the first start-of-fields match", "begin", "n", ",", "chunk", "=", "chunked", ".", "next", "yield_fields", ".", "call", "(", "[", "n", ",", "chunk", "]", ")", "unless", "n", ".", "zero?", "rescue", "StopIteration", "return", "end", "chunked", ".", "each", "(", "yield_fields", ")", "end" ]
Yields fields extracted from a input stream @param [String, nil] delimiter the field separator @param [Integer] field_count the number of fields to extract @param [Regexp] start_match a +Regexp+ that, when matched against the input stream, signifies the beginning of the next series of fields to yield @yieldparam [String] field each field extracted from the stream. If +start_match+ is matched with fewer than +field_count+ fields yielded since the last match, yields empty strings until +field_count+ is reached.
[ "Yields", "fields", "extracted", "from", "a", "input", "stream" ]
40730ae72b286e7508937e187fc000715d8a6892
https://github.com/infertux/bashcov/blob/40730ae72b286e7508937e187fc000715d8a6892/lib/bashcov/field_stream.rb#L36-L55
18,388
malept/thermite
lib/thermite/package.rb
Thermite.Package.build_package
def build_package filename = config.tarball_filename(config.toml[:package][:version]) relative_library_path = config.ruby_extension_path.sub("#{config.ruby_toplevel_dir}/", '') prepare_built_library Zlib::GzipWriter.open(filename) do |tgz| Dir.chdir(config.ruby_toplevel_dir) do Archive::Tar::Minitar.pack(relative_library_path, tgz) end end end
ruby
def build_package filename = config.tarball_filename(config.toml[:package][:version]) relative_library_path = config.ruby_extension_path.sub("#{config.ruby_toplevel_dir}/", '') prepare_built_library Zlib::GzipWriter.open(filename) do |tgz| Dir.chdir(config.ruby_toplevel_dir) do Archive::Tar::Minitar.pack(relative_library_path, tgz) end end end
[ "def", "build_package", "filename", "=", "config", ".", "tarball_filename", "(", "config", ".", "toml", "[", ":package", "]", "[", ":version", "]", ")", "relative_library_path", "=", "config", ".", "ruby_extension_path", ".", "sub", "(", "\"#{config.ruby_toplevel_dir}/\"", ",", "''", ")", "prepare_built_library", "Zlib", "::", "GzipWriter", ".", "open", "(", "filename", ")", "do", "|", "tgz", "|", "Dir", ".", "chdir", "(", "config", ".", "ruby_toplevel_dir", ")", "do", "Archive", "::", "Tar", "::", "Minitar", ".", "pack", "(", "relative_library_path", ",", "tgz", ")", "end", "end", "end" ]
Builds a tarball of the Rust-compiled shared library.
[ "Builds", "a", "tarball", "of", "the", "Rust", "-", "compiled", "shared", "library", "." ]
9b380eb9e069909ff346fb3079d5be340deccaac
https://github.com/malept/thermite/blob/9b380eb9e069909ff346fb3079d5be340deccaac/lib/thermite/package.rb#L32-L41
18,389
malept/thermite
lib/thermite/util.rb
Thermite.Util.debug
def debug(msg) # Should probably replace with a Logger return unless config.debug_filename @debug ||= File.open(config.debug_filename, 'w') @debug.write("#{msg}\n") @debug.flush end
ruby
def debug(msg) # Should probably replace with a Logger return unless config.debug_filename @debug ||= File.open(config.debug_filename, 'w') @debug.write("#{msg}\n") @debug.flush end
[ "def", "debug", "(", "msg", ")", "# Should probably replace with a Logger", "return", "unless", "config", ".", "debug_filename", "@debug", "||=", "File", ".", "open", "(", "config", ".", "debug_filename", ",", "'w'", ")", "@debug", ".", "write", "(", "\"#{msg}\\n\"", ")", "@debug", ".", "flush", "end" ]
Logs a debug message to the specified `config.debug_filename`, if set.
[ "Logs", "a", "debug", "message", "to", "the", "specified", "config", ".", "debug_filename", "if", "set", "." ]
9b380eb9e069909ff346fb3079d5be340deccaac
https://github.com/malept/thermite/blob/9b380eb9e069909ff346fb3079d5be340deccaac/lib/thermite/util.rb#L30-L37
18,390
malept/thermite
lib/thermite/custom_binary.rb
Thermite.CustomBinary.download_binary_from_custom_uri
def download_binary_from_custom_uri return false unless config.binary_uri_format version = config.crate_version uri ||= format( config.binary_uri_format, filename: config.tarball_filename(version), version: version ) return false unless (tgz = download_versioned_binary(uri, version)) debug "Unpacking binary from Cargo version: #{File.basename(uri)}" unpack_tarball(tgz) prepare_downloaded_library true end
ruby
def download_binary_from_custom_uri return false unless config.binary_uri_format version = config.crate_version uri ||= format( config.binary_uri_format, filename: config.tarball_filename(version), version: version ) return false unless (tgz = download_versioned_binary(uri, version)) debug "Unpacking binary from Cargo version: #{File.basename(uri)}" unpack_tarball(tgz) prepare_downloaded_library true end
[ "def", "download_binary_from_custom_uri", "return", "false", "unless", "config", ".", "binary_uri_format", "version", "=", "config", ".", "crate_version", "uri", "||=", "format", "(", "config", ".", "binary_uri_format", ",", "filename", ":", "config", ".", "tarball_filename", "(", "version", ")", ",", "version", ":", "version", ")", "return", "false", "unless", "(", "tgz", "=", "download_versioned_binary", "(", "uri", ",", "version", ")", ")", "debug", "\"Unpacking binary from Cargo version: #{File.basename(uri)}\"", "unpack_tarball", "(", "tgz", ")", "prepare_downloaded_library", "true", "end" ]
Downloads a Rust binary using a custom URI format, given the target OS and architecture. Requires the `binary_uri_format` option to be set. The version of the binary is determined by the crate version given in `Cargo.toml`. Returns whether a binary was found and unpacked.
[ "Downloads", "a", "Rust", "binary", "using", "a", "custom", "URI", "format", "given", "the", "target", "OS", "and", "architecture", "." ]
9b380eb9e069909ff346fb3079d5be340deccaac
https://github.com/malept/thermite/blob/9b380eb9e069909ff346fb3079d5be340deccaac/lib/thermite/custom_binary.rb#L36-L52
18,391
piotrmurach/github_cli
lib/github_cli/dsl.rb
GithubCLI.DSL.on_error
def on_error yield rescue Github::Error::NotFound => e terminal.newline ui.error 'Resource Not Found' terminal.newline exit 15 rescue GithubCLI::GithubCLIError => e GithubCLI.ui.error e.message GithubCLI.ui.debug e exit e.status_code rescue Interrupt => e GithubCLI.ui.error "\nQuitting..." GithubCLI.ui.debug e exit 1 rescue SystemExit => e exit e.status rescue Exception => e GithubCLI.ui.error "\nFatal error has occurred. " + e.message.to_s GithubCLI.ui.debug e exit 1 end
ruby
def on_error yield rescue Github::Error::NotFound => e terminal.newline ui.error 'Resource Not Found' terminal.newline exit 15 rescue GithubCLI::GithubCLIError => e GithubCLI.ui.error e.message GithubCLI.ui.debug e exit e.status_code rescue Interrupt => e GithubCLI.ui.error "\nQuitting..." GithubCLI.ui.debug e exit 1 rescue SystemExit => e exit e.status rescue Exception => e GithubCLI.ui.error "\nFatal error has occurred. " + e.message.to_s GithubCLI.ui.debug e exit 1 end
[ "def", "on_error", "yield", "rescue", "Github", "::", "Error", "::", "NotFound", "=>", "e", "terminal", ".", "newline", "ui", ".", "error", "'Resource Not Found'", "terminal", ".", "newline", "exit", "15", "rescue", "GithubCLI", "::", "GithubCLIError", "=>", "e", "GithubCLI", ".", "ui", ".", "error", "e", ".", "message", "GithubCLI", ".", "ui", ".", "debug", "e", "exit", "e", ".", "status_code", "rescue", "Interrupt", "=>", "e", "GithubCLI", ".", "ui", ".", "error", "\"\\nQuitting...\"", "GithubCLI", ".", "ui", ".", "debug", "e", "exit", "1", "rescue", "SystemExit", "=>", "e", "exit", "e", ".", "status", "rescue", "Exception", "=>", "e", "GithubCLI", ".", "ui", ".", "error", "\"\\nFatal error has occurred. \"", "+", "e", ".", "message", ".", "to_s", "GithubCLI", ".", "ui", ".", "debug", "e", "exit", "1", "end" ]
Defines behaviour on error to emit consistent type.
[ "Defines", "behaviour", "on", "error", "to", "emit", "consistent", "type", "." ]
394845fb629351917beeb62e607b833420410930
https://github.com/piotrmurach/github_cli/blob/394845fb629351917beeb62e607b833420410930/lib/github_cli/dsl.rb#L18-L39
18,392
piotrmurach/github_cli
lib/github_cli/util.rb
GithubCLI.Util.convert_value
def convert_value(value) case value when true then "true" when false then "false" when Hash then convert_value(value.values) when Array then value.map(&:to_s) else value.to_s end end
ruby
def convert_value(value) case value when true then "true" when false then "false" when Hash then convert_value(value.values) when Array then value.map(&:to_s) else value.to_s end end
[ "def", "convert_value", "(", "value", ")", "case", "value", "when", "true", "then", "\"true\"", "when", "false", "then", "\"false\"", "when", "Hash", "then", "convert_value", "(", "value", ".", "values", ")", "when", "Array", "then", "value", ".", "map", "(", ":to_s", ")", "else", "value", ".", "to_s", "end", "end" ]
Attempts to convert value object to string
[ "Attempts", "to", "convert", "value", "object", "to", "string" ]
394845fb629351917beeb62e607b833420410930
https://github.com/piotrmurach/github_cli/blob/394845fb629351917beeb62e607b833420410930/lib/github_cli/util.rb#L37-L45
18,393
piotrmurach/github_cli
lib/github_cli/manpage.rb
GithubCLI.Manpage.man_dir
def man_dir(path = nil) if @man_dir.nil? || path man_path = path || File.expand_path('../man', __FILE__) if File.directory?(man_path) @man_dir = man_path else fail "Manuals directory `#{man_path}` does not exist" end end @man_dir end
ruby
def man_dir(path = nil) if @man_dir.nil? || path man_path = path || File.expand_path('../man', __FILE__) if File.directory?(man_path) @man_dir = man_path else fail "Manuals directory `#{man_path}` does not exist" end end @man_dir end
[ "def", "man_dir", "(", "path", "=", "nil", ")", "if", "@man_dir", ".", "nil?", "||", "path", "man_path", "=", "path", "||", "File", ".", "expand_path", "(", "'../man'", ",", "__FILE__", ")", "if", "File", ".", "directory?", "(", "man_path", ")", "@man_dir", "=", "man_path", "else", "fail", "\"Manuals directory `#{man_path}` does not exist\"", "end", "end", "@man_dir", "end" ]
Full path to manual directory @return [String] @api private
[ "Full", "path", "to", "manual", "directory" ]
394845fb629351917beeb62e607b833420410930
https://github.com/piotrmurach/github_cli/blob/394845fb629351917beeb62e607b833420410930/lib/github_cli/manpage.rb#L20-L31
18,394
piotrmurach/github_cli
lib/github_cli/manpage.rb
GithubCLI.Manpage.manpage?
def manpage?(name, section = nil) return false if name.nil? manpages(name, section).any? end
ruby
def manpage?(name, section = nil) return false if name.nil? manpages(name, section).any? end
[ "def", "manpage?", "(", "name", ",", "section", "=", "nil", ")", "return", "false", "if", "name", ".", "nil?", "manpages", "(", "name", ",", "section", ")", ".", "any?", "end" ]
Check if manual exists for a command @param [String] command the command name @api public
[ "Check", "if", "manual", "exists", "for", "a", "command" ]
394845fb629351917beeb62e607b833420410930
https://github.com/piotrmurach/github_cli/blob/394845fb629351917beeb62e607b833420410930/lib/github_cli/manpage.rb#L48-L52
18,395
piotrmurach/github_cli
lib/github_cli/manpage.rb
GithubCLI.Manpage.read
def read(name, section = nil) return if name.nil? paths = manpages(name) return if paths.empty? if paths.size == 1 manpath = paths[0] elsif paths.size > 1 prompt = TTY::Prompt.new manpath = prompt.select("Choose manual to view?", paths) end if manpath run(manpath) else abort("No manuals found for #{name}") end end
ruby
def read(name, section = nil) return if name.nil? paths = manpages(name) return if paths.empty? if paths.size == 1 manpath = paths[0] elsif paths.size > 1 prompt = TTY::Prompt.new manpath = prompt.select("Choose manual to view?", paths) end if manpath run(manpath) else abort("No manuals found for #{name}") end end
[ "def", "read", "(", "name", ",", "section", "=", "nil", ")", "return", "if", "name", ".", "nil?", "paths", "=", "manpages", "(", "name", ")", "return", "if", "paths", ".", "empty?", "if", "paths", ".", "size", "==", "1", "manpath", "=", "paths", "[", "0", "]", "elsif", "paths", ".", "size", ">", "1", "prompt", "=", "TTY", "::", "Prompt", ".", "new", "manpath", "=", "prompt", ".", "select", "(", "\"Choose manual to view?\"", ",", "paths", ")", "end", "if", "manpath", "run", "(", "manpath", ")", "else", "abort", "(", "\"No manuals found for #{name}\"", ")", "end", "end" ]
Read manual page @api public
[ "Read", "manual", "page" ]
394845fb629351917beeb62e607b833420410930
https://github.com/piotrmurach/github_cli/blob/394845fb629351917beeb62e607b833420410930/lib/github_cli/manpage.rb#L76-L93
18,396
piotrmurach/github_cli
lib/github_cli/pager.rb
GithubCLI.Pager.page
def page return if not $stdout.tty? read_io, write_io = IO.pipe if Kernel.fork $stdin.reopen(read_io) read_io.close write_io.close # Don't page if the input is short enough ENV['LESS'] = 'FSRX' # Wait until we have input before we start the pager Kernel.select [$stdin] pager = Pager.pager_command Kernel.exec pager rescue Kernel.exec "/bin/sh", "-c", pager else # Child process $stdout.reopen(write_io) $stderr.reopen(write_io) if $stderr.tty? write_io.close read_io.close end end
ruby
def page return if not $stdout.tty? read_io, write_io = IO.pipe if Kernel.fork $stdin.reopen(read_io) read_io.close write_io.close # Don't page if the input is short enough ENV['LESS'] = 'FSRX' # Wait until we have input before we start the pager Kernel.select [$stdin] pager = Pager.pager_command Kernel.exec pager rescue Kernel.exec "/bin/sh", "-c", pager else # Child process $stdout.reopen(write_io) $stderr.reopen(write_io) if $stderr.tty? write_io.close read_io.close end end
[ "def", "page", "return", "if", "not", "$stdout", ".", "tty?", "read_io", ",", "write_io", "=", "IO", ".", "pipe", "if", "Kernel", ".", "fork", "$stdin", ".", "reopen", "(", "read_io", ")", "read_io", ".", "close", "write_io", ".", "close", "# Don't page if the input is short enough", "ENV", "[", "'LESS'", "]", "=", "'FSRX'", "# Wait until we have input before we start the pager", "Kernel", ".", "select", "[", "$stdin", "]", "pager", "=", "Pager", ".", "pager_command", "Kernel", ".", "exec", "pager", "rescue", "Kernel", ".", "exec", "\"/bin/sh\"", ",", "\"-c\"", ",", "pager", "else", "# Child process", "$stdout", ".", "reopen", "(", "write_io", ")", "$stderr", ".", "reopen", "(", "write_io", ")", "if", "$stderr", ".", "tty?", "write_io", ".", "close", "read_io", ".", "close", "end", "end" ]
Pages output using configured pager.
[ "Pages", "output", "using", "configured", "pager", "." ]
394845fb629351917beeb62e607b833420410930
https://github.com/piotrmurach/github_cli/blob/394845fb629351917beeb62e607b833420410930/lib/github_cli/pager.rb#L40-L66
18,397
Sutto/rocket_pants
lib/rocket_pants/controller/rescuable.rb
RocketPants.Rescuable.process_action
def process_action(*args) super rescue Exception => exception raise if RocketPants.pass_through_errors? # Otherwise, use the default built in handler. logger.error "Exception occured: #{exception.class.name} - #{exception.message}" logger.error "Exception backtrace:" exception.backtrace[0, 10].each do |backtrace_line| logger.error "=> #{backtrace_line}" end exception_notifier_callback.call(self, exception, request) render_error exception end
ruby
def process_action(*args) super rescue Exception => exception raise if RocketPants.pass_through_errors? # Otherwise, use the default built in handler. logger.error "Exception occured: #{exception.class.name} - #{exception.message}" logger.error "Exception backtrace:" exception.backtrace[0, 10].each do |backtrace_line| logger.error "=> #{backtrace_line}" end exception_notifier_callback.call(self, exception, request) render_error exception end
[ "def", "process_action", "(", "*", "args", ")", "super", "rescue", "Exception", "=>", "exception", "raise", "if", "RocketPants", ".", "pass_through_errors?", "# Otherwise, use the default built in handler.", "logger", ".", "error", "\"Exception occured: #{exception.class.name} - #{exception.message}\"", "logger", ".", "error", "\"Exception backtrace:\"", "exception", ".", "backtrace", "[", "0", ",", "10", "]", ".", "each", "do", "|", "backtrace_line", "|", "logger", ".", "error", "\"=> #{backtrace_line}\"", "end", "exception_notifier_callback", ".", "call", "(", "self", ",", "exception", ",", "request", ")", "render_error", "exception", "end" ]
Overrides the processing internals to rescue any exceptions and handle them with the registered exception rescue handler.
[ "Overrides", "the", "processing", "internals", "to", "rescue", "any", "exceptions", "and", "handle", "them", "with", "the", "registered", "exception", "rescue", "handler", "." ]
bddc27ada67a11ff34fa8065fe2b1b2627bd28ff
https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/rescuable.rb#L60-L72
18,398
Sutto/rocket_pants
lib/rocket_pants/controller/error_handling.rb
RocketPants.ErrorHandling.error!
def error!(name, *args) context = args.extract_options! klass = Errors[name] || Error exception = klass.new(*args).tap { |e| e.context = context } raise exception end
ruby
def error!(name, *args) context = args.extract_options! klass = Errors[name] || Error exception = klass.new(*args).tap { |e| e.context = context } raise exception end
[ "def", "error!", "(", "name", ",", "*", "args", ")", "context", "=", "args", ".", "extract_options!", "klass", "=", "Errors", "[", "name", "]", "||", "Error", "exception", "=", "klass", ".", "new", "(", "args", ")", ".", "tap", "{", "|", "e", "|", "e", ".", "context", "=", "context", "}", "raise", "exception", "end" ]
Dynamically looks up and then throws the error given by a symbolic name. Optionally takes a string message argument and a hash of 'context'. @overload error!(name, context = {}) @param [Symbol] name the name of the exception, looked up using RocketPants::Errors @param [Hash{Symbol => Object}] context the options passed to the error message translation. @overload error!(name, message, context = {}) @param [Symbol] name the name of the exception, looked up using RocketPants::Errors @param [String] message an optional message describing the error @param [Hash{Symbol => Object}] context the options passed to the error message translation. @raise [RocketPants::Error] the error from the given options
[ "Dynamically", "looks", "up", "and", "then", "throws", "the", "error", "given", "by", "a", "symbolic", "name", ".", "Optionally", "takes", "a", "string", "message", "argument", "and", "a", "hash", "of", "context", "." ]
bddc27ada67a11ff34fa8065fe2b1b2627bd28ff
https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/error_handling.rb#L40-L45
18,399
Sutto/rocket_pants
lib/rocket_pants/controller/error_handling.rb
RocketPants.ErrorHandling.lookup_error_metadata
def lookup_error_metadata(exception) context = lookup_error_context exception context.fetch(:metadata, {}).merge lookup_error_extras(exception) end
ruby
def lookup_error_metadata(exception) context = lookup_error_context exception context.fetch(:metadata, {}).merge lookup_error_extras(exception) end
[ "def", "lookup_error_metadata", "(", "exception", ")", "context", "=", "lookup_error_context", "exception", "context", ".", "fetch", "(", ":metadata", ",", "{", "}", ")", ".", "merge", "lookup_error_extras", "(", "exception", ")", "end" ]
Returns extra error details for a given object, making it useable for hooking in external exceptions.
[ "Returns", "extra", "error", "details", "for", "a", "given", "object", "making", "it", "useable", "for", "hooking", "in", "external", "exceptions", "." ]
bddc27ada67a11ff34fa8065fe2b1b2627bd28ff
https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/error_handling.rb#L102-L105