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
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
23,700
rightscale/right_scraper
lib/right_scraper/retrievers/checkout_base.rb
RightScraper::Retrievers.CheckoutBase.retrieve
def retrieve raise RetrieverError.new("retriever is unavailable") unless available? updated = false explanation = '' if exists? @logger.operation(:updating) do # a retriever may be able to determine that the repo directory is # already pointing to the same commit as the revision. in that case # we can return quickly. if remote_differs? # there is no point in updating and failing the size check when the # directory on disk already exceeds size limit; fall back to a clean # checkout in hopes that the latest revision corrects the issue. if size_limit_exceeded? explanation = 'switching to checkout due to existing directory exceeding size limimt' else # attempt update. begin do_update updated = true rescue ::RightScraper::Processes::Shell::LimitError # update exceeded a limitation; requires user intervention raise rescue Exception => e # retry with clean checkout after discarding repo dir. explanation = 'switching to checkout after unsuccessful update' end end else # no retrieval needed but warn exactly why we didn't do full # checkout to avoid being challenged about it. repo_ref = @repository.tag do_update_tag full_head_ref = @repository.tag abbreviated_head_ref = full_head_ref[0..6] if repo_ref == full_head_ref || repo_ref == abbreviated_head_ref detail = abbreviated_head_ref else detail = "#{repo_ref} = #{abbreviated_head_ref}" end message = "Skipped updating local directory due to the HEAD commit SHA " + "on local matching the remote repository reference (#{detail})." @logger.note_warning(message) return false end end end # Clean checkout only if not updated. unless updated @logger.operation(:checkout, explanation) do # remove any full or partial directory before attempting a clean # checkout in case repo_dir is in a bad state. if exists? ::FileUtils.remove_entry_secure(@repo_dir) end ::FileUtils.mkdir_p(@repo_dir) begin do_checkout rescue Exception # clean checkout failed; repo directory is in an undetermined # state and must be deleted to prevent a future update attempt. if exists? ::FileUtils.remove_entry_secure(@repo_dir) rescue nil end raise end end end true end
ruby
def retrieve raise RetrieverError.new("retriever is unavailable") unless available? updated = false explanation = '' if exists? @logger.operation(:updating) do # a retriever may be able to determine that the repo directory is # already pointing to the same commit as the revision. in that case # we can return quickly. if remote_differs? # there is no point in updating and failing the size check when the # directory on disk already exceeds size limit; fall back to a clean # checkout in hopes that the latest revision corrects the issue. if size_limit_exceeded? explanation = 'switching to checkout due to existing directory exceeding size limimt' else # attempt update. begin do_update updated = true rescue ::RightScraper::Processes::Shell::LimitError # update exceeded a limitation; requires user intervention raise rescue Exception => e # retry with clean checkout after discarding repo dir. explanation = 'switching to checkout after unsuccessful update' end end else # no retrieval needed but warn exactly why we didn't do full # checkout to avoid being challenged about it. repo_ref = @repository.tag do_update_tag full_head_ref = @repository.tag abbreviated_head_ref = full_head_ref[0..6] if repo_ref == full_head_ref || repo_ref == abbreviated_head_ref detail = abbreviated_head_ref else detail = "#{repo_ref} = #{abbreviated_head_ref}" end message = "Skipped updating local directory due to the HEAD commit SHA " + "on local matching the remote repository reference (#{detail})." @logger.note_warning(message) return false end end end # Clean checkout only if not updated. unless updated @logger.operation(:checkout, explanation) do # remove any full or partial directory before attempting a clean # checkout in case repo_dir is in a bad state. if exists? ::FileUtils.remove_entry_secure(@repo_dir) end ::FileUtils.mkdir_p(@repo_dir) begin do_checkout rescue Exception # clean checkout failed; repo directory is in an undetermined # state and must be deleted to prevent a future update attempt. if exists? ::FileUtils.remove_entry_secure(@repo_dir) rescue nil end raise end end end true end
[ "def", "retrieve", "raise", "RetrieverError", ".", "new", "(", "\"retriever is unavailable\"", ")", "unless", "available?", "updated", "=", "false", "explanation", "=", "''", "if", "exists?", "@logger", ".", "operation", "(", ":updating", ")", "do", "# a retriever may be able to determine that the repo directory is", "# already pointing to the same commit as the revision. in that case", "# we can return quickly.", "if", "remote_differs?", "# there is no point in updating and failing the size check when the", "# directory on disk already exceeds size limit; fall back to a clean", "# checkout in hopes that the latest revision corrects the issue.", "if", "size_limit_exceeded?", "explanation", "=", "'switching to checkout due to existing directory exceeding size limimt'", "else", "# attempt update.", "begin", "do_update", "updated", "=", "true", "rescue", "::", "RightScraper", "::", "Processes", "::", "Shell", "::", "LimitError", "# update exceeded a limitation; requires user intervention", "raise", "rescue", "Exception", "=>", "e", "# retry with clean checkout after discarding repo dir.", "explanation", "=", "'switching to checkout after unsuccessful update'", "end", "end", "else", "# no retrieval needed but warn exactly why we didn't do full", "# checkout to avoid being challenged about it.", "repo_ref", "=", "@repository", ".", "tag", "do_update_tag", "full_head_ref", "=", "@repository", ".", "tag", "abbreviated_head_ref", "=", "full_head_ref", "[", "0", "..", "6", "]", "if", "repo_ref", "==", "full_head_ref", "||", "repo_ref", "==", "abbreviated_head_ref", "detail", "=", "abbreviated_head_ref", "else", "detail", "=", "\"#{repo_ref} = #{abbreviated_head_ref}\"", "end", "message", "=", "\"Skipped updating local directory due to the HEAD commit SHA \"", "+", "\"on local matching the remote repository reference (#{detail}).\"", "@logger", ".", "note_warning", "(", "message", ")", "return", "false", "end", "end", "end", "# Clean checkout only if not updated.", "unless", "updated", "@logger", ".", "operation", "(", ":checkout", ",", "explanation", ")", "do", "# remove any full or partial directory before attempting a clean", "# checkout in case repo_dir is in a bad state.", "if", "exists?", "::", "FileUtils", ".", "remove_entry_secure", "(", "@repo_dir", ")", "end", "::", "FileUtils", ".", "mkdir_p", "(", "@repo_dir", ")", "begin", "do_checkout", "rescue", "Exception", "# clean checkout failed; repo directory is in an undetermined", "# state and must be deleted to prevent a future update attempt.", "if", "exists?", "::", "FileUtils", ".", "remove_entry_secure", "(", "@repo_dir", ")", "rescue", "nil", "end", "raise", "end", "end", "end", "true", "end" ]
Attempts to update and then resorts to clean checkout for repository.
[ "Attempts", "to", "update", "and", "then", "resorts", "to", "clean", "checkout", "for", "repository", "." ]
8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae
https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/checkout_base.rb#L39-L110
23,701
rightscale/right_scraper
lib/right_scraper/retrievers/checkout_base.rb
RightScraper::Retrievers.CheckoutBase.size_limit_exceeded?
def size_limit_exceeded? if @max_bytes # note that Dir.glob ignores hidden directories (e.g. ".git") so the # size total correctly excludes those hidden contents that are not to # be uploaded after scrape. this may cause the on-disk directory size # to far exceed the upload size. globbie = ::File.join(@repo_dir, '**/*') size = 0 ::Dir.glob(globbie) do |f| size += ::File.stat(f).size rescue 0 if ::File.file?(f) break if size > @max_bytes end size > @max_bytes else false end end
ruby
def size_limit_exceeded? if @max_bytes # note that Dir.glob ignores hidden directories (e.g. ".git") so the # size total correctly excludes those hidden contents that are not to # be uploaded after scrape. this may cause the on-disk directory size # to far exceed the upload size. globbie = ::File.join(@repo_dir, '**/*') size = 0 ::Dir.glob(globbie) do |f| size += ::File.stat(f).size rescue 0 if ::File.file?(f) break if size > @max_bytes end size > @max_bytes else false end end
[ "def", "size_limit_exceeded?", "if", "@max_bytes", "# note that Dir.glob ignores hidden directories (e.g. \".git\") so the", "# size total correctly excludes those hidden contents that are not to", "# be uploaded after scrape. this may cause the on-disk directory size", "# to far exceed the upload size.", "globbie", "=", "::", "File", ".", "join", "(", "@repo_dir", ",", "'**/*'", ")", "size", "=", "0", "::", "Dir", ".", "glob", "(", "globbie", ")", "do", "|", "f", "|", "size", "+=", "::", "File", ".", "stat", "(", "f", ")", ".", "size", "rescue", "0", "if", "::", "File", ".", "file?", "(", "f", ")", "break", "if", "size", ">", "@max_bytes", "end", "size", ">", "@max_bytes", "else", "false", "end", "end" ]
Determines if total size of files in repo_dir has exceeded size limit. === Return @return [TrueClass|FalseClass] true if size limit exceeded
[ "Determines", "if", "total", "size", "of", "files", "in", "repo_dir", "has", "exceeded", "size", "limit", "." ]
8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae
https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/checkout_base.rb#L135-L151
23,702
rightscale/right_scraper
lib/right_scraper/resources/cookbook.rb
RightScraper::Resources.Cookbook.to_hash
def to_hash { repository: repository, resource_hash: resource_hash, # location of cookbook manifest in S3 metadata: ::JSON.dump(metadata), # pass as opaque JSON blob pos: pos } end
ruby
def to_hash { repository: repository, resource_hash: resource_hash, # location of cookbook manifest in S3 metadata: ::JSON.dump(metadata), # pass as opaque JSON blob pos: pos } end
[ "def", "to_hash", "{", "repository", ":", "repository", ",", "resource_hash", ":", "resource_hash", ",", "# location of cookbook manifest in S3", "metadata", ":", "::", "JSON", ".", "dump", "(", "metadata", ")", ",", "# pass as opaque JSON blob", "pos", ":", "pos", "}", "end" ]
marshal cookbook to hash
[ "marshal", "cookbook", "to", "hash" ]
8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae
https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/resources/cookbook.rb#L72-L79
23,703
rightscale/right_git
lib/right_git/git/branch_collection.rb
RightGit::Git.BranchCollection.current
def current lines = @repo.git_output(['symbolic-ref', 'HEAD'], :raise_on_failure => false).lines if lines.size == 1 line = lines.first.strip if (match = HEAD_REF.match(line)) @branches.detect { |b| b.fullname == match[1] } elsif line == NO_HEAD_REF nil end else raise GitError, "Unexpected output from 'git symbolic-ref'; need 1 lines, got #{lines.size}" end end
ruby
def current lines = @repo.git_output(['symbolic-ref', 'HEAD'], :raise_on_failure => false).lines if lines.size == 1 line = lines.first.strip if (match = HEAD_REF.match(line)) @branches.detect { |b| b.fullname == match[1] } elsif line == NO_HEAD_REF nil end else raise GitError, "Unexpected output from 'git symbolic-ref'; need 1 lines, got #{lines.size}" end end
[ "def", "current", "lines", "=", "@repo", ".", "git_output", "(", "[", "'symbolic-ref'", ",", "'HEAD'", "]", ",", ":raise_on_failure", "=>", "false", ")", ".", "lines", "if", "lines", ".", "size", "==", "1", "line", "=", "lines", ".", "first", ".", "strip", "if", "(", "match", "=", "HEAD_REF", ".", "match", "(", "line", ")", ")", "@branches", ".", "detect", "{", "|", "b", "|", "b", ".", "fullname", "==", "match", "[", "1", "]", "}", "elsif", "line", "==", "NO_HEAD_REF", "nil", "end", "else", "raise", "GitError", ",", "\"Unexpected output from 'git symbolic-ref'; need 1 lines, got #{lines.size}\"", "end", "end" ]
Return a Branch object representing whichever branch is currently checked out, IF AND ONLY IF that branch is a member of the collection. If the current branch isn't part of the collection or HEAD refers to something other than a branch, return nil. @return [Branch] the current branch if any, nil otherwise
[ "Return", "a", "Branch", "object", "representing", "whichever", "branch", "is", "currently", "checked", "out", "IF", "AND", "ONLY", "IF", "that", "branch", "is", "a", "member", "of", "the", "collection", ".", "If", "the", "current", "branch", "isn", "t", "part", "of", "the", "collection", "or", "HEAD", "refers", "to", "something", "other", "than", "a", "branch", "return", "nil", "." ]
285f33996f56f08bc3f62b216695a6dbff12151d
https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/branch_collection.rb#L92-L105
23,704
rightscale/right_git
lib/right_git/git/branch_collection.rb
RightGit::Git.BranchCollection.merged
def merged(revision) # By hand, build a list of all branches known to be merged into master git_args = ['branch', '-a', '--merged', revision] all_merged = [] @repo.git_output(git_args).lines.each do |line| line.strip! all_merged << Branch.new(@repo, line) end # Filter the contents of this collection according to the big list merged = [] @branches.each do |candidate| # For some reason Set#include? does not play nice with our overridden comparison operators # for branches, so we need to do this the hard way :( merged << candidate if all_merged.detect { |b| candidate == b } end BranchCollection.new(@repo, merged) end
ruby
def merged(revision) # By hand, build a list of all branches known to be merged into master git_args = ['branch', '-a', '--merged', revision] all_merged = [] @repo.git_output(git_args).lines.each do |line| line.strip! all_merged << Branch.new(@repo, line) end # Filter the contents of this collection according to the big list merged = [] @branches.each do |candidate| # For some reason Set#include? does not play nice with our overridden comparison operators # for branches, so we need to do this the hard way :( merged << candidate if all_merged.detect { |b| candidate == b } end BranchCollection.new(@repo, merged) end
[ "def", "merged", "(", "revision", ")", "# By hand, build a list of all branches known to be merged into master", "git_args", "=", "[", "'branch'", ",", "'-a'", ",", "'--merged'", ",", "revision", "]", "all_merged", "=", "[", "]", "@repo", ".", "git_output", "(", "git_args", ")", ".", "lines", ".", "each", "do", "|", "line", "|", "line", ".", "strip!", "all_merged", "<<", "Branch", ".", "new", "(", "@repo", ",", "line", ")", "end", "# Filter the contents of this collection according to the big list", "merged", "=", "[", "]", "@branches", ".", "each", "do", "|", "candidate", "|", "# For some reason Set#include? does not play nice with our overridden comparison operators", "# for branches, so we need to do this the hard way :(", "merged", "<<", "candidate", "if", "all_merged", ".", "detect", "{", "|", "b", "|", "candidate", "==", "b", "}", "end", "BranchCollection", ".", "new", "(", "@repo", ",", "merged", ")", "end" ]
Queries and filters on branches reachable from the given revision, if any. @param [String] revision for listing reachable merged branches @return [BranchCollection] merged branches
[ "Queries", "and", "filters", "on", "branches", "reachable", "from", "the", "given", "revision", "if", "any", "." ]
285f33996f56f08bc3f62b216695a6dbff12151d
https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/branch_collection.rb#L138-L156
23,705
rightscale/right_git
lib/right_git/git/branch_collection.rb
RightGit::Git.BranchCollection.[]
def [](argument) case argument when String target = Branch.new(@repo, argument) @branches.detect { |b| b == target } else @branches.__send__(:[], argument) end end
ruby
def [](argument) case argument when String target = Branch.new(@repo, argument) @branches.detect { |b| b == target } else @branches.__send__(:[], argument) end end
[ "def", "[]", "(", "argument", ")", "case", "argument", "when", "String", "target", "=", "Branch", ".", "new", "(", "@repo", ",", "argument", ")", "@branches", ".", "detect", "{", "|", "b", "|", "b", "==", "target", "}", "else", "@branches", ".", "__send__", "(", ":[]", ",", "argument", ")", "end", "end" ]
Accessor that acts like either a Hash or Array accessor
[ "Accessor", "that", "acts", "like", "either", "a", "Hash", "or", "Array", "accessor" ]
285f33996f56f08bc3f62b216695a6dbff12151d
https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/branch_collection.rb#L159-L167
23,706
rightscale/right_git
lib/right_git/git/branch_collection.rb
RightGit::Git.BranchCollection.method_missing
def method_missing(meth, *args, &block) result = @branches.__send__(meth, *args, &block) if result.is_a?(::Array) BranchCollection.new(@repo, result) else result end end
ruby
def method_missing(meth, *args, &block) result = @branches.__send__(meth, *args, &block) if result.is_a?(::Array) BranchCollection.new(@repo, result) else result end end
[ "def", "method_missing", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "result", "=", "@branches", ".", "__send__", "(", "meth", ",", "args", ",", "block", ")", "if", "result", ".", "is_a?", "(", "::", "Array", ")", "BranchCollection", ".", "new", "(", "@repo", ",", "result", ")", "else", "result", "end", "end" ]
Dispatch to the underlying Array of Branch objects, allowing the branch collection to act a bit like an Array. If the dispatched-to method returns an Array, it is wrapped in another BranchCollection object before returning to the caller. This allows array-like method calls to be chained together without losing the BranchCollection-ness of the underlying object.
[ "Dispatch", "to", "the", "underlying", "Array", "of", "Branch", "objects", "allowing", "the", "branch", "collection", "to", "act", "a", "bit", "like", "an", "Array", "." ]
285f33996f56f08bc3f62b216695a6dbff12151d
https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/branch_collection.rb#L175-L183
23,707
rightscale/right_scraper
lib/right_scraper/scanners/cookbook_s3_upload.rb
RightScraper::Scanners.CookbookS3Upload.notice
def notice(relative_position) contents = yield name = Digest::MD5.hexdigest(contents) path = File.join('Files', name) unless @bucket.key(path).exists? @bucket.put(path, contents) end end
ruby
def notice(relative_position) contents = yield name = Digest::MD5.hexdigest(contents) path = File.join('Files', name) unless @bucket.key(path).exists? @bucket.put(path, contents) end end
[ "def", "notice", "(", "relative_position", ")", "contents", "=", "yield", "name", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "contents", ")", "path", "=", "File", ".", "join", "(", "'Files'", ",", "name", ")", "unless", "@bucket", ".", "key", "(", "path", ")", ".", "exists?", "@bucket", ".", "put", "(", "path", ",", "contents", ")", "end", "end" ]
Upload a file during scanning. === Block Return the data for this file. We use a block because it may not always be necessary to read the data. === Parameters relative_position(String):: relative pathname for file from root of cookbook
[ "Upload", "a", "file", "during", "scanning", "." ]
8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae
https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_s3_upload.rb#L79-L86
23,708
noprompt/vic
lib/vic/color.rb
Vic.Color.to_gui
def to_gui return to_standard_hex if hexadecimal? return Convert.xterm_to_hex(@value) if cterm? return :NONE if none? raise ColorError.new "can't convert \"#{ @value }\" to gui" end
ruby
def to_gui return to_standard_hex if hexadecimal? return Convert.xterm_to_hex(@value) if cterm? return :NONE if none? raise ColorError.new "can't convert \"#{ @value }\" to gui" end
[ "def", "to_gui", "return", "to_standard_hex", "if", "hexadecimal?", "return", "Convert", ".", "xterm_to_hex", "(", "@value", ")", "if", "cterm?", "return", ":NONE", "if", "none?", "raise", "ColorError", ".", "new", "\"can't convert \\\"#{ @value }\\\" to gui\"", "end" ]
Convert the color value to a hexadecimal color @return [Symbol,String] the color as either "NONE" or hexadecimal @api public
[ "Convert", "the", "color", "value", "to", "a", "hexadecimal", "color" ]
276e18fc5d81727023d3abfdf95829648818a9c4
https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/color.rb#L17-L23
23,709
noprompt/vic
lib/vic/color.rb
Vic.Color.to_cterm
def to_cterm return @value if cterm? return Convert.hex_to_xterm(to_standard_hex) if hexadecimal? return :NONE if none? raise ColorError.new "can't convert \"#{ @value }\" to cterm" end
ruby
def to_cterm return @value if cterm? return Convert.hex_to_xterm(to_standard_hex) if hexadecimal? return :NONE if none? raise ColorError.new "can't convert \"#{ @value }\" to cterm" end
[ "def", "to_cterm", "return", "@value", "if", "cterm?", "return", "Convert", ".", "hex_to_xterm", "(", "to_standard_hex", ")", "if", "hexadecimal?", "return", ":NONE", "if", "none?", "raise", "ColorError", ".", "new", "\"can't convert \\\"#{ @value }\\\" to cterm\"", "end" ]
Convert the color value to a cterm compatible color @return [Fixnum] the color as either "NONE" or cterm color @api public
[ "Convert", "the", "color", "value", "to", "a", "cterm", "compatible", "color" ]
276e18fc5d81727023d3abfdf95829648818a9c4
https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/color.rb#L31-L37
23,710
noprompt/vic
lib/vic/color.rb
Vic.Color.to_standard_hex
def to_standard_hex color = @value.dup color.insert(0, '#') unless color.start_with? '#' # Convert shorthand hex to standard hex. if color.size == 4 color.slice!(1, 3).chars { |char| color << char * 2 } end color end
ruby
def to_standard_hex color = @value.dup color.insert(0, '#') unless color.start_with? '#' # Convert shorthand hex to standard hex. if color.size == 4 color.slice!(1, 3).chars { |char| color << char * 2 } end color end
[ "def", "to_standard_hex", "color", "=", "@value", ".", "dup", "color", ".", "insert", "(", "0", ",", "'#'", ")", "unless", "color", ".", "start_with?", "'#'", "# Convert shorthand hex to standard hex.", "if", "color", ".", "size", "==", "4", "color", ".", "slice!", "(", "1", ",", "3", ")", ".", "chars", "{", "|", "char", "|", "color", "<<", "char", "*", "2", "}", "end", "color", "end" ]
Convert the color value to a standard hexadecimal value @example Color.new('333').send(:to_standard_hex) # => '#333333' @return [String] the color in standard hexadecimal format @api private
[ "Convert", "the", "color", "value", "to", "a", "standard", "hexadecimal", "value" ]
276e18fc5d81727023d3abfdf95829648818a9c4
https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/color.rb#L93-L102
23,711
rightscale/right_scraper
lib/right_scraper/retrievers/svn.rb
RightScraper::Retrievers.Svn.resolve_revision
def resolve_revision revision = @repository.tag.to_s.strip if revision.empty? revision = nil elsif (revision =~ SVN_REVISION_REGEX).nil? raise RetrieverError, "Revision reference contained illegal characters: #{revision.inspect}" end # timestamps can contain spaces; surround them with double quotes. revision = revision.inspect if revision.index(' ') revision end
ruby
def resolve_revision revision = @repository.tag.to_s.strip if revision.empty? revision = nil elsif (revision =~ SVN_REVISION_REGEX).nil? raise RetrieverError, "Revision reference contained illegal characters: #{revision.inspect}" end # timestamps can contain spaces; surround them with double quotes. revision = revision.inspect if revision.index(' ') revision end
[ "def", "resolve_revision", "revision", "=", "@repository", ".", "tag", ".", "to_s", ".", "strip", "if", "revision", ".", "empty?", "revision", "=", "nil", "elsif", "(", "revision", "=~", "SVN_REVISION_REGEX", ")", ".", "nil?", "raise", "RetrieverError", ",", "\"Revision reference contained illegal characters: #{revision.inspect}\"", "end", "# timestamps can contain spaces; surround them with double quotes.", "revision", "=", "revision", ".", "inspect", "if", "revision", ".", "index", "(", "' '", ")", "revision", "end" ]
ignoring additional info after revision
[ "ignoring", "additional", "info", "after", "revision" ]
8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae
https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/svn.rb#L116-L126
23,712
aidistan/ruby-biotcm
lib/biotcm/table.rb
BioTCM.Table.row_keys=
def row_keys=(val) raise ArgumentError, 'Illegal agrument type' unless val.is_a?(Array) raise ArgumentError, 'Unmatched size' if val.size < @row_keys.size @row_keys = val.map.with_index { |v, i| [v, i] }.to_h end
ruby
def row_keys=(val) raise ArgumentError, 'Illegal agrument type' unless val.is_a?(Array) raise ArgumentError, 'Unmatched size' if val.size < @row_keys.size @row_keys = val.map.with_index { |v, i| [v, i] }.to_h end
[ "def", "row_keys", "=", "(", "val", ")", "raise", "ArgumentError", ",", "'Illegal agrument type'", "unless", "val", ".", "is_a?", "(", "Array", ")", "raise", "ArgumentError", ",", "'Unmatched size'", "if", "val", ".", "size", "<", "@row_keys", ".", "size", "@row_keys", "=", "val", ".", "map", ".", "with_index", "{", "|", "v", ",", "i", "|", "[", "v", ",", "i", "]", "}", ".", "to_h", "end" ]
Set row keys @param val [Array]
[ "Set", "row", "keys" ]
89b798acc1773087d9e8b754187c884d57fd06d7
https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L77-L81
23,713
aidistan/ruby-biotcm
lib/biotcm/table.rb
BioTCM.Table.ele
def ele(row, col, val = nil) if val.nil? get_ele(row, col) else set_ele(row, col, val) end end
ruby
def ele(row, col, val = nil) if val.nil? get_ele(row, col) else set_ele(row, col, val) end end
[ "def", "ele", "(", "row", ",", "col", ",", "val", "=", "nil", ")", "if", "val", ".", "nil?", "get_ele", "(", "row", ",", "col", ")", "else", "set_ele", "(", "row", ",", "col", ",", "val", ")", "end", "end" ]
Access an element @overload ele(row, col) Get an element @param row [String] @param col [String] @return [String] @overload ele(row, col, val) Set an element @param row [String] @param col [String] @param val [String] @return [Table]
[ "Access", "an", "element" ]
89b798acc1773087d9e8b754187c884d57fd06d7
https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L119-L125
23,714
aidistan/ruby-biotcm
lib/biotcm/table.rb
BioTCM.Table.get_ele
def get_ele(row, col) row = @row_keys[row] col = @col_keys[col] row && col ? @content[row][col] : nil end
ruby
def get_ele(row, col) row = @row_keys[row] col = @col_keys[col] row && col ? @content[row][col] : nil end
[ "def", "get_ele", "(", "row", ",", "col", ")", "row", "=", "@row_keys", "[", "row", "]", "col", "=", "@col_keys", "[", "col", "]", "row", "&&", "col", "?", "@content", "[", "row", "]", "[", "col", "]", ":", "nil", "end" ]
Get an element @param row [String] @param col [String] @return [String]
[ "Get", "an", "element" ]
89b798acc1773087d9e8b754187c884d57fd06d7
https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L131-L135
23,715
aidistan/ruby-biotcm
lib/biotcm/table.rb
BioTCM.Table.set_ele
def set_ele(row, col, val) unless row.is_a?(String) && col.is_a?(String) && val.respond_to?(:to_s) raise ArgumentError, 'Illegal argument type' end set_row(row, [''] * @col_keys.size) unless @row_keys[row] set_col(col, [''] * @row_keys.size) unless @col_keys[col] row = @row_keys[row] col = @col_keys[col] @content[row][col] = val.to_s self end
ruby
def set_ele(row, col, val) unless row.is_a?(String) && col.is_a?(String) && val.respond_to?(:to_s) raise ArgumentError, 'Illegal argument type' end set_row(row, [''] * @col_keys.size) unless @row_keys[row] set_col(col, [''] * @row_keys.size) unless @col_keys[col] row = @row_keys[row] col = @col_keys[col] @content[row][col] = val.to_s self end
[ "def", "set_ele", "(", "row", ",", "col", ",", "val", ")", "unless", "row", ".", "is_a?", "(", "String", ")", "&&", "col", ".", "is_a?", "(", "String", ")", "&&", "val", ".", "respond_to?", "(", ":to_s", ")", "raise", "ArgumentError", ",", "'Illegal argument type'", "end", "set_row", "(", "row", ",", "[", "''", "]", "*", "@col_keys", ".", "size", ")", "unless", "@row_keys", "[", "row", "]", "set_col", "(", "col", ",", "[", "''", "]", "*", "@row_keys", ".", "size", ")", "unless", "@col_keys", "[", "col", "]", "row", "=", "@row_keys", "[", "row", "]", "col", "=", "@col_keys", "[", "col", "]", "@content", "[", "row", "]", "[", "col", "]", "=", "val", ".", "to_s", "self", "end" ]
Set an element @param row [String] @param col [String] @param val [String] @return [Table]
[ "Set", "an", "element" ]
89b798acc1773087d9e8b754187c884d57fd06d7
https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L142-L155
23,716
aidistan/ruby-biotcm
lib/biotcm/table.rb
BioTCM.Table.row
def row(row, val = nil) if val.nil? get_row(row) else set_row(row, val) end end
ruby
def row(row, val = nil) if val.nil? get_row(row) else set_row(row, val) end end
[ "def", "row", "(", "row", ",", "val", "=", "nil", ")", "if", "val", ".", "nil?", "get_row", "(", "row", ")", "else", "set_row", "(", "row", ",", "val", ")", "end", "end" ]
Access a row @overload row(row) Get a row @param row [String] @return [Hash] @overload row(row, val) Set a row @param row [String] @param val [Hash, Array] @return [Table]
[ "Access", "a", "row" ]
89b798acc1773087d9e8b754187c884d57fd06d7
https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L167-L173
23,717
aidistan/ruby-biotcm
lib/biotcm/table.rb
BioTCM.Table.get_row
def get_row(row) row = @row_keys[row] row.nil? ? nil : @col_keys.map { |c, ci| [c, @content[row][ci]] }.to_h end
ruby
def get_row(row) row = @row_keys[row] row.nil? ? nil : @col_keys.map { |c, ci| [c, @content[row][ci]] }.to_h end
[ "def", "get_row", "(", "row", ")", "row", "=", "@row_keys", "[", "row", "]", "row", ".", "nil?", "?", "nil", ":", "@col_keys", ".", "map", "{", "|", "c", ",", "ci", "|", "[", "c", ",", "@content", "[", "row", "]", "[", "ci", "]", "]", "}", ".", "to_h", "end" ]
Get a row @param row [String] @return [Hash]
[ "Get", "a", "row" ]
89b798acc1773087d9e8b754187c884d57fd06d7
https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L178-L181
23,718
aidistan/ruby-biotcm
lib/biotcm/table.rb
BioTCM.Table.set_row
def set_row(row, val) # Setter if !row.is_a?(String) || (!val.is_a?(Hash) && !val.is_a?(Array)) raise ArgumentError, 'Illegal argument type' elsif val.is_a?(Array) && val.size != col_keys.size raise ArgumentError, 'Column size not match' end case val when Array if @row_keys[row] row = @row_keys[row] @content[row] = val else @row_keys[row] = @row_keys.size @content << val end when Hash unless @row_keys[row] @row_keys[row] = @row_keys.size @content << ([''] * @col_keys.size) end row = @row_keys[row] val.each do |k, v| col = @col_keys[k] @content[row][col] = v if col end end self end
ruby
def set_row(row, val) # Setter if !row.is_a?(String) || (!val.is_a?(Hash) && !val.is_a?(Array)) raise ArgumentError, 'Illegal argument type' elsif val.is_a?(Array) && val.size != col_keys.size raise ArgumentError, 'Column size not match' end case val when Array if @row_keys[row] row = @row_keys[row] @content[row] = val else @row_keys[row] = @row_keys.size @content << val end when Hash unless @row_keys[row] @row_keys[row] = @row_keys.size @content << ([''] * @col_keys.size) end row = @row_keys[row] val.each do |k, v| col = @col_keys[k] @content[row][col] = v if col end end self end
[ "def", "set_row", "(", "row", ",", "val", ")", "# Setter", "if", "!", "row", ".", "is_a?", "(", "String", ")", "||", "(", "!", "val", ".", "is_a?", "(", "Hash", ")", "&&", "!", "val", ".", "is_a?", "(", "Array", ")", ")", "raise", "ArgumentError", ",", "'Illegal argument type'", "elsif", "val", ".", "is_a?", "(", "Array", ")", "&&", "val", ".", "size", "!=", "col_keys", ".", "size", "raise", "ArgumentError", ",", "'Column size not match'", "end", "case", "val", "when", "Array", "if", "@row_keys", "[", "row", "]", "row", "=", "@row_keys", "[", "row", "]", "@content", "[", "row", "]", "=", "val", "else", "@row_keys", "[", "row", "]", "=", "@row_keys", ".", "size", "@content", "<<", "val", "end", "when", "Hash", "unless", "@row_keys", "[", "row", "]", "@row_keys", "[", "row", "]", "=", "@row_keys", ".", "size", "@content", "<<", "(", "[", "''", "]", "*", "@col_keys", ".", "size", ")", "end", "row", "=", "@row_keys", "[", "row", "]", "val", ".", "each", "do", "|", "k", ",", "v", "|", "col", "=", "@col_keys", "[", "k", "]", "@content", "[", "row", "]", "[", "col", "]", "=", "v", "if", "col", "end", "end", "self", "end" ]
Set a row @param row [String] @param val [Hash, Array] @return [Table]
[ "Set", "a", "row" ]
89b798acc1773087d9e8b754187c884d57fd06d7
https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L187-L218
23,719
aidistan/ruby-biotcm
lib/biotcm/table.rb
BioTCM.Table.col
def col(col, val = nil) if val.nil? get_col(col) else set_col(col, val) end end
ruby
def col(col, val = nil) if val.nil? get_col(col) else set_col(col, val) end end
[ "def", "col", "(", "col", ",", "val", "=", "nil", ")", "if", "val", ".", "nil?", "get_col", "(", "col", ")", "else", "set_col", "(", "col", ",", "val", ")", "end", "end" ]
Access a column @overload col(col) Get a column @param col [String] @return [Hash] @overload col(col, val) Set a column @param col [String] @param val [Hash, Array] @return [Table]
[ "Access", "a", "column" ]
89b798acc1773087d9e8b754187c884d57fd06d7
https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L230-L236
23,720
aidistan/ruby-biotcm
lib/biotcm/table.rb
BioTCM.Table.get_col
def get_col(col) col = @col_keys[col] col.nil? ? nil : @row_keys.map { |r, ri| [r, @content[ri][col]] }.to_h end
ruby
def get_col(col) col = @col_keys[col] col.nil? ? nil : @row_keys.map { |r, ri| [r, @content[ri][col]] }.to_h end
[ "def", "get_col", "(", "col", ")", "col", "=", "@col_keys", "[", "col", "]", "col", ".", "nil?", "?", "nil", ":", "@row_keys", ".", "map", "{", "|", "r", ",", "ri", "|", "[", "r", ",", "@content", "[", "ri", "]", "[", "col", "]", "]", "}", ".", "to_h", "end" ]
Get a column @param col [String] @return [Hash]
[ "Get", "a", "column" ]
89b798acc1773087d9e8b754187c884d57fd06d7
https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L241-L244
23,721
aidistan/ruby-biotcm
lib/biotcm/table.rb
BioTCM.Table.set_col
def set_col(col, val) if !col.is_a?(String) || (!val.is_a?(Hash) && !val.is_a?(Array)) raise ArgumentError, 'Illegal argument type' elsif val.is_a?(Array) && val.size != row_keys.size raise ArgumentError, 'Row size not match' end case val when Array if @col_keys[col] col = @col_keys[col] val.each_with_index { |v, row| @content[row][col] = v } else col = @col_keys[col] = @col_keys.size val.each_with_index { |v, row| @content[row] << v } end when Hash unless @col_keys[col] @col_keys[col] = @col_keys.size @content.each { |arr| arr << '' } end col = @col_keys[col] val.each do |k, v| row = @row_keys[k] @content[row][col] = v if row end end self end
ruby
def set_col(col, val) if !col.is_a?(String) || (!val.is_a?(Hash) && !val.is_a?(Array)) raise ArgumentError, 'Illegal argument type' elsif val.is_a?(Array) && val.size != row_keys.size raise ArgumentError, 'Row size not match' end case val when Array if @col_keys[col] col = @col_keys[col] val.each_with_index { |v, row| @content[row][col] = v } else col = @col_keys[col] = @col_keys.size val.each_with_index { |v, row| @content[row] << v } end when Hash unless @col_keys[col] @col_keys[col] = @col_keys.size @content.each { |arr| arr << '' } end col = @col_keys[col] val.each do |k, v| row = @row_keys[k] @content[row][col] = v if row end end self end
[ "def", "set_col", "(", "col", ",", "val", ")", "if", "!", "col", ".", "is_a?", "(", "String", ")", "||", "(", "!", "val", ".", "is_a?", "(", "Hash", ")", "&&", "!", "val", ".", "is_a?", "(", "Array", ")", ")", "raise", "ArgumentError", ",", "'Illegal argument type'", "elsif", "val", ".", "is_a?", "(", "Array", ")", "&&", "val", ".", "size", "!=", "row_keys", ".", "size", "raise", "ArgumentError", ",", "'Row size not match'", "end", "case", "val", "when", "Array", "if", "@col_keys", "[", "col", "]", "col", "=", "@col_keys", "[", "col", "]", "val", ".", "each_with_index", "{", "|", "v", ",", "row", "|", "@content", "[", "row", "]", "[", "col", "]", "=", "v", "}", "else", "col", "=", "@col_keys", "[", "col", "]", "=", "@col_keys", ".", "size", "val", ".", "each_with_index", "{", "|", "v", ",", "row", "|", "@content", "[", "row", "]", "<<", "v", "}", "end", "when", "Hash", "unless", "@col_keys", "[", "col", "]", "@col_keys", "[", "col", "]", "=", "@col_keys", ".", "size", "@content", ".", "each", "{", "|", "arr", "|", "arr", "<<", "''", "}", "end", "col", "=", "@col_keys", "[", "col", "]", "val", ".", "each", "do", "|", "k", ",", "v", "|", "row", "=", "@row_keys", "[", "k", "]", "@content", "[", "row", "]", "[", "col", "]", "=", "v", "if", "row", "end", "end", "self", "end" ]
Set a column @param col [String] @param val [Hash, Array] @return [Table]
[ "Set", "a", "column" ]
89b798acc1773087d9e8b754187c884d57fd06d7
https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L250-L280
23,722
aidistan/ruby-biotcm
lib/biotcm/table.rb
BioTCM.Table.each_row
def each_row if block_given? @row_keys.each_key { |r| yield(r, row(r)) } self else Enumerator.new do |y| @row_keys.each_key { |r| y << [r, row(r)] } end end end
ruby
def each_row if block_given? @row_keys.each_key { |r| yield(r, row(r)) } self else Enumerator.new do |y| @row_keys.each_key { |r| y << [r, row(r)] } end end end
[ "def", "each_row", "if", "block_given?", "@row_keys", ".", "each_key", "{", "|", "r", "|", "yield", "(", "r", ",", "row", "(", "r", ")", ")", "}", "self", "else", "Enumerator", ".", "new", "do", "|", "y", "|", "@row_keys", ".", "each_key", "{", "|", "r", "|", "y", "<<", "[", "r", ",", "row", "(", "r", ")", "]", "}", "end", "end", "end" ]
Iterate by row
[ "Iterate", "by", "row" ]
89b798acc1773087d9e8b754187c884d57fd06d7
https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L283-L292
23,723
aidistan/ruby-biotcm
lib/biotcm/table.rb
BioTCM.Table.each_col
def each_col if block_given? @col_keys.each_key { |c| yield(c, col(c)) } self else Enumerator.new do |y| @col_keys.each_key { |c| y << [c, col(c)] } end end end
ruby
def each_col if block_given? @col_keys.each_key { |c| yield(c, col(c)) } self else Enumerator.new do |y| @col_keys.each_key { |c| y << [c, col(c)] } end end end
[ "def", "each_col", "if", "block_given?", "@col_keys", ".", "each_key", "{", "|", "c", "|", "yield", "(", "c", ",", "col", "(", "c", ")", ")", "}", "self", "else", "Enumerator", ".", "new", "do", "|", "y", "|", "@col_keys", ".", "each_key", "{", "|", "c", "|", "y", "<<", "[", "c", ",", "col", "(", "c", ")", "]", "}", "end", "end", "end" ]
Iterate by col
[ "Iterate", "by", "col" ]
89b798acc1773087d9e8b754187c884d57fd06d7
https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L295-L304
23,724
aidistan/ruby-biotcm
lib/biotcm/databases/hgnc/rescuer.rb
BioTCM::Databases::HGNC.Rescuer.rescue_symbol
def rescue_symbol(symbol, method = @rescue_method, rehearsal = false) return @rescue_history[symbol] if @rescue_history[symbol] case method when :auto auto_rescue = '' if @symbol2hgncid[symbol.upcase] auto_rescue = symbol.upcase elsif @symbol2hgncid[symbol.downcase] auto_rescue = symbol.downcase elsif @symbol2hgncid[symbol.delete('-')] auto_rescue = symbol.delete('-') elsif @symbol2hgncid[symbol.upcase.delete('-')] auto_rescue = symbol.upcase.delete('-') elsif @symbol2hgncid[symbol.downcase.delete('-')] auto_rescue = symbol.downcase.delete('-') # Add more rules here end # Record unless rehearsal BioTCM.logger.warn('HGNC') { "Unrecognized symbol \"#{symbol}\", \"#{auto_rescue}\" used instead" } @rescue_history[symbol] = auto_rescue end return auto_rescue when :manual # Try automatic rescue first if (auto_rescue = rescue_symbol(symbol, :auto, true)) != '' print "\"#{symbol}\" unrecognized. Use \"#{auto_rescue}\" instead? [Yn] " unless gets.chomp == 'n' @rescue_history[symbol] = auto_rescue unless rehearsal # rubocop:disable Metrics/BlockNesting return auto_rescue end end # Manually rescue loop do print "Please correct \"#{symbol}\" or press enter directly to return empty String instead:\n" unless (manual_rescue = gets.chomp) == '' || @symbol2hgncid[manual_rescue] puts "Failed to recognize \"#{manual_rescue}\"" next end unless rehearsal @rescue_history[symbol] = manual_rescue File.open(@rescue_history_filepath, 'a').print(symbol, "\t", manual_rescue, "\n") end return manual_rescue end end end
ruby
def rescue_symbol(symbol, method = @rescue_method, rehearsal = false) return @rescue_history[symbol] if @rescue_history[symbol] case method when :auto auto_rescue = '' if @symbol2hgncid[symbol.upcase] auto_rescue = symbol.upcase elsif @symbol2hgncid[symbol.downcase] auto_rescue = symbol.downcase elsif @symbol2hgncid[symbol.delete('-')] auto_rescue = symbol.delete('-') elsif @symbol2hgncid[symbol.upcase.delete('-')] auto_rescue = symbol.upcase.delete('-') elsif @symbol2hgncid[symbol.downcase.delete('-')] auto_rescue = symbol.downcase.delete('-') # Add more rules here end # Record unless rehearsal BioTCM.logger.warn('HGNC') { "Unrecognized symbol \"#{symbol}\", \"#{auto_rescue}\" used instead" } @rescue_history[symbol] = auto_rescue end return auto_rescue when :manual # Try automatic rescue first if (auto_rescue = rescue_symbol(symbol, :auto, true)) != '' print "\"#{symbol}\" unrecognized. Use \"#{auto_rescue}\" instead? [Yn] " unless gets.chomp == 'n' @rescue_history[symbol] = auto_rescue unless rehearsal # rubocop:disable Metrics/BlockNesting return auto_rescue end end # Manually rescue loop do print "Please correct \"#{symbol}\" or press enter directly to return empty String instead:\n" unless (manual_rescue = gets.chomp) == '' || @symbol2hgncid[manual_rescue] puts "Failed to recognize \"#{manual_rescue}\"" next end unless rehearsal @rescue_history[symbol] = manual_rescue File.open(@rescue_history_filepath, 'a').print(symbol, "\t", manual_rescue, "\n") end return manual_rescue end end end
[ "def", "rescue_symbol", "(", "symbol", ",", "method", "=", "@rescue_method", ",", "rehearsal", "=", "false", ")", "return", "@rescue_history", "[", "symbol", "]", "if", "@rescue_history", "[", "symbol", "]", "case", "method", "when", ":auto", "auto_rescue", "=", "''", "if", "@symbol2hgncid", "[", "symbol", ".", "upcase", "]", "auto_rescue", "=", "symbol", ".", "upcase", "elsif", "@symbol2hgncid", "[", "symbol", ".", "downcase", "]", "auto_rescue", "=", "symbol", ".", "downcase", "elsif", "@symbol2hgncid", "[", "symbol", ".", "delete", "(", "'-'", ")", "]", "auto_rescue", "=", "symbol", ".", "delete", "(", "'-'", ")", "elsif", "@symbol2hgncid", "[", "symbol", ".", "upcase", ".", "delete", "(", "'-'", ")", "]", "auto_rescue", "=", "symbol", ".", "upcase", ".", "delete", "(", "'-'", ")", "elsif", "@symbol2hgncid", "[", "symbol", ".", "downcase", ".", "delete", "(", "'-'", ")", "]", "auto_rescue", "=", "symbol", ".", "downcase", ".", "delete", "(", "'-'", ")", "# Add more rules here", "end", "# Record", "unless", "rehearsal", "BioTCM", ".", "logger", ".", "warn", "(", "'HGNC'", ")", "{", "\"Unrecognized symbol \\\"#{symbol}\\\", \\\"#{auto_rescue}\\\" used instead\"", "}", "@rescue_history", "[", "symbol", "]", "=", "auto_rescue", "end", "return", "auto_rescue", "when", ":manual", "# Try automatic rescue first", "if", "(", "auto_rescue", "=", "rescue_symbol", "(", "symbol", ",", ":auto", ",", "true", ")", ")", "!=", "''", "print", "\"\\\"#{symbol}\\\" unrecognized. Use \\\"#{auto_rescue}\\\" instead? [Yn] \"", "unless", "gets", ".", "chomp", "==", "'n'", "@rescue_history", "[", "symbol", "]", "=", "auto_rescue", "unless", "rehearsal", "# rubocop:disable Metrics/BlockNesting", "return", "auto_rescue", "end", "end", "# Manually rescue", "loop", "do", "print", "\"Please correct \\\"#{symbol}\\\" or press enter directly to return empty String instead:\\n\"", "unless", "(", "manual_rescue", "=", "gets", ".", "chomp", ")", "==", "''", "||", "@symbol2hgncid", "[", "manual_rescue", "]", "puts", "\"Failed to recognize \\\"#{manual_rescue}\\\"\"", "next", "end", "unless", "rehearsal", "@rescue_history", "[", "symbol", "]", "=", "manual_rescue", "File", ".", "open", "(", "@rescue_history_filepath", ",", "'a'", ")", ".", "print", "(", "symbol", ",", "\"\\t\"", ",", "manual_rescue", ",", "\"\\n\"", ")", "end", "return", "manual_rescue", "end", "end", "end" ]
Try to rescue a gene symbol @param symbol [String] Gene symbol @param method [Symbol] :auto or :manual @param rehearsal [Boolean] When set to true, neither outputing warnings nor modifying rescue history @return [String] "" if rescue failed
[ "Try", "to", "rescue", "a", "gene", "symbol" ]
89b798acc1773087d9e8b754187c884d57fd06d7
https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/databases/hgnc/rescuer.rb#L34-L85
23,725
codez/seed-fu-ndo
lib/seed-fu-ndo/seeder.rb
SeedFu.Seeder.seed_with_undo
def seed_with_undo if r = SeedFuNdo.recorder r.record self # return existing records in case they are processed by the caller @data.map { |record_data| find_record(record_data) } else seed_without_undo end end
ruby
def seed_with_undo if r = SeedFuNdo.recorder r.record self # return existing records in case they are processed by the caller @data.map { |record_data| find_record(record_data) } else seed_without_undo end end
[ "def", "seed_with_undo", "if", "r", "=", "SeedFuNdo", ".", "recorder", "r", ".", "record", "self", "# return existing records in case they are processed by the caller", "@data", ".", "map", "{", "|", "record_data", "|", "find_record", "(", "record_data", ")", "}", "else", "seed_without_undo", "end", "end" ]
Record instead of inserting the data if in recording mode.
[ "Record", "instead", "of", "inserting", "the", "data", "if", "in", "recording", "mode", "." ]
342995939e204a2c55f580778fc7f7c442fc1499
https://github.com/codez/seed-fu-ndo/blob/342995939e204a2c55f580778fc7f7c442fc1499/lib/seed-fu-ndo/seeder.rb#L7-L16
23,726
spatchcock/quantify
lib/quantify/dimensions.rb
Quantify.Dimensions.units
def units(by=nil) Unit.units.values.select { |unit| unit.dimensions == self }.map(&by).to_a end
ruby
def units(by=nil) Unit.units.values.select { |unit| unit.dimensions == self }.map(&by).to_a end
[ "def", "units", "(", "by", "=", "nil", ")", "Unit", ".", "units", ".", "values", ".", "select", "{", "|", "unit", "|", "unit", ".", "dimensions", "==", "self", "}", ".", "map", "(", "by", ")", ".", "to_a", "end" ]
Returns an array containing the known units which represent the physical quantity described by self If no argument is given, the array holds instances of Unit::Base (or subclasses) which represent each unit. Alternatively only the names or symbols of each unit can be returned by providing the appropriate unit attribute as a symbolized argument, e.g. Dimensions.energy.units #=> [ #<Quantify::Dimensions: .. >, #<Quantify::Dimensions: .. >, ... ] Dimensions.mass.units :name #=> [ 'kilogram', 'ounce', 'pound', ... ] Dimensions.length.units :symbol #=> [ 'm', 'ft', 'yd', ... ]
[ "Returns", "an", "array", "containing", "the", "known", "units", "which", "represent", "the", "physical", "quantity", "described", "by", "self" ]
e99c1995491d49667c7e89a2843389e1d924b446
https://github.com/spatchcock/quantify/blob/e99c1995491d49667c7e89a2843389e1d924b446/lib/quantify/dimensions.rb#L276-L278
23,727
spatchcock/quantify
lib/quantify/dimensions.rb
Quantify.Dimensions.si_unit
def si_unit return Unit.steridian if describe == 'solid angle' return Unit.radian if describe == 'plane angle' val = si_base_units return nil unless val return val[0] if val.length == 1 val = val.inject(Unit.unity) do |compound,unit| compound * unit end val = val.or_equivalent unless val.acts_as_equivalent_unit end
ruby
def si_unit return Unit.steridian if describe == 'solid angle' return Unit.radian if describe == 'plane angle' val = si_base_units return nil unless val return val[0] if val.length == 1 val = val.inject(Unit.unity) do |compound,unit| compound * unit end val = val.or_equivalent unless val.acts_as_equivalent_unit end
[ "def", "si_unit", "return", "Unit", ".", "steridian", "if", "describe", "==", "'solid angle'", "return", "Unit", ".", "radian", "if", "describe", "==", "'plane angle'", "val", "=", "si_base_units", "return", "nil", "unless", "val", "return", "val", "[", "0", "]", "if", "val", ".", "length", "==", "1", "val", "=", "val", ".", "inject", "(", "Unit", ".", "unity", ")", "do", "|", "compound", ",", "unit", "|", "compound", "*", "unit", "end", "val", "=", "val", ".", "or_equivalent", "unless", "val", ".", "acts_as_equivalent_unit", "end" ]
Returns the SI unit for the physical quantity described by self. Plane/solid angle are special cases which are dimensionless units, and so are handled explicitly. Otherwise, the si base units for each of the base dimensions of self are indentified and the corresponding compound unit is derived. If this new unit is the same as a known (SI derived) unit, the known unit is returned. Dimensions.energy.units #=> #<Quantify::Dimensions: .. > Dimensions.energy.si_unit.name #=> 'joule' Dimensions.kinematic_viscosity.si_unit.name #=> 'metre squared per second'
[ "Returns", "the", "SI", "unit", "for", "the", "physical", "quantity", "described", "by", "self", "." ]
e99c1995491d49667c7e89a2843389e1d924b446
https://github.com/spatchcock/quantify/blob/e99c1995491d49667c7e89a2843389e1d924b446/lib/quantify/dimensions.rb#L296-L307
23,728
spatchcock/quantify
lib/quantify/dimensions.rb
Quantify.Dimensions.si_base_units
def si_base_units(by=nil) val = self.to_hash.map do |dimension, index| dimension_name = dimension.remove_underscores Unit.base_quantity_si_units.select do |unit| unit.measures == dimension_name end.first.clone ** index end val = val.map(&by) if by val.to_a end
ruby
def si_base_units(by=nil) val = self.to_hash.map do |dimension, index| dimension_name = dimension.remove_underscores Unit.base_quantity_si_units.select do |unit| unit.measures == dimension_name end.first.clone ** index end val = val.map(&by) if by val.to_a end
[ "def", "si_base_units", "(", "by", "=", "nil", ")", "val", "=", "self", ".", "to_hash", ".", "map", "do", "|", "dimension", ",", "index", "|", "dimension_name", "=", "dimension", ".", "remove_underscores", "Unit", ".", "base_quantity_si_units", ".", "select", "do", "|", "unit", "|", "unit", ".", "measures", "==", "dimension_name", "end", ".", "first", ".", "clone", "**", "index", "end", "val", "=", "val", ".", "map", "(", "by", ")", "if", "by", "val", ".", "to_a", "end" ]
Returns an array representing the base SI units for the physical quantity described by self If no argument is given, the array holds instances of Unit::Base (or subclasses) which represent each base unit. Alternatively only the names or symbols of each unit can be returned by providing the appropriate unit attribute as a symbolized argument, e.g. Dimensions.energy.si_base_units #=> [ #<Quantify::Unit: .. >, #<Quantify::Unit: .. >, ... ] Dimensions.energy.si_base_units :name #=> [ "metre squared", "per second squared", "kilogram"] Dimensions.force.units :symbol #=> [ "m", "s^-2", "kg"]
[ "Returns", "an", "array", "representing", "the", "base", "SI", "units", "for", "the", "physical", "quantity", "described", "by", "self" ]
e99c1995491d49667c7e89a2843389e1d924b446
https://github.com/spatchcock/quantify/blob/e99c1995491d49667c7e89a2843389e1d924b446/lib/quantify/dimensions.rb#L329-L339
23,729
spatchcock/quantify
lib/quantify/dimensions.rb
Quantify.Dimensions.init_base_quantities
def init_base_quantities(options = { }) if options.has_key?(:physical_quantity) pq = options.delete(:physical_quantity) self.physical_quantity = pq.remove_underscores.downcase if pq end options.each_pair do |base_quantity, index| base_quantity = base_quantity.to_s.downcase.to_sym unless index.is_a?(Integer) && BASE_QUANTITIES.include?(base_quantity) raise Exceptions::InvalidDimensionError, "An invalid base quantity was specified (#{base_quantity})" end if @base_quantity_hash.has_key?(base_quantity) new_index = @base_quantity_hash[base_quantity] + index if new_index == 0 @base_quantity_hash.delete(base_quantity) else @base_quantity_hash[base_quantity] = new_index end else @base_quantity_hash[base_quantity] = index end end end
ruby
def init_base_quantities(options = { }) if options.has_key?(:physical_quantity) pq = options.delete(:physical_quantity) self.physical_quantity = pq.remove_underscores.downcase if pq end options.each_pair do |base_quantity, index| base_quantity = base_quantity.to_s.downcase.to_sym unless index.is_a?(Integer) && BASE_QUANTITIES.include?(base_quantity) raise Exceptions::InvalidDimensionError, "An invalid base quantity was specified (#{base_quantity})" end if @base_quantity_hash.has_key?(base_quantity) new_index = @base_quantity_hash[base_quantity] + index if new_index == 0 @base_quantity_hash.delete(base_quantity) else @base_quantity_hash[base_quantity] = new_index end else @base_quantity_hash[base_quantity] = index end end end
[ "def", "init_base_quantities", "(", "options", "=", "{", "}", ")", "if", "options", ".", "has_key?", "(", ":physical_quantity", ")", "pq", "=", "options", ".", "delete", "(", ":physical_quantity", ")", "self", ".", "physical_quantity", "=", "pq", ".", "remove_underscores", ".", "downcase", "if", "pq", "end", "options", ".", "each_pair", "do", "|", "base_quantity", ",", "index", "|", "base_quantity", "=", "base_quantity", ".", "to_s", ".", "downcase", ".", "to_sym", "unless", "index", ".", "is_a?", "(", "Integer", ")", "&&", "BASE_QUANTITIES", ".", "include?", "(", "base_quantity", ")", "raise", "Exceptions", "::", "InvalidDimensionError", ",", "\"An invalid base quantity was specified (#{base_quantity})\"", "end", "if", "@base_quantity_hash", ".", "has_key?", "(", "base_quantity", ")", "new_index", "=", "@base_quantity_hash", "[", "base_quantity", "]", "+", "index", "if", "new_index", "==", "0", "@base_quantity_hash", ".", "delete", "(", "base_quantity", ")", "else", "@base_quantity_hash", "[", "base_quantity", "]", "=", "new_index", "end", "else", "@base_quantity_hash", "[", "base_quantity", "]", "=", "index", "end", "end", "end" ]
Method for initializing the base quantities of self. Where base quantities are already defined, the new indices are added to the existing ones. This represents the multiplication of base quantities (multiplication of similar quantities involves the addition of their powers). This method is therefore used in the multiplication of Dimensions objects, but also in divisions and raising of powers following other operations.
[ "Method", "for", "initializing", "the", "base", "quantities", "of", "self", "." ]
e99c1995491d49667c7e89a2843389e1d924b446
https://github.com/spatchcock/quantify/blob/e99c1995491d49667c7e89a2843389e1d924b446/lib/quantify/dimensions.rb#L506-L527
23,730
spatchcock/quantify
lib/quantify/quantity.rb
Quantify.Quantity.to_s
def to_s format=:symbol if format == :name unit_string = @value == 1 || @value == -1 ? @unit.name : @unit.pluralized_name else unit_string = @unit.send format end string = "#{@value}" string += " #{unit_string}" unless unit_string.empty? string end
ruby
def to_s format=:symbol if format == :name unit_string = @value == 1 || @value == -1 ? @unit.name : @unit.pluralized_name else unit_string = @unit.send format end string = "#{@value}" string += " #{unit_string}" unless unit_string.empty? string end
[ "def", "to_s", "format", "=", ":symbol", "if", "format", "==", ":name", "unit_string", "=", "@value", "==", "1", "||", "@value", "==", "-", "1", "?", "@unit", ".", "name", ":", "@unit", ".", "pluralized_name", "else", "unit_string", "=", "@unit", ".", "send", "format", "end", "string", "=", "\"#{@value}\"", "string", "+=", "\" #{unit_string}\"", "unless", "unit_string", ".", "empty?", "string", "end" ]
Returns a string representation of the quantity, using the unit symbol
[ "Returns", "a", "string", "representation", "of", "the", "quantity", "using", "the", "unit", "symbol" ]
e99c1995491d49667c7e89a2843389e1d924b446
https://github.com/spatchcock/quantify/blob/e99c1995491d49667c7e89a2843389e1d924b446/lib/quantify/quantity.rb#L178-L189
23,731
spatchcock/quantify
lib/quantify/quantity.rb
Quantify.Quantity.to_si
def to_si if @unit.is_compound_unit? Quantity.new(@value,@unit).convert_compound_unit_to_si! elsif @unit.is_dimensionless? return self.clone elsif @value.nil? return Quantity.new(nil, @unit.si_unit) else self.to(@unit.si_unit) end end
ruby
def to_si if @unit.is_compound_unit? Quantity.new(@value,@unit).convert_compound_unit_to_si! elsif @unit.is_dimensionless? return self.clone elsif @value.nil? return Quantity.new(nil, @unit.si_unit) else self.to(@unit.si_unit) end end
[ "def", "to_si", "if", "@unit", ".", "is_compound_unit?", "Quantity", ".", "new", "(", "@value", ",", "@unit", ")", ".", "convert_compound_unit_to_si!", "elsif", "@unit", ".", "is_dimensionless?", "return", "self", ".", "clone", "elsif", "@value", ".", "nil?", "return", "Quantity", ".", "new", "(", "nil", ",", "@unit", ".", "si_unit", ")", "else", "self", ".", "to", "(", "@unit", ".", "si_unit", ")", "end", "end" ]
Converts a quantity to the equivalent quantity using only SI units
[ "Converts", "a", "quantity", "to", "the", "equivalent", "quantity", "using", "only", "SI", "units" ]
e99c1995491d49667c7e89a2843389e1d924b446
https://github.com/spatchcock/quantify/blob/e99c1995491d49667c7e89a2843389e1d924b446/lib/quantify/quantity.rb#L232-L242
23,732
noprompt/vic
lib/vic/color_scheme.rb
Vic.ColorScheme.highlight!
def highlight!(group, attributes={}) highlight(group, attributes.dup.tap { |hash| hash[:force] = true }) end
ruby
def highlight!(group, attributes={}) highlight(group, attributes.dup.tap { |hash| hash[:force] = true }) end
[ "def", "highlight!", "(", "group", ",", "attributes", "=", "{", "}", ")", "highlight", "(", "group", ",", "attributes", ".", "dup", ".", "tap", "{", "|", "hash", "|", "hash", "[", ":force", "]", "=", "true", "}", ")", "end" ]
Add or update a forced highlight @example scheme.highlight!(:Normal, fg: 'eee', bg: '333').force? # => true @param [Hash] attributes the attributes to set or update @return [Vic::Highlight] the highlight @api public
[ "Add", "or", "update", "a", "forced", "highlight" ]
276e18fc5d81727023d3abfdf95829648818a9c4
https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/color_scheme.rb#L143-L145
23,733
noprompt/vic
lib/vic/color_scheme.rb
Vic.ColorScheme.link
def link(*from_groups, to_group) from_groups.flatten.map do |from_group| # Don't add anything we don't already have. next if find_link(from_group, to_group) link = Link.new(from_group, to_group) link.tap { |l| @links << l } end.compact end
ruby
def link(*from_groups, to_group) from_groups.flatten.map do |from_group| # Don't add anything we don't already have. next if find_link(from_group, to_group) link = Link.new(from_group, to_group) link.tap { |l| @links << l } end.compact end
[ "def", "link", "(", "*", "from_groups", ",", "to_group", ")", "from_groups", ".", "flatten", ".", "map", "do", "|", "from_group", "|", "# Don't add anything we don't already have.", "next", "if", "find_link", "(", "from_group", ",", "to_group", ")", "link", "=", "Link", ".", "new", "(", "from_group", ",", "to_group", ")", "link", ".", "tap", "{", "|", "l", "|", "@links", "<<", "l", "}", "end", ".", "compact", "end" ]
Add highlight links to the colorscheme @example scheme.link(:rubyInstanceVariable, :rubyClassVariable) @param [String,Symbol] from_groups a list of groups to link from @param [String,Symbol] to_groups the group to link to @return [Array] the added links @api public
[ "Add", "highlight", "links", "to", "the", "colorscheme" ]
276e18fc5d81727023d3abfdf95829648818a9c4
https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/color_scheme.rb#L173-L180
23,734
noprompt/vic
lib/vic/color_scheme.rb
Vic.ColorScheme.link!
def link!(*from_groups, to_group) # Use the default method first. self.link(from_groups, to_group) # Then update the links. from_groups.flatten.map do |from_group| link = find_link(from_group, to_group) link.tap(&:force!) end end
ruby
def link!(*from_groups, to_group) # Use the default method first. self.link(from_groups, to_group) # Then update the links. from_groups.flatten.map do |from_group| link = find_link(from_group, to_group) link.tap(&:force!) end end
[ "def", "link!", "(", "*", "from_groups", ",", "to_group", ")", "# Use the default method first.", "self", ".", "link", "(", "from_groups", ",", "to_group", ")", "# Then update the links.", "from_groups", ".", "flatten", ".", "map", "do", "|", "from_group", "|", "link", "=", "find_link", "(", "from_group", ",", "to_group", ")", "link", ".", "tap", "(", ":force!", ")", "end", "end" ]
Add forced highlight links to the colorscheme @example scheme.link!(:rubyInstanceVariable, :rubyClassVariable) link = scheme.links.find do |l| l.from_group == :rubyInstanceVariable and l.to_group = :rubyClassVariable end link.force? # => true @param [String,Symbol] from_groups a list of groups to link from @param [String,Symbol] to_groups the group to link to @return [Array] the added/updated links @api public
[ "Add", "forced", "highlight", "links", "to", "the", "colorscheme" ]
276e18fc5d81727023d3abfdf95829648818a9c4
https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/color_scheme.rb#L201-L210
23,735
noprompt/vic
lib/vic/color_scheme.rb
Vic.ColorScheme.language
def language(name = nil, &block) return @language unless name and block_given? previous_language = self.language @language = name block.arity == 0 ? instance_eval(&block) : yield(self) @language = previous_language end
ruby
def language(name = nil, &block) return @language unless name and block_given? previous_language = self.language @language = name block.arity == 0 ? instance_eval(&block) : yield(self) @language = previous_language end
[ "def", "language", "(", "name", "=", "nil", ",", "&", "block", ")", "return", "@language", "unless", "name", "and", "block_given?", "previous_language", "=", "self", ".", "language", "@language", "=", "name", "block", ".", "arity", "==", "0", "?", "instance_eval", "(", "block", ")", ":", "yield", "(", "self", ")", "@language", "=", "previous_language", "end" ]
Return the language If a name and a block is passed the language will be temporarily set to name inside the block. @example scheme.language :ruby do |s| s.hi(:InstanceVariable) s.hi(:ClassVariable) end scheme.highlights.any? { |h| h.group == :rubyClassVarible } # => true @param [String,Symbol] name the language to temporarily set if a block is given @yieldparam [Vic::Colorscheme] the colorscheme @return [String,Symbol] the language setting @api public
[ "Return", "the", "language" ]
276e18fc5d81727023d3abfdf95829648818a9c4
https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/color_scheme.rb#L251-L258
23,736
rightscale/right_scraper
lib/right_scraper/scanners/cookbook_metadata_readonly.rb
RightScraper::Scanners.CookbookMetadataReadOnly.generated_metadata_json_readonly
def generated_metadata_json_readonly @logger.operation(:metadata_readonly) do # path constants freed_metadata_dir = (@cookbook.pos == '.' && freed_dir) || ::File.join(freed_dir, @cookbook.pos) freed_metadata_json_path = ::File.join(freed_metadata_dir, JSON_METADATA) # in the multi-pass case we will run this scanner only on the second # and any subsequent passed, which are outside of containment. the # metadata must have already been generated at this point or else it # should be considered an internal error. return ::File.read(freed_metadata_json_path) end end
ruby
def generated_metadata_json_readonly @logger.operation(:metadata_readonly) do # path constants freed_metadata_dir = (@cookbook.pos == '.' && freed_dir) || ::File.join(freed_dir, @cookbook.pos) freed_metadata_json_path = ::File.join(freed_metadata_dir, JSON_METADATA) # in the multi-pass case we will run this scanner only on the second # and any subsequent passed, which are outside of containment. the # metadata must have already been generated at this point or else it # should be considered an internal error. return ::File.read(freed_metadata_json_path) end end
[ "def", "generated_metadata_json_readonly", "@logger", ".", "operation", "(", ":metadata_readonly", ")", "do", "# path constants", "freed_metadata_dir", "=", "(", "@cookbook", ".", "pos", "==", "'.'", "&&", "freed_dir", ")", "||", "::", "File", ".", "join", "(", "freed_dir", ",", "@cookbook", ".", "pos", ")", "freed_metadata_json_path", "=", "::", "File", ".", "join", "(", "freed_metadata_dir", ",", "JSON_METADATA", ")", "# in the multi-pass case we will run this scanner only on the second", "# and any subsequent passed, which are outside of containment. the", "# metadata must have already been generated at this point or else it", "# should be considered an internal error.", "return", "::", "File", ".", "read", "(", "freed_metadata_json_path", ")", "end", "end" ]
Reads the existing generated 'metadata.json' or else fails. === Returns @return [String] metadata JSON text
[ "Reads", "the", "existing", "generated", "metadata", ".", "json", "or", "else", "fails", "." ]
8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae
https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata_readonly.rb#L58-L70
23,737
aidistan/ruby-biotcm
lib/biotcm/layer.rb
BioTCM.Layer.save
def save(path, prefix = '') FileUtils.mkdir_p(path) @edge_tab.save(File.expand_path(prefix + 'edges.tab', path)) @node_tab.save(File.expand_path(prefix + 'nodes.tab', path)) end
ruby
def save(path, prefix = '') FileUtils.mkdir_p(path) @edge_tab.save(File.expand_path(prefix + 'edges.tab', path)) @node_tab.save(File.expand_path(prefix + 'nodes.tab', path)) end
[ "def", "save", "(", "path", ",", "prefix", "=", "''", ")", "FileUtils", ".", "mkdir_p", "(", "path", ")", "@edge_tab", ".", "save", "(", "File", ".", "expand_path", "(", "prefix", "+", "'edges.tab'", ",", "path", ")", ")", "@node_tab", ".", "save", "(", "File", ".", "expand_path", "(", "prefix", "+", "'nodes.tab'", ",", "path", ")", ")", "end" ]
Create a layer from an edge tab and a node tab @param edge_tab [Table] @param node_tab [Table] Save the layer to disk @param path [String] path to output directory @param prefix [String]
[ "Create", "a", "layer", "from", "an", "edge", "tab", "and", "a", "node", "tab" ]
89b798acc1773087d9e8b754187c884d57fd06d7
https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/layer.rb#L120-L124
23,738
rightscale/right_scraper
lib/right_scraper/main.rb
RightScraper.Main.scrape
def scrape(repo, incremental=true, &callback) old_logger_callback = @logger.callback @logger.callback = callback errorlen = errors.size begin if retrieved = retrieve(repo) scan(retrieved) end rescue Exception # legacy logger handles communication with the end user and appending # to our error list; we just need to keep going. the new methodology # has no such guaranteed communication so the caller will decide how to # handle errors, etc. ensure @logger.callback = old_logger_callback cleanup end errors.size == errorlen end
ruby
def scrape(repo, incremental=true, &callback) old_logger_callback = @logger.callback @logger.callback = callback errorlen = errors.size begin if retrieved = retrieve(repo) scan(retrieved) end rescue Exception # legacy logger handles communication with the end user and appending # to our error list; we just need to keep going. the new methodology # has no such guaranteed communication so the caller will decide how to # handle errors, etc. ensure @logger.callback = old_logger_callback cleanup end errors.size == errorlen end
[ "def", "scrape", "(", "repo", ",", "incremental", "=", "true", ",", "&", "callback", ")", "old_logger_callback", "=", "@logger", ".", "callback", "@logger", ".", "callback", "=", "callback", "errorlen", "=", "errors", ".", "size", "begin", "if", "retrieved", "=", "retrieve", "(", "repo", ")", "scan", "(", "retrieved", ")", "end", "rescue", "Exception", "# legacy logger handles communication with the end user and appending", "# to our error list; we just need to keep going. the new methodology", "# has no such guaranteed communication so the caller will decide how to", "# handle errors, etc.", "ensure", "@logger", ".", "callback", "=", "old_logger_callback", "cleanup", "end", "errors", ".", "size", "==", "errorlen", "end" ]
Initialize scrape destination directory === Options <tt>:kind</tt>:: Type of scraper that will traverse directory for resources, one of :cookbook or :workflow <tt>:basedir</tt>:: Local directory where files are retrieved and scraped, use temporary directory if nil <tt>:max_bytes</tt>:: Maximum number of bytes to read from remote repo, unlimited if nil <tt>:max_seconds</tt>:: Maximum number of seconds to spend reading from remote repo, unlimited if nil Scrapes and scans a given repository. @deprecated the newer methodology will perform these operations in stages controlled externally instead of calling this all-in-one method. === Parameters repo(Hash|RightScraper::Repositories::Base):: Repository to be scraped Note: repo can either be a Hash or a RightScraper::Repositories::Base instance. See the RightScraper::Repositories::Base class for valid Hash keys. === Block If a block is given, it will be called back with progress information the block should take four arguments: - first argument is one of <tt>:begin</tt>, <tt>:commit</tt>, <tt>:abort</tt> which signifies what the scraper is trying to do and where it is when it does it - second argument is a symbol describing the operation being performed in an easy-to-match way - third argument is optional further explanation - fourth argument is the exception pending (only relevant for <tt>:abort</tt>) === Return true:: If scrape was successful false:: If scrape failed, call errors for information on failure === Raise 'Invalid repository type':: If repository type is not known
[ "Initialize", "scrape", "destination", "directory" ]
8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae
https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/main.rb#L110-L128
23,739
rightscale/right_scraper
lib/right_scraper/retrievers/download.rb
RightScraper::Retrievers.Download.retrieve
def retrieve raise RetrieverError.new("download retriever is unavailable") unless available? ::FileUtils.remove_entry_secure @repo_dir if File.exists?(@repo_dir) ::FileUtils.remove_entry_secure workdir if File.exists?(workdir) ::FileUtils.mkdir_p @repo_dir ::FileUtils.mkdir_p workdir file = ::File.join(workdir, "package") # TEAL FIX: we have to always-download the tarball before we can # determine if contents have changed, but afterward we can compare the # previous download against the latest downloaded and short-circuit the # remaining flow for the no-difference case. @logger.operation(:downloading) do credential_command = if @repository.first_credential && @repository.second_credential ['-u', "#{@repository.first_credential}:#{@repository.second_credential}"] else [] end @output = ::RightScale::RightPopen::SafeOutputBuffer.new @cmd = [ 'curl', '--silent', '--show-error', '--location', '--fail', '--location-trusted', '-o', file, credential_command, @repository.url ].flatten begin ::RightScale::RightPopen.popen3_sync( @cmd, :target => self, :pid_handler => :pid_download, :timeout_handler => :timeout_download, :size_limit_handler => :size_limit_download, :exit_handler => :exit_download, :stderr_handler => :output_download, :stdout_handler => :output_download, :inherit_io => true, # avoid killing any rails connection :watch_directory => workdir, :size_limit_bytes => @max_bytes, :timeout_seconds => @max_seconds) rescue Exception => e @logger.note_phase(:abort, :running_command, 'curl', e) raise end end note_tag(file) @logger.operation(:unpacking) do path = @repository.to_url.path if path =~ /\.gz$/ extraction = "xzf" elsif path =~ /\.bz2$/ extraction = "xjf" else extraction = "xf" end Dir.chdir(@repo_dir) do @output = ::RightScale::RightPopen::SafeOutputBuffer.new @cmd = ['tar', extraction, file] begin ::RightScale::RightPopen.popen3_sync( @cmd, :target => self, :pid_handler => :pid_download, :timeout_handler => :timeout_download, :size_limit_handler => :size_limit_download, :exit_handler => :exit_download, :stderr_handler => :output_download, :stdout_handler => :output_download, :inherit_io => true, # avoid killing any rails connection :watch_directory => @repo_dir, :size_limit_bytes => @max_bytes, :timeout_seconds => @max_seconds) rescue Exception => e @logger.note_phase(:abort, :running_command, @cmd.first, e) raise end end end true end
ruby
def retrieve raise RetrieverError.new("download retriever is unavailable") unless available? ::FileUtils.remove_entry_secure @repo_dir if File.exists?(@repo_dir) ::FileUtils.remove_entry_secure workdir if File.exists?(workdir) ::FileUtils.mkdir_p @repo_dir ::FileUtils.mkdir_p workdir file = ::File.join(workdir, "package") # TEAL FIX: we have to always-download the tarball before we can # determine if contents have changed, but afterward we can compare the # previous download against the latest downloaded and short-circuit the # remaining flow for the no-difference case. @logger.operation(:downloading) do credential_command = if @repository.first_credential && @repository.second_credential ['-u', "#{@repository.first_credential}:#{@repository.second_credential}"] else [] end @output = ::RightScale::RightPopen::SafeOutputBuffer.new @cmd = [ 'curl', '--silent', '--show-error', '--location', '--fail', '--location-trusted', '-o', file, credential_command, @repository.url ].flatten begin ::RightScale::RightPopen.popen3_sync( @cmd, :target => self, :pid_handler => :pid_download, :timeout_handler => :timeout_download, :size_limit_handler => :size_limit_download, :exit_handler => :exit_download, :stderr_handler => :output_download, :stdout_handler => :output_download, :inherit_io => true, # avoid killing any rails connection :watch_directory => workdir, :size_limit_bytes => @max_bytes, :timeout_seconds => @max_seconds) rescue Exception => e @logger.note_phase(:abort, :running_command, 'curl', e) raise end end note_tag(file) @logger.operation(:unpacking) do path = @repository.to_url.path if path =~ /\.gz$/ extraction = "xzf" elsif path =~ /\.bz2$/ extraction = "xjf" else extraction = "xf" end Dir.chdir(@repo_dir) do @output = ::RightScale::RightPopen::SafeOutputBuffer.new @cmd = ['tar', extraction, file] begin ::RightScale::RightPopen.popen3_sync( @cmd, :target => self, :pid_handler => :pid_download, :timeout_handler => :timeout_download, :size_limit_handler => :size_limit_download, :exit_handler => :exit_download, :stderr_handler => :output_download, :stdout_handler => :output_download, :inherit_io => true, # avoid killing any rails connection :watch_directory => @repo_dir, :size_limit_bytes => @max_bytes, :timeout_seconds => @max_seconds) rescue Exception => e @logger.note_phase(:abort, :running_command, @cmd.first, e) raise end end end true end
[ "def", "retrieve", "raise", "RetrieverError", ".", "new", "(", "\"download retriever is unavailable\"", ")", "unless", "available?", "::", "FileUtils", ".", "remove_entry_secure", "@repo_dir", "if", "File", ".", "exists?", "(", "@repo_dir", ")", "::", "FileUtils", ".", "remove_entry_secure", "workdir", "if", "File", ".", "exists?", "(", "workdir", ")", "::", "FileUtils", ".", "mkdir_p", "@repo_dir", "::", "FileUtils", ".", "mkdir_p", "workdir", "file", "=", "::", "File", ".", "join", "(", "workdir", ",", "\"package\"", ")", "# TEAL FIX: we have to always-download the tarball before we can", "# determine if contents have changed, but afterward we can compare the", "# previous download against the latest downloaded and short-circuit the", "# remaining flow for the no-difference case.", "@logger", ".", "operation", "(", ":downloading", ")", "do", "credential_command", "=", "if", "@repository", ".", "first_credential", "&&", "@repository", ".", "second_credential", "[", "'-u'", ",", "\"#{@repository.first_credential}:#{@repository.second_credential}\"", "]", "else", "[", "]", "end", "@output", "=", "::", "RightScale", "::", "RightPopen", "::", "SafeOutputBuffer", ".", "new", "@cmd", "=", "[", "'curl'", ",", "'--silent'", ",", "'--show-error'", ",", "'--location'", ",", "'--fail'", ",", "'--location-trusted'", ",", "'-o'", ",", "file", ",", "credential_command", ",", "@repository", ".", "url", "]", ".", "flatten", "begin", "::", "RightScale", "::", "RightPopen", ".", "popen3_sync", "(", "@cmd", ",", ":target", "=>", "self", ",", ":pid_handler", "=>", ":pid_download", ",", ":timeout_handler", "=>", ":timeout_download", ",", ":size_limit_handler", "=>", ":size_limit_download", ",", ":exit_handler", "=>", ":exit_download", ",", ":stderr_handler", "=>", ":output_download", ",", ":stdout_handler", "=>", ":output_download", ",", ":inherit_io", "=>", "true", ",", "# avoid killing any rails connection", ":watch_directory", "=>", "workdir", ",", ":size_limit_bytes", "=>", "@max_bytes", ",", ":timeout_seconds", "=>", "@max_seconds", ")", "rescue", "Exception", "=>", "e", "@logger", ".", "note_phase", "(", ":abort", ",", ":running_command", ",", "'curl'", ",", "e", ")", "raise", "end", "end", "note_tag", "(", "file", ")", "@logger", ".", "operation", "(", ":unpacking", ")", "do", "path", "=", "@repository", ".", "to_url", ".", "path", "if", "path", "=~", "/", "\\.", "/", "extraction", "=", "\"xzf\"", "elsif", "path", "=~", "/", "\\.", "/", "extraction", "=", "\"xjf\"", "else", "extraction", "=", "\"xf\"", "end", "Dir", ".", "chdir", "(", "@repo_dir", ")", "do", "@output", "=", "::", "RightScale", "::", "RightPopen", "::", "SafeOutputBuffer", ".", "new", "@cmd", "=", "[", "'tar'", ",", "extraction", ",", "file", "]", "begin", "::", "RightScale", "::", "RightPopen", ".", "popen3_sync", "(", "@cmd", ",", ":target", "=>", "self", ",", ":pid_handler", "=>", ":pid_download", ",", ":timeout_handler", "=>", ":timeout_download", ",", ":size_limit_handler", "=>", ":size_limit_download", ",", ":exit_handler", "=>", ":exit_download", ",", ":stderr_handler", "=>", ":output_download", ",", ":stdout_handler", "=>", ":output_download", ",", ":inherit_io", "=>", "true", ",", "# avoid killing any rails connection", ":watch_directory", "=>", "@repo_dir", ",", ":size_limit_bytes", "=>", "@max_bytes", ",", ":timeout_seconds", "=>", "@max_seconds", ")", "rescue", "Exception", "=>", "e", "@logger", ".", "note_phase", "(", ":abort", ",", ":running_command", ",", "@cmd", ".", "first", ",", "e", ")", "raise", "end", "end", "end", "true", "end" ]
Download tarball and unpack it
[ "Download", "tarball", "and", "unpack", "it" ]
8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae
https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/download.rb#L69-L149
23,740
gively/cadmus
lib/cadmus/renderers.rb
Cadmus.Renderable.setup_renderer
def setup_renderer(renderer) renderer.default_assigns = liquid_assigns if respond_to?(:liquid_assigns, true) renderer.default_registers = liquid_registers if respond_to?(:liquid_registers, true) renderer.default_filters = liquid_filters if respond_to?(:liquid_filters, true) end
ruby
def setup_renderer(renderer) renderer.default_assigns = liquid_assigns if respond_to?(:liquid_assigns, true) renderer.default_registers = liquid_registers if respond_to?(:liquid_registers, true) renderer.default_filters = liquid_filters if respond_to?(:liquid_filters, true) end
[ "def", "setup_renderer", "(", "renderer", ")", "renderer", ".", "default_assigns", "=", "liquid_assigns", "if", "respond_to?", "(", ":liquid_assigns", ",", "true", ")", "renderer", ".", "default_registers", "=", "liquid_registers", "if", "respond_to?", "(", ":liquid_registers", ",", "true", ")", "renderer", ".", "default_filters", "=", "liquid_filters", "if", "respond_to?", "(", ":liquid_filters", ",", "true", ")", "end" ]
Sets the values of +default_assigns+, +default_registers+ and +default_filters+ on a given renderer using the +liquid_assigns+, +liquid_registers+ and +liquid_filters+ methods, if they're defined.
[ "Sets", "the", "values", "of", "+", "default_assigns", "+", "+", "default_registers", "+", "and", "+", "default_filters", "+", "on", "a", "given", "renderer", "using", "the", "+", "liquid_assigns", "+", "+", "liquid_registers", "+", "and", "+", "liquid_filters", "+", "methods", "if", "they", "re", "defined", "." ]
5e0f8b6404da14e320d858eb8dacd12ae79dcfb0
https://github.com/gively/cadmus/blob/5e0f8b6404da14e320d858eb8dacd12ae79dcfb0/lib/cadmus/renderers.rb#L118-L122
23,741
fixrb/spectus
lib/spectus/expectation_target.rb
Spectus.ExpectationTarget.MUST
def MUST(m) RequirementLevel::High.new(m, false, subject, *challenges).result end
ruby
def MUST(m) RequirementLevel::High.new(m, false, subject, *challenges).result end
[ "def", "MUST", "(", "m", ")", "RequirementLevel", "::", "High", ".", "new", "(", "m", ",", "false", ",", "subject", ",", "challenges", ")", ".", "result", "end" ]
Create a new expection target @api private @param subject [Proc] The value which is compared with the expected value. rubocop:disable Style/MethodName rubocop:disable Naming/UncommunicativeMethodParamName @api public This word, or the terms "REQUIRED" or "SHALL", mean that the definition is an absolute requirement of the specification. @example _Absolute requirement_ definition it { 'foo'.upcase }.MUST eql 'FOO' @param m [#matches?] The matcher. @return [Result::Fail, Result::Pass] Report if the spec pass or fail.
[ "Create", "a", "new", "expection", "target" ]
547d994dede16de462f52f960948b80fa71fb515
https://github.com/fixrb/spectus/blob/547d994dede16de462f52f960948b80fa71fb515/lib/spectus/expectation_target.rb#L37-L39
23,742
fixrb/spectus
lib/spectus/expectation_target.rb
Spectus.ExpectationTarget.MUST_NOT
def MUST_NOT(m) RequirementLevel::High.new(m, true, subject, *challenges).result end
ruby
def MUST_NOT(m) RequirementLevel::High.new(m, true, subject, *challenges).result end
[ "def", "MUST_NOT", "(", "m", ")", "RequirementLevel", "::", "High", ".", "new", "(", "m", ",", "true", ",", "subject", ",", "challenges", ")", ".", "result", "end" ]
This phrase, or the phrase "SHALL NOT", mean that the definition is an absolute prohibition of the specification. @example _Absolute prohibition_ definition it { 'foo'.size }.MUST_NOT equal 42 @param m [#matches?] The matcher. @return [Result::Fail, Result::Pass] Report if the spec pass or fail.
[ "This", "phrase", "or", "the", "phrase", "SHALL", "NOT", "mean", "that", "the", "definition", "is", "an", "absolute", "prohibition", "of", "the", "specification", "." ]
547d994dede16de462f52f960948b80fa71fb515
https://github.com/fixrb/spectus/blob/547d994dede16de462f52f960948b80fa71fb515/lib/spectus/expectation_target.rb#L58-L60
23,743
fixrb/spectus
lib/spectus/expectation_target.rb
Spectus.ExpectationTarget.SHOULD
def SHOULD(m) RequirementLevel::Medium.new(m, false, subject, *challenges).result end
ruby
def SHOULD(m) RequirementLevel::Medium.new(m, false, subject, *challenges).result end
[ "def", "SHOULD", "(", "m", ")", "RequirementLevel", "::", "Medium", ".", "new", "(", "m", ",", "false", ",", "subject", ",", "challenges", ")", ".", "result", "end" ]
This word, or the adjective "RECOMMENDED", mean that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course. @example _Recommended_ definition it { 'foo'.valid_encoding? }.SHOULD equal true @param m [#matches?] The matcher. @return [Result::Fail, Result::Pass] Report if the spec pass or fail.
[ "This", "word", "or", "the", "adjective", "RECOMMENDED", "mean", "that", "there", "may", "exist", "valid", "reasons", "in", "particular", "circumstances", "to", "ignore", "a", "particular", "item", "but", "the", "full", "implications", "must", "be", "understood", "and", "carefully", "weighed", "before", "choosing", "a", "different", "course", "." ]
547d994dede16de462f52f960948b80fa71fb515
https://github.com/fixrb/spectus/blob/547d994dede16de462f52f960948b80fa71fb515/lib/spectus/expectation_target.rb#L81-L83
23,744
fixrb/spectus
lib/spectus/expectation_target.rb
Spectus.ExpectationTarget.SHOULD_NOT
def SHOULD_NOT(m) RequirementLevel::Medium.new(m, true, subject, *challenges).result end
ruby
def SHOULD_NOT(m) RequirementLevel::Medium.new(m, true, subject, *challenges).result end
[ "def", "SHOULD_NOT", "(", "m", ")", "RequirementLevel", "::", "Medium", ".", "new", "(", "m", ",", "true", ",", "subject", ",", "challenges", ")", ".", "result", "end" ]
This phrase, or the phrase "NOT RECOMMENDED" mean that there may exist valid reasons in particular circumstances when the particular behavior is acceptable or even useful, but the full implications should be understood and the case carefully weighed before implementing any behavior described with this label. @example _Not recommended_ definition it { ''.blank? }.SHOULD_NOT raise_exception NoMethodError @param m [#matches?] The matcher. @return [Result::Fail, Result::Pass] Report if the spec pass or fail.
[ "This", "phrase", "or", "the", "phrase", "NOT", "RECOMMENDED", "mean", "that", "there", "may", "exist", "valid", "reasons", "in", "particular", "circumstances", "when", "the", "particular", "behavior", "is", "acceptable", "or", "even", "useful", "but", "the", "full", "implications", "should", "be", "understood", "and", "the", "case", "carefully", "weighed", "before", "implementing", "any", "behavior", "described", "with", "this", "label", "." ]
547d994dede16de462f52f960948b80fa71fb515
https://github.com/fixrb/spectus/blob/547d994dede16de462f52f960948b80fa71fb515/lib/spectus/expectation_target.rb#L105-L107
23,745
rightscale/right_scraper
lib/right_scraper/scrapers/cookbook.rb
RightScraper::Scrapers.Cookbook.find_next
def find_next(dir) @logger.operation(:finding_next_cookbook, "in #{dir.path}") do if COOKBOOK_SENTINELS.any? { |f| File.exists?(File.join(dir.path, f)) } @logger.operation(:reading_cookbook, "from #{dir.path}") do cookbook = RightScraper::Resources::Cookbook.new( @repository, strip_repo_dir(dir.path), repo_dir) @builder.go(dir.path, cookbook) cookbook end else @stack << dir search_dirs end end end
ruby
def find_next(dir) @logger.operation(:finding_next_cookbook, "in #{dir.path}") do if COOKBOOK_SENTINELS.any? { |f| File.exists?(File.join(dir.path, f)) } @logger.operation(:reading_cookbook, "from #{dir.path}") do cookbook = RightScraper::Resources::Cookbook.new( @repository, strip_repo_dir(dir.path), repo_dir) @builder.go(dir.path, cookbook) cookbook end else @stack << dir search_dirs end end end
[ "def", "find_next", "(", "dir", ")", "@logger", ".", "operation", "(", ":finding_next_cookbook", ",", "\"in #{dir.path}\"", ")", "do", "if", "COOKBOOK_SENTINELS", ".", "any?", "{", "|", "f", "|", "File", ".", "exists?", "(", "File", ".", "join", "(", "dir", ".", "path", ",", "f", ")", ")", "}", "@logger", ".", "operation", "(", ":reading_cookbook", ",", "\"from #{dir.path}\"", ")", "do", "cookbook", "=", "RightScraper", "::", "Resources", "::", "Cookbook", ".", "new", "(", "@repository", ",", "strip_repo_dir", "(", "dir", ".", "path", ")", ",", "repo_dir", ")", "@builder", ".", "go", "(", "dir", ".", "path", ",", "cookbook", ")", "cookbook", "end", "else", "@stack", "<<", "dir", "search_dirs", "end", "end", "end" ]
Find the next cookbook, starting in dir. === Parameters dir(Dir):: directory to begin search in
[ "Find", "the", "next", "cookbook", "starting", "in", "dir", "." ]
8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae
https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scrapers/cookbook.rb#L37-L53
23,746
rightscale/right_scraper
lib/right_scraper/scrapers/base.rb
RightScraper::Scrapers.Base.search_dirs
def search_dirs @logger.operation(:searching) do until @stack.empty? dir = @stack.last entry = dir.read if entry == nil dir.close @stack.pop next end next if entry == '.' || entry == '..' next if ignorable?(entry) fullpath = File.join(dir.path, entry) if File.directory?(fullpath) result = find_next(Dir.new(fullpath)) break end end result end end
ruby
def search_dirs @logger.operation(:searching) do until @stack.empty? dir = @stack.last entry = dir.read if entry == nil dir.close @stack.pop next end next if entry == '.' || entry == '..' next if ignorable?(entry) fullpath = File.join(dir.path, entry) if File.directory?(fullpath) result = find_next(Dir.new(fullpath)) break end end result end end
[ "def", "search_dirs", "@logger", ".", "operation", "(", ":searching", ")", "do", "until", "@stack", ".", "empty?", "dir", "=", "@stack", ".", "last", "entry", "=", "dir", ".", "read", "if", "entry", "==", "nil", "dir", ".", "close", "@stack", ".", "pop", "next", "end", "next", "if", "entry", "==", "'.'", "||", "entry", "==", "'..'", "next", "if", "ignorable?", "(", "entry", ")", "fullpath", "=", "File", ".", "join", "(", "dir", ".", "path", ",", "entry", ")", "if", "File", ".", "directory?", "(", "fullpath", ")", "result", "=", "find_next", "(", "Dir", ".", "new", "(", "fullpath", ")", ")", "break", "end", "end", "result", "end", "end" ]
Search the directory stack looking for the next resource.
[ "Search", "the", "directory", "stack", "looking", "for", "the", "next", "resource", "." ]
8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae
https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scrapers/base.rb#L247-L270
23,747
rightscale/right_scraper
lib/right_scraper/scanners/union.rb
RightScraper::Scanners.Union.notice
def notice(relative_position) data = nil @subscanners.each {|scanner| scanner.notice(relative_position) { data = yield if data.nil? data } } end
ruby
def notice(relative_position) data = nil @subscanners.each {|scanner| scanner.notice(relative_position) { data = yield if data.nil? data } } end
[ "def", "notice", "(", "relative_position", ")", "data", "=", "nil", "@subscanners", ".", "each", "{", "|", "scanner", "|", "scanner", ".", "notice", "(", "relative_position", ")", "{", "data", "=", "yield", "if", "data", ".", "nil?", "data", "}", "}", "end" ]
Notice a file during scanning. === Block Return the data for this file. We use a block because it may not always be necessary to read the data. === Parameters relative_position(String):: relative pathname for the file from the root of resource
[ "Notice", "a", "file", "during", "scanning", "." ]
8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae
https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/union.rb#L71-L78
23,748
rightscale/right_scraper
spec/spec_helper.rb
RightScraper.SpecHelpers.create_file_layout
def create_file_layout(path, layout) FileUtils.mkdir_p(path) result = [] layout.each do |elem| if elem.is_a?(Hash) elem.each do |k, v| full_path = File.join(path, k) FileUtils.mkdir_p(full_path) result += create_file_layout(full_path, v) end elsif elem.is_a?(FileContent) fullpath = ::File.join(path, elem.name) File.open(fullpath, 'w') { |f| f.write elem.content } result << fullpath else fullpath = ::File.join(path, elem.to_s) File.open(fullpath, 'w') { |f| f.puts elem.to_s } result << fullpath end end result end
ruby
def create_file_layout(path, layout) FileUtils.mkdir_p(path) result = [] layout.each do |elem| if elem.is_a?(Hash) elem.each do |k, v| full_path = File.join(path, k) FileUtils.mkdir_p(full_path) result += create_file_layout(full_path, v) end elsif elem.is_a?(FileContent) fullpath = ::File.join(path, elem.name) File.open(fullpath, 'w') { |f| f.write elem.content } result << fullpath else fullpath = ::File.join(path, elem.to_s) File.open(fullpath, 'w') { |f| f.puts elem.to_s } result << fullpath end end result end
[ "def", "create_file_layout", "(", "path", ",", "layout", ")", "FileUtils", ".", "mkdir_p", "(", "path", ")", "result", "=", "[", "]", "layout", ".", "each", "do", "|", "elem", "|", "if", "elem", ".", "is_a?", "(", "Hash", ")", "elem", ".", "each", "do", "|", "k", ",", "v", "|", "full_path", "=", "File", ".", "join", "(", "path", ",", "k", ")", "FileUtils", ".", "mkdir_p", "(", "full_path", ")", "result", "+=", "create_file_layout", "(", "full_path", ",", "v", ")", "end", "elsif", "elem", ".", "is_a?", "(", "FileContent", ")", "fullpath", "=", "::", "File", ".", "join", "(", "path", ",", "elem", ".", "name", ")", "File", ".", "open", "(", "fullpath", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "elem", ".", "content", "}", "result", "<<", "fullpath", "else", "fullpath", "=", "::", "File", ".", "join", "(", "path", ",", "elem", ".", "to_s", ")", "File", ".", "open", "(", "fullpath", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "puts", "elem", ".", "to_s", "}", "result", "<<", "fullpath", "end", "end", "result", "end" ]
Create file layout from given array Strings in array correspond to files while Hashes correspond to folders File content is equal to filename === Parameters @param [String] path where layout should be created @param [Array] layout to be created === Return @return [Array] list of created file paths
[ "Create", "file", "layout", "from", "given", "array", "Strings", "in", "array", "correspond", "to", "files", "while", "Hashes", "correspond", "to", "folders", "File", "content", "is", "equal", "to", "filename" ]
8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae
https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/spec/spec_helper.rb#L181-L202
23,749
rightscale/right_scraper
spec/spec_helper.rb
RightScraper.SpecHelpers.extract_file_layout
def extract_file_layout(path, ignore=[]) return [] unless File.directory?(path) dirs = [] files = [] ignore += [ '.', '..' ] Dir.foreach(path) do |f| next if ignore.include?(f) full_path = File.join(path, f) if File.directory?(full_path) dirs << { f => extract_file_layout(full_path, ignore) } else files << f end end dirs + files.sort end
ruby
def extract_file_layout(path, ignore=[]) return [] unless File.directory?(path) dirs = [] files = [] ignore += [ '.', '..' ] Dir.foreach(path) do |f| next if ignore.include?(f) full_path = File.join(path, f) if File.directory?(full_path) dirs << { f => extract_file_layout(full_path, ignore) } else files << f end end dirs + files.sort end
[ "def", "extract_file_layout", "(", "path", ",", "ignore", "=", "[", "]", ")", "return", "[", "]", "unless", "File", ".", "directory?", "(", "path", ")", "dirs", "=", "[", "]", "files", "=", "[", "]", "ignore", "+=", "[", "'.'", ",", "'..'", "]", "Dir", ".", "foreach", "(", "path", ")", "do", "|", "f", "|", "next", "if", "ignore", ".", "include?", "(", "f", ")", "full_path", "=", "File", ".", "join", "(", "path", ",", "f", ")", "if", "File", ".", "directory?", "(", "full_path", ")", "dirs", "<<", "{", "f", "=>", "extract_file_layout", "(", "full_path", ",", "ignore", ")", "}", "else", "files", "<<", "f", "end", "end", "dirs", "+", "files", ".", "sort", "end" ]
Extract array representing file layout for given directory === Parameters path(String):: Path to directory whose layout is to be retrieved layout(Array):: Array being updated with layout, same as return value, empty array by default ignore(Array):: Optional: Name of files or directories that should be ignored === Return layout(Array):: Corresponding layout as used by 'create_file_layout'
[ "Extract", "array", "representing", "file", "layout", "for", "given", "directory" ]
8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae
https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/spec/spec_helper.rb#L213-L228
23,750
rightscale/right_scraper
lib/right_scraper/repositories/base.rb
RightScraper::Repositories.Base.equal_repo?
def equal_repo?(other) if other.is_a?(RightScraper::Repositories::Base) repository_hash == other.repository_hash else false end end
ruby
def equal_repo?(other) if other.is_a?(RightScraper::Repositories::Base) repository_hash == other.repository_hash else false end end
[ "def", "equal_repo?", "(", "other", ")", "if", "other", ".", "is_a?", "(", "RightScraper", "::", "Repositories", "::", "Base", ")", "repository_hash", "==", "other", ".", "repository_hash", "else", "false", "end", "end" ]
Return true if this repository and +other+ represent the same repository including the same checkout tag. === Parameters other(Repositories::Base):: repository to compare with === Returns Boolean:: true iff this repository and +other+ are the same Return true if this repository and +other+ represent the same repository, excluding the checkout tag. === Parameters other(Repositories::Base):: repository to compare with === Returns Boolean:: true iff this repository and +other+ are the same
[ "Return", "true", "if", "this", "repository", "and", "+", "other", "+", "represent", "the", "same", "repository", "including", "the", "same", "checkout", "tag", "." ]
8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae
https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/repositories/base.rb#L206-L212
23,751
rightscale/right_scraper
lib/right_scraper/repositories/base.rb
RightScraper::Repositories.Base.add_users_to
def add_users_to(uri, username=nil, password=nil) begin uri = URI.parse(uri) if uri.instance_of?(String) if username userinfo = URI.escape(username, USERPW) userinfo += ":" + URI.escape(password, USERPW) unless password.nil? uri.userinfo = userinfo end uri rescue URI::InvalidURIError if uri =~ PATTERN::GIT_URI user, host, path = $1, $2, $3 userinfo = URI.escape(user, USERPW) userinfo += ":" + URI.escape(username, USERPW) unless username.nil? path = "/" + path unless path.start_with?('/') URI::Generic::build({:scheme => "ssh", :userinfo => userinfo, :host => host, :path => path }) else raise end end end
ruby
def add_users_to(uri, username=nil, password=nil) begin uri = URI.parse(uri) if uri.instance_of?(String) if username userinfo = URI.escape(username, USERPW) userinfo += ":" + URI.escape(password, USERPW) unless password.nil? uri.userinfo = userinfo end uri rescue URI::InvalidURIError if uri =~ PATTERN::GIT_URI user, host, path = $1, $2, $3 userinfo = URI.escape(user, USERPW) userinfo += ":" + URI.escape(username, USERPW) unless username.nil? path = "/" + path unless path.start_with?('/') URI::Generic::build({:scheme => "ssh", :userinfo => userinfo, :host => host, :path => path }) else raise end end end
[ "def", "add_users_to", "(", "uri", ",", "username", "=", "nil", ",", "password", "=", "nil", ")", "begin", "uri", "=", "URI", ".", "parse", "(", "uri", ")", "if", "uri", ".", "instance_of?", "(", "String", ")", "if", "username", "userinfo", "=", "URI", ".", "escape", "(", "username", ",", "USERPW", ")", "userinfo", "+=", "\":\"", "+", "URI", ".", "escape", "(", "password", ",", "USERPW", ")", "unless", "password", ".", "nil?", "uri", ".", "userinfo", "=", "userinfo", "end", "uri", "rescue", "URI", "::", "InvalidURIError", "if", "uri", "=~", "PATTERN", "::", "GIT_URI", "user", ",", "host", ",", "path", "=", "$1", ",", "$2", ",", "$3", "userinfo", "=", "URI", ".", "escape", "(", "user", ",", "USERPW", ")", "userinfo", "+=", "\":\"", "+", "URI", ".", "escape", "(", "username", ",", "USERPW", ")", "unless", "username", ".", "nil?", "path", "=", "\"/\"", "+", "path", "unless", "path", ".", "start_with?", "(", "'/'", ")", "URI", "::", "Generic", "::", "build", "(", "{", ":scheme", "=>", "\"ssh\"", ",", ":userinfo", "=>", "userinfo", ",", ":host", "=>", "host", ",", ":path", "=>", "path", "}", ")", "else", "raise", "end", "end", "end" ]
Return a URI with the given username and password set. === Parameters uri(URI or String):: URI to add user identification to === Returns URI:: URI with username and password identification added
[ "Return", "a", "URI", "with", "the", "given", "username", "and", "password", "set", "." ]
8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae
https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/repositories/base.rb#L250-L274
23,752
mare-imbrium/canis
lib/canis/core/util/rcommandwindow.rb
Canis.KeyDispatcher.process_key
def process_key ch chr = nil if ch > 0 and ch < 256 chr = ch.chr end return :UNHANDLED unless @key_map @key_map.each_pair do |k,p| #$log.debug "KKK: processing key #{ch} #{chr} " if (k == ch || k == chr) #$log.debug "KKK: checking match == #{k}: #{ch} #{chr} " # compare both int key and chr #$log.debug "KKK: found match 1 #{ch} #{chr} " p.call(self, ch) return 0 elsif k.respond_to? :include? #$log.debug "KKK: checking match include #{k}: #{ch} #{chr} " # this bombs if its a String and we check for include of a ch. if !k.is_a?( String ) && (k.include?( ch ) || k.include?(chr)) #$log.debug "KKK: found match include #{ch} #{chr} " p.call(self, ch) return 0 end elsif k.is_a? Regexp if k.match(chr) #$log.debug "KKK: found match regex #{ch} #{chr} " p.call(self, ch) return 0 end end end return :UNHANDLED end
ruby
def process_key ch chr = nil if ch > 0 and ch < 256 chr = ch.chr end return :UNHANDLED unless @key_map @key_map.each_pair do |k,p| #$log.debug "KKK: processing key #{ch} #{chr} " if (k == ch || k == chr) #$log.debug "KKK: checking match == #{k}: #{ch} #{chr} " # compare both int key and chr #$log.debug "KKK: found match 1 #{ch} #{chr} " p.call(self, ch) return 0 elsif k.respond_to? :include? #$log.debug "KKK: checking match include #{k}: #{ch} #{chr} " # this bombs if its a String and we check for include of a ch. if !k.is_a?( String ) && (k.include?( ch ) || k.include?(chr)) #$log.debug "KKK: found match include #{ch} #{chr} " p.call(self, ch) return 0 end elsif k.is_a? Regexp if k.match(chr) #$log.debug "KKK: found match regex #{ch} #{chr} " p.call(self, ch) return 0 end end end return :UNHANDLED end
[ "def", "process_key", "ch", "chr", "=", "nil", "if", "ch", ">", "0", "and", "ch", "<", "256", "chr", "=", "ch", ".", "chr", "end", "return", ":UNHANDLED", "unless", "@key_map", "@key_map", ".", "each_pair", "do", "|", "k", ",", "p", "|", "#$log.debug \"KKK: processing key #{ch} #{chr} \"", "if", "(", "k", "==", "ch", "||", "k", "==", "chr", ")", "#$log.debug \"KKK: checking match == #{k}: #{ch} #{chr} \"", "# compare both int key and chr", "#$log.debug \"KKK: found match 1 #{ch} #{chr} \"", "p", ".", "call", "(", "self", ",", "ch", ")", "return", "0", "elsif", "k", ".", "respond_to?", ":include?", "#$log.debug \"KKK: checking match include #{k}: #{ch} #{chr} \"", "# this bombs if its a String and we check for include of a ch.", "if", "!", "k", ".", "is_a?", "(", "String", ")", "&&", "(", "k", ".", "include?", "(", "ch", ")", "||", "k", ".", "include?", "(", "chr", ")", ")", "#$log.debug \"KKK: found match include #{ch} #{chr} \"", "p", ".", "call", "(", "self", ",", "ch", ")", "return", "0", "end", "elsif", "k", ".", "is_a?", "Regexp", "if", "k", ".", "match", "(", "chr", ")", "#$log.debug \"KKK: found match regex #{ch} #{chr} \"", "p", ".", "call", "(", "self", ",", "ch", ")", "return", "0", "end", "end", "end", "return", ":UNHANDLED", "end" ]
checks the key against +@key_map+ if its set @param [Integer] ch character read by +Window+ @return [0, :UNHANDLED] 0 if processed, :UNHANDLED if not processed so higher level can process
[ "checks", "the", "key", "against", "+" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L463-L494
23,753
mare-imbrium/canis
lib/canis/core/util/rcommandwindow.rb
Canis.KeyDispatcher.default_string_key_map
def default_string_key_map require 'canis/core/include/action' @key_map ||= {} @key_map[ Regexp.new('[a-zA-Z0-9_\.\/]') ] = Action.new("Append to pattern") { |obj, ch| obj.buffer << ch.chr obj.buffer_changed } @key_map[ [127, ?\C-h.getbyte(0)] ] = Action.new("Delete Prev Char") { |obj, ch| # backspace buff = obj.buffer buff = buff[0..-2] unless buff == "" obj.set_buffer buff } end
ruby
def default_string_key_map require 'canis/core/include/action' @key_map ||= {} @key_map[ Regexp.new('[a-zA-Z0-9_\.\/]') ] = Action.new("Append to pattern") { |obj, ch| obj.buffer << ch.chr obj.buffer_changed } @key_map[ [127, ?\C-h.getbyte(0)] ] = Action.new("Delete Prev Char") { |obj, ch| # backspace buff = obj.buffer buff = buff[0..-2] unless buff == "" obj.set_buffer buff } end
[ "def", "default_string_key_map", "require", "'canis/core/include/action'", "@key_map", "||=", "{", "}", "@key_map", "[", "Regexp", ".", "new", "(", "'[a-zA-Z0-9_\\.\\/]'", ")", "]", "=", "Action", ".", "new", "(", "\"Append to pattern\"", ")", "{", "|", "obj", ",", "ch", "|", "obj", ".", "buffer", "<<", "ch", ".", "chr", "obj", ".", "buffer_changed", "}", "@key_map", "[", "[", "127", ",", "?\\C-h", ".", "getbyte", "(", "0", ")", "]", "]", "=", "Action", ".", "new", "(", "\"Delete Prev Char\"", ")", "{", "|", "obj", ",", "ch", "|", "# backspace", "buff", "=", "obj", ".", "buffer", "buff", "=", "buff", "[", "0", "..", "-", "2", "]", "unless", "buff", "==", "\"\"", "obj", ".", "set_buffer", "buff", "}", "end" ]
setting up some keys This is currently an insertion key map, if you want a String named +@buffer+ updated. Expects buffer_changed and set_buffer to exist as well as +buffer()+. TODO add left and right arrow keys for changing insertion point. And other keys. XXX Why are we trying to duplicate a Field here ??
[ "setting", "up", "some", "keys", "This", "is", "currently", "an", "insertion", "key", "map", "if", "you", "want", "a", "String", "named", "+" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L500-L513
23,754
mare-imbrium/canis
lib/canis/core/util/rcommandwindow.rb
Canis.CommandWindow.press
def press ch ch = ch.getbyte(0) if ch.class==String ## 1.9 $log.debug " XXX press #{ch} " if $log.debug? case ch when -1 return when KEY_F1, 27, ?\C-q.getbyte(0) @stop = true return when KEY_ENTER, 10, 13 #$log.debug "popup ENTER : #{@selected_index} " #$log.debug "popup ENTER : #{field.name}" if !field.nil? @stop = true return when ?\C-d.getbyte(0) @start += @height-1 bounds_check when KEY_UP @start -= 1 @start = 0 if @start < 0 when KEY_DOWN @start += 1 bounds_check when ?\C-b.getbyte(0) @start -= @height-1 @start = 0 if @start < 0 when 0 @start = 0 end Ncurses::Panel.update_panels(); Ncurses.doupdate(); @window.wrefresh end
ruby
def press ch ch = ch.getbyte(0) if ch.class==String ## 1.9 $log.debug " XXX press #{ch} " if $log.debug? case ch when -1 return when KEY_F1, 27, ?\C-q.getbyte(0) @stop = true return when KEY_ENTER, 10, 13 #$log.debug "popup ENTER : #{@selected_index} " #$log.debug "popup ENTER : #{field.name}" if !field.nil? @stop = true return when ?\C-d.getbyte(0) @start += @height-1 bounds_check when KEY_UP @start -= 1 @start = 0 if @start < 0 when KEY_DOWN @start += 1 bounds_check when ?\C-b.getbyte(0) @start -= @height-1 @start = 0 if @start < 0 when 0 @start = 0 end Ncurses::Panel.update_panels(); Ncurses.doupdate(); @window.wrefresh end
[ "def", "press", "ch", "ch", "=", "ch", ".", "getbyte", "(", "0", ")", "if", "ch", ".", "class", "==", "String", "## 1.9", "$log", ".", "debug", "\" XXX press #{ch} \"", "if", "$log", ".", "debug?", "case", "ch", "when", "-", "1", "return", "when", "KEY_F1", ",", "27", ",", "?\\C-q", ".", "getbyte", "(", "0", ")", "@stop", "=", "true", "return", "when", "KEY_ENTER", ",", "10", ",", "13", "#$log.debug \"popup ENTER : #{@selected_index} \"", "#$log.debug \"popup ENTER : #{field.name}\" if !field.nil?", "@stop", "=", "true", "return", "when", "?\\C-d", ".", "getbyte", "(", "0", ")", "@start", "+=", "@height", "-", "1", "bounds_check", "when", "KEY_UP", "@start", "-=", "1", "@start", "=", "0", "if", "@start", "<", "0", "when", "KEY_DOWN", "@start", "+=", "1", "bounds_check", "when", "?\\C-b", ".", "getbyte", "(", "0", ")", "@start", "-=", "@height", "-", "1", "@start", "=", "0", "if", "@start", "<", "0", "when", "0", "@start", "=", "0", "end", "Ncurses", "::", "Panel", ".", "update_panels", "(", ")", ";", "Ncurses", ".", "doupdate", "(", ")", ";", "@window", ".", "wrefresh", "end" ]
handles a key, commandline
[ "handles", "a", "key", "commandline" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L226-L258
23,755
mare-imbrium/canis
lib/canis/core/util/rcommandwindow.rb
Canis.CommandWindow.configure
def configure(*val , &block) case val.size when 1 return @config[val[0]] when 2 @config[val[0]] = val[1] instance_variable_set("@#{val[0]}", val[1]) end instance_eval &block if block_given? end
ruby
def configure(*val , &block) case val.size when 1 return @config[val[0]] when 2 @config[val[0]] = val[1] instance_variable_set("@#{val[0]}", val[1]) end instance_eval &block if block_given? end
[ "def", "configure", "(", "*", "val", ",", "&", "block", ")", "case", "val", ".", "size", "when", "1", "return", "@config", "[", "val", "[", "0", "]", "]", "when", "2", "@config", "[", "val", "[", "0", "]", "]", "=", "val", "[", "1", "]", "instance_variable_set", "(", "\"@#{val[0]}\"", ",", "val", "[", "1", "]", ")", "end", "instance_eval", "block", "if", "block_given?", "end" ]
might as well add more keys for paging.
[ "might", "as", "well", "add", "more", "keys", "for", "paging", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L261-L270
23,756
mare-imbrium/canis
lib/canis/core/util/rcommandwindow.rb
Canis.ControlPHandler.recursive_search
def recursive_search glob="**/*" @command = Proc.new {|str| Dir.glob(glob).select do |p| p.index str; end } end
ruby
def recursive_search glob="**/*" @command = Proc.new {|str| Dir.glob(glob).select do |p| p.index str; end } end
[ "def", "recursive_search", "glob", "=", "\"**/*\"", "@command", "=", "Proc", ".", "new", "{", "|", "str", "|", "Dir", ".", "glob", "(", "glob", ")", ".", "select", "do", "|", "p", "|", "p", ".", "index", "str", ";", "end", "}", "end" ]
a default proc to requery data based on glob supplied and the pattern user enters
[ "a", "default", "proc", "to", "requery", "data", "based", "on", "glob", "supplied", "and", "the", "pattern", "user", "enters" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L788-L790
23,757
mare-imbrium/canis
lib/canis/core/util/rcommandwindow.rb
Canis.ControlPHandler.data_changed
def data_changed list sz = list.size @source.text(list) wh = @source.form.window.height @source.form.window.hide th = @source.height sh = Ncurses.LINES-1 if sz < @maxht # rows is less than tp size so reduce tp and window @source.height = sz nl = _new_layout sz+1 $log.debug "XXX: adjust ht to #{sz} layout is #{nl} size is #{sz}" @source.form.window.resize_with(nl) #Window.refresh_all else # expand the window ht to maxht tt = @maxht-1 @source.height = tt nl = _new_layout tt+1 $log.debug "XXX: increase ht to #{tt} def layout is #{nl} size is #{sz}" @source.form.window.resize_with(nl) end @source.fire_dimension_changed @source.init_vars # do if rows is less than current_index. @source.set_form_row @source.form.window.show #Window.refresh_all @source.form.window.wrefresh Ncurses::Panel.update_panels(); Ncurses.doupdate(); end
ruby
def data_changed list sz = list.size @source.text(list) wh = @source.form.window.height @source.form.window.hide th = @source.height sh = Ncurses.LINES-1 if sz < @maxht # rows is less than tp size so reduce tp and window @source.height = sz nl = _new_layout sz+1 $log.debug "XXX: adjust ht to #{sz} layout is #{nl} size is #{sz}" @source.form.window.resize_with(nl) #Window.refresh_all else # expand the window ht to maxht tt = @maxht-1 @source.height = tt nl = _new_layout tt+1 $log.debug "XXX: increase ht to #{tt} def layout is #{nl} size is #{sz}" @source.form.window.resize_with(nl) end @source.fire_dimension_changed @source.init_vars # do if rows is less than current_index. @source.set_form_row @source.form.window.show #Window.refresh_all @source.form.window.wrefresh Ncurses::Panel.update_panels(); Ncurses.doupdate(); end
[ "def", "data_changed", "list", "sz", "=", "list", ".", "size", "@source", ".", "text", "(", "list", ")", "wh", "=", "@source", ".", "form", ".", "window", ".", "height", "@source", ".", "form", ".", "window", ".", "hide", "th", "=", "@source", ".", "height", "sh", "=", "Ncurses", ".", "LINES", "-", "1", "if", "sz", "<", "@maxht", "# rows is less than tp size so reduce tp and window", "@source", ".", "height", "=", "sz", "nl", "=", "_new_layout", "sz", "+", "1", "$log", ".", "debug", "\"XXX: adjust ht to #{sz} layout is #{nl} size is #{sz}\"", "@source", ".", "form", ".", "window", ".", "resize_with", "(", "nl", ")", "#Window.refresh_all", "else", "# expand the window ht to maxht", "tt", "=", "@maxht", "-", "1", "@source", ".", "height", "=", "tt", "nl", "=", "_new_layout", "tt", "+", "1", "$log", ".", "debug", "\"XXX: increase ht to #{tt} def layout is #{nl} size is #{sz}\"", "@source", ".", "form", ".", "window", ".", "resize_with", "(", "nl", ")", "end", "@source", ".", "fire_dimension_changed", "@source", ".", "init_vars", "# do if rows is less than current_index.", "@source", ".", "set_form_row", "@source", ".", "form", ".", "window", ".", "show", "#Window.refresh_all", "@source", ".", "form", ".", "window", ".", "wrefresh", "Ncurses", "::", "Panel", ".", "update_panels", "(", ")", ";", "Ncurses", ".", "doupdate", "(", ")", ";", "end" ]
specify command to requery data def command &block @command = block end alias :command= :command signal that the data has changed and should be redisplayed with window resizing etc.
[ "specify", "command", "to", "requery", "data", "def", "command", "&block" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L800-L833
23,758
mare-imbrium/canis
lib/canis/core/util/rcommandwindow.rb
Canis.ControlPHandler.buffer_changed
def buffer_changed # display the pattern on the header @header.text1(">>>#{@buffer}_") if @header @header.text_right(Dir.pwd) if @header @no_match = false if @command @list = @command.call(@buffer) else @list = @__list.select do |line| line.index @buffer end end sz = @list.size if sz == 0 Ncurses.beep #return 1 #this should make ENTER and arrow keys unusable except for BS or Esc, @list = ["No entries"] @no_match = true end data_changed @list 0 end
ruby
def buffer_changed # display the pattern on the header @header.text1(">>>#{@buffer}_") if @header @header.text_right(Dir.pwd) if @header @no_match = false if @command @list = @command.call(@buffer) else @list = @__list.select do |line| line.index @buffer end end sz = @list.size if sz == 0 Ncurses.beep #return 1 #this should make ENTER and arrow keys unusable except for BS or Esc, @list = ["No entries"] @no_match = true end data_changed @list 0 end
[ "def", "buffer_changed", "# display the pattern on the header", "@header", ".", "text1", "(", "\">>>#{@buffer}_\"", ")", "if", "@header", "@header", ".", "text_right", "(", "Dir", ".", "pwd", ")", "if", "@header", "@no_match", "=", "false", "if", "@command", "@list", "=", "@command", ".", "call", "(", "@buffer", ")", "else", "@list", "=", "@__list", ".", "select", "do", "|", "line", "|", "line", ".", "index", "@buffer", "end", "end", "sz", "=", "@list", ".", "size", "if", "sz", "==", "0", "Ncurses", ".", "beep", "#return 1", "#this should make ENTER and arrow keys unusable except for BS or Esc, ", "@list", "=", "[", "\"No entries\"", "]", "@no_match", "=", "true", "end", "data_changed", "@list", "0", "end" ]
signal that the user has added or deleted a char from the pattern and data should be requeried, etc
[ "signal", "that", "the", "user", "has", "added", "or", "deleted", "a", "char", "from", "the", "pattern", "and", "data", "should", "be", "requeried", "etc" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L842-L865
23,759
mare-imbrium/canis
lib/canis/core/util/rcommandwindow.rb
Canis.ControlPHandler.handle_key
def handle_key ch $log.debug " HANDLER GOT KEY #{ch} " @keyint = ch @keychr = nil # accumulate keys in a string # need to track insertion point if user uses left and right arrow @buffer ||= "" chr = nil chr = ch.chr if ch > 47 and ch < 127 @keychr = chr # Don't let user hit enter or keys if no match if [13,10, KEY_ENTER, KEY_UP, KEY_DOWN].include? ch if @no_match $log.warn "XXX: KEY GOT WAS #{ch}, #{chr} " # viewer has already blocked KEY_ENTER ! return 0 if [13,10, KEY_ENTER, KEY_UP, KEY_DOWN].include? ch else if [13,10, KEY_ENTER].include? ch @source.form.window.ungetch(1001) return 0 end end end ret = process_key ch # revert to the basic handling of key_map and refreshing pad. # but this will rerun the keys and may once again run a mapping. @source._handle_key(ch) if ret == :UNHANDLED end
ruby
def handle_key ch $log.debug " HANDLER GOT KEY #{ch} " @keyint = ch @keychr = nil # accumulate keys in a string # need to track insertion point if user uses left and right arrow @buffer ||= "" chr = nil chr = ch.chr if ch > 47 and ch < 127 @keychr = chr # Don't let user hit enter or keys if no match if [13,10, KEY_ENTER, KEY_UP, KEY_DOWN].include? ch if @no_match $log.warn "XXX: KEY GOT WAS #{ch}, #{chr} " # viewer has already blocked KEY_ENTER ! return 0 if [13,10, KEY_ENTER, KEY_UP, KEY_DOWN].include? ch else if [13,10, KEY_ENTER].include? ch @source.form.window.ungetch(1001) return 0 end end end ret = process_key ch # revert to the basic handling of key_map and refreshing pad. # but this will rerun the keys and may once again run a mapping. @source._handle_key(ch) if ret == :UNHANDLED end
[ "def", "handle_key", "ch", "$log", ".", "debug", "\" HANDLER GOT KEY #{ch} \"", "@keyint", "=", "ch", "@keychr", "=", "nil", "# accumulate keys in a string", "# need to track insertion point if user uses left and right arrow", "@buffer", "||=", "\"\"", "chr", "=", "nil", "chr", "=", "ch", ".", "chr", "if", "ch", ">", "47", "and", "ch", "<", "127", "@keychr", "=", "chr", "# Don't let user hit enter or keys if no match", "if", "[", "13", ",", "10", ",", "KEY_ENTER", ",", "KEY_UP", ",", "KEY_DOWN", "]", ".", "include?", "ch", "if", "@no_match", "$log", ".", "warn", "\"XXX: KEY GOT WAS #{ch}, #{chr} \"", "# viewer has already blocked KEY_ENTER !", "return", "0", "if", "[", "13", ",", "10", ",", "KEY_ENTER", ",", "KEY_UP", ",", "KEY_DOWN", "]", ".", "include?", "ch", "else", "if", "[", "13", ",", "10", ",", "KEY_ENTER", "]", ".", "include?", "ch", "@source", ".", "form", ".", "window", ".", "ungetch", "(", "1001", ")", "return", "0", "end", "end", "end", "ret", "=", "process_key", "ch", "# revert to the basic handling of key_map and refreshing pad.", "# but this will rerun the keys and may once again run a mapping.", "@source", ".", "_handle_key", "(", "ch", ")", "if", "ret", "==", ":UNHANDLED", "end" ]
key handler of Controlphandler which overrides KeyDispatcher since we need to intercept KEY_ENTER @param [Integer] ch is key read by window. WARNING: Please note that if this is used in +Viewer.view+, that +view+ has already trapped CLOSE_KEY which is KEY_ENTER/13 for closing, so we won't get 13 anywhere
[ "key", "handler", "of", "Controlphandler", "which", "overrides", "KeyDispatcher", "since", "we", "need", "to", "intercept", "KEY_ENTER" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L873-L900
23,760
mare-imbrium/canis
lib/canis/core/util/rcommandwindow.rb
Canis.ControlPHandler.default_key_map
def default_key_map tp = source source.bind_key(?\M-n.getbyte(0), 'goto_end'){ tp.goto_end } source.bind_key(?\M-p.getbyte(0), 'goto_start'){ tp.goto_start } end
ruby
def default_key_map tp = source source.bind_key(?\M-n.getbyte(0), 'goto_end'){ tp.goto_end } source.bind_key(?\M-p.getbyte(0), 'goto_start'){ tp.goto_start } end
[ "def", "default_key_map", "tp", "=", "source", "source", ".", "bind_key", "(", "?\\M-n", ".", "getbyte", "(", "0", ")", ",", "'goto_end'", ")", "{", "tp", ".", "goto_end", "}", "source", ".", "bind_key", "(", "?\\M-p", ".", "getbyte", "(", "0", ")", ",", "'goto_start'", ")", "{", "tp", ".", "goto_start", "}", "end" ]
setting up some keys
[ "setting", "up", "some", "keys" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L903-L907
23,761
mare-imbrium/canis
lib/canis/core/util/rcommandwindow.rb
Canis.ControlPHandler.directory_key_map
def directory_key_map @key_map["<"] = Action.new("Goto Parent Dir") { |obj| # go to parent dir $log.debug "KKK: called proc for <" Dir.chdir("..") obj.buffer_changed } @key_map[">"] = Action.new("Change Dir"){ |obj| $log.debug "KKK: called proc for > : #{obj.current_value} " # step into directory dir = obj.current_value if File.directory? dir Dir.chdir dir obj.buffer_changed end } end
ruby
def directory_key_map @key_map["<"] = Action.new("Goto Parent Dir") { |obj| # go to parent dir $log.debug "KKK: called proc for <" Dir.chdir("..") obj.buffer_changed } @key_map[">"] = Action.new("Change Dir"){ |obj| $log.debug "KKK: called proc for > : #{obj.current_value} " # step into directory dir = obj.current_value if File.directory? dir Dir.chdir dir obj.buffer_changed end } end
[ "def", "directory_key_map", "@key_map", "[", "\"<\"", "]", "=", "Action", ".", "new", "(", "\"Goto Parent Dir\"", ")", "{", "|", "obj", "|", "# go to parent dir", "$log", ".", "debug", "\"KKK: called proc for <\"", "Dir", ".", "chdir", "(", "\"..\"", ")", "obj", ".", "buffer_changed", "}", "@key_map", "[", "\">\"", "]", "=", "Action", ".", "new", "(", "\"Change Dir\"", ")", "{", "|", "obj", "|", "$log", ".", "debug", "\"KKK: called proc for > : #{obj.current_value} \"", "# step into directory", "dir", "=", "obj", ".", "current_value", "if", "File", ".", "directory?", "dir", "Dir", ".", "chdir", "dir", "obj", ".", "buffer_changed", "end", "}", "end" ]
specific actions for directory listers currently for stepping into directory under cursor and going to parent dir.
[ "specific", "actions", "for", "directory", "listers", "currently", "for", "stepping", "into", "directory", "under", "cursor", "and", "going", "to", "parent", "dir", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L912-L929
23,762
mare-imbrium/canis
lib/canis/core/include/bordertitle.rb
Canis.BorderTitle.print_borders
def print_borders bordertitle_init unless @_bordertitle_init_called raise ArgumentError, "Graphic not set" unless @graphic raise "#{self} needs width" unless @width raise "#{self} needs height" unless @height width = @width height = @height-1 window = @graphic startcol = @col startrow = @row @color_pair = get_color($datacolor) bordercolor = @border_color || @color_pair borderatt = @border_attrib || Ncurses::A_NORMAL window.print_border startrow, startcol, height, width, bordercolor, borderatt print_title end
ruby
def print_borders bordertitle_init unless @_bordertitle_init_called raise ArgumentError, "Graphic not set" unless @graphic raise "#{self} needs width" unless @width raise "#{self} needs height" unless @height width = @width height = @height-1 window = @graphic startcol = @col startrow = @row @color_pair = get_color($datacolor) bordercolor = @border_color || @color_pair borderatt = @border_attrib || Ncurses::A_NORMAL window.print_border startrow, startcol, height, width, bordercolor, borderatt print_title end
[ "def", "print_borders", "bordertitle_init", "unless", "@_bordertitle_init_called", "raise", "ArgumentError", ",", "\"Graphic not set\"", "unless", "@graphic", "raise", "\"#{self} needs width\"", "unless", "@width", "raise", "\"#{self} needs height\"", "unless", "@height", "width", "=", "@width", "height", "=", "@height", "-", "1", "window", "=", "@graphic", "startcol", "=", "@col", "startrow", "=", "@row", "@color_pair", "=", "get_color", "(", "$datacolor", ")", "bordercolor", "=", "@border_color", "||", "@color_pair", "borderatt", "=", "@border_attrib", "||", "Ncurses", "::", "A_NORMAL", "window", ".", "print_border", "startrow", ",", "startcol", ",", "height", ",", "width", ",", "bordercolor", ",", "borderatt", "print_title", "end" ]
why the dash does it reduce height by one.
[ "why", "the", "dash", "does", "it", "reduce", "height", "by", "one", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/include/bordertitle.rb#L16-L31
23,763
mare-imbrium/canis
lib/canis/core/widgets/deprecated/rlist.rb
Canis.List.list
def list *val return @list if val.empty? alist = val[0] case alist when Array @list = alist # I possibly should call init_vars in these 3 cases but am doing the minimal 2013-04-10 - 18:27 # Based no issue: https://github.com/mare-imbrium/canis/issues/15 @current_index = @toprow = @pcol = 0 when NilClass @list = [] # or nil ? @current_index = @toprow = @pcol = 0 when Variable @list = alist.value @current_index = @toprow = @pcol = 0 else raise ArgumentError, "Listbox list(): do not know how to handle #{alist.class} " end clear_selection @repaint_required = true @widget_scrolled = true # 2011-10-15 @list end
ruby
def list *val return @list if val.empty? alist = val[0] case alist when Array @list = alist # I possibly should call init_vars in these 3 cases but am doing the minimal 2013-04-10 - 18:27 # Based no issue: https://github.com/mare-imbrium/canis/issues/15 @current_index = @toprow = @pcol = 0 when NilClass @list = [] # or nil ? @current_index = @toprow = @pcol = 0 when Variable @list = alist.value @current_index = @toprow = @pcol = 0 else raise ArgumentError, "Listbox list(): do not know how to handle #{alist.class} " end clear_selection @repaint_required = true @widget_scrolled = true # 2011-10-15 @list end
[ "def", "list", "*", "val", "return", "@list", "if", "val", ".", "empty?", "alist", "=", "val", "[", "0", "]", "case", "alist", "when", "Array", "@list", "=", "alist", "# I possibly should call init_vars in these 3 cases but am doing the minimal 2013-04-10 - 18:27 ", "# Based no issue: https://github.com/mare-imbrium/canis/issues/15", "@current_index", "=", "@toprow", "=", "@pcol", "=", "0", "when", "NilClass", "@list", "=", "[", "]", "# or nil ?", "@current_index", "=", "@toprow", "=", "@pcol", "=", "0", "when", "Variable", "@list", "=", "alist", ".", "value", "@current_index", "=", "@toprow", "=", "@pcol", "=", "0", "else", "raise", "ArgumentError", ",", "\"Listbox list(): do not know how to handle #{alist.class} \"", "end", "clear_selection", "@repaint_required", "=", "true", "@widget_scrolled", "=", "true", "# 2011-10-15 ", "@list", "end" ]
provide data to List in the form of an Array or Variable or ListDataModel. This will create a default ListSelectionModel. CHANGE as on 2010-09-21 12:53: If explicit nil passed then dummy datamodel and selection model created From now on, constructor will call this, so this can always happen. NOTE: sometimes this can be added much after its painted. Do not expect this to be called from constructor, although that is the usual case. it can be dependent on some other list or tree. @param [Array, Variable, ListDataModel] data to populate list with @return [ListDataModel] just created or assigned
[ "provide", "data", "to", "List", "in", "the", "form", "of", "an", "Array", "or", "Variable", "or", "ListDataModel", ".", "This", "will", "create", "a", "default", "ListSelectionModel", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/deprecated/rlist.rb#L175-L198
23,764
mare-imbrium/canis
lib/canis/core/widgets/deprecated/rlist.rb
Canis.List.ask_search_backward
def ask_search_backward regex = get_string("Enter regex to search (backward)") @last_regex = regex ix = @list.find_prev regex, @current_index if ix.nil? alert("No matching data for: #{regex}") else set_focus_on(ix) end end
ruby
def ask_search_backward regex = get_string("Enter regex to search (backward)") @last_regex = regex ix = @list.find_prev regex, @current_index if ix.nil? alert("No matching data for: #{regex}") else set_focus_on(ix) end end
[ "def", "ask_search_backward", "regex", "=", "get_string", "(", "\"Enter regex to search (backward)\"", ")", "@last_regex", "=", "regex", "ix", "=", "@list", ".", "find_prev", "regex", ",", "@current_index", "if", "ix", ".", "nil?", "alert", "(", "\"No matching data for: #{regex}\"", ")", "else", "set_focus_on", "(", "ix", ")", "end", "end" ]
gets string to search and calls data models find prev
[ "gets", "string", "to", "search", "and", "calls", "data", "models", "find", "prev" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/deprecated/rlist.rb#L360-L369
23,765
mare-imbrium/canis
lib/canis/core/widgets/deprecated/rlist.rb
Canis.List.repaint
def repaint #:nodoc: return unless @repaint_required # # TRYING OUT dangerous 2011-10-15 @repaint_required = false @repaint_required = true if @widget_scrolled || @pcol != @old_pcol || @record_changed || @property_changed unless @repaint_required unhighlight_row @old_selected_index highlight_selected_row end return unless @repaint_required $log.debug "BASICLIST REPAINT WILL HAPPEN #{current_index} " # not sure where to put this, once for all or repeat 2010-02-17 23:07 RFED16 my_win = @form ? @form.window : @target_window @graphic = my_win unless @graphic raise " #{@name} neither form, nor target window given LB paint " unless my_win raise " #{@name} NO GRAPHIC set as yet LB paint " unless @graphic raise "width or height not given w:#{@width} , h:#{@height} " if @width.nil? || @height.nil? @win_left = my_win.left @win_top = my_win.top @left_margin ||= @row_selected_symbol.length # we are making sure display len does not exceed width XXX hope this does not wreak havoc elsewhere _dl = [@display_length || 100, @width-@internal_width-@left_margin].min # 2011-09-17 RK overwriting when we move grabbar in vimsplit $log.debug "basiclistbox repaint #{@name} graphic #{@graphic}" #$log.debug "XXX repaint to_print #{@to_print_borders} " print_borders unless @suppress_borders # do this once only, unless everything changes #maxlen = @maxlen || @width-2 tm = list() rc = row_count @longest_line = @width $log.debug " rbasiclistbox #{row_count}, w:#{@width} , maxlen:#{@maxlen} " if rc > 0 # just added in case no data passed tr = @toprow acolor = get_color $datacolor h = scrollatrow() r,c = rowcol 0.upto(h) do |hh| crow = tr+hh if crow < rc _focussed = @current_index == crow ? true : false # row focussed ? focus_type = _focussed focus_type = :SOFT_FOCUS if _focussed && !@focussed selected = is_row_selected crow content = tm[crow] # 2009-01-17 18:37 chomp giving error in some cases says frozen content = convert_value_to_text content, crow # 2010-09-23 20:12 # by now it has to be a String if content.is_a? String content = content.dup sanitize content if @sanitization_required truncate content if @truncation_required end ## set the selector symbol if requested selection_symbol = '' if @show_selector if selected selection_symbol = @row_selected_symbol else selection_symbol = @row_unselected_symbol end @graphic.printstring r+hh, c, selection_symbol, acolor,@attr end #renderer = get_default_cell_renderer_for_class content.class.to_s renderer = cell_renderer() renderer.display_length = _dl # 2011-09-17 RK overwriting when we move grabbar in vimsplit renderer.repaint @graphic, r+hh, c+@left_margin, crow, content, focus_type, selected else # clear rows @graphic.printstring r+hh, c, " " * (@width-@internal_width), acolor,@attr end end end # rc == 0 @repaint_required = false # 2011-10-13 @widget_scrolled = false @record_changed = false @property_changed = false @old_pcol = @pcol end
ruby
def repaint #:nodoc: return unless @repaint_required # # TRYING OUT dangerous 2011-10-15 @repaint_required = false @repaint_required = true if @widget_scrolled || @pcol != @old_pcol || @record_changed || @property_changed unless @repaint_required unhighlight_row @old_selected_index highlight_selected_row end return unless @repaint_required $log.debug "BASICLIST REPAINT WILL HAPPEN #{current_index} " # not sure where to put this, once for all or repeat 2010-02-17 23:07 RFED16 my_win = @form ? @form.window : @target_window @graphic = my_win unless @graphic raise " #{@name} neither form, nor target window given LB paint " unless my_win raise " #{@name} NO GRAPHIC set as yet LB paint " unless @graphic raise "width or height not given w:#{@width} , h:#{@height} " if @width.nil? || @height.nil? @win_left = my_win.left @win_top = my_win.top @left_margin ||= @row_selected_symbol.length # we are making sure display len does not exceed width XXX hope this does not wreak havoc elsewhere _dl = [@display_length || 100, @width-@internal_width-@left_margin].min # 2011-09-17 RK overwriting when we move grabbar in vimsplit $log.debug "basiclistbox repaint #{@name} graphic #{@graphic}" #$log.debug "XXX repaint to_print #{@to_print_borders} " print_borders unless @suppress_borders # do this once only, unless everything changes #maxlen = @maxlen || @width-2 tm = list() rc = row_count @longest_line = @width $log.debug " rbasiclistbox #{row_count}, w:#{@width} , maxlen:#{@maxlen} " if rc > 0 # just added in case no data passed tr = @toprow acolor = get_color $datacolor h = scrollatrow() r,c = rowcol 0.upto(h) do |hh| crow = tr+hh if crow < rc _focussed = @current_index == crow ? true : false # row focussed ? focus_type = _focussed focus_type = :SOFT_FOCUS if _focussed && !@focussed selected = is_row_selected crow content = tm[crow] # 2009-01-17 18:37 chomp giving error in some cases says frozen content = convert_value_to_text content, crow # 2010-09-23 20:12 # by now it has to be a String if content.is_a? String content = content.dup sanitize content if @sanitization_required truncate content if @truncation_required end ## set the selector symbol if requested selection_symbol = '' if @show_selector if selected selection_symbol = @row_selected_symbol else selection_symbol = @row_unselected_symbol end @graphic.printstring r+hh, c, selection_symbol, acolor,@attr end #renderer = get_default_cell_renderer_for_class content.class.to_s renderer = cell_renderer() renderer.display_length = _dl # 2011-09-17 RK overwriting when we move grabbar in vimsplit renderer.repaint @graphic, r+hh, c+@left_margin, crow, content, focus_type, selected else # clear rows @graphic.printstring r+hh, c, " " * (@width-@internal_width), acolor,@attr end end end # rc == 0 @repaint_required = false # 2011-10-13 @widget_scrolled = false @record_changed = false @property_changed = false @old_pcol = @pcol end
[ "def", "repaint", "#:nodoc:", "return", "unless", "@repaint_required", "#", "# TRYING OUT dangerous 2011-10-15 ", "@repaint_required", "=", "false", "@repaint_required", "=", "true", "if", "@widget_scrolled", "||", "@pcol", "!=", "@old_pcol", "||", "@record_changed", "||", "@property_changed", "unless", "@repaint_required", "unhighlight_row", "@old_selected_index", "highlight_selected_row", "end", "return", "unless", "@repaint_required", "$log", ".", "debug", "\"BASICLIST REPAINT WILL HAPPEN #{current_index} \"", "# not sure where to put this, once for all or repeat 2010-02-17 23:07 RFED16", "my_win", "=", "@form", "?", "@form", ".", "window", ":", "@target_window", "@graphic", "=", "my_win", "unless", "@graphic", "raise", "\" #{@name} neither form, nor target window given LB paint \"", "unless", "my_win", "raise", "\" #{@name} NO GRAPHIC set as yet LB paint \"", "unless", "@graphic", "raise", "\"width or height not given w:#{@width} , h:#{@height} \"", "if", "@width", ".", "nil?", "||", "@height", ".", "nil?", "@win_left", "=", "my_win", ".", "left", "@win_top", "=", "my_win", ".", "top", "@left_margin", "||=", "@row_selected_symbol", ".", "length", "# we are making sure display len does not exceed width XXX hope this does not wreak havoc elsewhere", "_dl", "=", "[", "@display_length", "||", "100", ",", "@width", "-", "@internal_width", "-", "@left_margin", "]", ".", "min", "# 2011-09-17 RK overwriting when we move grabbar in vimsplit", "$log", ".", "debug", "\"basiclistbox repaint #{@name} graphic #{@graphic}\"", "#$log.debug \"XXX repaint to_print #{@to_print_borders} \"", "print_borders", "unless", "@suppress_borders", "# do this once only, unless everything changes", "#maxlen = @maxlen || @width-2", "tm", "=", "list", "(", ")", "rc", "=", "row_count", "@longest_line", "=", "@width", "$log", ".", "debug", "\" rbasiclistbox #{row_count}, w:#{@width} , maxlen:#{@maxlen} \"", "if", "rc", ">", "0", "# just added in case no data passed", "tr", "=", "@toprow", "acolor", "=", "get_color", "$datacolor", "h", "=", "scrollatrow", "(", ")", "r", ",", "c", "=", "rowcol", "0", ".", "upto", "(", "h", ")", "do", "|", "hh", "|", "crow", "=", "tr", "+", "hh", "if", "crow", "<", "rc", "_focussed", "=", "@current_index", "==", "crow", "?", "true", ":", "false", "# row focussed ?", "focus_type", "=", "_focussed", "focus_type", "=", ":SOFT_FOCUS", "if", "_focussed", "&&", "!", "@focussed", "selected", "=", "is_row_selected", "crow", "content", "=", "tm", "[", "crow", "]", "# 2009-01-17 18:37 chomp giving error in some cases says frozen", "content", "=", "convert_value_to_text", "content", ",", "crow", "# 2010-09-23 20:12 ", "# by now it has to be a String", "if", "content", ".", "is_a?", "String", "content", "=", "content", ".", "dup", "sanitize", "content", "if", "@sanitization_required", "truncate", "content", "if", "@truncation_required", "end", "## set the selector symbol if requested", "selection_symbol", "=", "''", "if", "@show_selector", "if", "selected", "selection_symbol", "=", "@row_selected_symbol", "else", "selection_symbol", "=", "@row_unselected_symbol", "end", "@graphic", ".", "printstring", "r", "+", "hh", ",", "c", ",", "selection_symbol", ",", "acolor", ",", "@attr", "end", "#renderer = get_default_cell_renderer_for_class content.class.to_s", "renderer", "=", "cell_renderer", "(", ")", "renderer", ".", "display_length", "=", "_dl", "# 2011-09-17 RK overwriting when we move grabbar in vimsplit", "renderer", ".", "repaint", "@graphic", ",", "r", "+", "hh", ",", "c", "+", "@left_margin", ",", "crow", ",", "content", ",", "focus_type", ",", "selected", "else", "# clear rows", "@graphic", ".", "printstring", "r", "+", "hh", ",", "c", ",", "\" \"", "*", "(", "@width", "-", "@internal_width", ")", ",", "acolor", ",", "@attr", "end", "end", "end", "# rc == 0", "@repaint_required", "=", "false", "# 2011-10-13 ", "@widget_scrolled", "=", "false", "@record_changed", "=", "false", "@property_changed", "=", "false", "@old_pcol", "=", "@pcol", "end" ]
this method chops the data to length before giving it to the renderer, this can cause problems if the renderer does some processing. also, it pans the data horizontally giving the renderer a section of it.
[ "this", "method", "chops", "the", "data", "to", "length", "before", "giving", "it", "to", "the", "renderer", "this", "can", "cause", "problems", "if", "the", "renderer", "does", "some", "processing", ".", "also", "it", "pans", "the", "data", "horizontally", "giving", "the", "renderer", "a", "section", "of", "it", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/deprecated/rlist.rb#L416-L495
23,766
mare-imbrium/canis
lib/canis/core/widgets/deprecated/rlist.rb
Canis.List.sanitize
def sanitize content #:nodoc: if content.is_a? String content.chomp! content.gsub!(/\t/, ' ') # don't display tab content.gsub!(/[^[:print:]]/, '') # don't display non print characters else content end end
ruby
def sanitize content #:nodoc: if content.is_a? String content.chomp! content.gsub!(/\t/, ' ') # don't display tab content.gsub!(/[^[:print:]]/, '') # don't display non print characters else content end end
[ "def", "sanitize", "content", "#:nodoc:", "if", "content", ".", "is_a?", "String", "content", ".", "chomp!", "content", ".", "gsub!", "(", "/", "\\t", "/", ",", "' '", ")", "# don't display tab", "content", ".", "gsub!", "(", "/", "/", ",", "''", ")", "# don't display non print characters", "else", "content", "end", "end" ]
takes a block, this way anyone extending this klass can just pass a block to do his job This modifies the string
[ "takes", "a", "block", "this", "way", "anyone", "extending", "this", "klass", "can", "just", "pass", "a", "block", "to", "do", "his", "job", "This", "modifies", "the", "string" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/deprecated/rlist.rb#L536-L544
23,767
mare-imbrium/canis
lib/canis/core/widgets/deprecated/rlist.rb
Canis.List.init_actions
def init_actions am = action_manager() am.add_action(Action.new("&Disable selection") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } ) am.add_action(Action.new("&Edit Toggle") { @edit_toggle = !@edit_toggle; $status_message.value = "Edit toggle is #{@edit_toggle}" }) end
ruby
def init_actions am = action_manager() am.add_action(Action.new("&Disable selection") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } ) am.add_action(Action.new("&Edit Toggle") { @edit_toggle = !@edit_toggle; $status_message.value = "Edit toggle is #{@edit_toggle}" }) end
[ "def", "init_actions", "am", "=", "action_manager", "(", ")", "am", ".", "add_action", "(", "Action", ".", "new", "(", "\"&Disable selection\"", ")", "{", "@selection_mode", "=", ":none", ";", "unbind_key", "(", "32", ")", ";", "bind_key", "(", "32", ",", ":scroll_forward", ")", ";", "}", ")", "am", ".", "add_action", "(", "Action", ".", "new", "(", "\"&Edit Toggle\"", ")", "{", "@edit_toggle", "=", "!", "@edit_toggle", ";", "$status_message", ".", "value", "=", "\"Edit toggle is #{@edit_toggle}\"", "}", ")", "end" ]
Define actions that can be popped up by PromptMenu or other menubar Currently, only PromptMenu, but we can start contextually appending to Menubar or others
[ "Define", "actions", "that", "can", "be", "popped", "up", "by", "PromptMenu", "or", "other", "menubar", "Currently", "only", "PromptMenu", "but", "we", "can", "start", "contextually", "appending", "to", "Menubar", "or", "others" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/deprecated/rlist.rb#L625-L629
23,768
mare-imbrium/canis
lib/canis/core/widgets/box.rb
Canis.Box.repaint
def repaint return unless @repaint_required bc = $datacolor bordercolor = @border_color || bc borderatt = @border_attrib || Ncurses::A_NORMAL @window.print_border row, col, height, width, bordercolor, borderatt #print_borders print_title @repaint_required = false end
ruby
def repaint return unless @repaint_required bc = $datacolor bordercolor = @border_color || bc borderatt = @border_attrib || Ncurses::A_NORMAL @window.print_border row, col, height, width, bordercolor, borderatt #print_borders print_title @repaint_required = false end
[ "def", "repaint", "return", "unless", "@repaint_required", "bc", "=", "$datacolor", "bordercolor", "=", "@border_color", "||", "bc", "borderatt", "=", "@border_attrib", "||", "Ncurses", "::", "A_NORMAL", "@window", ".", "print_border", "row", ",", "col", ",", "height", ",", "width", ",", "bordercolor", ",", "borderatt", "#print_borders", "print_title", "@repaint_required", "=", "false", "end" ]
repaint the scrollbar
[ "repaint", "the", "scrollbar" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/box.rb#L42-L51
23,769
mare-imbrium/canis
lib/canis/core/util/widgetshortcuts.rb
Canis.WidgetShortcuts.dock
def dock labels, config={}, &block require 'canis/core/widgets/keylabelprinter' klp = Canis::KeyLabelPrinter.new @form, labels, config, &block end
ruby
def dock labels, config={}, &block require 'canis/core/widgets/keylabelprinter' klp = Canis::KeyLabelPrinter.new @form, labels, config, &block end
[ "def", "dock", "labels", ",", "config", "=", "{", "}", ",", "&", "block", "require", "'canis/core/widgets/keylabelprinter'", "klp", "=", "Canis", "::", "KeyLabelPrinter", ".", "new", "@form", ",", "labels", ",", "config", ",", "block", "end" ]
prints pine-like key labels
[ "prints", "pine", "-", "like", "key", "labels" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/widgetshortcuts.rb#L198-L201
23,770
mare-imbrium/canis
lib/canis/core/util/widgetshortcuts.rb
Canis.WidgetShortcuts.status_line
def status_line config={}, &block require 'canis/core/widgets/statusline' sl = Canis::StatusLine.new @form, config, &block end
ruby
def status_line config={}, &block require 'canis/core/widgets/statusline' sl = Canis::StatusLine.new @form, config, &block end
[ "def", "status_line", "config", "=", "{", "}", ",", "&", "block", "require", "'canis/core/widgets/statusline'", "sl", "=", "Canis", "::", "StatusLine", ".", "new", "@form", ",", "config", ",", "block", "end" ]
prints a status line at bottom where mode's statuses et can be reflected
[ "prints", "a", "status", "line", "at", "bottom", "where", "mode", "s", "statuses", "et", "can", "be", "reflected" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/widgetshortcuts.rb#L205-L208
23,771
mare-imbrium/canis
lib/canis/core/util/widgetshortcuts.rb
Canis.WidgetShortcuts.table
def table config={}, &block #def tabular_widget config={}, &block require 'canis/core/widgets/table' events = [:PROPERTY_CHANGE, :LEAVE, :ENTER, :CHANGE, :ENTER_ROW, :PRESS ] block_event = nil # if no width given, expand to stack width #config.delete :title useform = nil w = Table.new useform, config # NO BLOCK GIVEN w.width ||= :expand w.height ||= :expand # TODO This has to come before other in stack next one will overwrite. _position(w) if block_given? #@current_object << w yield_or_eval &block #@current_object.pop end return w end
ruby
def table config={}, &block #def tabular_widget config={}, &block require 'canis/core/widgets/table' events = [:PROPERTY_CHANGE, :LEAVE, :ENTER, :CHANGE, :ENTER_ROW, :PRESS ] block_event = nil # if no width given, expand to stack width #config.delete :title useform = nil w = Table.new useform, config # NO BLOCK GIVEN w.width ||= :expand w.height ||= :expand # TODO This has to come before other in stack next one will overwrite. _position(w) if block_given? #@current_object << w yield_or_eval &block #@current_object.pop end return w end
[ "def", "table", "config", "=", "{", "}", ",", "&", "block", "#def tabular_widget config={}, &block", "require", "'canis/core/widgets/table'", "events", "=", "[", ":PROPERTY_CHANGE", ",", ":LEAVE", ",", ":ENTER", ",", ":CHANGE", ",", ":ENTER_ROW", ",", ":PRESS", "]", "block_event", "=", "nil", "# if no width given, expand to stack width", "#config.delete :title", "useform", "=", "nil", "w", "=", "Table", ".", "new", "useform", ",", "config", "# NO BLOCK GIVEN", "w", ".", "width", "||=", ":expand", "w", ".", "height", "||=", ":expand", "# TODO This has to come before other in stack next one will overwrite.", "_position", "(", "w", ")", "if", "block_given?", "#@current_object << w", "yield_or_eval", "block", "#@current_object.pop", "end", "return", "w", "end" ]
creates a simple readonly table, that allows users to click on rows and also on the header. Header clicking is for column-sorting.
[ "creates", "a", "simple", "readonly", "table", "that", "allows", "users", "to", "click", "on", "rows", "and", "also", "on", "the", "header", ".", "Header", "clicking", "is", "for", "column", "-", "sorting", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/widgetshortcuts.rb#L273-L292
23,772
mare-imbrium/canis
lib/canis/core/util/widgetshortcuts.rb
Canis.WidgetShortcuts._configure
def _configure s s[:row] ||= 0 s[:col] ||= 0 s[:row] += (s[:margin_top] || 0) s[:col] += (s[:margin_left] || 0) s[:width] = FFI::NCurses.COLS-s[:col] if s[:width] == :expand s[:height] = FFI::NCurses.LINES-s[:row] if s[:height] == :expand # 2011-11-30 last = @_ws_active.last if last if s[:width_pc] if last.is_a? WsStack s[:width] = (last[:width] * (s[:width_pc].to_i * 0.01)).floor else # i think this width is picked up by next stack in this flow last[:item_width] = (last[:width] * (s[:width_pc].to_i* 0.01)).floor end end if s[:height_pc] if last.is_a? WsFlow s[:height] = ( (last[:height] * s[:height_pc].to_i)/100).floor else # this works only for flows within stacks not for an object unless # you put a single object in a flow s[:item_height] = ( (last[:height] * s[:height_pc].to_i)/100).floor end #alert "item height set as #{s[:height]} for #{s} " end if last.is_a? WsStack s[:row] += (last[:row] || 0) s[:col] += (last[:col] || 0) else s[:row] += (last[:row] || 0) s[:col] += (last[:col] || 0) # we are updating with item_width as each st finishes s[:width] ||= last[:item_width] # end else # this should be outer most flow or stack, if nothing mentioned # trying this out s[:width] ||= :expand s[:height] ||= :expand s[:width] = FFI::NCurses.COLS-s[:col] if s[:width] == :expand s[:height] = FFI::NCurses.LINES-s[:row] if s[:height] == :expand # 2011-11-30 end s[:components] = [] end
ruby
def _configure s s[:row] ||= 0 s[:col] ||= 0 s[:row] += (s[:margin_top] || 0) s[:col] += (s[:margin_left] || 0) s[:width] = FFI::NCurses.COLS-s[:col] if s[:width] == :expand s[:height] = FFI::NCurses.LINES-s[:row] if s[:height] == :expand # 2011-11-30 last = @_ws_active.last if last if s[:width_pc] if last.is_a? WsStack s[:width] = (last[:width] * (s[:width_pc].to_i * 0.01)).floor else # i think this width is picked up by next stack in this flow last[:item_width] = (last[:width] * (s[:width_pc].to_i* 0.01)).floor end end if s[:height_pc] if last.is_a? WsFlow s[:height] = ( (last[:height] * s[:height_pc].to_i)/100).floor else # this works only for flows within stacks not for an object unless # you put a single object in a flow s[:item_height] = ( (last[:height] * s[:height_pc].to_i)/100).floor end #alert "item height set as #{s[:height]} for #{s} " end if last.is_a? WsStack s[:row] += (last[:row] || 0) s[:col] += (last[:col] || 0) else s[:row] += (last[:row] || 0) s[:col] += (last[:col] || 0) # we are updating with item_width as each st finishes s[:width] ||= last[:item_width] # end else # this should be outer most flow or stack, if nothing mentioned # trying this out s[:width] ||= :expand s[:height] ||= :expand s[:width] = FFI::NCurses.COLS-s[:col] if s[:width] == :expand s[:height] = FFI::NCurses.LINES-s[:row] if s[:height] == :expand # 2011-11-30 end s[:components] = [] end
[ "def", "_configure", "s", "s", "[", ":row", "]", "||=", "0", "s", "[", ":col", "]", "||=", "0", "s", "[", ":row", "]", "+=", "(", "s", "[", ":margin_top", "]", "||", "0", ")", "s", "[", ":col", "]", "+=", "(", "s", "[", ":margin_left", "]", "||", "0", ")", "s", "[", ":width", "]", "=", "FFI", "::", "NCurses", ".", "COLS", "-", "s", "[", ":col", "]", "if", "s", "[", ":width", "]", "==", ":expand", "s", "[", ":height", "]", "=", "FFI", "::", "NCurses", ".", "LINES", "-", "s", "[", ":row", "]", "if", "s", "[", ":height", "]", "==", ":expand", "# 2011-11-30 ", "last", "=", "@_ws_active", ".", "last", "if", "last", "if", "s", "[", ":width_pc", "]", "if", "last", ".", "is_a?", "WsStack", "s", "[", ":width", "]", "=", "(", "last", "[", ":width", "]", "*", "(", "s", "[", ":width_pc", "]", ".", "to_i", "*", "0.01", ")", ")", ".", "floor", "else", "# i think this width is picked up by next stack in this flow", "last", "[", ":item_width", "]", "=", "(", "last", "[", ":width", "]", "*", "(", "s", "[", ":width_pc", "]", ".", "to_i", "*", "0.01", ")", ")", ".", "floor", "end", "end", "if", "s", "[", ":height_pc", "]", "if", "last", ".", "is_a?", "WsFlow", "s", "[", ":height", "]", "=", "(", "(", "last", "[", ":height", "]", "*", "s", "[", ":height_pc", "]", ".", "to_i", ")", "/", "100", ")", ".", "floor", "else", "# this works only for flows within stacks not for an object unless", "# you put a single object in a flow", "s", "[", ":item_height", "]", "=", "(", "(", "last", "[", ":height", "]", "*", "s", "[", ":height_pc", "]", ".", "to_i", ")", "/", "100", ")", ".", "floor", "end", "#alert \"item height set as #{s[:height]} for #{s} \"", "end", "if", "last", ".", "is_a?", "WsStack", "s", "[", ":row", "]", "+=", "(", "last", "[", ":row", "]", "||", "0", ")", "s", "[", ":col", "]", "+=", "(", "last", "[", ":col", "]", "||", "0", ")", "else", "s", "[", ":row", "]", "+=", "(", "last", "[", ":row", "]", "||", "0", ")", "s", "[", ":col", "]", "+=", "(", "last", "[", ":col", "]", "||", "0", ")", "# we are updating with item_width as each st finishes", "s", "[", ":width", "]", "||=", "last", "[", ":item_width", "]", "# ", "end", "else", "# this should be outer most flow or stack, if nothing mentioned", "# trying this out", "s", "[", ":width", "]", "||=", ":expand", "s", "[", ":height", "]", "||=", ":expand", "s", "[", ":width", "]", "=", "FFI", "::", "NCurses", ".", "COLS", "-", "s", "[", ":col", "]", "if", "s", "[", ":width", "]", "==", ":expand", "s", "[", ":height", "]", "=", "FFI", "::", "NCurses", ".", "LINES", "-", "s", "[", ":row", "]", "if", "s", "[", ":height", "]", "==", ":expand", "# 2011-11-30 ", "end", "s", "[", ":components", "]", "=", "[", "]", "end" ]
This configures a stack or flow not the objects inside
[ "This", "configures", "a", "stack", "or", "flow", "not", "the", "objects", "inside" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/widgetshortcuts.rb#L469-L513
23,773
CloudStack-extras/knife-cloudstack
lib/chef/knife/cs_server_create.rb
KnifeCloudstack.CsServerCreate.is_ssh_open?
def is_ssh_open?(ip) s = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) sa = Socket.sockaddr_in(locate_config_value(:ssh_port), ip) begin s.connect_nonblock(sa) rescue Errno::EINPROGRESS resp = IO.select(nil, [s], nil, 1) if resp.nil? sleep SSH_POLL_INTERVAL return false end begin s.connect_nonblock(sa) rescue Errno::EISCONN Chef::Log.debug("sshd accepting connections on #{ip}") yield return true rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH sleep SSH_POLL_INTERVAL return false end ensure s && s.close end end
ruby
def is_ssh_open?(ip) s = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) sa = Socket.sockaddr_in(locate_config_value(:ssh_port), ip) begin s.connect_nonblock(sa) rescue Errno::EINPROGRESS resp = IO.select(nil, [s], nil, 1) if resp.nil? sleep SSH_POLL_INTERVAL return false end begin s.connect_nonblock(sa) rescue Errno::EISCONN Chef::Log.debug("sshd accepting connections on #{ip}") yield return true rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH sleep SSH_POLL_INTERVAL return false end ensure s && s.close end end
[ "def", "is_ssh_open?", "(", "ip", ")", "s", "=", "Socket", ".", "new", "(", "Socket", "::", "AF_INET", ",", "Socket", "::", "SOCK_STREAM", ",", "0", ")", "sa", "=", "Socket", ".", "sockaddr_in", "(", "locate_config_value", "(", ":ssh_port", ")", ",", "ip", ")", "begin", "s", ".", "connect_nonblock", "(", "sa", ")", "rescue", "Errno", "::", "EINPROGRESS", "resp", "=", "IO", ".", "select", "(", "nil", ",", "[", "s", "]", ",", "nil", ",", "1", ")", "if", "resp", ".", "nil?", "sleep", "SSH_POLL_INTERVAL", "return", "false", "end", "begin", "s", ".", "connect_nonblock", "(", "sa", ")", "rescue", "Errno", "::", "EISCONN", "Chef", "::", "Log", ".", "debug", "(", "\"sshd accepting connections on #{ip}\"", ")", "yield", "return", "true", "rescue", "Errno", "::", "ECONNREFUSED", ",", "Errno", "::", "EHOSTUNREACH", "sleep", "SSH_POLL_INTERVAL", "return", "false", "end", "ensure", "s", "&&", "s", ".", "close", "end", "end" ]
noinspection RubyArgCount,RubyResolve
[ "noinspection", "RubyArgCount", "RubyResolve" ]
7fa996cabac740b8c29e7b0c84508134372823bd
https://github.com/CloudStack-extras/knife-cloudstack/blob/7fa996cabac740b8c29e7b0c84508134372823bd/lib/chef/knife/cs_server_create.rb#L539-L565
23,774
kristianmandrup/cream
lib/cream/controller/user_control.rb
Cream.UserControl.sign_in
def sign_in(resource_or_scope, *args) options = args.extract_options! scope = Devise::Mapping.find_scope!(resource_or_scope) resource = args.last || resource_or_scope expire_session_data_after_sign_in! warden.set_user(resource, options.merge!(:scope => scope)) # set user id post_signin resource, options end
ruby
def sign_in(resource_or_scope, *args) options = args.extract_options! scope = Devise::Mapping.find_scope!(resource_or_scope) resource = args.last || resource_or_scope expire_session_data_after_sign_in! warden.set_user(resource, options.merge!(:scope => scope)) # set user id post_signin resource, options end
[ "def", "sign_in", "(", "resource_or_scope", ",", "*", "args", ")", "options", "=", "args", ".", "extract_options!", "scope", "=", "Devise", "::", "Mapping", ".", "find_scope!", "(", "resource_or_scope", ")", "resource", "=", "args", ".", "last", "||", "resource_or_scope", "expire_session_data_after_sign_in!", "warden", ".", "set_user", "(", "resource", ",", "options", ".", "merge!", "(", ":scope", "=>", "scope", ")", ")", "# set user id", "post_signin", "resource", ",", "options", "end" ]
Sign in an user that already was authenticated. This helper is useful for logging users in after sign up. Examples: sign_in :user, @user # sign_in(scope, resource) sign_in @user # sign_in(resource) sign_in @user, :event => :authentication # sign_in(resource, options)
[ "Sign", "in", "an", "user", "that", "already", "was", "authenticated", ".", "This", "helper", "is", "useful", "for", "logging", "users", "in", "after", "sign", "up", "." ]
6edbdc8796b4a942e11d1054649b2e058c90c9d8
https://github.com/kristianmandrup/cream/blob/6edbdc8796b4a942e11d1054649b2e058c90c9d8/lib/cream/controller/user_control.rb#L54-L63
23,775
kristianmandrup/cream
lib/cream/controller/user_control.rb
Cream.UserControl.sign_out
def sign_out(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) warden.user(scope) # Without loading user here, before_logout hook is not called warden.raw_session.inspect # Without this inspect here. The session does not clear. warden.logout(scope) # user id post_signout scope end
ruby
def sign_out(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) warden.user(scope) # Without loading user here, before_logout hook is not called warden.raw_session.inspect # Without this inspect here. The session does not clear. warden.logout(scope) # user id post_signout scope end
[ "def", "sign_out", "(", "resource_or_scope", ")", "scope", "=", "Devise", "::", "Mapping", ".", "find_scope!", "(", "resource_or_scope", ")", "warden", ".", "user", "(", "scope", ")", "# Without loading user here, before_logout hook is not called", "warden", ".", "raw_session", ".", "inspect", "# Without this inspect here. The session does not clear.", "warden", ".", "logout", "(", "scope", ")", "# user id ", "post_signout", "scope", "end" ]
Sign out a given user or scope. This helper is useful for signing out an user after deleting accounts. Examples: sign_out :user # sign_out(scope) sign_out @user # sign_out(resource)
[ "Sign", "out", "a", "given", "user", "or", "scope", ".", "This", "helper", "is", "useful", "for", "signing", "out", "an", "user", "after", "deleting", "accounts", "." ]
6edbdc8796b4a942e11d1054649b2e058c90c9d8
https://github.com/kristianmandrup/cream/blob/6edbdc8796b4a942e11d1054649b2e058c90c9d8/lib/cream/controller/user_control.rb#L78-L85
23,776
mare-imbrium/canis
lib/canis/core/widgets/extras/rtextarea.rb
Canis.TextArea.insert
def insert off0, data _maxlen = @maxlen || @width - @internal_width if data.length > _maxlen data = wrap_text data # $log.debug "after wrap text done :#{data}" data = data.split("\n") data[-1] << "\r" #XXXX data.each do |row| @list.insert off0, row off0 += 1 end else data << "\r" if data[-1,1] != "\r" #XXXX @list.insert off0, data end # expecting array !! #data.each do |row| #@list.insert off0, row #off0 += 1 #end #$log.debug " AFTER INSERT: #{@list}" end
ruby
def insert off0, data _maxlen = @maxlen || @width - @internal_width if data.length > _maxlen data = wrap_text data # $log.debug "after wrap text done :#{data}" data = data.split("\n") data[-1] << "\r" #XXXX data.each do |row| @list.insert off0, row off0 += 1 end else data << "\r" if data[-1,1] != "\r" #XXXX @list.insert off0, data end # expecting array !! #data.each do |row| #@list.insert off0, row #off0 += 1 #end #$log.debug " AFTER INSERT: #{@list}" end
[ "def", "insert", "off0", ",", "data", "_maxlen", "=", "@maxlen", "||", "@width", "-", "@internal_width", "if", "data", ".", "length", ">", "_maxlen", "data", "=", "wrap_text", "data", "# $log.debug \"after wrap text done :#{data}\"", "data", "=", "data", ".", "split", "(", "\"\\n\"", ")", "data", "[", "-", "1", "]", "<<", "\"\\r\"", "#XXXX", "data", ".", "each", "do", "|", "row", "|", "@list", ".", "insert", "off0", ",", "row", "off0", "+=", "1", "end", "else", "data", "<<", "\"\\r\"", "if", "data", "[", "-", "1", ",", "1", "]", "!=", "\"\\r\"", "#XXXX", "@list", ".", "insert", "off0", ",", "data", "end", "# expecting array !! ", "#data.each do |row|", "#@list.insert off0, row", "#off0 += 1", "#end", "#$log.debug \" AFTER INSERT: #{@list}\"", "end" ]
trying to wrap and insert
[ "trying", "to", "wrap", "and", "insert" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/extras/rtextarea.rb#L114-L135
23,777
mare-imbrium/canis
lib/canis/core/widgets/extras/rtextarea.rb
Canis.TextArea.<<
def << data # if width if nil, either set it, or add this to a container that sets it before calling this method _maxlen = @maxlen || @width - @internal_width if data.length > _maxlen #$log.debug "wrapped append for #{data}" data = wrap_text data #$log.debug "after wrap text for :#{data}" data = data.split("\n") # 2009-01-01 22:24 the \n was needed so we would put a space at time of writing. # we need a soft return so a space can be added when pushing down. # commented off 2008-12-28 21:59 #data.each {|line| @list << line+"\n"} data.each {|line| @list << line} @list[-1] << "\r" #XXXX else #$log.debug "normal append for #{data}" data << "\r" if data[-1,1] != "\r" #XXXX @list << data end set_modified # added 2009-03-07 18:29 goto_end if @auto_scroll self end
ruby
def << data # if width if nil, either set it, or add this to a container that sets it before calling this method _maxlen = @maxlen || @width - @internal_width if data.length > _maxlen #$log.debug "wrapped append for #{data}" data = wrap_text data #$log.debug "after wrap text for :#{data}" data = data.split("\n") # 2009-01-01 22:24 the \n was needed so we would put a space at time of writing. # we need a soft return so a space can be added when pushing down. # commented off 2008-12-28 21:59 #data.each {|line| @list << line+"\n"} data.each {|line| @list << line} @list[-1] << "\r" #XXXX else #$log.debug "normal append for #{data}" data << "\r" if data[-1,1] != "\r" #XXXX @list << data end set_modified # added 2009-03-07 18:29 goto_end if @auto_scroll self end
[ "def", "<<", "data", "# if width if nil, either set it, or add this to a container that sets it before calling this method", "_maxlen", "=", "@maxlen", "||", "@width", "-", "@internal_width", "if", "data", ".", "length", ">", "_maxlen", "#$log.debug \"wrapped append for #{data}\"", "data", "=", "wrap_text", "data", "#$log.debug \"after wrap text for :#{data}\"", "data", "=", "data", ".", "split", "(", "\"\\n\"", ")", "# 2009-01-01 22:24 the \\n was needed so we would put a space at time of writing.", "# we need a soft return so a space can be added when pushing down.", "# commented off 2008-12-28 21:59 ", "#data.each {|line| @list << line+\"\\n\"}", "data", ".", "each", "{", "|", "line", "|", "@list", "<<", "line", "}", "@list", "[", "-", "1", "]", "<<", "\"\\r\"", "#XXXX", "else", "#$log.debug \"normal append for #{data}\"", "data", "<<", "\"\\r\"", "if", "data", "[", "-", "1", ",", "1", "]", "!=", "\"\\r\"", "#XXXX", "@list", "<<", "data", "end", "set_modified", "# added 2009-03-07 18:29 ", "goto_end", "if", "@auto_scroll", "self", "end" ]
wraps line sent in if longer than _maxlen Typically a line is sent in. We wrap and put a hard return at end.
[ "wraps", "line", "sent", "in", "if", "longer", "than", "_maxlen", "Typically", "a", "line", "is", "sent", "in", ".", "We", "wrap", "and", "put", "a", "hard", "return", "at", "end", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/extras/rtextarea.rb#L139-L161
23,778
mare-imbrium/canis
lib/canis/core/widgets/extras/rtextarea.rb
Canis.TextArea.undo_delete
def undo_delete # added 2008-11-27 12:43 paste delete buffer into insertion point return if @delete_buffer.nil? $log.warn "undo_delete is broken! perhaps cannot be used . textarea 347 " # FIXME - can be an array case @delete_buffer when Array # we need to unroll array, and it could be lines not just a string str = @delete_buffer.first else str = @delete_buffer end @buffer.insert @curpos, str set_modified fire_handler :CHANGE, InputDataEvent.new(@curpos,@curpos+@delete_buffer.length, self, :INSERT, @current_index, @delete_buffer) # 2008-12-24 18:34 end
ruby
def undo_delete # added 2008-11-27 12:43 paste delete buffer into insertion point return if @delete_buffer.nil? $log.warn "undo_delete is broken! perhaps cannot be used . textarea 347 " # FIXME - can be an array case @delete_buffer when Array # we need to unroll array, and it could be lines not just a string str = @delete_buffer.first else str = @delete_buffer end @buffer.insert @curpos, str set_modified fire_handler :CHANGE, InputDataEvent.new(@curpos,@curpos+@delete_buffer.length, self, :INSERT, @current_index, @delete_buffer) # 2008-12-24 18:34 end
[ "def", "undo_delete", "# added 2008-11-27 12:43 paste delete buffer into insertion point", "return", "if", "@delete_buffer", ".", "nil?", "$log", ".", "warn", "\"undo_delete is broken! perhaps cannot be used . textarea 347 \"", "# FIXME - can be an array", "case", "@delete_buffer", "when", "Array", "# we need to unroll array, and it could be lines not just a string", "str", "=", "@delete_buffer", ".", "first", "else", "str", "=", "@delete_buffer", "end", "@buffer", ".", "insert", "@curpos", ",", "str", "set_modified", "fire_handler", ":CHANGE", ",", "InputDataEvent", ".", "new", "(", "@curpos", ",", "@curpos", "+", "@delete_buffer", ".", "length", ",", "self", ",", ":INSERT", ",", "@current_index", ",", "@delete_buffer", ")", "# 2008-12-24 18:34 ", "end" ]
this is broken, delete_buffer could be a line or a string or array of lines
[ "this", "is", "broken", "delete_buffer", "could", "be", "a", "line", "or", "a", "string", "or", "array", "of", "lines" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/extras/rtextarea.rb#L376-L391
23,779
mare-imbrium/canis
lib/canis/core/widgets/extras/rtextarea.rb
Canis.TextArea.insert_break
def insert_break return -1 unless @editable # insert a blank row and append rest of this line to cursor $log.debug "ENTER PRESSED at #{@curpos}, on row #{@current_index}" @delete_buffer = (delete_eol || "") @list[@current_index] << "\r" $log.debug "DELETE BUFFER #{@delete_buffer}" @list.insert @current_index+1, @delete_buffer @curpos = 0 down col = @orig_col + @col_offset setrowcol @row+1, col # FIXME maybe this should be insert line since line inserted, not just data, undo will delete it fire_handler :CHANGE, InputDataEvent.new(@curpos,@curpos+@delete_buffer.length, self, :INSERT_LINE, @current_index, @delete_buffer) # 2008-12-24 18:34 end
ruby
def insert_break return -1 unless @editable # insert a blank row and append rest of this line to cursor $log.debug "ENTER PRESSED at #{@curpos}, on row #{@current_index}" @delete_buffer = (delete_eol || "") @list[@current_index] << "\r" $log.debug "DELETE BUFFER #{@delete_buffer}" @list.insert @current_index+1, @delete_buffer @curpos = 0 down col = @orig_col + @col_offset setrowcol @row+1, col # FIXME maybe this should be insert line since line inserted, not just data, undo will delete it fire_handler :CHANGE, InputDataEvent.new(@curpos,@curpos+@delete_buffer.length, self, :INSERT_LINE, @current_index, @delete_buffer) # 2008-12-24 18:34 end
[ "def", "insert_break", "return", "-", "1", "unless", "@editable", "# insert a blank row and append rest of this line to cursor", "$log", ".", "debug", "\"ENTER PRESSED at #{@curpos}, on row #{@current_index}\"", "@delete_buffer", "=", "(", "delete_eol", "||", "\"\"", ")", "@list", "[", "@current_index", "]", "<<", "\"\\r\"", "$log", ".", "debug", "\"DELETE BUFFER #{@delete_buffer}\"", "@list", ".", "insert", "@current_index", "+", "1", ",", "@delete_buffer", "@curpos", "=", "0", "down", "col", "=", "@orig_col", "+", "@col_offset", "setrowcol", "@row", "+", "1", ",", "col", "# FIXME maybe this should be insert line since line inserted, not just data, undo will delete it", "fire_handler", ":CHANGE", ",", "InputDataEvent", ".", "new", "(", "@curpos", ",", "@curpos", "+", "@delete_buffer", ".", "length", ",", "self", ",", ":INSERT_LINE", ",", "@current_index", ",", "@delete_buffer", ")", "# 2008-12-24 18:34 ", "end" ]
FIXME - fire event not correct, not undo'ing correctly, check row and also slash r append
[ "FIXME", "-", "fire", "event", "not", "correct", "not", "undo", "ing", "correctly", "check", "row", "and", "also", "slash", "r", "append" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/extras/rtextarea.rb#L393-L407
23,780
mare-imbrium/canis
lib/canis/core/widgets/extras/rtextarea.rb
Canis.TextArea.set_form_col
def set_form_col col1=@curpos @curpos = col1 @cols_panned ||= 0 cursor_bounds_check ## added win_col on 2009-12-28 20:21 for embedded forms BUFFERED TRYING OUT win_col = 0 # 2010-02-07 23:19 new cursor stuff #col = win_col + @orig_col + @col_offset + @curpos #col = win_col + @orig_col + @col_offset + @curpos + @cols_panned # 2010-01-14 13:31 changed orig_col to col for embedded forms, splitpanes. col = win_col + @col + @col_offset + @curpos + @cols_panned $log.debug "sfc: wc:#{win_col} col:#{@col}, coff:#{@col_offset}. cp:#{@curpos} colsp:#{@cols_panned} . " #@form.setrowcol @form.row, col # added 2009-12-29 18:50 BUFFERED $log.debug " TA calling setformrow col nil, #{col} " setrowcol nil, col # added 2009-12-29 18:50 BUFFERED @repaint_footer_required = true end
ruby
def set_form_col col1=@curpos @curpos = col1 @cols_panned ||= 0 cursor_bounds_check ## added win_col on 2009-12-28 20:21 for embedded forms BUFFERED TRYING OUT win_col = 0 # 2010-02-07 23:19 new cursor stuff #col = win_col + @orig_col + @col_offset + @curpos #col = win_col + @orig_col + @col_offset + @curpos + @cols_panned # 2010-01-14 13:31 changed orig_col to col for embedded forms, splitpanes. col = win_col + @col + @col_offset + @curpos + @cols_panned $log.debug "sfc: wc:#{win_col} col:#{@col}, coff:#{@col_offset}. cp:#{@curpos} colsp:#{@cols_panned} . " #@form.setrowcol @form.row, col # added 2009-12-29 18:50 BUFFERED $log.debug " TA calling setformrow col nil, #{col} " setrowcol nil, col # added 2009-12-29 18:50 BUFFERED @repaint_footer_required = true end
[ "def", "set_form_col", "col1", "=", "@curpos", "@curpos", "=", "col1", "@cols_panned", "||=", "0", "cursor_bounds_check", "## added win_col on 2009-12-28 20:21 for embedded forms BUFFERED TRYING OUT", "win_col", "=", "0", "# 2010-02-07 23:19 new cursor stuff", "#col = win_col + @orig_col + @col_offset + @curpos", "#col = win_col + @orig_col + @col_offset + @curpos + @cols_panned", "# 2010-01-14 13:31 changed orig_col to col for embedded forms, splitpanes.", "col", "=", "win_col", "+", "@col", "+", "@col_offset", "+", "@curpos", "+", "@cols_panned", "$log", ".", "debug", "\"sfc: wc:#{win_col} col:#{@col}, coff:#{@col_offset}. cp:#{@curpos} colsp:#{@cols_panned} . \"", "#@form.setrowcol @form.row, col # added 2009-12-29 18:50 BUFFERED", "$log", ".", "debug", "\" TA calling setformrow col nil, #{col} \"", "setrowcol", "nil", ",", "col", "# added 2009-12-29 18:50 BUFFERED", "@repaint_footer_required", "=", "true", "end" ]
set cursor on correct column
[ "set", "cursor", "on", "correct", "column" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/extras/rtextarea.rb#L409-L425
23,781
mare-imbrium/canis
lib/canis/core/widgets/extras/rtextarea.rb
Canis.TextArea.insert_wrap
def insert_wrap lineno, pos, lastchars _maxlen = @maxlen || @width - @internal_width @list[lineno].insert pos, lastchars len = @list[lineno].length if len > _maxlen push_last_word lineno #- sometime i may push down 10 chars but the last word is less end end
ruby
def insert_wrap lineno, pos, lastchars _maxlen = @maxlen || @width - @internal_width @list[lineno].insert pos, lastchars len = @list[lineno].length if len > _maxlen push_last_word lineno #- sometime i may push down 10 chars but the last word is less end end
[ "def", "insert_wrap", "lineno", ",", "pos", ",", "lastchars", "_maxlen", "=", "@maxlen", "||", "@width", "-", "@internal_width", "@list", "[", "lineno", "]", ".", "insert", "pos", ",", "lastchars", "len", "=", "@list", "[", "lineno", "]", ".", "length", "if", "len", ">", "_maxlen", "push_last_word", "lineno", "#- sometime i may push down 10 chars but the last word is less", "end", "end" ]
this attempts to recursively insert into a row, seeing that any stuff exceeding is pushed down further. Yes, it should check for a para end and insert. Currently it could add to next para.
[ "this", "attempts", "to", "recursively", "insert", "into", "a", "row", "seeing", "that", "any", "stuff", "exceeding", "is", "pushed", "down", "further", ".", "Yes", "it", "should", "check", "for", "a", "para", "end", "and", "insert", ".", "Currently", "it", "could", "add", "to", "next", "para", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/extras/rtextarea.rb#L686-L693
23,782
mare-imbrium/canis
lib/canis/core/widgets/extras/rtextarea.rb
Canis.TextArea.putch
def putch char _maxlen = @maxlen || @width - @internal_width @buffer ||= @list[@current_index] return -1 if !@editable #or @buffer.length >= _maxlen #if @chars_allowed != nil # remove useless functionality #return if char.match(@chars_allowed).nil? #end raise "putch expects only one char" if char.length != 1 oldcurpos = @curpos #$log.debug "putch : pr:#{@current_index}, cp:#{@curpos}, char:#{char}, lc:#{@buffer[-1]}, buf:(#{@buffer})" if @overwrite_mode @buffer[@curpos] = char else @buffer.insert(@curpos, char) end @curpos += 1 #$log.debug "putch INS: cp:#{@curpos}, max:#{_maxlen}, buf:(#{@buffer.length})" if @curpos-1 > _maxlen or @buffer.length()-1 > _maxlen lastchars, lastspace = push_last_word @current_index #$log.debug "last sapce #{lastspace}, lastchars:#{lastchars},lc:#{lastchars[-1]}, #{@list[@current_index]} " ## wrap on word XX If last char is 10 then insert line @buffer = @list[@current_index] if @curpos-1 > _maxlen or @curpos-1 > @buffer.length()-1 ret = down # keep the cursor in the same position in the string that was pushed down. @curpos = oldcurpos - lastspace #lastchars.length # 0 end end set_form_row @buffer = @list[@current_index] set_form_col @modified = true fire_handler :CHANGE, InputDataEvent.new(oldcurpos,@curpos, self, :INSERT, @current_index, char) # 2008-12-24 18:34 @repaint_required = true 0 end
ruby
def putch char _maxlen = @maxlen || @width - @internal_width @buffer ||= @list[@current_index] return -1 if !@editable #or @buffer.length >= _maxlen #if @chars_allowed != nil # remove useless functionality #return if char.match(@chars_allowed).nil? #end raise "putch expects only one char" if char.length != 1 oldcurpos = @curpos #$log.debug "putch : pr:#{@current_index}, cp:#{@curpos}, char:#{char}, lc:#{@buffer[-1]}, buf:(#{@buffer})" if @overwrite_mode @buffer[@curpos] = char else @buffer.insert(@curpos, char) end @curpos += 1 #$log.debug "putch INS: cp:#{@curpos}, max:#{_maxlen}, buf:(#{@buffer.length})" if @curpos-1 > _maxlen or @buffer.length()-1 > _maxlen lastchars, lastspace = push_last_word @current_index #$log.debug "last sapce #{lastspace}, lastchars:#{lastchars},lc:#{lastchars[-1]}, #{@list[@current_index]} " ## wrap on word XX If last char is 10 then insert line @buffer = @list[@current_index] if @curpos-1 > _maxlen or @curpos-1 > @buffer.length()-1 ret = down # keep the cursor in the same position in the string that was pushed down. @curpos = oldcurpos - lastspace #lastchars.length # 0 end end set_form_row @buffer = @list[@current_index] set_form_col @modified = true fire_handler :CHANGE, InputDataEvent.new(oldcurpos,@curpos, self, :INSERT, @current_index, char) # 2008-12-24 18:34 @repaint_required = true 0 end
[ "def", "putch", "char", "_maxlen", "=", "@maxlen", "||", "@width", "-", "@internal_width", "@buffer", "||=", "@list", "[", "@current_index", "]", "return", "-", "1", "if", "!", "@editable", "#or @buffer.length >= _maxlen", "#if @chars_allowed != nil # remove useless functionality", "#return if char.match(@chars_allowed).nil?", "#end", "raise", "\"putch expects only one char\"", "if", "char", ".", "length", "!=", "1", "oldcurpos", "=", "@curpos", "#$log.debug \"putch : pr:#{@current_index}, cp:#{@curpos}, char:#{char}, lc:#{@buffer[-1]}, buf:(#{@buffer})\"", "if", "@overwrite_mode", "@buffer", "[", "@curpos", "]", "=", "char", "else", "@buffer", ".", "insert", "(", "@curpos", ",", "char", ")", "end", "@curpos", "+=", "1", "#$log.debug \"putch INS: cp:#{@curpos}, max:#{_maxlen}, buf:(#{@buffer.length})\"", "if", "@curpos", "-", "1", ">", "_maxlen", "or", "@buffer", ".", "length", "(", ")", "-", "1", ">", "_maxlen", "lastchars", ",", "lastspace", "=", "push_last_word", "@current_index", "#$log.debug \"last sapce #{lastspace}, lastchars:#{lastchars},lc:#{lastchars[-1]}, #{@list[@current_index]} \"", "## wrap on word XX If last char is 10 then insert line", "@buffer", "=", "@list", "[", "@current_index", "]", "if", "@curpos", "-", "1", ">", "_maxlen", "or", "@curpos", "-", "1", ">", "@buffer", ".", "length", "(", ")", "-", "1", "ret", "=", "down", "# keep the cursor in the same position in the string that was pushed down.", "@curpos", "=", "oldcurpos", "-", "lastspace", "#lastchars.length # 0", "end", "end", "set_form_row", "@buffer", "=", "@list", "[", "@current_index", "]", "set_form_col", "@modified", "=", "true", "fire_handler", ":CHANGE", ",", "InputDataEvent", ".", "new", "(", "oldcurpos", ",", "@curpos", ",", "self", ",", ":INSERT", ",", "@current_index", ",", "char", ")", "# 2008-12-24 18:34 ", "@repaint_required", "=", "true", "0", "end" ]
add one char. careful, i shoved a string in yesterday.
[ "add", "one", "char", ".", "careful", "i", "shoved", "a", "string", "in", "yesterday", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/extras/rtextarea.rb#L696-L731
23,783
mare-imbrium/canis
lib/canis/core/widgets/extras/rtextarea.rb
Canis.TextArea.remove_last_word
def remove_last_word lineno @list[lineno].chomp! line=@list[lineno] lastspace = line.rindex(" ") if !lastspace.nil? lastchars = line[lastspace+1..-1] @list[lineno].slice!(lastspace..-1) $log.debug " remove_last: lastspace #{lastspace},#{lastchars},#{@list[lineno]}" fire_handler :CHANGE, InputDataEvent.new(lastspace,lastchars.length, self, :DELETE, lineno, lastchars) # 2008-12-26 23:06 return lastchars end return nil end
ruby
def remove_last_word lineno @list[lineno].chomp! line=@list[lineno] lastspace = line.rindex(" ") if !lastspace.nil? lastchars = line[lastspace+1..-1] @list[lineno].slice!(lastspace..-1) $log.debug " remove_last: lastspace #{lastspace},#{lastchars},#{@list[lineno]}" fire_handler :CHANGE, InputDataEvent.new(lastspace,lastchars.length, self, :DELETE, lineno, lastchars) # 2008-12-26 23:06 return lastchars end return nil end
[ "def", "remove_last_word", "lineno", "@list", "[", "lineno", "]", ".", "chomp!", "line", "=", "@list", "[", "lineno", "]", "lastspace", "=", "line", ".", "rindex", "(", "\" \"", ")", "if", "!", "lastspace", ".", "nil?", "lastchars", "=", "line", "[", "lastspace", "+", "1", "..", "-", "1", "]", "@list", "[", "lineno", "]", ".", "slice!", "(", "lastspace", "..", "-", "1", ")", "$log", ".", "debug", "\" remove_last: lastspace #{lastspace},#{lastchars},#{@list[lineno]}\"", "fire_handler", ":CHANGE", ",", "InputDataEvent", ".", "new", "(", "lastspace", ",", "lastchars", ".", "length", ",", "self", ",", ":DELETE", ",", "lineno", ",", "lastchars", ")", "# 2008-12-26 23:06 ", "return", "lastchars", "end", "return", "nil", "end" ]
removes and returns last word in given line number, or nil if no whitespace
[ "removes", "and", "returns", "last", "word", "in", "given", "line", "number", "or", "nil", "if", "no", "whitespace" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/extras/rtextarea.rb#L733-L745
23,784
mare-imbrium/canis
lib/canis/core/widgets/extras/rtextarea.rb
Canis.TextArea.move_chars_up
def move_chars_up oldprow = @current_index oldcurpos = @curpos _maxlen = @maxlen || @width - @internal_width space_left = _maxlen - @buffer.length can_move = [space_left, next_line.length].min carry_up = @list[@current_index+1].slice!(0, can_move) @list[@current_index] << carry_up delete_line(@current_index+1) if next_line().length==0 fire_handler :CHANGE, InputDataEvent.new(oldcurpos,oldcurpos+can_move, self, :INSERT, oldprow, carry_up) # 2008-12-24 18:34 end
ruby
def move_chars_up oldprow = @current_index oldcurpos = @curpos _maxlen = @maxlen || @width - @internal_width space_left = _maxlen - @buffer.length can_move = [space_left, next_line.length].min carry_up = @list[@current_index+1].slice!(0, can_move) @list[@current_index] << carry_up delete_line(@current_index+1) if next_line().length==0 fire_handler :CHANGE, InputDataEvent.new(oldcurpos,oldcurpos+can_move, self, :INSERT, oldprow, carry_up) # 2008-12-24 18:34 end
[ "def", "move_chars_up", "oldprow", "=", "@current_index", "oldcurpos", "=", "@curpos", "_maxlen", "=", "@maxlen", "||", "@width", "-", "@internal_width", "space_left", "=", "_maxlen", "-", "@buffer", ".", "length", "can_move", "=", "[", "space_left", ",", "next_line", ".", "length", "]", ".", "min", "carry_up", "=", "@list", "[", "@current_index", "+", "1", "]", ".", "slice!", "(", "0", ",", "can_move", ")", "@list", "[", "@current_index", "]", "<<", "carry_up", "delete_line", "(", "@current_index", "+", "1", ")", "if", "next_line", "(", ")", ".", "length", "==", "0", "fire_handler", ":CHANGE", ",", "InputDataEvent", ".", "new", "(", "oldcurpos", ",", "oldcurpos", "+", "can_move", ",", "self", ",", ":INSERT", ",", "oldprow", ",", "carry_up", ")", "# 2008-12-24 18:34 ", "end" ]
tries to move up as many as possible should not be called if line ends in "\r"
[ "tries", "to", "move", "up", "as", "many", "as", "possible", "should", "not", "be", "called", "if", "line", "ends", "in", "\\", "r" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/extras/rtextarea.rb#L775-L785
23,785
mare-imbrium/canis
lib/canis/core/widgets/extras/rtextarea.rb
Canis.TextArea.get_text
def get_text l = getvalue str = "" old = " " l.each_with_index do |line, i| tmp = line.gsub("\n","") tmp.gsub!("\r", "\n") if old[-1,1] !~ /\s/ and tmp[0,1] !~ /\s/ str << " " end str << tmp old = tmp end str end
ruby
def get_text l = getvalue str = "" old = " " l.each_with_index do |line, i| tmp = line.gsub("\n","") tmp.gsub!("\r", "\n") if old[-1,1] !~ /\s/ and tmp[0,1] !~ /\s/ str << " " end str << tmp old = tmp end str end
[ "def", "get_text", "l", "=", "getvalue", "str", "=", "\"\"", "old", "=", "\" \"", "l", ".", "each_with_index", "do", "|", "line", ",", "i", "|", "tmp", "=", "line", ".", "gsub", "(", "\"\\n\"", ",", "\"\"", ")", "tmp", ".", "gsub!", "(", "\"\\r\"", ",", "\"\\n\"", ")", "if", "old", "[", "-", "1", ",", "1", "]", "!~", "/", "\\s", "/", "and", "tmp", "[", "0", ",", "1", "]", "!~", "/", "\\s", "/", "str", "<<", "\" \"", "end", "str", "<<", "tmp", "old", "=", "tmp", "end", "str", "end" ]
def to_s this was just annoying in debugs
[ "def", "to_s", "this", "was", "just", "annoying", "in", "debugs" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/extras/rtextarea.rb#L812-L826
23,786
mare-imbrium/canis
lib/canis/core/widgets/deprecated/rtree.rb
Canis.Tree.root
def root node=nil, asks_allow_children=false, &block if @treemodel return @treemodel.root unless node raise ArgumentError, "Root already set" end raise ArgumentError, "root: node cannot be nil" unless node @treemodel = Canis::DefaultTreeModel.new(node, asks_allow_children, &block) end
ruby
def root node=nil, asks_allow_children=false, &block if @treemodel return @treemodel.root unless node raise ArgumentError, "Root already set" end raise ArgumentError, "root: node cannot be nil" unless node @treemodel = Canis::DefaultTreeModel.new(node, asks_allow_children, &block) end
[ "def", "root", "node", "=", "nil", ",", "asks_allow_children", "=", "false", ",", "&", "block", "if", "@treemodel", "return", "@treemodel", ".", "root", "unless", "node", "raise", "ArgumentError", ",", "\"Root already set\"", "end", "raise", "ArgumentError", ",", "\"root: node cannot be nil\"", "unless", "node", "@treemodel", "=", "Canis", "::", "DefaultTreeModel", ".", "new", "(", "node", ",", "asks_allow_children", ",", "block", ")", "end" ]
Sets the given node as root and returns treemodel. Returns root if no argument given. Now we return root if already set Made node nillable so we can return root. @raise ArgumentError if setting a root after its set or passing nil if its not been set.
[ "Sets", "the", "given", "node", "as", "root", "and", "returns", "treemodel", ".", "Returns", "root", "if", "no", "argument", "given", ".", "Now", "we", "return", "root", "if", "already", "set", "Made", "node", "nillable", "so", "we", "can", "return", "root", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/deprecated/rtree.rb#L159-L167
23,787
mare-imbrium/canis
lib/canis/core/widgets/deprecated/rtree.rb
Canis.Tree.select_default_values
def select_default_values return if @default_value.nil? # NOTE list not yet created raise "list has not yet been created" unless @list index = node_to_row @default_value raise "could not find node #{@default_value}, #{@list} " unless index return unless index @current_index = index toggle_row_selection @default_value = nil end
ruby
def select_default_values return if @default_value.nil? # NOTE list not yet created raise "list has not yet been created" unless @list index = node_to_row @default_value raise "could not find node #{@default_value}, #{@list} " unless index return unless index @current_index = index toggle_row_selection @default_value = nil end
[ "def", "select_default_values", "return", "if", "@default_value", ".", "nil?", "# NOTE list not yet created", "raise", "\"list has not yet been created\"", "unless", "@list", "index", "=", "node_to_row", "@default_value", "raise", "\"could not find node #{@default_value}, #{@list} \"", "unless", "index", "return", "unless", "index", "@current_index", "=", "index", "toggle_row_selection", "@default_value", "=", "nil", "end" ]
thanks to shoes, not sure how this will impact since widget has text. show default value as selected and fire handler for it This is called in repaint, so can raise an error if called on creation or before repaint. Just set @default_value, and let us handle the rest. Suggestions are welcome.
[ "thanks", "to", "shoes", "not", "sure", "how", "this", "will", "impact", "since", "widget", "has", "text", ".", "show", "default", "value", "as", "selected", "and", "fire", "handler", "for", "it", "This", "is", "called", "in", "repaint", "so", "can", "raise", "an", "error", "if", "called", "on", "creation", "or", "before", "repaint", ".", "Just", "set" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/deprecated/rtree.rb#L244-L254
23,788
mare-imbrium/canis
lib/canis/core/widgets/deprecated/rtree.rb
Canis.Tree.node_to_row
def node_to_row node crow = nil @list.each_with_index { |e,i| if e == node crow = i break end } crow end
ruby
def node_to_row node crow = nil @list.each_with_index { |e,i| if e == node crow = i break end } crow end
[ "def", "node_to_row", "node", "crow", "=", "nil", "@list", ".", "each_with_index", "{", "|", "e", ",", "i", "|", "if", "e", "==", "node", "crow", "=", "i", "break", "end", "}", "crow", "end" ]
convert a given node to row
[ "convert", "a", "given", "node", "to", "row" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/deprecated/rtree.rb#L563-L572
23,789
mare-imbrium/canis
lib/canis/core/widgets/deprecated/rtree.rb
Canis.Tree.expand_parents
def expand_parents node _path = node.tree_path _path.each do |e| # if already expanded parent then break we should break #set_expanded_state(e, true) expand_node(e) end end
ruby
def expand_parents node _path = node.tree_path _path.each do |e| # if already expanded parent then break we should break #set_expanded_state(e, true) expand_node(e) end end
[ "def", "expand_parents", "node", "_path", "=", "node", ".", "tree_path", "_path", ".", "each", "do", "|", "e", "|", "# if already expanded parent then break we should break", "#set_expanded_state(e, true) ", "expand_node", "(", "e", ")", "end", "end" ]
goes up to root of this node, and expands down to this node this is often required to make a specific node visible such as in a dir listing when current dir is deep in heirarchy.
[ "goes", "up", "to", "root", "of", "this", "node", "and", "expands", "down", "to", "this", "node", "this", "is", "often", "required", "to", "make", "a", "specific", "node", "visible", "such", "as", "in", "a", "dir", "listing", "when", "current", "dir", "is", "deep", "in", "heirarchy", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/deprecated/rtree.rb#L620-L627
23,790
mare-imbrium/canis
lib/canis/core/widgets/deprecated/rtree.rb
Canis.Tree.expand_children
def expand_children node=:current_index $multiplier = 999 if !$multiplier || $multiplier == 0 node = row_to_node if node == :current_index return if node.children.empty? # or node.is_leaf? #node.children.each do |e| #expand_node e # this will keep expanding parents #expand_children e #end node.breadth_each($multiplier) do |e| expand_node e end $multiplier = 0 _structure_changed true end
ruby
def expand_children node=:current_index $multiplier = 999 if !$multiplier || $multiplier == 0 node = row_to_node if node == :current_index return if node.children.empty? # or node.is_leaf? #node.children.each do |e| #expand_node e # this will keep expanding parents #expand_children e #end node.breadth_each($multiplier) do |e| expand_node e end $multiplier = 0 _structure_changed true end
[ "def", "expand_children", "node", "=", ":current_index", "$multiplier", "=", "999", "if", "!", "$multiplier", "||", "$multiplier", "==", "0", "node", "=", "row_to_node", "if", "node", "==", ":current_index", "return", "if", "node", ".", "children", ".", "empty?", "# or node.is_leaf?", "#node.children.each do |e| ", "#expand_node e # this will keep expanding parents", "#expand_children e", "#end", "node", ".", "breadth_each", "(", "$multiplier", ")", "do", "|", "e", "|", "expand_node", "e", "end", "$multiplier", "=", "0", "_structure_changed", "true", "end" ]
this expands all the children of a node, recursively we can't use multiplier concept here since we are doing a preorder enumeration we need to do a breadth first enumeration to use a multiplier
[ "this", "expands", "all", "the", "children", "of", "a", "node", "recursively", "we", "can", "t", "use", "multiplier", "concept", "here", "since", "we", "are", "doing", "a", "preorder", "enumeration", "we", "need", "to", "do", "a", "breadth", "first", "enumeration", "to", "use", "a", "multiplier" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/deprecated/rtree.rb#L632-L645
23,791
mare-imbrium/canis
lib/canis/core/widgets/table.rb
Canis.DefaultTableRowSorter.sort
def sort return unless @model return if @sort_keys.empty? $log.debug "TABULAR SORT KEYS #{sort_keys} " # first row is the header which should remain in place # We could have kept column headers separate, but then too much of mucking around # with textpad, this way we avoid touching it header = @model.delete_at 0 begin # next line often can give error "array within array" - i think on date fields that # contain nils @model.sort!{|x,y| res = 0 @sort_keys.each { |ee| e = ee.abs-1 # since we had offsetted by 1 earlier abse = e.abs if ee < 0 xx = x[abse] yy = y[abse] # the following checks are since nil values cause an error to be raised if xx.nil? && yy.nil? res = 0 elsif xx.nil? res = 1 elsif yy.nil? res = -1 else res = y[abse] <=> x[abse] end else xx = x[e] yy = y[e] # the following checks are since nil values cause an error to be raised # whereas we want a nil to be wither treated as a zero or a blank if xx.nil? && yy.nil? res = 0 elsif xx.nil? res = -1 elsif yy.nil? res = 1 else res = x[e] <=> y[e] end end break if res != 0 } res } ensure @model.insert 0, header if header end end
ruby
def sort return unless @model return if @sort_keys.empty? $log.debug "TABULAR SORT KEYS #{sort_keys} " # first row is the header which should remain in place # We could have kept column headers separate, but then too much of mucking around # with textpad, this way we avoid touching it header = @model.delete_at 0 begin # next line often can give error "array within array" - i think on date fields that # contain nils @model.sort!{|x,y| res = 0 @sort_keys.each { |ee| e = ee.abs-1 # since we had offsetted by 1 earlier abse = e.abs if ee < 0 xx = x[abse] yy = y[abse] # the following checks are since nil values cause an error to be raised if xx.nil? && yy.nil? res = 0 elsif xx.nil? res = 1 elsif yy.nil? res = -1 else res = y[abse] <=> x[abse] end else xx = x[e] yy = y[e] # the following checks are since nil values cause an error to be raised # whereas we want a nil to be wither treated as a zero or a blank if xx.nil? && yy.nil? res = 0 elsif xx.nil? res = -1 elsif yy.nil? res = 1 else res = x[e] <=> y[e] end end break if res != 0 } res } ensure @model.insert 0, header if header end end
[ "def", "sort", "return", "unless", "@model", "return", "if", "@sort_keys", ".", "empty?", "$log", ".", "debug", "\"TABULAR SORT KEYS #{sort_keys} \"", "# first row is the header which should remain in place", "# We could have kept column headers separate, but then too much of mucking around", "# with textpad, this way we avoid touching it", "header", "=", "@model", ".", "delete_at", "0", "begin", "# next line often can give error \"array within array\" - i think on date fields that", "# contain nils", "@model", ".", "sort!", "{", "|", "x", ",", "y", "|", "res", "=", "0", "@sort_keys", ".", "each", "{", "|", "ee", "|", "e", "=", "ee", ".", "abs", "-", "1", "# since we had offsetted by 1 earlier", "abse", "=", "e", ".", "abs", "if", "ee", "<", "0", "xx", "=", "x", "[", "abse", "]", "yy", "=", "y", "[", "abse", "]", "# the following checks are since nil values cause an error to be raised", "if", "xx", ".", "nil?", "&&", "yy", ".", "nil?", "res", "=", "0", "elsif", "xx", ".", "nil?", "res", "=", "1", "elsif", "yy", ".", "nil?", "res", "=", "-", "1", "else", "res", "=", "y", "[", "abse", "]", "<=>", "x", "[", "abse", "]", "end", "else", "xx", "=", "x", "[", "e", "]", "yy", "=", "y", "[", "e", "]", "# the following checks are since nil values cause an error to be raised", "# whereas we want a nil to be wither treated as a zero or a blank", "if", "xx", ".", "nil?", "&&", "yy", ".", "nil?", "res", "=", "0", "elsif", "xx", ".", "nil?", "res", "=", "-", "1", "elsif", "yy", ".", "nil?", "res", "=", "1", "else", "res", "=", "x", "[", "e", "]", "<=>", "y", "[", "e", "]", "end", "end", "break", "if", "res", "!=", "0", "}", "res", "}", "ensure", "@model", ".", "insert", "0", ",", "header", "if", "header", "end", "end" ]
sorts the model based on sort keys and reverse flags @sort_keys contains indices to sort on @reverse_flags is an array of booleans, true for reverse, nil or false for ascending
[ "sorts", "the", "model", "based", "on", "sort", "keys", "and", "reverse", "flags" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/table.rb#L117-L168
23,792
mare-imbrium/canis
lib/canis/core/widgets/table.rb
Canis.DefaultTableRowSorter.toggle_sort_order
def toggle_sort_order index index += 1 # increase by 1, since 0 won't multiple by -1 # internally, reverse sort is maintained by multiplying number by -1 @sort_keys ||= [] if @sort_keys.first && index == @sort_keys.first.abs @sort_keys[0] *= -1 else @sort_keys.delete index # in case its already there @sort_keys.delete(index*-1) # in case its already there @sort_keys.unshift index # don't let it go on increasing if @sort_keys.size > 3 @sort_keys.pop end end end
ruby
def toggle_sort_order index index += 1 # increase by 1, since 0 won't multiple by -1 # internally, reverse sort is maintained by multiplying number by -1 @sort_keys ||= [] if @sort_keys.first && index == @sort_keys.first.abs @sort_keys[0] *= -1 else @sort_keys.delete index # in case its already there @sort_keys.delete(index*-1) # in case its already there @sort_keys.unshift index # don't let it go on increasing if @sort_keys.size > 3 @sort_keys.pop end end end
[ "def", "toggle_sort_order", "index", "index", "+=", "1", "# increase by 1, since 0 won't multiple by -1", "# internally, reverse sort is maintained by multiplying number by -1", "@sort_keys", "||=", "[", "]", "if", "@sort_keys", ".", "first", "&&", "index", "==", "@sort_keys", ".", "first", ".", "abs", "@sort_keys", "[", "0", "]", "*=", "-", "1", "else", "@sort_keys", ".", "delete", "index", "# in case its already there", "@sort_keys", ".", "delete", "(", "index", "-", "1", ")", "# in case its already there", "@sort_keys", ".", "unshift", "index", "# don't let it go on increasing", "if", "@sort_keys", ".", "size", ">", "3", "@sort_keys", ".", "pop", "end", "end", "end" ]
toggle the sort order if given column offset is primary sort key Otherwise, insert as primary sort key, ascending.
[ "toggle", "the", "sort", "order", "if", "given", "column", "offset", "is", "primary", "sort", "key", "Otherwise", "insert", "as", "primary", "sort", "key", "ascending", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/table.rb#L171-L186
23,793
mare-imbrium/canis
lib/canis/core/widgets/table.rb
Canis.DefaultTableRenderer.convert_value_to_text
def convert_value_to_text r str = [] fmt = nil field = nil # we need to loop through chash and get index from it and get that row from r each_column {|c,i| e = r[c.index] w = c.width l = e.to_s.length # if value is longer than width, then truncate it if l > w fmt = "%.#{w}s " else case c.align when :right fmt = "%#{w}s " else fmt = "%-#{w}s " end end field = fmt % e # if we really want to print a single column with color, we need to print here itself # each cell. If we want the user to use tmux formatting in the column itself ... # FIXME - this must not be done for headers. #if c.color #field = "#[fg=#{c.color}]#{field}#[/end]" #end str << field } return str end
ruby
def convert_value_to_text r str = [] fmt = nil field = nil # we need to loop through chash and get index from it and get that row from r each_column {|c,i| e = r[c.index] w = c.width l = e.to_s.length # if value is longer than width, then truncate it if l > w fmt = "%.#{w}s " else case c.align when :right fmt = "%#{w}s " else fmt = "%-#{w}s " end end field = fmt % e # if we really want to print a single column with color, we need to print here itself # each cell. If we want the user to use tmux formatting in the column itself ... # FIXME - this must not be done for headers. #if c.color #field = "#[fg=#{c.color}]#{field}#[/end]" #end str << field } return str end
[ "def", "convert_value_to_text", "r", "str", "=", "[", "]", "fmt", "=", "nil", "field", "=", "nil", "# we need to loop through chash and get index from it and get that row from r", "each_column", "{", "|", "c", ",", "i", "|", "e", "=", "r", "[", "c", ".", "index", "]", "w", "=", "c", ".", "width", "l", "=", "e", ".", "to_s", ".", "length", "# if value is longer than width, then truncate it", "if", "l", ">", "w", "fmt", "=", "\"%.#{w}s \"", "else", "case", "c", ".", "align", "when", ":right", "fmt", "=", "\"%#{w}s \"", "else", "fmt", "=", "\"%-#{w}s \"", "end", "end", "field", "=", "fmt", "%", "e", "# if we really want to print a single column with color, we need to print here itself", "# each cell. If we want the user to use tmux formatting in the column itself ...", "# FIXME - this must not be done for headers.", "#if c.color", "#field = \"#[fg=#{c.color}]#{field}#[/end]\"", "#end", "str", "<<", "field", "}", "return", "str", "end" ]
Takes the array of row data and formats it using column widths and returns an array which is used for printing return an array so caller can color columns if need be
[ "Takes", "the", "array", "of", "row", "data", "and", "formats", "it", "using", "column", "widths", "and", "returns", "an", "array", "which", "is", "used", "for", "printing" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/table.rb#L244-L274
23,794
mare-imbrium/canis
lib/canis/core/widgets/table.rb
Canis.DefaultTableRenderer.render_data
def render_data pad, lineno, text text = text.join # FIXME why repeatedly getting this colorpair cp = @color_pair att = @attrib # added for selection, but will crash if selection is not extended !!! XXX if @source.is_row_selected? lineno att = REVERSE # FIXME currentl this overflows into next row end FFI::NCurses.wattron(pad,FFI::NCurses.COLOR_PAIR(cp) | att) FFI::NCurses.mvwaddstr(pad, lineno, 0, text) FFI::NCurses.wattroff(pad,FFI::NCurses.COLOR_PAIR(cp) | att) end
ruby
def render_data pad, lineno, text text = text.join # FIXME why repeatedly getting this colorpair cp = @color_pair att = @attrib # added for selection, but will crash if selection is not extended !!! XXX if @source.is_row_selected? lineno att = REVERSE # FIXME currentl this overflows into next row end FFI::NCurses.wattron(pad,FFI::NCurses.COLOR_PAIR(cp) | att) FFI::NCurses.mvwaddstr(pad, lineno, 0, text) FFI::NCurses.wattroff(pad,FFI::NCurses.COLOR_PAIR(cp) | att) end
[ "def", "render_data", "pad", ",", "lineno", ",", "text", "text", "=", "text", ".", "join", "# FIXME why repeatedly getting this colorpair", "cp", "=", "@color_pair", "att", "=", "@attrib", "# added for selection, but will crash if selection is not extended !!! XXX", "if", "@source", ".", "is_row_selected?", "lineno", "att", "=", "REVERSE", "# FIXME currentl this overflows into next row", "end", "FFI", "::", "NCurses", ".", "wattron", "(", "pad", ",", "FFI", "::", "NCurses", ".", "COLOR_PAIR", "(", "cp", ")", "|", "att", ")", "FFI", "::", "NCurses", ".", "mvwaddstr", "(", "pad", ",", "lineno", ",", "0", ",", "text", ")", "FFI", "::", "NCurses", ".", "wattroff", "(", "pad", ",", "FFI", "::", "NCurses", ".", "COLOR_PAIR", "(", "cp", ")", "|", "att", ")", "end" ]
passes padded data for final printing or data row this allows user to do row related coloring without having to tamper with the headers or other internal workings. This will not be called if column specific colorign is in effect. @param text is an array of strings, in the order of actual printing with hidden cols removed
[ "passes", "padded", "data", "for", "final", "printing", "or", "data", "row", "this", "allows", "user", "to", "do", "row", "related", "coloring", "without", "having", "to", "tamper", "with", "the", "headers", "or", "other", "internal", "workings", ".", "This", "will", "not", "be", "called", "if", "column", "specific", "colorign", "is", "in", "effect", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/table.rb#L307-L321
23,795
mare-imbrium/canis
lib/canis/core/widgets/table.rb
Canis.DefaultTableRenderer.check_colors
def check_colors each_column {|c,i| if c.color || c.bgcolor || c.attrib @_check_coloring = true return end @_check_coloring = false } end
ruby
def check_colors each_column {|c,i| if c.color || c.bgcolor || c.attrib @_check_coloring = true return end @_check_coloring = false } end
[ "def", "check_colors", "each_column", "{", "|", "c", ",", "i", "|", "if", "c", ".", "color", "||", "c", ".", "bgcolor", "||", "c", ".", "attrib", "@_check_coloring", "=", "true", "return", "end", "@_check_coloring", "=", "false", "}", "end" ]
check if we need to individually color columns or we can do the entire row in one shot
[ "check", "if", "we", "need", "to", "individually", "color", "columns", "or", "we", "can", "do", "the", "entire", "row", "in", "one", "shot" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/table.rb#L343-L351
23,796
mare-imbrium/canis
lib/canis/core/widgets/table.rb
Canis.Table.get_column
def get_column index return @chash[index] if @chash[index] # create a new entry since none present c = ColumnInfo.new c.index = index @chash[index] = c return c end
ruby
def get_column index return @chash[index] if @chash[index] # create a new entry since none present c = ColumnInfo.new c.index = index @chash[index] = c return c end
[ "def", "get_column", "index", "return", "@chash", "[", "index", "]", "if", "@chash", "[", "index", "]", "# create a new entry since none present", "c", "=", "ColumnInfo", ".", "new", "c", ".", "index", "=", "index", "@chash", "[", "index", "]", "=", "c", "return", "c", "end" ]
retrieve the column info structure for the given offset. The offset pertains to the visible offset not actual offset in data model. These two differ when we move a column. @return ColumnInfo object containing width align color bgcolor attrib hidden
[ "retrieve", "the", "column", "info", "structure", "for", "the", "given", "offset", ".", "The", "offset", "pertains", "to", "the", "visible", "offset", "not", "actual", "offset", "in", "data", "model", ".", "These", "two", "differ", "when", "we", "move", "a", "column", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/table.rb#L450-L457
23,797
mare-imbrium/canis
lib/canis/core/widgets/table.rb
Canis.Table.content_cols
def content_cols total = 0 #@chash.each_pair { |i, c| #@chash.each_with_index { |c, i| #next if c.hidden each_column {|c,i| w = c.width # if you use prepare_format then use w+2 due to separator symbol total += w + 1 } return total end
ruby
def content_cols total = 0 #@chash.each_pair { |i, c| #@chash.each_with_index { |c, i| #next if c.hidden each_column {|c,i| w = c.width # if you use prepare_format then use w+2 due to separator symbol total += w + 1 } return total end
[ "def", "content_cols", "total", "=", "0", "#@chash.each_pair { |i, c|", "#@chash.each_with_index { |c, i|", "#next if c.hidden", "each_column", "{", "|", "c", ",", "i", "|", "w", "=", "c", ".", "width", "# if you use prepare_format then use w+2 due to separator symbol", "total", "+=", "w", "+", "1", "}", "return", "total", "end" ]
calculate pad width based on widths of columns
[ "calculate", "pad", "width", "based", "on", "widths", "of", "columns" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/table.rb#L465-L476
23,798
mare-imbrium/canis
lib/canis/core/widgets/table.rb
Canis.Table.fire_column_event
def fire_column_event eve require 'canis/core/include/ractionevent' aev = TextActionEvent.new self, eve, get_column(@column_pointer.current_index), @column_pointer.current_index, @column_pointer.last_index fire_handler eve, aev end
ruby
def fire_column_event eve require 'canis/core/include/ractionevent' aev = TextActionEvent.new self, eve, get_column(@column_pointer.current_index), @column_pointer.current_index, @column_pointer.last_index fire_handler eve, aev end
[ "def", "fire_column_event", "eve", "require", "'canis/core/include/ractionevent'", "aev", "=", "TextActionEvent", ".", "new", "self", ",", "eve", ",", "get_column", "(", "@column_pointer", ".", "current_index", ")", ",", "@column_pointer", ".", "current_index", ",", "@column_pointer", ".", "last_index", "fire_handler", "eve", ",", "aev", "end" ]
a column traversal has happened. FIXME needs to be looked into. is this consistent naming wise and are we using the correct object In old system it was TABLE_TRAVERSAL_EVENT
[ "a", "column", "traversal", "has", "happened", ".", "FIXME", "needs", "to", "be", "looked", "into", ".", "is", "this", "consistent", "naming", "wise", "and", "are", "we", "using", "the", "correct", "object", "In", "old", "system", "it", "was", "TABLE_TRAVERSAL_EVENT" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/table.rb#L551-L555
23,799
mare-imbrium/canis
lib/canis/core/widgets/table.rb
Canis.Table._init_model
def _init_model array # clear the column data -- this line should be called otherwise previous tables stuff will remain. @chash.clear array.each_with_index { |e,i| # if columns added later we could be overwriting the width c = get_column(i) c.width ||= 10 } # maintains index in current pointer and gives next or prev @column_pointer = Circular.new array.size()-1 end
ruby
def _init_model array # clear the column data -- this line should be called otherwise previous tables stuff will remain. @chash.clear array.each_with_index { |e,i| # if columns added later we could be overwriting the width c = get_column(i) c.width ||= 10 } # maintains index in current pointer and gives next or prev @column_pointer = Circular.new array.size()-1 end
[ "def", "_init_model", "array", "# clear the column data -- this line should be called otherwise previous tables stuff will remain.", "@chash", ".", "clear", "array", ".", "each_with_index", "{", "|", "e", ",", "i", "|", "# if columns added later we could be overwriting the width", "c", "=", "get_column", "(", "i", ")", "c", ".", "width", "||=", "10", "}", "# maintains index in current pointer and gives next or prev", "@column_pointer", "=", "Circular", ".", "new", "array", ".", "size", "(", ")", "-", "1", "end" ]
size each column based on widths of this row of data. Only changed width if no width for that column
[ "size", "each", "column", "based", "on", "widths", "of", "this", "row", "of", "data", ".", "Only", "changed", "width", "if", "no", "width", "for", "that", "column" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/table.rb#L649-L659