id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
22,500
willglynn/ruby-zbar
lib/zbar/image.rb
ZBar.Image.convert
def convert(format) ptr = ZBar.zbar_image_convert(@img, format) if ptr.null? raise ArgumentError, "conversion failed" else Image.new(ptr) end end
ruby
def convert(format) ptr = ZBar.zbar_image_convert(@img, format) if ptr.null? raise ArgumentError, "conversion failed" else Image.new(ptr) end end
[ "def", "convert", "(", "format", ")", "ptr", "=", "ZBar", ".", "zbar_image_convert", "(", "@img", ",", "format", ")", "if", "ptr", ".", "null?", "raise", "ArgumentError", ",", "\"conversion failed\"", "else", "Image", ".", "new", "(", "ptr", ")", "end", "end" ]
Ask ZBar to convert this image to a new format, returning a new Image. Not all conversions are possible: for example, if ZBar was built without JPEG support, it cannot convert JPEGs into anything else.
[ "Ask", "ZBar", "to", "convert", "this", "image", "to", "a", "new", "format", "returning", "a", "new", "Image", "." ]
014ce55d4f4a41597bf20f5b1c529c53ecfbfd05
https://github.com/willglynn/ruby-zbar/blob/014ce55d4f4a41597bf20f5b1c529c53ecfbfd05/lib/zbar/image.rb#L93-L100
22,501
lassebunk/metamagic
lib/metamagic/renderer.rb
Metamagic.Renderer.transform_hash
def transform_hash(hash, path = "") hash.each_with_object({}) do |(k, v), ret| key = path + k.to_s if v.is_a?(Hash) ret.merge! transform_hash(v, "#{key}:") else ret[key] = v end end end
ruby
def transform_hash(hash, path = "") hash.each_with_object({}) do |(k, v), ret| key = path + k.to_s if v.is_a?(Hash) ret.merge! transform_hash(v, "#{key}:") else ret[key] = v end end end
[ "def", "transform_hash", "(", "hash", ",", "path", "=", "\"\"", ")", "hash", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "k", ",", "v", ")", ",", "ret", "|", "key", "=", "path", "+", "k", ".", "to_s", "if", "v", ".", "is_a?", "(", "Hash", ")", "ret", ".", "merge!", "transform_hash", "(", "v", ",", "\"#{key}:\"", ")", "else", "ret", "[", "key", "]", "=", "v", "end", "end", "end" ]
Transforms a nested hash into meta property keys.
[ "Transforms", "a", "nested", "hash", "into", "meta", "property", "keys", "." ]
daf259d49795485f5c6b27a00586e0217b8f0ce4
https://github.com/lassebunk/metamagic/blob/daf259d49795485f5c6b27a00586e0217b8f0ce4/lib/metamagic/renderer.rb#L112-L122
22,502
blockchain/api-v1-client-ruby
lib/blockchain/wallet.rb
Blockchain.Wallet.parse_json
def parse_json(response) json_response = JSON.parse(response) error = json_response['error'] if !error.nil? then raise APIException.new(error) end return json_response end
ruby
def parse_json(response) json_response = JSON.parse(response) error = json_response['error'] if !error.nil? then raise APIException.new(error) end return json_response end
[ "def", "parse_json", "(", "response", ")", "json_response", "=", "JSON", ".", "parse", "(", "response", ")", "error", "=", "json_response", "[", "'error'", "]", "if", "!", "error", ".", "nil?", "then", "raise", "APIException", ".", "new", "(", "error", ")", "end", "return", "json_response", "end" ]
convenience method that parses a response into json AND makes sure there are no errors
[ "convenience", "method", "that", "parses", "a", "response", "into", "json", "AND", "makes", "sure", "there", "are", "no", "errors" ]
85423b2e20bbe6928019f6441968eacdf7ca7f81
https://github.com/blockchain/api-v1-client-ruby/blob/85423b2e20bbe6928019f6441968eacdf7ca7f81/lib/blockchain/wallet.rb#L123-L128
22,503
ruby-numo/numo-gnuplot
lib/numo/gnuplot.rb
Numo.Gnuplot.stats
def stats(filename,*args) fn = OptArg.quote(filename) opt = OptArg.parse(*args) puts send_cmd "stats #{fn} #{opt}" end
ruby
def stats(filename,*args) fn = OptArg.quote(filename) opt = OptArg.parse(*args) puts send_cmd "stats #{fn} #{opt}" end
[ "def", "stats", "(", "filename", ",", "*", "args", ")", "fn", "=", "OptArg", ".", "quote", "(", "filename", ")", "opt", "=", "OptArg", ".", "parse", "(", "args", ")", "puts", "send_cmd", "\"stats #{fn} #{opt}\"", "end" ]
This command prepares a statistical summary of the data in one or two columns of a file.
[ "This", "command", "prepares", "a", "statistical", "summary", "of", "the", "data", "in", "one", "or", "two", "columns", "of", "a", "file", "." ]
1f555ab430a1be9944002108895fabdd26942ead
https://github.com/ruby-numo/numo-gnuplot/blob/1f555ab430a1be9944002108895fabdd26942ead/lib/numo/gnuplot.rb#L135-L139
22,504
29decibel/html2markdown
lib/html2markdown/converter.rb
HTML2Markdown.Converter.parse_element
def parse_element(ele) if ele.is_a? Nokogiri::XML::Text return "#{ele.text}\n" else if (children = ele.children).count > 0 return wrap_node(ele,children.map {|ele| parse_element(ele)}.join ) else return wrap_node(ele,ele.text) end end end
ruby
def parse_element(ele) if ele.is_a? Nokogiri::XML::Text return "#{ele.text}\n" else if (children = ele.children).count > 0 return wrap_node(ele,children.map {|ele| parse_element(ele)}.join ) else return wrap_node(ele,ele.text) end end end
[ "def", "parse_element", "(", "ele", ")", "if", "ele", ".", "is_a?", "Nokogiri", "::", "XML", "::", "Text", "return", "\"#{ele.text}\\n\"", "else", "if", "(", "children", "=", "ele", ".", "children", ")", ".", "count", ">", "0", "return", "wrap_node", "(", "ele", ",", "children", ".", "map", "{", "|", "ele", "|", "parse_element", "(", "ele", ")", "}", ".", "join", ")", "else", "return", "wrap_node", "(", "ele", ",", "ele", ".", "text", ")", "end", "end", "end" ]
a normal element maybe text maybe node
[ "a", "normal", "element", "maybe", "text", "maybe", "node" ]
26c6a539a2e0540b349bd21c006d285196d5e54f
https://github.com/29decibel/html2markdown/blob/26c6a539a2e0540b349bd21c006d285196d5e54f/lib/html2markdown/converter.rb#L16-L26
22,505
29decibel/html2markdown
lib/html2markdown/converter.rb
HTML2Markdown.Converter.wrap_node
def wrap_node(node,contents=nil) result = '' contents.strip! unless contents==nil # check if there is a custom parse exist if respond_to? "parse_#{node.name}" return self.send("parse_#{node.name}",node,contents) end # skip hidden node return '' if node['style'] and node['style'] =~ /display:\s*none/ # default parse case node.name.downcase when 'i' when 'script' when 'style' when 'li' result << "* #{contents}\n" when 'blockquote' contents.split('\n').each do |part| result << ">#{contents}\n" end when 'p' result << "\n#{contents}\n" when 'strong' result << "**#{contents}**\n" when 'h1' result << "# #{contents}\n" when 'h2' result << "## #{contents}\n" when 'h3' result << "### #{contents}\n" when 'h4' result << "#### #{contents}\n" when 'h5' result << "##### #{contents}\n" when 'h6' result << "###### #{contents}\n" when 'hr' result << "****\n" when 'br' result << "\n" when 'img' result << "![#{node['alt']}](#{node['src']})" when 'a' result << "[#{contents}](#{node['href']})" else result << contents unless contents == nil end result end
ruby
def wrap_node(node,contents=nil) result = '' contents.strip! unless contents==nil # check if there is a custom parse exist if respond_to? "parse_#{node.name}" return self.send("parse_#{node.name}",node,contents) end # skip hidden node return '' if node['style'] and node['style'] =~ /display:\s*none/ # default parse case node.name.downcase when 'i' when 'script' when 'style' when 'li' result << "* #{contents}\n" when 'blockquote' contents.split('\n').each do |part| result << ">#{contents}\n" end when 'p' result << "\n#{contents}\n" when 'strong' result << "**#{contents}**\n" when 'h1' result << "# #{contents}\n" when 'h2' result << "## #{contents}\n" when 'h3' result << "### #{contents}\n" when 'h4' result << "#### #{contents}\n" when 'h5' result << "##### #{contents}\n" when 'h6' result << "###### #{contents}\n" when 'hr' result << "****\n" when 'br' result << "\n" when 'img' result << "![#{node['alt']}](#{node['src']})" when 'a' result << "[#{contents}](#{node['href']})" else result << contents unless contents == nil end result end
[ "def", "wrap_node", "(", "node", ",", "contents", "=", "nil", ")", "result", "=", "''", "contents", ".", "strip!", "unless", "contents", "==", "nil", "# check if there is a custom parse exist", "if", "respond_to?", "\"parse_#{node.name}\"", "return", "self", ".", "send", "(", "\"parse_#{node.name}\"", ",", "node", ",", "contents", ")", "end", "# skip hidden node", "return", "''", "if", "node", "[", "'style'", "]", "and", "node", "[", "'style'", "]", "=~", "/", "\\s", "/", "# default parse", "case", "node", ".", "name", ".", "downcase", "when", "'i'", "when", "'script'", "when", "'style'", "when", "'li'", "result", "<<", "\"* #{contents}\\n\"", "when", "'blockquote'", "contents", ".", "split", "(", "'\\n'", ")", ".", "each", "do", "|", "part", "|", "result", "<<", "\">#{contents}\\n\"", "end", "when", "'p'", "result", "<<", "\"\\n#{contents}\\n\"", "when", "'strong'", "result", "<<", "\"**#{contents}**\\n\"", "when", "'h1'", "result", "<<", "\"# #{contents}\\n\"", "when", "'h2'", "result", "<<", "\"## #{contents}\\n\"", "when", "'h3'", "result", "<<", "\"### #{contents}\\n\"", "when", "'h4'", "result", "<<", "\"#### #{contents}\\n\"", "when", "'h5'", "result", "<<", "\"##### #{contents}\\n\"", "when", "'h6'", "result", "<<", "\"###### #{contents}\\n\"", "when", "'hr'", "result", "<<", "\"****\\n\"", "when", "'br'", "result", "<<", "\"\\n\"", "when", "'img'", "result", "<<", "\"![#{node['alt']}](#{node['src']})\"", "when", "'a'", "result", "<<", "\"[#{contents}](#{node['href']})\"", "else", "result", "<<", "contents", "unless", "contents", "==", "nil", "end", "result", "end" ]
wrap node with markdown
[ "wrap", "node", "with", "markdown" ]
26c6a539a2e0540b349bd21c006d285196d5e54f
https://github.com/29decibel/html2markdown/blob/26c6a539a2e0540b349bd21c006d285196d5e54f/lib/html2markdown/converter.rb#L29-L77
22,506
29decibel/html2markdown
lib/html2markdown/converter.rb
HTML2Markdown.Converter.method_missing
def method_missing(name,*args,&block) self.class.send :define_method,"parse_#{name}" do |node,contents| block.call node,contents end end
ruby
def method_missing(name,*args,&block) self.class.send :define_method,"parse_#{name}" do |node,contents| block.call node,contents end end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "self", ".", "class", ".", "send", ":define_method", ",", "\"parse_#{name}\"", "do", "|", "node", ",", "contents", "|", "block", ".", "call", "node", ",", "contents", "end", "end" ]
define custom node processor
[ "define", "custom", "node", "processor" ]
26c6a539a2e0540b349bd21c006d285196d5e54f
https://github.com/29decibel/html2markdown/blob/26c6a539a2e0540b349bd21c006d285196d5e54f/lib/html2markdown/converter.rb#L80-L84
22,507
jirutka/asciidoctor-rouge
lib/asciidoctor/rouge/callouts_substitutor.rb
Asciidoctor::Rouge.CalloutsSubstitutor.convert_line
def convert_line(line_num) return '' unless @callouts.key? line_num @callouts[line_num] .map { |num| convert_callout(num) } .join(' ') end
ruby
def convert_line(line_num) return '' unless @callouts.key? line_num @callouts[line_num] .map { |num| convert_callout(num) } .join(' ') end
[ "def", "convert_line", "(", "line_num", ")", "return", "''", "unless", "@callouts", ".", "key?", "line_num", "@callouts", "[", "line_num", "]", ".", "map", "{", "|", "num", "|", "convert_callout", "(", "num", ")", "}", ".", "join", "(", "' '", ")", "end" ]
Converts the extracted callout markers for the specified line. @param line_num [Integer] the line number (1-based). @return [String] converted callout markers for the _line_num_, or an empty string if there are no callouts for that line.
[ "Converts", "the", "extracted", "callout", "markers", "for", "the", "specified", "line", "." ]
f01387cb4278c26ede3c81c2b3aa9bca9e950fd9
https://github.com/jirutka/asciidoctor-rouge/blob/f01387cb4278c26ede3c81c2b3aa9bca9e950fd9/lib/asciidoctor/rouge/callouts_substitutor.rb#L51-L57
22,508
jirutka/asciidoctor-rouge
lib/asciidoctor/rouge/html_formatter.rb
Asciidoctor::Rouge.HtmlFormatter.stream_lines
def stream_lines(tokens, line_num) yield line_start(line_num) tokens.each do |token, value| yield @inner.span(token, value) end yield line_end(line_num) end
ruby
def stream_lines(tokens, line_num) yield line_start(line_num) tokens.each do |token, value| yield @inner.span(token, value) end yield line_end(line_num) end
[ "def", "stream_lines", "(", "tokens", ",", "line_num", ")", "yield", "line_start", "(", "line_num", ")", "tokens", ".", "each", "do", "|", "token", ",", "value", "|", "yield", "@inner", ".", "span", "(", "token", ",", "value", ")", "end", "yield", "line_end", "(", "line_num", ")", "end" ]
Formats tokens on the specified line into HTML. @param tokens [Array<Rouge::Token>] tokens on the line. @param line_nums [Integer] the line number (1-based). @yield [String] gives formatted content.
[ "Formats", "tokens", "on", "the", "specified", "line", "into", "HTML", "." ]
f01387cb4278c26ede3c81c2b3aa9bca9e950fd9
https://github.com/jirutka/asciidoctor-rouge/blob/f01387cb4278c26ede3c81c2b3aa9bca9e950fd9/lib/asciidoctor/rouge/html_formatter.rb#L71-L79
22,509
aptinio/text-table
lib/text-table/table.rb
Text.Table.to_s
def to_s rendered_rows = [separator] + text_table_rows.map(&:to_s) + [separator] rendered_rows.unshift [separator, text_table_head.to_s] if head rendered_rows << [text_table_foot.to_s, separator] if foot rendered_rows.join end
ruby
def to_s rendered_rows = [separator] + text_table_rows.map(&:to_s) + [separator] rendered_rows.unshift [separator, text_table_head.to_s] if head rendered_rows << [text_table_foot.to_s, separator] if foot rendered_rows.join end
[ "def", "to_s", "rendered_rows", "=", "[", "separator", "]", "+", "text_table_rows", ".", "map", "(", ":to_s", ")", "+", "[", "separator", "]", "rendered_rows", ".", "unshift", "[", "separator", ",", "text_table_head", ".", "to_s", "]", "if", "head", "rendered_rows", "<<", "[", "text_table_foot", ".", "to_s", ",", "separator", "]", "if", "foot", "rendered_rows", ".", "join", "end" ]
Renders a pretty plain-text table.
[ "Renders", "a", "pretty", "plain", "-", "text", "table", "." ]
42b0f78f8771d4649a7d7b959bce221656eeac58
https://github.com/aptinio/text-table/blob/42b0f78f8771d4649a7d7b959bce221656eeac58/lib/text-table/table.rb#L168-L173
22,510
aptinio/text-table
lib/text-table/table.rb
Text.Table.align_column
def align_column(column_number, alignment) set_alignment = Proc.new do |row, column_number_block, alignment_block| cell = row.find do |cell_row| row[0...row.index(cell_row)].map {|c| c.is_a?(Hash) ? c[:colspan] || 1 : 1}.inject(0, &:+) == column_number_block - 1 end row[row.index(cell)] = hashify(cell, {:align => alignment_block}) if cell and not(cell.is_a?(Hash) && cell[:colspan].to_i > 0) end rows.each do |row| next if row == :separator set_alignment.call(row, column_number, alignment) end set_alignment.call(foot, column_number, alignment) if foot return self end
ruby
def align_column(column_number, alignment) set_alignment = Proc.new do |row, column_number_block, alignment_block| cell = row.find do |cell_row| row[0...row.index(cell_row)].map {|c| c.is_a?(Hash) ? c[:colspan] || 1 : 1}.inject(0, &:+) == column_number_block - 1 end row[row.index(cell)] = hashify(cell, {:align => alignment_block}) if cell and not(cell.is_a?(Hash) && cell[:colspan].to_i > 0) end rows.each do |row| next if row == :separator set_alignment.call(row, column_number, alignment) end set_alignment.call(foot, column_number, alignment) if foot return self end
[ "def", "align_column", "(", "column_number", ",", "alignment", ")", "set_alignment", "=", "Proc", ".", "new", "do", "|", "row", ",", "column_number_block", ",", "alignment_block", "|", "cell", "=", "row", ".", "find", "do", "|", "cell_row", "|", "row", "[", "0", "...", "row", ".", "index", "(", "cell_row", ")", "]", ".", "map", "{", "|", "c", "|", "c", ".", "is_a?", "(", "Hash", ")", "?", "c", "[", ":colspan", "]", "||", "1", ":", "1", "}", ".", "inject", "(", "0", ",", ":+", ")", "==", "column_number_block", "-", "1", "end", "row", "[", "row", ".", "index", "(", "cell", ")", "]", "=", "hashify", "(", "cell", ",", "{", ":align", "=>", "alignment_block", "}", ")", "if", "cell", "and", "not", "(", "cell", ".", "is_a?", "(", "Hash", ")", "&&", "cell", "[", ":colspan", "]", ".", "to_i", ">", "0", ")", "end", "rows", ".", "each", "do", "|", "row", "|", "next", "if", "row", "==", ":separator", "set_alignment", ".", "call", "(", "row", ",", "column_number", ",", "alignment", ")", "end", "set_alignment", ".", "call", "(", "foot", ",", "column_number", ",", "alignment", ")", "if", "foot", "return", "self", "end" ]
Aligns the cells and the footer of a column. table = Text::Table.new :rows => [%w(a bb), %w(aa bbb), %w(aaa b)] puts table # +-----+-----+ # | a | bb | # | aa | bbb | # | aaa | b | # +-----+-----+ table.align_column 2, :right # +-----+-----+ # | a | bb | # | aa | bbb | # | aaa | b | # +-----+-----+ Note that headers, spanned cells and cells with explicit alignments are not affected by <tt>align_column</tt>.
[ "Aligns", "the", "cells", "and", "the", "footer", "of", "a", "column", "." ]
42b0f78f8771d4649a7d7b959bce221656eeac58
https://github.com/aptinio/text-table/blob/42b0f78f8771d4649a7d7b959bce221656eeac58/lib/text-table/table.rb#L196-L209
22,511
jirutka/asciidoctor-rouge
lib/asciidoctor/rouge/passthroughs_substitutor.rb
Asciidoctor::Rouge.PassthroughsSubstitutor.restore
def restore(text) return text if @node.passthroughs.empty? # Fix passthrough placeholders that got caught up in syntax highlighting. text = text.gsub(PASS_SLOT_RX, "#{PASS_START_MARK}\\1#{PASS_END_MARK}") # Restore converted passthroughs. @node.restore_passthroughs(text) end
ruby
def restore(text) return text if @node.passthroughs.empty? # Fix passthrough placeholders that got caught up in syntax highlighting. text = text.gsub(PASS_SLOT_RX, "#{PASS_START_MARK}\\1#{PASS_END_MARK}") # Restore converted passthroughs. @node.restore_passthroughs(text) end
[ "def", "restore", "(", "text", ")", "return", "text", "if", "@node", ".", "passthroughs", ".", "empty?", "# Fix passthrough placeholders that got caught up in syntax highlighting.", "text", "=", "text", ".", "gsub", "(", "PASS_SLOT_RX", ",", "\"#{PASS_START_MARK}\\\\1#{PASS_END_MARK}\"", ")", "# Restore converted passthroughs.", "@node", ".", "restore_passthroughs", "(", "text", ")", "end" ]
Restores the extracted passthroughs by reinserting them into the placeholder positions. @param text [String] the text into which to restore the passthroughs. @return [String] a copy of the *text* with restored passthroughs.
[ "Restores", "the", "extracted", "passthroughs", "by", "reinserting", "them", "into", "the", "placeholder", "positions", "." ]
f01387cb4278c26ede3c81c2b3aa9bca9e950fd9
https://github.com/jirutka/asciidoctor-rouge/blob/f01387cb4278c26ede3c81c2b3aa9bca9e950fd9/lib/asciidoctor/rouge/passthroughs_substitutor.rb#L36-L44
22,512
voormedia/crafty
lib/crafty/tools.rb
Crafty.Tools.element!
def element!(name, content = nil, attributes = nil) build! do if content or block_given? @_crafted << "<#{name}#{Tools.format_attributes(attributes)}>" if block_given? value = yield content = value if !@_appended or value.kind_of? String end content = content.to_s @_crafted << Tools.escape(content) if content != "" @_crafted << "</#{name}>" else @_crafted << "<#{name}#{Tools.format_attributes(attributes)}/>" end end end
ruby
def element!(name, content = nil, attributes = nil) build! do if content or block_given? @_crafted << "<#{name}#{Tools.format_attributes(attributes)}>" if block_given? value = yield content = value if !@_appended or value.kind_of? String end content = content.to_s @_crafted << Tools.escape(content) if content != "" @_crafted << "</#{name}>" else @_crafted << "<#{name}#{Tools.format_attributes(attributes)}/>" end end end
[ "def", "element!", "(", "name", ",", "content", "=", "nil", ",", "attributes", "=", "nil", ")", "build!", "do", "if", "content", "or", "block_given?", "@_crafted", "<<", "\"<#{name}#{Tools.format_attributes(attributes)}>\"", "if", "block_given?", "value", "=", "yield", "content", "=", "value", "if", "!", "@_appended", "or", "value", ".", "kind_of?", "String", "end", "content", "=", "content", ".", "to_s", "@_crafted", "<<", "Tools", ".", "escape", "(", "content", ")", "if", "content", "!=", "\"\"", "@_crafted", "<<", "\"</#{name}>\"", "else", "@_crafted", "<<", "\"<#{name}#{Tools.format_attributes(attributes)}/>\"", "end", "end", "end" ]
Write an element with the given name, content and attributes. If there is no content and no block is given, a self-closing element is created. Provide an empty string as content to create an empty, non-self-closing element.
[ "Write", "an", "element", "with", "the", "given", "name", "content", "and", "attributes", ".", "If", "there", "is", "no", "content", "and", "no", "block", "is", "given", "a", "self", "-", "closing", "element", "is", "created", ".", "Provide", "an", "empty", "string", "as", "content", "to", "create", "an", "empty", "non", "-", "self", "-", "closing", "element", "." ]
fe2fcaee92f72f614ff2af2e9ba62175aabbb5bd
https://github.com/voormedia/crafty/blob/fe2fcaee92f72f614ff2af2e9ba62175aabbb5bd/lib/crafty/tools.rb#L54-L69
22,513
mindset/scorm
lib/scorm/package.rb
Scorm.Package.extract!
def extract!(force = false) return if @options[:dry_run] && !force # If opening an already extracted package; do nothing. if not package? return end # Create the path to the course FileUtils.mkdir_p(@path) Zip::ZipFile::foreach(@package) do |entry| entry_path = File.join(@path, entry.name) entry_dir = File.dirname(entry_path) FileUtils.mkdir_p(entry_dir) unless File.exists?(entry_dir) entry.extract(entry_path) end end
ruby
def extract!(force = false) return if @options[:dry_run] && !force # If opening an already extracted package; do nothing. if not package? return end # Create the path to the course FileUtils.mkdir_p(@path) Zip::ZipFile::foreach(@package) do |entry| entry_path = File.join(@path, entry.name) entry_dir = File.dirname(entry_path) FileUtils.mkdir_p(entry_dir) unless File.exists?(entry_dir) entry.extract(entry_path) end end
[ "def", "extract!", "(", "force", "=", "false", ")", "return", "if", "@options", "[", ":dry_run", "]", "&&", "!", "force", "# If opening an already extracted package; do nothing.", "if", "not", "package?", "return", "end", "# Create the path to the course", "FileUtils", ".", "mkdir_p", "(", "@path", ")", "Zip", "::", "ZipFile", "::", "foreach", "(", "@package", ")", "do", "|", "entry", "|", "entry_path", "=", "File", ".", "join", "(", "@path", ",", "entry", ".", "name", ")", "entry_dir", "=", "File", ".", "dirname", "(", "entry_path", ")", "FileUtils", ".", "mkdir_p", "(", "entry_dir", ")", "unless", "File", ".", "exists?", "(", "entry_dir", ")", "entry", ".", "extract", "(", "entry_path", ")", "end", "end" ]
Extracts the content of the package to the course repository. This will be done automatically when opening a package so this method will rarely be used. If the +dry_run+ option was set to +true+ when the package was opened nothing will happen. This behavior can be overridden with the +force+ parameter.
[ "Extracts", "the", "content", "of", "the", "package", "to", "the", "course", "repository", ".", "This", "will", "be", "done", "automatically", "when", "opening", "a", "package", "so", "this", "method", "will", "rarely", "be", "used", ".", "If", "the", "+", "dry_run", "+", "option", "was", "set", "to", "+", "true", "+", "when", "the", "package", "was", "opened", "nothing", "will", "happen", ".", "This", "behavior", "can", "be", "overridden", "with", "the", "+", "force", "+", "parameter", "." ]
b1cb060c1e38d215231bb50829e9cc686c2b5710
https://github.com/mindset/scorm/blob/b1cb060c1e38d215231bb50829e9cc686c2b5710/lib/scorm/package.rb#L123-L140
22,514
mindset/scorm
lib/scorm/package.rb
Scorm.Package.path_to
def path_to(relative_filename, relative = false) if relative File.join(@name, relative_filename) else File.join(@path, relative_filename) end end
ruby
def path_to(relative_filename, relative = false) if relative File.join(@name, relative_filename) else File.join(@path, relative_filename) end end
[ "def", "path_to", "(", "relative_filename", ",", "relative", "=", "false", ")", "if", "relative", "File", ".", "join", "(", "@name", ",", "relative_filename", ")", "else", "File", ".", "join", "(", "@path", ",", "relative_filename", ")", "end", "end" ]
Computes the absolute path to a file in an extracted package given its relative path. The argument +relative+ can be used to get the path relative to the course repository. Ex. <tt>pkg.path => '/var/lms/courses/MyCourse/'</tt> <tt>pkg.course_repository => '/var/lms/courses/'</tt> <tt>path_to('images/myimg.jpg') => '/var/lms/courses/MyCourse/images/myimg.jpg'</tt> <tt>path_to('images/myimg.jpg', true) => 'MyCourse/images/myimg.jpg'</tt>
[ "Computes", "the", "absolute", "path", "to", "a", "file", "in", "an", "extracted", "package", "given", "its", "relative", "path", ".", "The", "argument", "+", "relative", "+", "can", "be", "used", "to", "get", "the", "path", "relative", "to", "the", "course", "repository", "." ]
b1cb060c1e38d215231bb50829e9cc686c2b5710
https://github.com/mindset/scorm/blob/b1cb060c1e38d215231bb50829e9cc686c2b5710/lib/scorm/package.rb#L186-L192
22,515
notonthehighstreet/svelte
lib/svelte/swagger_builder.rb
Svelte.SwaggerBuilder.make_resource
def make_resource resource = Module.new paths.each do |path| new_module = PathBuilder.build(path: path, module_constant: resource) path.operations.each do |operation| OperationBuilder.build(operation: operation, module_constant: new_module, configuration: configuration) end end Service.const_set(module_name, resource) end
ruby
def make_resource resource = Module.new paths.each do |path| new_module = PathBuilder.build(path: path, module_constant: resource) path.operations.each do |operation| OperationBuilder.build(operation: operation, module_constant: new_module, configuration: configuration) end end Service.const_set(module_name, resource) end
[ "def", "make_resource", "resource", "=", "Module", ".", "new", "paths", ".", "each", "do", "|", "path", "|", "new_module", "=", "PathBuilder", ".", "build", "(", "path", ":", "path", ",", "module_constant", ":", "resource", ")", "path", ".", "operations", ".", "each", "do", "|", "operation", "|", "OperationBuilder", ".", "build", "(", "operation", ":", "operation", ",", "module_constant", ":", "new_module", ",", "configuration", ":", "configuration", ")", "end", "end", "Service", ".", "const_set", "(", "module_name", ",", "resource", ")", "end" ]
Creates a new SwaggerBuilder @param raw_hash [Hash] Swagger API definition @param module_name [String] name of the constant you want built @param options [Hash] Swagger API options. It will be used to build the [Configuration]. Supports the `:host` value for now. Dynamically creates a new resource on top of `Svelte::Service` with the name `module_name`, based on the Swagger API description provided in `raw_hash` @return [Module] the module built
[ "Creates", "a", "new", "SwaggerBuilder" ]
75abb1a8d65372c7df27bfa1921e55efe48839ac
https://github.com/notonthehighstreet/svelte/blob/75abb1a8d65372c7df27bfa1921e55efe48839ac/lib/svelte/swagger_builder.rb#L22-L33
22,516
notonthehighstreet/svelte
lib/svelte/model_factory.rb
Svelte.ModelFactory.define_models
def define_models(json) return unless json models = {} model_definitions = json['definitions'] model_definitions.each do |model_name, parameters| attributes = parameters['properties'].keys model = Class.new do attr_reader(*attributes.map(&:to_sym)) parameters['properties'].each do |attribute, options| define_method("#{attribute}=", lambda do |value| if public_send(attribute).nil? || !public_send(attribute).present? permitted_values = options.fetch('enum', []) required = parameters.fetch('required', []).include?(attribute) instance_variable_set( "@#{attribute}", Parameter.new(options['type'], permitted_values: permitted_values, required: required) ) end instance_variable_get("@#{attribute}").value = value end) end end define_initialize_on(model: model) define_attributes_on(model: model) define_required_attributes_on(model: model) define_json_for_model_on(model: model) define_nested_models_on(model: model) define_as_json_on(model: model) define_to_json_on(model: model) define_validate_on(model: model) define_valid_on(model: model) model.instance_variable_set('@json_for_model', parameters.freeze) constant_name_for_model = StringManipulator.constant_name_for(model_name) models[constant_name_for_model] = model end models.each do |model_name, model| const_set(model_name, model) end end
ruby
def define_models(json) return unless json models = {} model_definitions = json['definitions'] model_definitions.each do |model_name, parameters| attributes = parameters['properties'].keys model = Class.new do attr_reader(*attributes.map(&:to_sym)) parameters['properties'].each do |attribute, options| define_method("#{attribute}=", lambda do |value| if public_send(attribute).nil? || !public_send(attribute).present? permitted_values = options.fetch('enum', []) required = parameters.fetch('required', []).include?(attribute) instance_variable_set( "@#{attribute}", Parameter.new(options['type'], permitted_values: permitted_values, required: required) ) end instance_variable_get("@#{attribute}").value = value end) end end define_initialize_on(model: model) define_attributes_on(model: model) define_required_attributes_on(model: model) define_json_for_model_on(model: model) define_nested_models_on(model: model) define_as_json_on(model: model) define_to_json_on(model: model) define_validate_on(model: model) define_valid_on(model: model) model.instance_variable_set('@json_for_model', parameters.freeze) constant_name_for_model = StringManipulator.constant_name_for(model_name) models[constant_name_for_model] = model end models.each do |model_name, model| const_set(model_name, model) end end
[ "def", "define_models", "(", "json", ")", "return", "unless", "json", "models", "=", "{", "}", "model_definitions", "=", "json", "[", "'definitions'", "]", "model_definitions", ".", "each", "do", "|", "model_name", ",", "parameters", "|", "attributes", "=", "parameters", "[", "'properties'", "]", ".", "keys", "model", "=", "Class", ".", "new", "do", "attr_reader", "(", "attributes", ".", "map", "(", ":to_sym", ")", ")", "parameters", "[", "'properties'", "]", ".", "each", "do", "|", "attribute", ",", "options", "|", "define_method", "(", "\"#{attribute}=\"", ",", "lambda", "do", "|", "value", "|", "if", "public_send", "(", "attribute", ")", ".", "nil?", "||", "!", "public_send", "(", "attribute", ")", ".", "present?", "permitted_values", "=", "options", ".", "fetch", "(", "'enum'", ",", "[", "]", ")", "required", "=", "parameters", ".", "fetch", "(", "'required'", ",", "[", "]", ")", ".", "include?", "(", "attribute", ")", "instance_variable_set", "(", "\"@#{attribute}\"", ",", "Parameter", ".", "new", "(", "options", "[", "'type'", "]", ",", "permitted_values", ":", "permitted_values", ",", "required", ":", "required", ")", ")", "end", "instance_variable_get", "(", "\"@#{attribute}\"", ")", ".", "value", "=", "value", "end", ")", "end", "end", "define_initialize_on", "(", "model", ":", "model", ")", "define_attributes_on", "(", "model", ":", "model", ")", "define_required_attributes_on", "(", "model", ":", "model", ")", "define_json_for_model_on", "(", "model", ":", "model", ")", "define_nested_models_on", "(", "model", ":", "model", ")", "define_as_json_on", "(", "model", ":", "model", ")", "define_to_json_on", "(", "model", ":", "model", ")", "define_validate_on", "(", "model", ":", "model", ")", "define_valid_on", "(", "model", ":", "model", ")", "model", ".", "instance_variable_set", "(", "'@json_for_model'", ",", "parameters", ".", "freeze", ")", "constant_name_for_model", "=", "StringManipulator", ".", "constant_name_for", "(", "model_name", ")", "models", "[", "constant_name_for_model", "]", "=", "model", "end", "models", ".", "each", "do", "|", "model_name", ",", "model", "|", "const_set", "(", "model_name", ",", "model", ")", "end", "end" ]
Creates typed Ruby objects from JSON definitions. These definitions are found in the Swagger JSON spec as a top-level key, "definitions". @param json [Hash] hash of a swagger models definition @return [Hash] A hash of model names to models created
[ "Creates", "typed", "Ruby", "objects", "from", "JSON", "definitions", ".", "These", "definitions", "are", "found", "in", "the", "Swagger", "JSON", "spec", "as", "a", "top", "-", "level", "key", "definitions", "." ]
75abb1a8d65372c7df27bfa1921e55efe48839ac
https://github.com/notonthehighstreet/svelte/blob/75abb1a8d65372c7df27bfa1921e55efe48839ac/lib/svelte/model_factory.rb#L12-L58
22,517
zigotto/googl
lib/googl.rb
Googl.OAuth2.server
def server(client_id, client_secret, redirect_uri) Googl::OAuth2::Server.new(client_id, client_secret, redirect_uri) end
ruby
def server(client_id, client_secret, redirect_uri) Googl::OAuth2::Server.new(client_id, client_secret, redirect_uri) end
[ "def", "server", "(", "client_id", ",", "client_secret", ",", "redirect_uri", ")", "Googl", "::", "OAuth2", "::", "Server", ".", "new", "(", "client_id", ",", "client_secret", ",", "redirect_uri", ")", "end" ]
OAuth 2.0 for server-side web applications The server-side flow for web applications with servers that can securely store persistent information client = Googl::OAuth2.server("client_id", "client_secret", "redirect_uri")
[ "OAuth", "2", ".", "0", "for", "server", "-", "side", "web", "applications" ]
cb917a05c70bebb0deda556f2c931dd0830a4f2e
https://github.com/zigotto/googl/blob/cb917a05c70bebb0deda556f2c931dd0830a4f2e/lib/googl.rb#L128-L130
22,518
cryptosphere/cryptor
lib/cryptor/encoding.rb
Cryptor.Encoding.decode
def decode(string) padding_size = string.bytesize % 4 padded_string = padding_size > 0 ? string + '=' * (4 - padding_size) : string Base64.urlsafe_decode64(padded_string) end
ruby
def decode(string) padding_size = string.bytesize % 4 padded_string = padding_size > 0 ? string + '=' * (4 - padding_size) : string Base64.urlsafe_decode64(padded_string) end
[ "def", "decode", "(", "string", ")", "padding_size", "=", "string", ".", "bytesize", "%", "4", "padded_string", "=", "padding_size", ">", "0", "?", "string", "+", "'='", "*", "(", "4", "-", "padding_size", ")", ":", "string", "Base64", ".", "urlsafe_decode64", "(", "padded_string", ")", "end" ]
Decode an unpadded URL-safe Base64 string @param string [String] URL-safe Base64 string to be decoded (sans '=' padding) @return [String] decoded string
[ "Decode", "an", "unpadded", "URL", "-", "safe", "Base64", "string" ]
44a1263b2dede1c35b56419725bb47c213bf38d3
https://github.com/cryptosphere/cryptor/blob/44a1263b2dede1c35b56419725bb47c213bf38d3/lib/cryptor/encoding.rb#L20-L25
22,519
notonthehighstreet/svelte
lib/svelte/path.rb
Svelte.Path.operations
def operations validate_operations @operations ||= @raw_operations.map do |operation, properties| Operation.new(verb: operation, properties: properties, path: self) end end
ruby
def operations validate_operations @operations ||= @raw_operations.map do |operation, properties| Operation.new(verb: operation, properties: properties, path: self) end end
[ "def", "operations", "validate_operations", "@operations", "||=", "@raw_operations", ".", "map", "do", "|", "operation", ",", "properties", "|", "Operation", ".", "new", "(", "verb", ":", "operation", ",", "properties", ":", "properties", ",", "path", ":", "self", ")", "end", "end" ]
Creates a new Path. @param path [String] path i.e. `'/store/inventory'` @param operations [Hash] path operations Path operations @return [Array<Operation>] list of operations for the path
[ "Creates", "a", "new", "Path", "." ]
75abb1a8d65372c7df27bfa1921e55efe48839ac
https://github.com/notonthehighstreet/svelte/blob/75abb1a8d65372c7df27bfa1921e55efe48839ac/lib/svelte/path.rb#L17-L22
22,520
ombulabs/harvesting
lib/harvesting/client.rb
Harvesting.Client.create
def create(entity) url = "#{DEFAULT_HOST}/#{entity.path}" uri = URI(url) response = http_response(:post, uri, body: entity.to_hash) entity.attributes = JSON.parse(response.body) entity end
ruby
def create(entity) url = "#{DEFAULT_HOST}/#{entity.path}" uri = URI(url) response = http_response(:post, uri, body: entity.to_hash) entity.attributes = JSON.parse(response.body) entity end
[ "def", "create", "(", "entity", ")", "url", "=", "\"#{DEFAULT_HOST}/#{entity.path}\"", "uri", "=", "URI", "(", "url", ")", "response", "=", "http_response", "(", ":post", ",", "uri", ",", "body", ":", "entity", ".", "to_hash", ")", "entity", ".", "attributes", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", "entity", "end" ]
Creates an `entity` in your Harvest account. @param entity [Harvesting::Models::Base] A new record in your Harvest account @return [Harvesting::Models::Base] A subclass of `Harvesting::Models::Base` updated with the response from Harvest
[ "Creates", "an", "entity", "in", "your", "Harvest", "account", "." ]
b60135184cb0eba5ef10660560c59b63e97e025e
https://github.com/ombulabs/harvesting/blob/b60135184cb0eba5ef10660560c59b63e97e025e/lib/harvesting/client.rb#L93-L99
22,521
ombulabs/harvesting
lib/harvesting/client.rb
Harvesting.Client.delete
def delete(entity) url = "#{DEFAULT_HOST}/#{entity.path}" uri = URI(url) response = http_response(:delete, uri) raise UnprocessableRequest(response.to_s) unless response.code.to_i == 200 JSON.parse(response.body) end
ruby
def delete(entity) url = "#{DEFAULT_HOST}/#{entity.path}" uri = URI(url) response = http_response(:delete, uri) raise UnprocessableRequest(response.to_s) unless response.code.to_i == 200 JSON.parse(response.body) end
[ "def", "delete", "(", "entity", ")", "url", "=", "\"#{DEFAULT_HOST}/#{entity.path}\"", "uri", "=", "URI", "(", "url", ")", "response", "=", "http_response", "(", ":delete", ",", "uri", ")", "raise", "UnprocessableRequest", "(", "response", ".", "to_s", ")", "unless", "response", ".", "code", ".", "to_i", "==", "200", "JSON", ".", "parse", "(", "response", ".", "body", ")", "end" ]
It removes an `entity` from your Harvest account. @param entity [Harvesting::Models::Base] A record to be removed from your Harvest account @return [Hash] @raise [UnprocessableRequest] When HTTP response is not 200 OK
[ "It", "removes", "an", "entity", "from", "your", "Harvest", "account", "." ]
b60135184cb0eba5ef10660560c59b63e97e025e
https://github.com/ombulabs/harvesting/blob/b60135184cb0eba5ef10660560c59b63e97e025e/lib/harvesting/client.rb#L118-L124
22,522
ombulabs/harvesting
lib/harvesting/client.rb
Harvesting.Client.get
def get(path, opts = {}) url = "#{DEFAULT_HOST}/#{path}" url += "?#{opts.map {|k, v| "#{k}=#{v}"}.join("&")}" if opts.any? uri = URI(url) response = http_response(:get, uri) JSON.parse(response.body) end
ruby
def get(path, opts = {}) url = "#{DEFAULT_HOST}/#{path}" url += "?#{opts.map {|k, v| "#{k}=#{v}"}.join("&")}" if opts.any? uri = URI(url) response = http_response(:get, uri) JSON.parse(response.body) end
[ "def", "get", "(", "path", ",", "opts", "=", "{", "}", ")", "url", "=", "\"#{DEFAULT_HOST}/#{path}\"", "url", "+=", "\"?#{opts.map {|k, v| \"#{k}=#{v}\"}.join(\"&\")}\"", "if", "opts", ".", "any?", "uri", "=", "URI", "(", "url", ")", "response", "=", "http_response", "(", ":get", ",", "uri", ")", "JSON", ".", "parse", "(", "response", ".", "body", ")", "end" ]
Performs a GET request and returned the parsed JSON as a Hash. @param path [String] path to be combined with `DEFAULT_HOST` @param opts [Hash] key/values will get passed as HTTP (GET) parameters @return [Hash]
[ "Performs", "a", "GET", "request", "and", "returned", "the", "parsed", "JSON", "as", "a", "Hash", "." ]
b60135184cb0eba5ef10660560c59b63e97e025e
https://github.com/ombulabs/harvesting/blob/b60135184cb0eba5ef10660560c59b63e97e025e/lib/harvesting/client.rb#L131-L137
22,523
ruby-jokes/job_interview
lib/job_interview/knapsack.rb
JobInterview.Knapsack.knapsack
def knapsack(items, capacity, algorithm = :dynamic) if algorithm == :memoize knapsack_memoize(items, capacity) elsif algorithm == :dynamic knapsack_dynamic_programming(items, capacity) end end
ruby
def knapsack(items, capacity, algorithm = :dynamic) if algorithm == :memoize knapsack_memoize(items, capacity) elsif algorithm == :dynamic knapsack_dynamic_programming(items, capacity) end end
[ "def", "knapsack", "(", "items", ",", "capacity", ",", "algorithm", "=", ":dynamic", ")", "if", "algorithm", "==", ":memoize", "knapsack_memoize", "(", "items", ",", "capacity", ")", "elsif", "algorithm", "==", ":dynamic", "knapsack_dynamic_programming", "(", "items", ",", "capacity", ")", "end", "end" ]
Given a set of items, each with a weight and a value, determines the maximum profit you can have while keeping the overall weight smaller than the capacity of the knapsack. @param items [Array<Array>] An array of pairs (weight, profit) representing the items @param capacity [Integer] The capacity of the knapsack @param algorithm [:memoize, :dynamic] The algorithm used to solve this, defaults to :dynamic
[ "Given", "a", "set", "of", "items", "each", "with", "a", "weight", "and", "a", "value", "determines", "the", "maximum", "profit", "you", "can", "have", "while", "keeping", "the", "overall", "weight", "smaller", "than", "the", "capacity", "of", "the", "knapsack", "." ]
d66ed33d61b63c9ec82a9ed2debd008e947ac448
https://github.com/ruby-jokes/job_interview/blob/d66ed33d61b63c9ec82a9ed2debd008e947ac448/lib/job_interview/knapsack.rb#L12-L18
22,524
dspinhirne/netaddr-rb
lib/ipv4net.rb
NetAddr.IPv4Net.prev_sib
def prev_sib() if (self.network.addr == 0) return nil end shift = 32 - self.netmask.prefix_len addr = ((self.network.addr>>shift) - 1) << shift return IPv4Net.new(IPv4.new(addr), self.netmask) end
ruby
def prev_sib() if (self.network.addr == 0) return nil end shift = 32 - self.netmask.prefix_len addr = ((self.network.addr>>shift) - 1) << shift return IPv4Net.new(IPv4.new(addr), self.netmask) end
[ "def", "prev_sib", "(", ")", "if", "(", "self", ".", "network", ".", "addr", "==", "0", ")", "return", "nil", "end", "shift", "=", "32", "-", "self", ".", "netmask", ".", "prefix_len", "addr", "=", "(", "(", "self", ".", "network", ".", "addr", ">>", "shift", ")", "-", "1", ")", "<<", "shift", "return", "IPv4Net", ".", "new", "(", "IPv4", ".", "new", "(", "addr", ")", ",", "self", ".", "netmask", ")", "end" ]
prev_sib returns the network immediately preceding this one or nil if this network is 0.0.0.0.
[ "prev_sib", "returns", "the", "network", "immediately", "preceding", "this", "one", "or", "nil", "if", "this", "network", "is", "0", ".", "0", ".", "0", ".", "0", "." ]
38a4a64300a2a9d228bcaf436bea8f368bc20fc5
https://github.com/dspinhirne/netaddr-rb/blob/38a4a64300a2a9d228bcaf436bea8f368bc20fc5/lib/ipv4net.rb#L142-L150
22,525
dspinhirne/netaddr-rb
lib/ipv4net.rb
NetAddr.IPv4Net.summ
def summ(other) if (!other.kind_of?(IPv4Net)) raise ArgumentError, "Expected an IPv4Net object for 'other' but got a #{other.class}." end # netmasks must be identical if (self.netmask.prefix_len != other.netmask.prefix_len) return nil end # merge-able networks will be identical if you right shift them by the number of bits in the hostmask + 1 shift = 32 - self.netmask.prefix_len + 1 addr = self.network.addr >> shift otherAddr = other.network.addr >> shift if (addr != otherAddr) return nil end return self.resize(self.netmask.prefix_len - 1) end
ruby
def summ(other) if (!other.kind_of?(IPv4Net)) raise ArgumentError, "Expected an IPv4Net object for 'other' but got a #{other.class}." end # netmasks must be identical if (self.netmask.prefix_len != other.netmask.prefix_len) return nil end # merge-able networks will be identical if you right shift them by the number of bits in the hostmask + 1 shift = 32 - self.netmask.prefix_len + 1 addr = self.network.addr >> shift otherAddr = other.network.addr >> shift if (addr != otherAddr) return nil end return self.resize(self.netmask.prefix_len - 1) end
[ "def", "summ", "(", "other", ")", "if", "(", "!", "other", ".", "kind_of?", "(", "IPv4Net", ")", ")", "raise", "ArgumentError", ",", "\"Expected an IPv4Net object for 'other' but got a #{other.class}.\"", "end", "# netmasks must be identical", "if", "(", "self", ".", "netmask", ".", "prefix_len", "!=", "other", ".", "netmask", ".", "prefix_len", ")", "return", "nil", "end", "# merge-able networks will be identical if you right shift them by the number of bits in the hostmask + 1", "shift", "=", "32", "-", "self", ".", "netmask", ".", "prefix_len", "+", "1", "addr", "=", "self", ".", "network", ".", "addr", ">>", "shift", "otherAddr", "=", "other", ".", "network", ".", "addr", ">>", "shift", "if", "(", "addr", "!=", "otherAddr", ")", "return", "nil", "end", "return", "self", ".", "resize", "(", "self", ".", "netmask", ".", "prefix_len", "-", "1", ")", "end" ]
summ creates a summary address from this IPv4Net and another. It returns nil if the two networks are incapable of being summarized.
[ "summ", "creates", "a", "summary", "address", "from", "this", "IPv4Net", "and", "another", ".", "It", "returns", "nil", "if", "the", "two", "networks", "are", "incapable", "of", "being", "summarized", "." ]
38a4a64300a2a9d228bcaf436bea8f368bc20fc5
https://github.com/dspinhirne/netaddr-rb/blob/38a4a64300a2a9d228bcaf436bea8f368bc20fc5/lib/ipv4net.rb#L198-L216
22,526
dspinhirne/netaddr-rb
lib/ipv6net.rb
NetAddr.IPv6Net.contains
def contains(ip) if (!ip.kind_of?(IPv6)) raise ArgumentError, "Expected an IPv6 object for 'ip' but got a #{ip.class}." end if (@base.addr == ip.addr & @m128.mask) return true end return false end
ruby
def contains(ip) if (!ip.kind_of?(IPv6)) raise ArgumentError, "Expected an IPv6 object for 'ip' but got a #{ip.class}." end if (@base.addr == ip.addr & @m128.mask) return true end return false end
[ "def", "contains", "(", "ip", ")", "if", "(", "!", "ip", ".", "kind_of?", "(", "IPv6", ")", ")", "raise", "ArgumentError", ",", "\"Expected an IPv6 object for 'ip' but got a #{ip.class}.\"", "end", "if", "(", "@base", ".", "addr", "==", "ip", ".", "addr", "&", "@m128", ".", "mask", ")", "return", "true", "end", "return", "false", "end" ]
contains returns true if the IPv6Net contains the IPv6
[ "contains", "returns", "true", "if", "the", "IPv6Net", "contains", "the", "IPv6" ]
38a4a64300a2a9d228bcaf436bea8f368bc20fc5
https://github.com/dspinhirne/netaddr-rb/blob/38a4a64300a2a9d228bcaf436bea8f368bc20fc5/lib/ipv6net.rb#L61-L69
22,527
dspinhirne/netaddr-rb
lib/eui64.rb
NetAddr.EUI64.bytes
def bytes() return [ (@addr >> 56 & 0xff).to_s(16).rjust(2, "0"), (@addr >> 48 & 0xff).to_s(16).rjust(2, "0"), (@addr >> 40 & 0xff).to_s(16).rjust(2, "0"), (@addr >> 32 & 0xff).to_s(16).rjust(2, "0"), (@addr >> 24 & 0xff).to_s(16).rjust(2, "0"), (@addr >> 16 & 0xff).to_s(16).rjust(2, "0"), (@addr >> 8 & 0xff).to_s(16).rjust(2, "0"), (@addr & 0xff).to_s(16).rjust(2, "0"), ] end
ruby
def bytes() return [ (@addr >> 56 & 0xff).to_s(16).rjust(2, "0"), (@addr >> 48 & 0xff).to_s(16).rjust(2, "0"), (@addr >> 40 & 0xff).to_s(16).rjust(2, "0"), (@addr >> 32 & 0xff).to_s(16).rjust(2, "0"), (@addr >> 24 & 0xff).to_s(16).rjust(2, "0"), (@addr >> 16 & 0xff).to_s(16).rjust(2, "0"), (@addr >> 8 & 0xff).to_s(16).rjust(2, "0"), (@addr & 0xff).to_s(16).rjust(2, "0"), ] end
[ "def", "bytes", "(", ")", "return", "[", "(", "@addr", ">>", "56", "&", "0xff", ")", ".", "to_s", "(", "16", ")", ".", "rjust", "(", "2", ",", "\"0\"", ")", ",", "(", "@addr", ">>", "48", "&", "0xff", ")", ".", "to_s", "(", "16", ")", ".", "rjust", "(", "2", ",", "\"0\"", ")", ",", "(", "@addr", ">>", "40", "&", "0xff", ")", ".", "to_s", "(", "16", ")", ".", "rjust", "(", "2", ",", "\"0\"", ")", ",", "(", "@addr", ">>", "32", "&", "0xff", ")", ".", "to_s", "(", "16", ")", ".", "rjust", "(", "2", ",", "\"0\"", ")", ",", "(", "@addr", ">>", "24", "&", "0xff", ")", ".", "to_s", "(", "16", ")", ".", "rjust", "(", "2", ",", "\"0\"", ")", ",", "(", "@addr", ">>", "16", "&", "0xff", ")", ".", "to_s", "(", "16", ")", ".", "rjust", "(", "2", ",", "\"0\"", ")", ",", "(", "@addr", ">>", "8", "&", "0xff", ")", ".", "to_s", "(", "16", ")", ".", "rjust", "(", "2", ",", "\"0\"", ")", ",", "(", "@addr", "&", "0xff", ")", ".", "to_s", "(", "16", ")", ".", "rjust", "(", "2", ",", "\"0\"", ")", ",", "]", "end" ]
bytes returns a list containing each byte of the EUI64 as a String.
[ "bytes", "returns", "a", "list", "containing", "each", "byte", "of", "the", "EUI64", "as", "a", "String", "." ]
38a4a64300a2a9d228bcaf436bea8f368bc20fc5
https://github.com/dspinhirne/netaddr-rb/blob/38a4a64300a2a9d228bcaf436bea8f368bc20fc5/lib/eui64.rb#L41-L52
22,528
piotrmurach/tty-config
lib/tty/config.rb
TTY.Config.set
def set(*keys, value: nil, &block) assert_either_value_or_block(value, block) keys = convert_to_keys(keys) key = flatten_keys(keys) value_to_eval = block || value if validators.key?(key) if callable_without_params?(value_to_eval) value_to_eval = delay_validation(key, value_to_eval) else assert_valid(key, value) end end deepest_setting = deep_set(@settings, *keys[0...-1]) deepest_setting[keys.last] = value_to_eval deepest_setting[keys.last] end
ruby
def set(*keys, value: nil, &block) assert_either_value_or_block(value, block) keys = convert_to_keys(keys) key = flatten_keys(keys) value_to_eval = block || value if validators.key?(key) if callable_without_params?(value_to_eval) value_to_eval = delay_validation(key, value_to_eval) else assert_valid(key, value) end end deepest_setting = deep_set(@settings, *keys[0...-1]) deepest_setting[keys.last] = value_to_eval deepest_setting[keys.last] end
[ "def", "set", "(", "*", "keys", ",", "value", ":", "nil", ",", "&", "block", ")", "assert_either_value_or_block", "(", "value", ",", "block", ")", "keys", "=", "convert_to_keys", "(", "keys", ")", "key", "=", "flatten_keys", "(", "keys", ")", "value_to_eval", "=", "block", "||", "value", "if", "validators", ".", "key?", "(", "key", ")", "if", "callable_without_params?", "(", "value_to_eval", ")", "value_to_eval", "=", "delay_validation", "(", "key", ",", "value_to_eval", ")", "else", "assert_valid", "(", "key", ",", "value", ")", "end", "end", "deepest_setting", "=", "deep_set", "(", "@settings", ",", "keys", "[", "0", "...", "-", "1", "]", ")", "deepest_setting", "[", "keys", ".", "last", "]", "=", "value_to_eval", "deepest_setting", "[", "keys", ".", "last", "]", "end" ]
Set a value for a composite key and overrides any existing keys. Keys are case-insensitive @api public
[ "Set", "a", "value", "for", "a", "composite", "key", "and", "overrides", "any", "existing", "keys", ".", "Keys", "are", "case", "-", "insensitive" ]
08c4109cdfa3e7caed1368174ef4c4cb96239f4e
https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L179-L197
22,529
piotrmurach/tty-config
lib/tty/config.rb
TTY.Config.set_if_empty
def set_if_empty(*keys, value: nil, &block) return unless deep_find(@settings, keys.last.to_s).nil? block ? set(*keys, &block) : set(*keys, value: value) end
ruby
def set_if_empty(*keys, value: nil, &block) return unless deep_find(@settings, keys.last.to_s).nil? block ? set(*keys, &block) : set(*keys, value: value) end
[ "def", "set_if_empty", "(", "*", "keys", ",", "value", ":", "nil", ",", "&", "block", ")", "return", "unless", "deep_find", "(", "@settings", ",", "keys", ".", "last", ".", "to_s", ")", ".", "nil?", "block", "?", "set", "(", "keys", ",", "block", ")", ":", "set", "(", "keys", ",", "value", ":", "value", ")", "end" ]
Set a value for a composite key if not present already @param [Array[String|Symbol]] keys the keys to set value for @api public
[ "Set", "a", "value", "for", "a", "composite", "key", "if", "not", "present", "already" ]
08c4109cdfa3e7caed1368174ef4c4cb96239f4e
https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L205-L208
22,530
piotrmurach/tty-config
lib/tty/config.rb
TTY.Config.set_from_env
def set_from_env(*keys, &block) assert_keys_with_block(convert_to_keys(keys), block) key = flatten_keys(keys) env_key = block.nil? ? key : block.() env_key = to_env_key(env_key) @envs[key.to_s.downcase] = env_key end
ruby
def set_from_env(*keys, &block) assert_keys_with_block(convert_to_keys(keys), block) key = flatten_keys(keys) env_key = block.nil? ? key : block.() env_key = to_env_key(env_key) @envs[key.to_s.downcase] = env_key end
[ "def", "set_from_env", "(", "*", "keys", ",", "&", "block", ")", "assert_keys_with_block", "(", "convert_to_keys", "(", "keys", ")", ",", "block", ")", "key", "=", "flatten_keys", "(", "keys", ")", "env_key", "=", "block", ".", "nil?", "?", "key", ":", "block", ".", "(", ")", "env_key", "=", "to_env_key", "(", "env_key", ")", "@envs", "[", "key", ".", "to_s", ".", "downcase", "]", "=", "env_key", "end" ]
Bind a key to ENV variable @example set_from_env(:host) set_from_env(:foo, :bar) { 'HOST' } @param [Array[String]] keys the keys to bind to ENV variables @api public
[ "Bind", "a", "key", "to", "ENV", "variable" ]
08c4109cdfa3e7caed1368174ef4c4cb96239f4e
https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L220-L226
22,531
piotrmurach/tty-config
lib/tty/config.rb
TTY.Config.fetch
def fetch(*keys, default: nil, &block) # check alias real_key = @aliases[flatten_keys(keys)] keys = real_key.split(key_delim) if real_key keys = convert_to_keys(keys) env_key = autoload_env? ? to_env_key(keys[0]) : @envs[flatten_keys(keys)] # first try settings value = deep_fetch(@settings, *keys) # then try ENV var if value.nil? && env_key value = ENV[env_key] end # then try default value = block || default if value.nil? while callable_without_params?(value) value = value.call end value end
ruby
def fetch(*keys, default: nil, &block) # check alias real_key = @aliases[flatten_keys(keys)] keys = real_key.split(key_delim) if real_key keys = convert_to_keys(keys) env_key = autoload_env? ? to_env_key(keys[0]) : @envs[flatten_keys(keys)] # first try settings value = deep_fetch(@settings, *keys) # then try ENV var if value.nil? && env_key value = ENV[env_key] end # then try default value = block || default if value.nil? while callable_without_params?(value) value = value.call end value end
[ "def", "fetch", "(", "*", "keys", ",", "default", ":", "nil", ",", "&", "block", ")", "# check alias", "real_key", "=", "@aliases", "[", "flatten_keys", "(", "keys", ")", "]", "keys", "=", "real_key", ".", "split", "(", "key_delim", ")", "if", "real_key", "keys", "=", "convert_to_keys", "(", "keys", ")", "env_key", "=", "autoload_env?", "?", "to_env_key", "(", "keys", "[", "0", "]", ")", ":", "@envs", "[", "flatten_keys", "(", "keys", ")", "]", "# first try settings", "value", "=", "deep_fetch", "(", "@settings", ",", "keys", ")", "# then try ENV var", "if", "value", ".", "nil?", "&&", "env_key", "value", "=", "ENV", "[", "env_key", "]", "end", "# then try default", "value", "=", "block", "||", "default", "if", "value", ".", "nil?", "while", "callable_without_params?", "(", "value", ")", "value", "=", "value", ".", "call", "end", "value", "end" ]
Fetch value under a composite key @param [Array[String|Symbol]] keys the keys to get value at @param [Object] default @api public
[ "Fetch", "value", "under", "a", "composite", "key" ]
08c4109cdfa3e7caed1368174ef4c4cb96239f4e
https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L245-L265
22,532
piotrmurach/tty-config
lib/tty/config.rb
TTY.Config.append
def append(*values, to: nil) keys = Array(to) set(*keys, value: Array(fetch(*keys)) + values) end
ruby
def append(*values, to: nil) keys = Array(to) set(*keys, value: Array(fetch(*keys)) + values) end
[ "def", "append", "(", "*", "values", ",", "to", ":", "nil", ")", "keys", "=", "Array", "(", "to", ")", "set", "(", "keys", ",", "value", ":", "Array", "(", "fetch", "(", "keys", ")", ")", "+", "values", ")", "end" ]
Append values to an already existing nested key @param [Array[String|Symbol]] values the values to append @api public
[ "Append", "values", "to", "an", "already", "existing", "nested", "key" ]
08c4109cdfa3e7caed1368174ef4c4cb96239f4e
https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L282-L285
22,533
piotrmurach/tty-config
lib/tty/config.rb
TTY.Config.remove
def remove(*values, from: nil) keys = Array(from) set(*keys, value: Array(fetch(*keys)) - values) end
ruby
def remove(*values, from: nil) keys = Array(from) set(*keys, value: Array(fetch(*keys)) - values) end
[ "def", "remove", "(", "*", "values", ",", "from", ":", "nil", ")", "keys", "=", "Array", "(", "from", ")", "set", "(", "keys", ",", "value", ":", "Array", "(", "fetch", "(", "keys", ")", ")", "-", "values", ")", "end" ]
Remove a set of values from a nested key @param [Array[String|Symbol]] keys the keys for a value removal @api public
[ "Remove", "a", "set", "of", "values", "from", "a", "nested", "key" ]
08c4109cdfa3e7caed1368174ef4c4cb96239f4e
https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L293-L296
22,534
piotrmurach/tty-config
lib/tty/config.rb
TTY.Config.alias_setting
def alias_setting(*keys, to: nil) flat_setting = flatten_keys(keys) alias_keys = Array(to) alias_key = flatten_keys(alias_keys) if alias_key == flat_setting raise ArgumentError, 'Alias matches setting key' end if fetch(alias_key) raise ArgumentError, 'Setting already exists with an alias ' \ "'#{alias_keys.map(&:inspect).join(', ')}'" end @aliases[alias_key] = flat_setting end
ruby
def alias_setting(*keys, to: nil) flat_setting = flatten_keys(keys) alias_keys = Array(to) alias_key = flatten_keys(alias_keys) if alias_key == flat_setting raise ArgumentError, 'Alias matches setting key' end if fetch(alias_key) raise ArgumentError, 'Setting already exists with an alias ' \ "'#{alias_keys.map(&:inspect).join(', ')}'" end @aliases[alias_key] = flat_setting end
[ "def", "alias_setting", "(", "*", "keys", ",", "to", ":", "nil", ")", "flat_setting", "=", "flatten_keys", "(", "keys", ")", "alias_keys", "=", "Array", "(", "to", ")", "alias_key", "=", "flatten_keys", "(", "alias_keys", ")", "if", "alias_key", "==", "flat_setting", "raise", "ArgumentError", ",", "'Alias matches setting key'", "end", "if", "fetch", "(", "alias_key", ")", "raise", "ArgumentError", ",", "'Setting already exists with an alias '", "\"'#{alias_keys.map(&:inspect).join(', ')}'\"", "end", "@aliases", "[", "alias_key", "]", "=", "flat_setting", "end" ]
Define an alias to a nested key @example alias_setting(:foo, to: :bar) @param [Array[String]] keys the alias key @api public
[ "Define", "an", "alias", "to", "a", "nested", "key" ]
08c4109cdfa3e7caed1368174ef4c4cb96239f4e
https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L318-L333
22,535
piotrmurach/tty-config
lib/tty/config.rb
TTY.Config.validate
def validate(*keys, &validator) key = flatten_keys(keys) values = validators[key] || [] values << validator validators[key] = values end
ruby
def validate(*keys, &validator) key = flatten_keys(keys) values = validators[key] || [] values << validator validators[key] = values end
[ "def", "validate", "(", "*", "keys", ",", "&", "validator", ")", "key", "=", "flatten_keys", "(", "keys", ")", "values", "=", "validators", "[", "key", "]", "||", "[", "]", "values", "<<", "validator", "validators", "[", "key", "]", "=", "values", "end" ]
Register a validation rule for a nested key @param [Array[String]] keys a deep nested keys @param [Proc] validator the logic to use to validate given nested key @api public
[ "Register", "a", "validation", "rule", "for", "a", "nested", "key" ]
08c4109cdfa3e7caed1368174ef4c4cb96239f4e
https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L343-L348
22,536
piotrmurach/tty-config
lib/tty/config.rb
TTY.Config.read
def read(file = find_file, format: :auto) if file.nil? raise ReadError, 'No file found to read configuration from!' elsif !::File.exist?(file) raise ReadError, "Configuration file `#{file}` does not exist!" end merge(unmarshal(file, format: format)) end
ruby
def read(file = find_file, format: :auto) if file.nil? raise ReadError, 'No file found to read configuration from!' elsif !::File.exist?(file) raise ReadError, "Configuration file `#{file}` does not exist!" end merge(unmarshal(file, format: format)) end
[ "def", "read", "(", "file", "=", "find_file", ",", "format", ":", ":auto", ")", "if", "file", ".", "nil?", "raise", "ReadError", ",", "'No file found to read configuration from!'", "elsif", "!", "::", "File", ".", "exist?", "(", "file", ")", "raise", "ReadError", ",", "\"Configuration file `#{file}` does not exist!\"", "end", "merge", "(", "unmarshal", "(", "file", ",", "format", ":", "format", ")", ")", "end" ]
Find and read a configuration file. If the file doesn't exist or if there is an error loading it the TTY::Config::ReadError will be raised. @param [String] file the path to the configuration file to be read @param [String] format the format to read configuration in @raise [TTY::Config::ReadError] @api public
[ "Find", "and", "read", "a", "configuration", "file", "." ]
08c4109cdfa3e7caed1368174ef4c4cb96239f4e
https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L386-L394
22,537
piotrmurach/tty-config
lib/tty/config.rb
TTY.Config.write
def write(file = find_file, force: false, format: :auto) if file && ::File.exist?(file) if !force raise WriteError, "File `#{file}` already exists. " \ 'Use :force option to overwrite.' elsif !::File.writable?(file) raise WriteError, "Cannot write to #{file}." end end if file.nil? dir = @location_paths.empty? ? Dir.pwd : @location_paths.first file = ::File.join(dir, "#{filename}#{@extname}") end content = marshal(file, @settings, format: format) ::File.write(file, content) end
ruby
def write(file = find_file, force: false, format: :auto) if file && ::File.exist?(file) if !force raise WriteError, "File `#{file}` already exists. " \ 'Use :force option to overwrite.' elsif !::File.writable?(file) raise WriteError, "Cannot write to #{file}." end end if file.nil? dir = @location_paths.empty? ? Dir.pwd : @location_paths.first file = ::File.join(dir, "#{filename}#{@extname}") end content = marshal(file, @settings, format: format) ::File.write(file, content) end
[ "def", "write", "(", "file", "=", "find_file", ",", "force", ":", "false", ",", "format", ":", ":auto", ")", "if", "file", "&&", "::", "File", ".", "exist?", "(", "file", ")", "if", "!", "force", "raise", "WriteError", ",", "\"File `#{file}` already exists. \"", "'Use :force option to overwrite.'", "elsif", "!", "::", "File", ".", "writable?", "(", "file", ")", "raise", "WriteError", ",", "\"Cannot write to #{file}.\"", "end", "end", "if", "file", ".", "nil?", "dir", "=", "@location_paths", ".", "empty?", "?", "Dir", ".", "pwd", ":", "@location_paths", ".", "first", "file", "=", "::", "File", ".", "join", "(", "dir", ",", "\"#{filename}#{@extname}\"", ")", "end", "content", "=", "marshal", "(", "file", ",", "@settings", ",", "format", ":", "format", ")", "::", "File", ".", "write", "(", "file", ",", "content", ")", "end" ]
Write current configuration to a file. @param [String] file the path to a file @api public
[ "Write", "current", "configuration", "to", "a", "file", "." ]
08c4109cdfa3e7caed1368174ef4c4cb96239f4e
https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L402-L419
22,538
piotrmurach/tty-config
lib/tty/config.rb
TTY.Config.assert_either_value_or_block
def assert_either_value_or_block(value, block) if value.nil? && block.nil? raise ArgumentError, 'Need to set either value or block' elsif !(value.nil? || block.nil?) raise ArgumentError, "Can't set both value and block" end end
ruby
def assert_either_value_or_block(value, block) if value.nil? && block.nil? raise ArgumentError, 'Need to set either value or block' elsif !(value.nil? || block.nil?) raise ArgumentError, "Can't set both value and block" end end
[ "def", "assert_either_value_or_block", "(", "value", ",", "block", ")", "if", "value", ".", "nil?", "&&", "block", ".", "nil?", "raise", "ArgumentError", ",", "'Need to set either value or block'", "elsif", "!", "(", "value", ".", "nil?", "||", "block", ".", "nil?", ")", "raise", "ArgumentError", ",", "\"Can't set both value and block\"", "end", "end" ]
Ensure that value is set either through parameter or block @api private
[ "Ensure", "that", "value", "is", "set", "either", "through", "parameter", "or", "block" ]
08c4109cdfa3e7caed1368174ef4c4cb96239f4e
https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L434-L440
22,539
piotrmurach/tty-config
lib/tty/config.rb
TTY.Config.assert_valid
def assert_valid(key, value) validators[key].each do |validator| validator.call(key, value) end end
ruby
def assert_valid(key, value) validators[key].each do |validator| validator.call(key, value) end end
[ "def", "assert_valid", "(", "key", ",", "value", ")", "validators", "[", "key", "]", ".", "each", "do", "|", "validator", "|", "validator", ".", "call", "(", "key", ",", "value", ")", "end", "end" ]
Check if key passes all registered validations for a key @param [String] key @param [Object] value @api private
[ "Check", "if", "key", "passes", "all", "registered", "validations", "for", "a", "key" ]
08c4109cdfa3e7caed1368174ef4c4cb96239f4e
https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L473-L477
22,540
piotrmurach/tty-config
lib/tty/config.rb
TTY.Config.deep_set
def deep_set(settings, *keys) return settings if keys.empty? key, *rest = *keys value = settings[key] if value.nil? && rest.empty? settings[key] = {} elsif value.nil? && !rest.empty? settings[key] = {} deep_set(settings[key], *rest) else # nested hash value present settings[key] = value deep_set(settings[key], *rest) end end
ruby
def deep_set(settings, *keys) return settings if keys.empty? key, *rest = *keys value = settings[key] if value.nil? && rest.empty? settings[key] = {} elsif value.nil? && !rest.empty? settings[key] = {} deep_set(settings[key], *rest) else # nested hash value present settings[key] = value deep_set(settings[key], *rest) end end
[ "def", "deep_set", "(", "settings", ",", "*", "keys", ")", "return", "settings", "if", "keys", ".", "empty?", "key", ",", "*", "rest", "=", "keys", "value", "=", "settings", "[", "key", "]", "if", "value", ".", "nil?", "&&", "rest", ".", "empty?", "settings", "[", "key", "]", "=", "{", "}", "elsif", "value", ".", "nil?", "&&", "!", "rest", ".", "empty?", "settings", "[", "key", "]", "=", "{", "}", "deep_set", "(", "settings", "[", "key", "]", ",", "rest", ")", "else", "# nested hash value present", "settings", "[", "key", "]", "=", "value", "deep_set", "(", "settings", "[", "key", "]", ",", "rest", ")", "end", "end" ]
Set value under deeply nested keys The scan starts with the top level key and follows a sequence of keys. In case where intermediate keys do not exist, a new hash is created. @param [Hash] settings @param [Array[Object]] the keys to nest @api private
[ "Set", "value", "under", "deeply", "nested", "keys" ]
08c4109cdfa3e7caed1368174ef4c4cb96239f4e
https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L497-L511
22,541
piotrmurach/tty-config
lib/tty/config.rb
TTY.Config.deep_fetch
def deep_fetch(settings, *keys) key, *rest = keys value = settings.fetch(key.to_s, settings[key.to_sym]) if value.nil? || rest.empty? value else deep_fetch(value, *rest) end end
ruby
def deep_fetch(settings, *keys) key, *rest = keys value = settings.fetch(key.to_s, settings[key.to_sym]) if value.nil? || rest.empty? value else deep_fetch(value, *rest) end end
[ "def", "deep_fetch", "(", "settings", ",", "*", "keys", ")", "key", ",", "*", "rest", "=", "keys", "value", "=", "settings", ".", "fetch", "(", "key", ".", "to_s", ",", "settings", "[", "key", ".", "to_sym", "]", ")", "if", "value", ".", "nil?", "||", "rest", ".", "empty?", "value", "else", "deep_fetch", "(", "value", ",", "rest", ")", "end", "end" ]
Fetch value under deeply nested keys with indiffernt key access @param [Hash] settings @param [Array[Object]] keys @api private
[ "Fetch", "value", "under", "deeply", "nested", "keys", "with", "indiffernt", "key", "access" ]
08c4109cdfa3e7caed1368174ef4c4cb96239f4e
https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L547-L555
22,542
piotrmurach/tty-config
lib/tty/config.rb
TTY.Config.marshal
def marshal(file, data, format: :auto) file_ext = ::File.extname(file) ext = (format == :auto ? file_ext : ".#{format}") self.extname = file_ext self.filename = ::File.basename(file, file_ext) case ext when *EXTENSIONS[:yaml] load_write_dep('yaml', ext) YAML.dump(self.class.normalize_hash(data, :to_s)) when *EXTENSIONS[:json] load_write_dep('json', ext) JSON.pretty_generate(data) when *EXTENSIONS[:toml] load_write_dep('toml', ext) TOML::Generator.new(data).body when *EXTENSIONS[:ini] Config.generate(data) else raise WriteError, "Config file format `#{ext}` is not supported." end end
ruby
def marshal(file, data, format: :auto) file_ext = ::File.extname(file) ext = (format == :auto ? file_ext : ".#{format}") self.extname = file_ext self.filename = ::File.basename(file, file_ext) case ext when *EXTENSIONS[:yaml] load_write_dep('yaml', ext) YAML.dump(self.class.normalize_hash(data, :to_s)) when *EXTENSIONS[:json] load_write_dep('json', ext) JSON.pretty_generate(data) when *EXTENSIONS[:toml] load_write_dep('toml', ext) TOML::Generator.new(data).body when *EXTENSIONS[:ini] Config.generate(data) else raise WriteError, "Config file format `#{ext}` is not supported." end end
[ "def", "marshal", "(", "file", ",", "data", ",", "format", ":", ":auto", ")", "file_ext", "=", "::", "File", ".", "extname", "(", "file", ")", "ext", "=", "(", "format", "==", ":auto", "?", "file_ext", ":", "\".#{format}\"", ")", "self", ".", "extname", "=", "file_ext", "self", ".", "filename", "=", "::", "File", ".", "basename", "(", "file", ",", "file_ext", ")", "case", "ext", "when", "EXTENSIONS", "[", ":yaml", "]", "load_write_dep", "(", "'yaml'", ",", "ext", ")", "YAML", ".", "dump", "(", "self", ".", "class", ".", "normalize_hash", "(", "data", ",", ":to_s", ")", ")", "when", "EXTENSIONS", "[", ":json", "]", "load_write_dep", "(", "'json'", ",", "ext", ")", "JSON", ".", "pretty_generate", "(", "data", ")", "when", "EXTENSIONS", "[", ":toml", "]", "load_write_dep", "(", "'toml'", ",", "ext", ")", "TOML", "::", "Generator", ".", "new", "(", "data", ")", ".", "body", "when", "EXTENSIONS", "[", ":ini", "]", "Config", ".", "generate", "(", "data", ")", "else", "raise", "WriteError", ",", "\"Config file format `#{ext}` is not supported.\"", "end", "end" ]
Marshal data hash into a configuration file content @return [String] @api private
[ "Marshal", "data", "hash", "into", "a", "configuration", "file", "content" ]
08c4109cdfa3e7caed1368174ef4c4cb96239f4e
https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L637-L658
22,543
lgromanowski/acme-plugin
lib/acme_plugin.rb
AcmePlugin.CertGenerator.save_certificate
def save_certificate(certificate) return unless certificate return HerokuOutput.new(common_domain_name, certificate).output unless ENV['DYNO'].nil? output_dir = File.join(Rails.root, @options[:output_cert_dir]) return FileOutput.new(common_domain_name, certificate, output_dir).output if File.directory?(output_dir) Rails.logger.error("Output directory: '#{output_dir}' does not exist!") end
ruby
def save_certificate(certificate) return unless certificate return HerokuOutput.new(common_domain_name, certificate).output unless ENV['DYNO'].nil? output_dir = File.join(Rails.root, @options[:output_cert_dir]) return FileOutput.new(common_domain_name, certificate, output_dir).output if File.directory?(output_dir) Rails.logger.error("Output directory: '#{output_dir}' does not exist!") end
[ "def", "save_certificate", "(", "certificate", ")", "return", "unless", "certificate", "return", "HerokuOutput", ".", "new", "(", "common_domain_name", ",", "certificate", ")", ".", "output", "unless", "ENV", "[", "'DYNO'", "]", ".", "nil?", "output_dir", "=", "File", ".", "join", "(", "Rails", ".", "root", ",", "@options", "[", ":output_cert_dir", "]", ")", "return", "FileOutput", ".", "new", "(", "common_domain_name", ",", "certificate", ",", "output_dir", ")", ".", "output", "if", "File", ".", "directory?", "(", "output_dir", ")", "Rails", ".", "logger", ".", "error", "(", "\"Output directory: '#{output_dir}' does not exist!\"", ")", "end" ]
Save the certificate and key
[ "Save", "the", "certificate", "and", "key" ]
1a0875d509cb658045b0ae9c76b1d32d09c3d0ab
https://github.com/lgromanowski/acme-plugin/blob/1a0875d509cb658045b0ae9c76b1d32d09c3d0ab/lib/acme_plugin.rb#L138-L144
22,544
junegunn/jdbc-helper
lib/jdbc-helper/wrapper/table_wrapper.rb
JDBCHelper.TableWrapper.count
def count *where sql, *binds = SQLHelper.count :table => name, :where => @query_where + where, :prepared => true pstmt = prepare :count, sql pstmt.query(*binds).to_a[0][0].to_i end
ruby
def count *where sql, *binds = SQLHelper.count :table => name, :where => @query_where + where, :prepared => true pstmt = prepare :count, sql pstmt.query(*binds).to_a[0][0].to_i end
[ "def", "count", "*", "where", "sql", ",", "*", "binds", "=", "SQLHelper", ".", "count", ":table", "=>", "name", ",", ":where", "=>", "@query_where", "+", "where", ",", ":prepared", "=>", "true", "pstmt", "=", "prepare", ":count", ",", "sql", "pstmt", ".", "query", "(", "binds", ")", ".", "to_a", "[", "0", "]", "[", "0", "]", ".", "to_i", "end" ]
Retrieves the count of the table @param [List of Hash/String] where Filter conditions @return [Fixnum] Count of the records.
[ "Retrieves", "the", "count", "of", "the", "table" ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L52-L56
22,545
junegunn/jdbc-helper
lib/jdbc-helper/wrapper/table_wrapper.rb
JDBCHelper.TableWrapper.insert_ignore
def insert_ignore data_hash = {} sql, *binds = SQLHelper.insert_ignore :table => name, :data => @query_default.merge(data_hash), :prepared => true pstmt = prepare :insert, sql pstmt.set_fetch_size @fetch_size if @fetch_size pstmt.send @update_method, *binds end
ruby
def insert_ignore data_hash = {} sql, *binds = SQLHelper.insert_ignore :table => name, :data => @query_default.merge(data_hash), :prepared => true pstmt = prepare :insert, sql pstmt.set_fetch_size @fetch_size if @fetch_size pstmt.send @update_method, *binds end
[ "def", "insert_ignore", "data_hash", "=", "{", "}", "sql", ",", "*", "binds", "=", "SQLHelper", ".", "insert_ignore", ":table", "=>", "name", ",", ":data", "=>", "@query_default", ".", "merge", "(", "data_hash", ")", ",", ":prepared", "=>", "true", "pstmt", "=", "prepare", ":insert", ",", "sql", "pstmt", ".", "set_fetch_size", "@fetch_size", "if", "@fetch_size", "pstmt", ".", "send", "@update_method", ",", "binds", "end" ]
Inserts a record into the table with the given hash. Skip insertion when duplicate record is found. @note This is not SQL standard. Only works if the database supports insert ignore syntax. @param [Hash] data_hash Column values in Hash @return [Fixnum] Number of affected records
[ "Inserts", "a", "record", "into", "the", "table", "with", "the", "given", "hash", ".", "Skip", "insertion", "when", "duplicate", "record", "is", "found", "." ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L81-L88
22,546
junegunn/jdbc-helper
lib/jdbc-helper/wrapper/table_wrapper.rb
JDBCHelper.TableWrapper.replace
def replace data_hash = {} sql, *binds = SQLHelper.replace :table => name, :data => @query_default.merge(data_hash), :prepared => true pstmt = prepare :insert, sql pstmt.send @update_method, *binds end
ruby
def replace data_hash = {} sql, *binds = SQLHelper.replace :table => name, :data => @query_default.merge(data_hash), :prepared => true pstmt = prepare :insert, sql pstmt.send @update_method, *binds end
[ "def", "replace", "data_hash", "=", "{", "}", "sql", ",", "*", "binds", "=", "SQLHelper", ".", "replace", ":table", "=>", "name", ",", ":data", "=>", "@query_default", ".", "merge", "(", "data_hash", ")", ",", ":prepared", "=>", "true", "pstmt", "=", "prepare", ":insert", ",", "sql", "pstmt", ".", "send", "@update_method", ",", "binds", "end" ]
Replaces a record in the table with the new one with the same unique key. @note This is not SQL standard. Only works if the database supports replace syntax. @param [Hash] data_hash Column values in Hash @return [Fixnum] Number of affected records
[ "Replaces", "a", "record", "in", "the", "table", "with", "the", "new", "one", "with", "the", "same", "unique", "key", "." ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L94-L100
22,547
junegunn/jdbc-helper
lib/jdbc-helper/wrapper/table_wrapper.rb
JDBCHelper.TableWrapper.delete
def delete *where sql, *binds = SQLHelper.delete(:table => name, :where => @query_where + where, :prepared => true) pstmt = prepare :delete, sql pstmt.send @update_method, *binds end
ruby
def delete *where sql, *binds = SQLHelper.delete(:table => name, :where => @query_where + where, :prepared => true) pstmt = prepare :delete, sql pstmt.send @update_method, *binds end
[ "def", "delete", "*", "where", "sql", ",", "*", "binds", "=", "SQLHelper", ".", "delete", "(", ":table", "=>", "name", ",", ":where", "=>", "@query_where", "+", "where", ",", ":prepared", "=>", "true", ")", "pstmt", "=", "prepare", ":delete", ",", "sql", "pstmt", ".", "send", "@update_method", ",", "binds", "end" ]
Deletes records matching given condtion @param [List of Hash/String] where Delete filters @return [Fixnum] Number of affected records
[ "Deletes", "records", "matching", "given", "condtion" ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L122-L126
22,548
junegunn/jdbc-helper
lib/jdbc-helper/wrapper/table_wrapper.rb
JDBCHelper.TableWrapper.select
def select *fields, &block obj = self.dup obj.instance_variable_set :@query_select, fields unless fields.empty? ret obj, &block end
ruby
def select *fields, &block obj = self.dup obj.instance_variable_set :@query_select, fields unless fields.empty? ret obj, &block end
[ "def", "select", "*", "fields", ",", "&", "block", "obj", "=", "self", ".", "dup", "obj", ".", "instance_variable_set", ":@query_select", ",", "fields", "unless", "fields", ".", "empty?", "ret", "obj", ",", "block", "end" ]
Returns a new TableWrapper object which can be used to execute a select statement for the table selecting only the specified fields. If a block is given, executes the select statement and yields each row to the block. @param [*String/*Symbol] fields List of fields to select @return [JDBCHelper::TableWrapper] @since 0.4.0
[ "Returns", "a", "new", "TableWrapper", "object", "which", "can", "be", "used", "to", "execute", "a", "select", "statement", "for", "the", "table", "selecting", "only", "the", "specified", "fields", ".", "If", "a", "block", "is", "given", "executes", "the", "select", "statement", "and", "yields", "each", "row", "to", "the", "block", "." ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L155-L159
22,549
junegunn/jdbc-helper
lib/jdbc-helper/wrapper/table_wrapper.rb
JDBCHelper.TableWrapper.where
def where *conditions, &block raise ArgumentError.new("Wrong number of arguments") if conditions.empty? obj = self.dup obj.instance_variable_set :@query_where, @query_where + conditions ret obj, &block end
ruby
def where *conditions, &block raise ArgumentError.new("Wrong number of arguments") if conditions.empty? obj = self.dup obj.instance_variable_set :@query_where, @query_where + conditions ret obj, &block end
[ "def", "where", "*", "conditions", ",", "&", "block", "raise", "ArgumentError", ".", "new", "(", "\"Wrong number of arguments\"", ")", "if", "conditions", ".", "empty?", "obj", "=", "self", ".", "dup", "obj", ".", "instance_variable_set", ":@query_where", ",", "@query_where", "+", "conditions", "ret", "obj", ",", "block", "end" ]
Returns a new TableWrapper object which can be used to execute a select statement for the table with the specified filter conditions. If a block is given, executes the select statement and yields each row to the block. @param [List of Hash/String] conditions Filter conditions @return [JDBCHelper::TableWrapper] @since 0.4.0
[ "Returns", "a", "new", "TableWrapper", "object", "which", "can", "be", "used", "to", "execute", "a", "select", "statement", "for", "the", "table", "with", "the", "specified", "filter", "conditions", ".", "If", "a", "block", "is", "given", "executes", "the", "select", "statement", "and", "yields", "each", "row", "to", "the", "block", "." ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L168-L174
22,550
junegunn/jdbc-helper
lib/jdbc-helper/wrapper/table_wrapper.rb
JDBCHelper.TableWrapper.order
def order *criteria, &block raise ArgumentError.new("Wrong number of arguments") if criteria.empty? obj = self.dup obj.instance_variable_set :@query_order, criteria ret obj, &block end
ruby
def order *criteria, &block raise ArgumentError.new("Wrong number of arguments") if criteria.empty? obj = self.dup obj.instance_variable_set :@query_order, criteria ret obj, &block end
[ "def", "order", "*", "criteria", ",", "&", "block", "raise", "ArgumentError", ".", "new", "(", "\"Wrong number of arguments\"", ")", "if", "criteria", ".", "empty?", "obj", "=", "self", ".", "dup", "obj", ".", "instance_variable_set", ":@query_order", ",", "criteria", "ret", "obj", ",", "block", "end" ]
Returns a new TableWrapper object which can be used to execute a select statement for the table with the given sorting criteria. If a block is given, executes the select statement and yields each row to the block. @param [*String/*Symbol] criteria Sorting criteria @return [JDBCHelper::TableWrapper] @since 0.4.0
[ "Returns", "a", "new", "TableWrapper", "object", "which", "can", "be", "used", "to", "execute", "a", "select", "statement", "for", "the", "table", "with", "the", "given", "sorting", "criteria", ".", "If", "a", "block", "is", "given", "executes", "the", "select", "statement", "and", "yields", "each", "row", "to", "the", "block", "." ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L192-L197
22,551
junegunn/jdbc-helper
lib/jdbc-helper/wrapper/table_wrapper.rb
JDBCHelper.TableWrapper.default
def default data_hash, &block raise ArgumentError.new("Hash required") unless data_hash.kind_of? Hash obj = self.dup obj.instance_variable_set :@query_default, @query_default.merge(data_hash) ret obj, &block end
ruby
def default data_hash, &block raise ArgumentError.new("Hash required") unless data_hash.kind_of? Hash obj = self.dup obj.instance_variable_set :@query_default, @query_default.merge(data_hash) ret obj, &block end
[ "def", "default", "data_hash", ",", "&", "block", "raise", "ArgumentError", ".", "new", "(", "\"Hash required\"", ")", "unless", "data_hash", ".", "kind_of?", "Hash", "obj", "=", "self", ".", "dup", "obj", ".", "instance_variable_set", ":@query_default", ",", "@query_default", ".", "merge", "(", "data_hash", ")", "ret", "obj", ",", "block", "end" ]
Returns a new TableWrapper object with default values, which will be applied to the subsequent inserts and updates. @param [Hash] data_hash Default values @return [JDBCHelper::TableWrapper] @since 0.4.5
[ "Returns", "a", "new", "TableWrapper", "object", "with", "default", "values", "which", "will", "be", "applied", "to", "the", "subsequent", "inserts", "and", "updates", "." ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L204-L210
22,552
junegunn/jdbc-helper
lib/jdbc-helper/wrapper/table_wrapper.rb
JDBCHelper.TableWrapper.fetch_size
def fetch_size fsz, &block obj = self.dup obj.instance_variable_set :@fetch_size, fsz ret obj, &block end
ruby
def fetch_size fsz, &block obj = self.dup obj.instance_variable_set :@fetch_size, fsz ret obj, &block end
[ "def", "fetch_size", "fsz", ",", "&", "block", "obj", "=", "self", ".", "dup", "obj", ".", "instance_variable_set", ":@fetch_size", ",", "fsz", "ret", "obj", ",", "block", "end" ]
Returns a new TableWrapper object with the given fetch size. If a block is given, executes the select statement and yields each row to the block. @param [Fixnum] fsz Fetch size @return [JDBCHelper::TableWrapper] @since 0.7.7
[ "Returns", "a", "new", "TableWrapper", "object", "with", "the", "given", "fetch", "size", ".", "If", "a", "block", "is", "given", "executes", "the", "select", "statement", "and", "yields", "each", "row", "to", "the", "block", "." ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L217-L221
22,553
junegunn/jdbc-helper
lib/jdbc-helper/wrapper/table_wrapper.rb
JDBCHelper.TableWrapper.each
def each &block sql, *binds = SQLHelper.select( :prepared => true, :table => name, :project => @query_select, :where => @query_where, :order => @query_order, :limit => @query_limit) pstmt = prepare :select, sql pstmt.enumerate(*binds, &block) end
ruby
def each &block sql, *binds = SQLHelper.select( :prepared => true, :table => name, :project => @query_select, :where => @query_where, :order => @query_order, :limit => @query_limit) pstmt = prepare :select, sql pstmt.enumerate(*binds, &block) end
[ "def", "each", "&", "block", "sql", ",", "*", "binds", "=", "SQLHelper", ".", "select", "(", ":prepared", "=>", "true", ",", ":table", "=>", "name", ",", ":project", "=>", "@query_select", ",", ":where", "=>", "@query_where", ",", ":order", "=>", "@query_order", ",", ":limit", "=>", "@query_limit", ")", "pstmt", "=", "prepare", ":select", ",", "sql", "pstmt", ".", "enumerate", "(", "binds", ",", "block", ")", "end" ]
Executes a select SQL for the table and returns an Enumerable object, or yields each row if block is given. @return [JDBCHelper::Connection::ResultSet] @since 0.4.0
[ "Executes", "a", "select", "SQL", "for", "the", "table", "and", "returns", "an", "Enumerable", "object", "or", "yields", "each", "row", "if", "block", "is", "given", "." ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L227-L237
22,554
junegunn/jdbc-helper
lib/jdbc-helper/wrapper/table_wrapper.rb
JDBCHelper.TableWrapper.clear_batch
def clear_batch *types types = [:insert, :update, :delete] if types.empty? types.each do |type| raise ArgumentError.new("Invalid type: #{type}") unless @pstmts.has_key?(type) @pstmts[type].values.each(&:clear_batch) end nil end
ruby
def clear_batch *types types = [:insert, :update, :delete] if types.empty? types.each do |type| raise ArgumentError.new("Invalid type: #{type}") unless @pstmts.has_key?(type) @pstmts[type].values.each(&:clear_batch) end nil end
[ "def", "clear_batch", "*", "types", "types", "=", "[", ":insert", ",", ":update", ",", ":delete", "]", "if", "types", ".", "empty?", "types", ".", "each", "do", "|", "type", "|", "raise", "ArgumentError", ".", "new", "(", "\"Invalid type: #{type}\"", ")", "unless", "@pstmts", ".", "has_key?", "(", "type", ")", "@pstmts", "[", "type", "]", ".", "values", ".", "each", "(", ":clear_batch", ")", "end", "nil", "end" ]
Clear batched operations. @param [*Symbol] types Types of batched operations to clear. If not given, :insert, :update and :delete. @return [nil]
[ "Clear", "batched", "operations", "." ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L267-L274
22,555
junegunn/jdbc-helper
lib/jdbc-helper/wrapper/table_wrapper.rb
JDBCHelper.TableWrapper.close
def close @pstmts.each do |typ, hash| hash.each do |sql, pstmt| pstmt.close if pstmt end @pstmts[typ] = {} end end
ruby
def close @pstmts.each do |typ, hash| hash.each do |sql, pstmt| pstmt.close if pstmt end @pstmts[typ] = {} end end
[ "def", "close", "@pstmts", ".", "each", "do", "|", "typ", ",", "hash", "|", "hash", ".", "each", "do", "|", "sql", ",", "pstmt", "|", "pstmt", ".", "close", "if", "pstmt", "end", "@pstmts", "[", "typ", "]", "=", "{", "}", "end", "end" ]
Closes the prepared statements @since 0.5.0
[ "Closes", "the", "prepared", "statements" ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L329-L336
22,556
junegunn/jdbc-helper
lib/jdbc-helper/wrapper/function_wrapper.rb
JDBCHelper.FunctionWrapper.call
def call(*args) pstmt = @connection.prepare("select #{name}(#{args.map{'?'}.join ','})#{@suffix}") begin pstmt.query(*args).to_a[0][0] ensure pstmt.close end end
ruby
def call(*args) pstmt = @connection.prepare("select #{name}(#{args.map{'?'}.join ','})#{@suffix}") begin pstmt.query(*args).to_a[0][0] ensure pstmt.close end end
[ "def", "call", "(", "*", "args", ")", "pstmt", "=", "@connection", ".", "prepare", "(", "\"select #{name}(#{args.map{'?'}.join ','})#{@suffix}\"", ")", "begin", "pstmt", ".", "query", "(", "args", ")", ".", "to_a", "[", "0", "]", "[", "0", "]", "ensure", "pstmt", ".", "close", "end", "end" ]
Returns the result of the function call with the given parameters
[ "Returns", "the", "result", "of", "the", "function", "call", "with", "the", "given", "parameters" ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/function_wrapper.rb#L27-L34
22,557
junegunn/jdbc-helper
lib/jdbc-helper/wrapper/procedure_wrapper.rb
JDBCHelper.ProcedureWrapper.call
def call(*args) params = build_params args cstmt = @connection.prepare_call "{call #{name}(#{Array.new(@cols.length){'?'}.join ', '})}" begin process_result( args, cstmt.call(*params) ) ensure cstmt.close end end
ruby
def call(*args) params = build_params args cstmt = @connection.prepare_call "{call #{name}(#{Array.new(@cols.length){'?'}.join ', '})}" begin process_result( args, cstmt.call(*params) ) ensure cstmt.close end end
[ "def", "call", "(", "*", "args", ")", "params", "=", "build_params", "args", "cstmt", "=", "@connection", ".", "prepare_call", "\"{call #{name}(#{Array.new(@cols.length){'?'}.join ', '})}\"", "begin", "process_result", "(", "args", ",", "cstmt", ".", "call", "(", "params", ")", ")", "ensure", "cstmt", ".", "close", "end", "end" ]
Executes the procedure and returns the values of INOUT & OUT parameters in Hash @return [Hash]
[ "Executes", "the", "procedure", "and", "returns", "the", "values", "of", "INOUT", "&", "OUT", "parameters", "in", "Hash" ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/procedure_wrapper.rb#L21-L29
22,558
fernet/fernet-rb
lib/fernet/bit_packing.rb
Fernet.BitPacking.unpack_int64_bigendian
def unpack_int64_bigendian(bytes) bytes.each_byte.to_a.reverse.each_with_index. reduce(0) { |val, (byte, index)| val | (byte << (index * 8)) } end
ruby
def unpack_int64_bigendian(bytes) bytes.each_byte.to_a.reverse.each_with_index. reduce(0) { |val, (byte, index)| val | (byte << (index * 8)) } end
[ "def", "unpack_int64_bigendian", "(", "bytes", ")", "bytes", ".", "each_byte", ".", "to_a", ".", "reverse", ".", "each_with_index", ".", "reduce", "(", "0", ")", "{", "|", "val", ",", "(", "byte", ",", "index", ")", "|", "val", "|", "(", "byte", "<<", "(", "index", "*", "8", ")", ")", "}", "end" ]
Internal - unpacks a string of big endian, 64 bit integers bytes - an array of ints Returns the original byte sequence as a string
[ "Internal", "-", "unpacks", "a", "string", "of", "big", "endian", "64", "bit", "integers" ]
90b1c8358abeeae14ddb4cdda677297e1938652c
https://github.com/fernet/fernet-rb/blob/90b1c8358abeeae14ddb4cdda677297e1938652c/lib/fernet/bit_packing.rb#L23-L26
22,559
junegunn/jdbc-helper
lib/jdbc-helper/connection.rb
JDBCHelper.Connection.transaction
def transaction check_closed raise ArgumentError.new("Transaction block not given") unless block_given? tx = Transaction.send :new, @conn ac = @conn.get_auto_commit status = :unknown begin @conn.set_auto_commit false yield tx @conn.commit status = :committed rescue Transaction::Commit status = :committed rescue Transaction::Rollback status = :rolledback ensure @conn.rollback if status == :unknown && @conn.get_auto_commit == false @conn.set_auto_commit ac end status == :committed end
ruby
def transaction check_closed raise ArgumentError.new("Transaction block not given") unless block_given? tx = Transaction.send :new, @conn ac = @conn.get_auto_commit status = :unknown begin @conn.set_auto_commit false yield tx @conn.commit status = :committed rescue Transaction::Commit status = :committed rescue Transaction::Rollback status = :rolledback ensure @conn.rollback if status == :unknown && @conn.get_auto_commit == false @conn.set_auto_commit ac end status == :committed end
[ "def", "transaction", "check_closed", "raise", "ArgumentError", ".", "new", "(", "\"Transaction block not given\"", ")", "unless", "block_given?", "tx", "=", "Transaction", ".", "send", ":new", ",", "@conn", "ac", "=", "@conn", ".", "get_auto_commit", "status", "=", ":unknown", "begin", "@conn", ".", "set_auto_commit", "false", "yield", "tx", "@conn", ".", "commit", "status", "=", ":committed", "rescue", "Transaction", "::", "Commit", "status", "=", ":committed", "rescue", "Transaction", "::", "Rollback", "status", "=", ":rolledback", "ensure", "@conn", ".", "rollback", "if", "status", "==", ":unknown", "&&", "@conn", ".", "get_auto_commit", "==", "false", "@conn", ".", "set_auto_commit", "ac", "end", "status", "==", ":committed", "end" ]
Executes the given code block as a transaction. Returns true if the transaction is committed. A transaction object is passed to the block, which only has commit and rollback methods. The execution breaks out of the code block when either of the methods is called. @yield [JDBCHelper::Connection::Transaction] Responds to commit and rollback. @return [Boolean] True if committed
[ "Executes", "the", "given", "code", "block", "as", "a", "transaction", ".", "Returns", "true", "if", "the", "transaction", "is", "committed", ".", "A", "transaction", "object", "is", "passed", "to", "the", "block", "which", "only", "has", "commit", "and", "rollback", "methods", ".", "The", "execution", "breaks", "out", "of", "the", "code", "block", "when", "either", "of", "the", "methods", "is", "called", "." ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/connection.rb#L231-L252
22,560
junegunn/jdbc-helper
lib/jdbc-helper/connection.rb
JDBCHelper.Connection.execute
def execute(qstr) check_closed stmt = @spool.take begin if stmt.execute(qstr) ResultSet.send(:new, stmt.getResultSet) { @spool.give stmt } else rset = stmt.getUpdateCount @spool.give stmt rset end rescue Exception => e @spool.give stmt raise end end
ruby
def execute(qstr) check_closed stmt = @spool.take begin if stmt.execute(qstr) ResultSet.send(:new, stmt.getResultSet) { @spool.give stmt } else rset = stmt.getUpdateCount @spool.give stmt rset end rescue Exception => e @spool.give stmt raise end end
[ "def", "execute", "(", "qstr", ")", "check_closed", "stmt", "=", "@spool", ".", "take", "begin", "if", "stmt", ".", "execute", "(", "qstr", ")", "ResultSet", ".", "send", "(", ":new", ",", "stmt", ".", "getResultSet", ")", "{", "@spool", ".", "give", "stmt", "}", "else", "rset", "=", "stmt", ".", "getUpdateCount", "@spool", ".", "give", "stmt", "rset", "end", "rescue", "Exception", "=>", "e", "@spool", ".", "give", "stmt", "raise", "end", "end" ]
Executes an SQL and returns the count of the update rows or a ResultSet object depending on the type of the given statement. If a ResultSet is returned, it must be enumerated or closed. @param [String] qstr SQL string @return [Fixnum|ResultSet]
[ "Executes", "an", "SQL", "and", "returns", "the", "count", "of", "the", "update", "rows", "or", "a", "ResultSet", "object", "depending", "on", "the", "type", "of", "the", "given", "statement", ".", "If", "a", "ResultSet", "is", "returned", "it", "must", "be", "enumerated", "or", "closed", "." ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/connection.rb#L259-L275
22,561
junegunn/jdbc-helper
lib/jdbc-helper/connection.rb
JDBCHelper.Connection.query
def query(qstr, &blk) check_closed stmt = @spool.take begin rset = stmt.execute_query(qstr) rescue Exception => e @spool.give stmt raise end enum = ResultSet.send(:new, rset) { @spool.give stmt } if block_given? enum.each do |row| yield row end else enum end end
ruby
def query(qstr, &blk) check_closed stmt = @spool.take begin rset = stmt.execute_query(qstr) rescue Exception => e @spool.give stmt raise end enum = ResultSet.send(:new, rset) { @spool.give stmt } if block_given? enum.each do |row| yield row end else enum end end
[ "def", "query", "(", "qstr", ",", "&", "blk", ")", "check_closed", "stmt", "=", "@spool", ".", "take", "begin", "rset", "=", "stmt", ".", "execute_query", "(", "qstr", ")", "rescue", "Exception", "=>", "e", "@spool", ".", "give", "stmt", "raise", "end", "enum", "=", "ResultSet", ".", "send", "(", ":new", ",", "rset", ")", "{", "@spool", ".", "give", "stmt", "}", "if", "block_given?", "enum", ".", "each", "do", "|", "row", "|", "yield", "row", "end", "else", "enum", "end", "end" ]
Executes a select query. When a code block is given, each row of the result is passed to the block one by one. If not given, ResultSet is returned, which can be used to enumerate through the result set. ResultSet is closed automatically when all the rows in the result set is consumed. @example Nested querying conn.query("SELECT a FROM T") do | trow | conn.query("SELECT * FROM U_#{trow.a}").each_slice(10) do | urows | # ... end end @param [String] qstr SQL string @yield [JDBCHelper::Connection::Row] @return [Array]
[ "Executes", "a", "select", "query", ".", "When", "a", "code", "block", "is", "given", "each", "row", "of", "the", "result", "is", "passed", "to", "the", "block", "one", "by", "one", ".", "If", "not", "given", "ResultSet", "is", "returned", "which", "can", "be", "used", "to", "enumerate", "through", "the", "result", "set", ".", "ResultSet", "is", "closed", "automatically", "when", "all", "the", "rows", "in", "the", "result", "set", "is", "consumed", "." ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/connection.rb#L302-L321
22,562
junegunn/jdbc-helper
lib/jdbc-helper/connection.rb
JDBCHelper.Connection.execute_batch
def execute_batch check_closed cnt = 0 if @bstmt cnt += @bstmt.execute_batch.inject(:+) || 0 @spool.give @bstmt @bstmt = nil end @pstmts.each do |pstmt| cnt += pstmt.execute_batch end cnt end
ruby
def execute_batch check_closed cnt = 0 if @bstmt cnt += @bstmt.execute_batch.inject(:+) || 0 @spool.give @bstmt @bstmt = nil end @pstmts.each do |pstmt| cnt += pstmt.execute_batch end cnt end
[ "def", "execute_batch", "check_closed", "cnt", "=", "0", "if", "@bstmt", "cnt", "+=", "@bstmt", ".", "execute_batch", ".", "inject", "(", ":+", ")", "||", "0", "@spool", ".", "give", "@bstmt", "@bstmt", "=", "nil", "end", "@pstmts", ".", "each", "do", "|", "pstmt", "|", "cnt", "+=", "pstmt", ".", "execute_batch", "end", "cnt", "end" ]
Executes batched statements including prepared statements. No effect when no statement is added @return [Fixnum] Sum of all update counts
[ "Executes", "batched", "statements", "including", "prepared", "statements", ".", "No", "effect", "when", "no", "statement", "is", "added" ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/connection.rb#L337-L353
22,563
junegunn/jdbc-helper
lib/jdbc-helper/connection.rb
JDBCHelper.Connection.table
def table table_name table = JDBCHelper::TableWrapper.new(self, table_name) table = table.fetch_size(@fetch_size) if @fetch_size @table_wrappers[table_name] ||= table end
ruby
def table table_name table = JDBCHelper::TableWrapper.new(self, table_name) table = table.fetch_size(@fetch_size) if @fetch_size @table_wrappers[table_name] ||= table end
[ "def", "table", "table_name", "table", "=", "JDBCHelper", "::", "TableWrapper", ".", "new", "(", "self", ",", "table_name", ")", "table", "=", "table", ".", "fetch_size", "(", "@fetch_size", ")", "if", "@fetch_size", "@table_wrappers", "[", "table_name", "]", "||=", "table", "end" ]
Returns a table wrapper for the given table name @since 0.2.0 @param [String/Symbol] table_name Name of the table to be wrapped @return [JDBCHelper::TableWrapper]
[ "Returns", "a", "table", "wrapper", "for", "the", "given", "table", "name" ]
0c0e7142ca7faab93db68d526753032ab2dc652f
https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/connection.rb#L406-L410
22,564
chargify/chargify_api_ares
lib/chargify_api_ares/resources/subscription.rb
Chargify.Subscription.save
def save self.attributes.stringify_keys! self.attributes.delete('customer') self.attributes.delete('product') self.attributes.delete('credit_card') self.attributes.delete('bank_account') self.attributes.delete('paypal_account') self.attributes, options = extract_uniqueness_token(attributes) self.prefix_options.merge!(options) super end
ruby
def save self.attributes.stringify_keys! self.attributes.delete('customer') self.attributes.delete('product') self.attributes.delete('credit_card') self.attributes.delete('bank_account') self.attributes.delete('paypal_account') self.attributes, options = extract_uniqueness_token(attributes) self.prefix_options.merge!(options) super end
[ "def", "save", "self", ".", "attributes", ".", "stringify_keys!", "self", ".", "attributes", ".", "delete", "(", "'customer'", ")", "self", ".", "attributes", ".", "delete", "(", "'product'", ")", "self", ".", "attributes", ".", "delete", "(", "'credit_card'", ")", "self", ".", "attributes", ".", "delete", "(", "'bank_account'", ")", "self", ".", "attributes", ".", "delete", "(", "'paypal_account'", ")", "self", ".", "attributes", ",", "options", "=", "extract_uniqueness_token", "(", "attributes", ")", "self", ".", "prefix_options", ".", "merge!", "(", "options", ")", "super", "end" ]
Strip off nested attributes of associations before saving, or type-mismatch errors will occur
[ "Strip", "off", "nested", "attributes", "of", "associations", "before", "saving", "or", "type", "-", "mismatch", "errors", "will", "occur" ]
b0c2c7d2bec9213982868cf43a2c83fa1bf78880
https://github.com/chargify/chargify_api_ares/blob/b0c2c7d2bec9213982868cf43a2c83fa1bf78880/lib/chargify_api_ares/resources/subscription.rb#L11-L22
22,565
gbiczo/oxcelix
lib/oxcelix/workbook.rb
Oxcelix.Workbook.unpack
def unpack(filename) @destination = Dir.mktmpdir Zip::File.open(filename){ |zip_file| zip_file.each{ |f| f_path=File.join(@destination, f.name) FileUtils.mkdir_p(File.dirname(f_path)) zip_file.extract(f, f_path) unless File.exists?(f_path) } } end
ruby
def unpack(filename) @destination = Dir.mktmpdir Zip::File.open(filename){ |zip_file| zip_file.each{ |f| f_path=File.join(@destination, f.name) FileUtils.mkdir_p(File.dirname(f_path)) zip_file.extract(f, f_path) unless File.exists?(f_path) } } end
[ "def", "unpack", "(", "filename", ")", "@destination", "=", "Dir", ".", "mktmpdir", "Zip", "::", "File", ".", "open", "(", "filename", ")", "{", "|", "zip_file", "|", "zip_file", ".", "each", "{", "|", "f", "|", "f_path", "=", "File", ".", "join", "(", "@destination", ",", "f", ".", "name", ")", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "f_path", ")", ")", "zip_file", ".", "extract", "(", "f", ",", "f_path", ")", "unless", "File", ".", "exists?", "(", "f_path", ")", "}", "}", "end" ]
Unzips the excel file to a temporary directory. The directory will be removed at the end of the parsing stage when invoked by initialize, otherwise at exit. @param [String] filename the name of the Excel file to be unpacked
[ "Unzips", "the", "excel", "file", "to", "a", "temporary", "directory", ".", "The", "directory", "will", "be", "removed", "at", "the", "end", "of", "the", "parsing", "stage", "when", "invoked", "by", "initialize", "otherwise", "at", "exit", "." ]
144378e62c5288781db53345ec9d400dc7a70dc3
https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/workbook.rb#L72-L81
22,566
gbiczo/oxcelix
lib/oxcelix/workbook.rb
Oxcelix.Workbook.parse
def parse(options={}) @sheets.each do |x| if !options[:paginate].nil? lines = options[:paginate][0]; page = options[:paginate][1] sheet = PagSheet.new(lines, page) elsif !options[:cellrange].nil? range = options[:cellrange] sheet = Cellrange.new(range) else sheet = Xlsheet.new() end File.open(@destination+"/xl/#{x[:filename]}", 'r') do |f| Ox.sax_parse(sheet, f) end comments = mkcomments(x[:comments]) sheet.cellarray.each do |sh| sh.numformat = @styles.styleary[sh.style.to_i] if sh.type=="s" sh.value = @sharedstrings[sh.value.to_i] end if !comments.nil? comm=comments.select {|c| c[:ref]==(sh.xlcoords)} if comm.size > 0 sh.comment=comm[0][:comment] end comments.delete_if{|c| c[:ref]==(sh.xlcoords)} end end x[:cells] = sheet.cellarray x[:mergedcells] = sheet.mergedcells end matrixto options end
ruby
def parse(options={}) @sheets.each do |x| if !options[:paginate].nil? lines = options[:paginate][0]; page = options[:paginate][1] sheet = PagSheet.new(lines, page) elsif !options[:cellrange].nil? range = options[:cellrange] sheet = Cellrange.new(range) else sheet = Xlsheet.new() end File.open(@destination+"/xl/#{x[:filename]}", 'r') do |f| Ox.sax_parse(sheet, f) end comments = mkcomments(x[:comments]) sheet.cellarray.each do |sh| sh.numformat = @styles.styleary[sh.style.to_i] if sh.type=="s" sh.value = @sharedstrings[sh.value.to_i] end if !comments.nil? comm=comments.select {|c| c[:ref]==(sh.xlcoords)} if comm.size > 0 sh.comment=comm[0][:comment] end comments.delete_if{|c| c[:ref]==(sh.xlcoords)} end end x[:cells] = sheet.cellarray x[:mergedcells] = sheet.mergedcells end matrixto options end
[ "def", "parse", "(", "options", "=", "{", "}", ")", "@sheets", ".", "each", "do", "|", "x", "|", "if", "!", "options", "[", ":paginate", "]", ".", "nil?", "lines", "=", "options", "[", ":paginate", "]", "[", "0", "]", ";", "page", "=", "options", "[", ":paginate", "]", "[", "1", "]", "sheet", "=", "PagSheet", ".", "new", "(", "lines", ",", "page", ")", "elsif", "!", "options", "[", ":cellrange", "]", ".", "nil?", "range", "=", "options", "[", ":cellrange", "]", "sheet", "=", "Cellrange", ".", "new", "(", "range", ")", "else", "sheet", "=", "Xlsheet", ".", "new", "(", ")", "end", "File", ".", "open", "(", "@destination", "+", "\"/xl/#{x[:filename]}\"", ",", "'r'", ")", "do", "|", "f", "|", "Ox", ".", "sax_parse", "(", "sheet", ",", "f", ")", "end", "comments", "=", "mkcomments", "(", "x", "[", ":comments", "]", ")", "sheet", ".", "cellarray", ".", "each", "do", "|", "sh", "|", "sh", ".", "numformat", "=", "@styles", ".", "styleary", "[", "sh", ".", "style", ".", "to_i", "]", "if", "sh", ".", "type", "==", "\"s\"", "sh", ".", "value", "=", "@sharedstrings", "[", "sh", ".", "value", ".", "to_i", "]", "end", "if", "!", "comments", ".", "nil?", "comm", "=", "comments", ".", "select", "{", "|", "c", "|", "c", "[", ":ref", "]", "==", "(", "sh", ".", "xlcoords", ")", "}", "if", "comm", ".", "size", ">", "0", "sh", ".", "comment", "=", "comm", "[", "0", "]", "[", ":comment", "]", "end", "comments", ".", "delete_if", "{", "|", "c", "|", "c", "[", ":ref", "]", "==", "(", "sh", ".", "xlcoords", ")", "}", "end", "end", "x", "[", ":cells", "]", "=", "sheet", ".", "cellarray", "x", "[", ":mergedcells", "]", "=", "sheet", ".", "mergedcells", "end", "matrixto", "options", "end" ]
Parses sheet data by feeding the output of the Xlsheet SAX parser into the arrays representing the sheets. @param [Hash] options Options that affect the parser.
[ "Parses", "sheet", "data", "by", "feeding", "the", "output", "of", "the", "Xlsheet", "SAX", "parser", "into", "the", "arrays", "representing", "the", "sheets", "." ]
144378e62c5288781db53345ec9d400dc7a70dc3
https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/workbook.rb#L103-L136
22,567
gbiczo/oxcelix
lib/oxcelix/workbook.rb
Oxcelix.Workbook.commentsrel
def commentsrel unless Dir[@destination + '/xl/worksheets/_rels'].empty? Find.find(@destination + '/xl/worksheets/_rels') do |path| if File.basename(path).split(".").last=='rels' a=IO.read(path) f=Ox::load(a) f.locate("Relationships/*").each do |x| if x[:Target].include?"comments" @sheets.each do |s| if "worksheets/" + File.basename(path,".rels")==s[:filename] s[:comments]=x[:Target] end end end end end end else @sheets.each do |s| s[:comments]=nil end end end
ruby
def commentsrel unless Dir[@destination + '/xl/worksheets/_rels'].empty? Find.find(@destination + '/xl/worksheets/_rels') do |path| if File.basename(path).split(".").last=='rels' a=IO.read(path) f=Ox::load(a) f.locate("Relationships/*").each do |x| if x[:Target].include?"comments" @sheets.each do |s| if "worksheets/" + File.basename(path,".rels")==s[:filename] s[:comments]=x[:Target] end end end end end end else @sheets.each do |s| s[:comments]=nil end end end
[ "def", "commentsrel", "unless", "Dir", "[", "@destination", "+", "'/xl/worksheets/_rels'", "]", ".", "empty?", "Find", ".", "find", "(", "@destination", "+", "'/xl/worksheets/_rels'", ")", "do", "|", "path", "|", "if", "File", ".", "basename", "(", "path", ")", ".", "split", "(", "\".\"", ")", ".", "last", "==", "'rels'", "a", "=", "IO", ".", "read", "(", "path", ")", "f", "=", "Ox", "::", "load", "(", "a", ")", "f", ".", "locate", "(", "\"Relationships/*\"", ")", ".", "each", "do", "|", "x", "|", "if", "x", "[", ":Target", "]", ".", "include?", "\"comments\"", "@sheets", ".", "each", "do", "|", "s", "|", "if", "\"worksheets/\"", "+", "File", ".", "basename", "(", "path", ",", "\".rels\"", ")", "==", "s", "[", ":filename", "]", "s", "[", ":comments", "]", "=", "x", "[", ":Target", "]", "end", "end", "end", "end", "end", "end", "else", "@sheets", ".", "each", "do", "|", "s", "|", "s", "[", ":comments", "]", "=", "nil", "end", "end", "end" ]
Build the relationship between sheets and the XML files storing the comments to the actual sheet.
[ "Build", "the", "relationship", "between", "sheets", "and", "the", "XML", "files", "storing", "the", "comments", "to", "the", "actual", "sheet", "." ]
144378e62c5288781db53345ec9d400dc7a70dc3
https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/workbook.rb#L192-L214
22,568
gbiczo/oxcelix
lib/oxcelix/workbook.rb
Oxcelix.Workbook.shstrings
def shstrings strings = Sharedstrings.new() File.open(@destination + '/xl/sharedStrings.xml', 'r') do |f| Ox.sax_parse(strings, f) end @sharedstrings=strings.stringarray end
ruby
def shstrings strings = Sharedstrings.new() File.open(@destination + '/xl/sharedStrings.xml', 'r') do |f| Ox.sax_parse(strings, f) end @sharedstrings=strings.stringarray end
[ "def", "shstrings", "strings", "=", "Sharedstrings", ".", "new", "(", ")", "File", ".", "open", "(", "@destination", "+", "'/xl/sharedStrings.xml'", ",", "'r'", ")", "do", "|", "f", "|", "Ox", ".", "sax_parse", "(", "strings", ",", "f", ")", "end", "@sharedstrings", "=", "strings", ".", "stringarray", "end" ]
Invokes the Sharedstrings helper class
[ "Invokes", "the", "Sharedstrings", "helper", "class" ]
144378e62c5288781db53345ec9d400dc7a70dc3
https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/workbook.rb#L217-L223
22,569
gbiczo/oxcelix
lib/oxcelix/workbook.rb
Oxcelix.Workbook.mkcomments
def mkcomments(commentfile) unless commentfile.nil? comms = Comments.new() File.open(@destination + '/xl/'+commentfile.gsub('../', ''), 'r') do |f| Ox.sax_parse(comms, f) end return comms.commarray end end
ruby
def mkcomments(commentfile) unless commentfile.nil? comms = Comments.new() File.open(@destination + '/xl/'+commentfile.gsub('../', ''), 'r') do |f| Ox.sax_parse(comms, f) end return comms.commarray end end
[ "def", "mkcomments", "(", "commentfile", ")", "unless", "commentfile", ".", "nil?", "comms", "=", "Comments", ".", "new", "(", ")", "File", ".", "open", "(", "@destination", "+", "'/xl/'", "+", "commentfile", ".", "gsub", "(", "'../'", ",", "''", ")", ",", "'r'", ")", "do", "|", "f", "|", "Ox", ".", "sax_parse", "(", "comms", ",", "f", ")", "end", "return", "comms", ".", "commarray", "end", "end" ]
Parses the comments related to the actual sheet. @param [String] commentfile @return [Array] a collection of comments relative to the Excel sheet currently processed
[ "Parses", "the", "comments", "related", "to", "the", "actual", "sheet", "." ]
144378e62c5288781db53345ec9d400dc7a70dc3
https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/workbook.rb#L228-L236
22,570
gbiczo/oxcelix
lib/oxcelix/workbook.rb
Oxcelix.Workbook.mergevalues
def mergevalues(m, col, row, valuecell) if valuecell != nil valuecell.xlcoords=(col.col_name)+(row+1).to_s m[row, col]=valuecell return m, valuecell else valuecell=Cell.new valuecell.xlcoords=(col.col_name)+(row+1).to_s m[row, col]=valuecell return m, valuecell end end
ruby
def mergevalues(m, col, row, valuecell) if valuecell != nil valuecell.xlcoords=(col.col_name)+(row+1).to_s m[row, col]=valuecell return m, valuecell else valuecell=Cell.new valuecell.xlcoords=(col.col_name)+(row+1).to_s m[row, col]=valuecell return m, valuecell end end
[ "def", "mergevalues", "(", "m", ",", "col", ",", "row", ",", "valuecell", ")", "if", "valuecell", "!=", "nil", "valuecell", ".", "xlcoords", "=", "(", "col", ".", "col_name", ")", "+", "(", "row", "+", "1", ")", ".", "to_s", "m", "[", "row", ",", "col", "]", "=", "valuecell", "return", "m", ",", "valuecell", "else", "valuecell", "=", "Cell", ".", "new", "valuecell", ".", "xlcoords", "=", "(", "col", ".", "col_name", ")", "+", "(", "row", "+", "1", ")", ".", "to_s", "m", "[", "row", ",", "col", "]", "=", "valuecell", "return", "m", ",", "valuecell", "end", "end" ]
Replace the empty values of the mergegroup with cell values or nil. @param [Matrix] m the Sheet object @param [Integer] col Column of the actual cell @param [Integer] row Row of the actual cell @param [Cell] valuecell A Cell containing the value to be copied over the mergegroup @return [Matrix, Cell] the sheet and the new (empty) cell or nil.
[ "Replace", "the", "empty", "values", "of", "the", "mergegroup", "with", "cell", "values", "or", "nil", "." ]
144378e62c5288781db53345ec9d400dc7a70dc3
https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/workbook.rb#L311-L322
22,571
gbiczo/oxcelix
lib/oxcelix/numformats.rb
Oxcelix.Numformats.datetime
def datetime formatcode deminutified = formatcode.downcase.gsub(/(?<hrs>H|h)(?<div>.)m/, '\k<hrs>\k<div>i') .gsub(/im/, 'ii') .gsub(/m(?<div>.)(?<secs>s)/, 'i\k<div>\k<secs>') .gsub(/mi/, 'ii') return deminutified.gsub(/[yMmDdHhSsi]*/, Dtmap) end
ruby
def datetime formatcode deminutified = formatcode.downcase.gsub(/(?<hrs>H|h)(?<div>.)m/, '\k<hrs>\k<div>i') .gsub(/im/, 'ii') .gsub(/m(?<div>.)(?<secs>s)/, 'i\k<div>\k<secs>') .gsub(/mi/, 'ii') return deminutified.gsub(/[yMmDdHhSsi]*/, Dtmap) end
[ "def", "datetime", "formatcode", "deminutified", "=", "formatcode", ".", "downcase", ".", "gsub", "(", "/", "/", ",", "'\\k<hrs>\\k<div>i'", ")", ".", "gsub", "(", "/", "/", ",", "'ii'", ")", ".", "gsub", "(", "/", "/", ",", "'i\\k<div>\\k<secs>'", ")", ".", "gsub", "(", "/", "/", ",", "'ii'", ")", "return", "deminutified", ".", "gsub", "(", "/", "/", ",", "Dtmap", ")", "end" ]
Convert excel-style date formats into ruby DateTime strftime format strings @param [String] formatcode an Excel number format string. @return [String] a DateTime::strftime format string.
[ "Convert", "excel", "-", "style", "date", "formats", "into", "ruby", "DateTime", "strftime", "format", "strings" ]
144378e62c5288781db53345ec9d400dc7a70dc3
https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/numformats.rb#L67-L73
22,572
gbiczo/oxcelix
lib/oxcelix/numformats.rb
Oxcelix.Numberhelper.to_ru
def to_ru if [email protected]? || Numformats::Formatarray[@numformat.to_i][:xl] == nil || Numformats::Formatarray[@numformat.to_i][:xl].downcase == "general" return @value end if Numformats::Formatarray[@numformat.to_i][:cls] == 'date' return DateTime.new(1899, 12, 30) + (eval @value) elsif Numformats::Formatarray[@numformat.to_i][:cls] == 'numeric' || Numformats::Formatarray[@numformat.to_i][:cls] == 'rational' return eval @value rescue @value end end
ruby
def to_ru if [email protected]? || Numformats::Formatarray[@numformat.to_i][:xl] == nil || Numformats::Formatarray[@numformat.to_i][:xl].downcase == "general" return @value end if Numformats::Formatarray[@numformat.to_i][:cls] == 'date' return DateTime.new(1899, 12, 30) + (eval @value) elsif Numformats::Formatarray[@numformat.to_i][:cls] == 'numeric' || Numformats::Formatarray[@numformat.to_i][:cls] == 'rational' return eval @value rescue @value end end
[ "def", "to_ru", "if", "!", "@value", ".", "numeric?", "||", "Numformats", "::", "Formatarray", "[", "@numformat", ".", "to_i", "]", "[", ":xl", "]", "==", "nil", "||", "Numformats", "::", "Formatarray", "[", "@numformat", ".", "to_i", "]", "[", ":xl", "]", ".", "downcase", "==", "\"general\"", "return", "@value", "end", "if", "Numformats", "::", "Formatarray", "[", "@numformat", ".", "to_i", "]", "[", ":cls", "]", "==", "'date'", "return", "DateTime", ".", "new", "(", "1899", ",", "12", ",", "30", ")", "+", "(", "eval", "@value", ")", "elsif", "Numformats", "::", "Formatarray", "[", "@numformat", ".", "to_i", "]", "[", ":cls", "]", "==", "'numeric'", "||", "Numformats", "::", "Formatarray", "[", "@numformat", ".", "to_i", "]", "[", ":cls", "]", "==", "'rational'", "return", "eval", "@value", "rescue", "@value", "end", "end" ]
Get the cell's value and excel format string and return a string, a ruby Numeric or a DateTime object accordingly @return [Object] A ruby object that holds and represents the value stored in the cell. Conversion is based on cell formatting. @example Get the value of a cell: c = w.sheets[0]["B3"] # => <Oxcelix::Cell:0x00000002a5b368 @xlcoords="A3", @style="84", @type="n", @value="41155", @numformat=14> c.to_ru # => <DateTime: 2012-09-03T00:00:00+00:00 ((2456174j,0s,0n),+0s,2299161j)>
[ "Get", "the", "cell", "s", "value", "and", "excel", "format", "string", "and", "return", "a", "string", "a", "ruby", "Numeric", "or", "a", "DateTime", "object", "accordingly" ]
144378e62c5288781db53345ec9d400dc7a70dc3
https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/numformats.rb#L85-L94
22,573
gbiczo/oxcelix
lib/oxcelix/numformats.rb
Oxcelix.Numberhelper.to_fmt
def to_fmt begin if Numformats::Formatarray[@numformat.to_i][:cls] == 'date' self.to_ru.strftime(Numformats::Formatarray[@numformat][:ostring]) rescue @value elsif Numformats::Formatarray[@numformat.to_i][:cls] == 'numeric' || Numformats::Formatarray[@numformat.to_i][:cls] == 'rational' sprintf(Numformats::Formatarray[@numformat][:ostring], self.to_ru) rescue @value else return @value end end end
ruby
def to_fmt begin if Numformats::Formatarray[@numformat.to_i][:cls] == 'date' self.to_ru.strftime(Numformats::Formatarray[@numformat][:ostring]) rescue @value elsif Numformats::Formatarray[@numformat.to_i][:cls] == 'numeric' || Numformats::Formatarray[@numformat.to_i][:cls] == 'rational' sprintf(Numformats::Formatarray[@numformat][:ostring], self.to_ru) rescue @value else return @value end end end
[ "def", "to_fmt", "begin", "if", "Numformats", "::", "Formatarray", "[", "@numformat", ".", "to_i", "]", "[", ":cls", "]", "==", "'date'", "self", ".", "to_ru", ".", "strftime", "(", "Numformats", "::", "Formatarray", "[", "@numformat", "]", "[", ":ostring", "]", ")", "rescue", "@value", "elsif", "Numformats", "::", "Formatarray", "[", "@numformat", ".", "to_i", "]", "[", ":cls", "]", "==", "'numeric'", "||", "Numformats", "::", "Formatarray", "[", "@numformat", ".", "to_i", "]", "[", ":cls", "]", "==", "'rational'", "sprintf", "(", "Numformats", "::", "Formatarray", "[", "@numformat", "]", "[", ":ostring", "]", ",", "self", ".", "to_ru", ")", "rescue", "@value", "else", "return", "@value", "end", "end", "end" ]
Get the cell's value, convert it with to_ru and finally, format it based on the value's type. @return [String] Value gets formatted depending on its class. If it is a DateTime, the #DateTime.strftime method is used, if it holds a number, the #Kernel::sprintf is run. @example Get the formatted value of a cell: c = w.sheets[0]["B3"] # => <Oxcelix::Cell:0x00000002a5b368 @xlcoords="A3", @style="84", @type="n", @value="41155", @numformat=14> c.to_fmt # => "3/9/2012"
[ "Get", "the", "cell", "s", "value", "convert", "it", "with", "to_ru", "and", "finally", "format", "it", "based", "on", "the", "value", "s", "type", "." ]
144378e62c5288781db53345ec9d400dc7a70dc3
https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/numformats.rb#L103-L113
22,574
gbiczo/oxcelix
lib/oxcelix/sheet.rb
Oxcelix.Sheet.to_m
def to_m(*attrs) m=Matrix.build(self.row_size, self.column_size){nil} self.each_with_index do |x, row, col| if attrs.size == 0 || attrs.nil? m[row, col] = x.value end end return m end
ruby
def to_m(*attrs) m=Matrix.build(self.row_size, self.column_size){nil} self.each_with_index do |x, row, col| if attrs.size == 0 || attrs.nil? m[row, col] = x.value end end return m end
[ "def", "to_m", "(", "*", "attrs", ")", "m", "=", "Matrix", ".", "build", "(", "self", ".", "row_size", ",", "self", ".", "column_size", ")", "{", "nil", "}", "self", ".", "each_with_index", "do", "|", "x", ",", "row", ",", "col", "|", "if", "attrs", ".", "size", "==", "0", "||", "attrs", ".", "nil?", "m", "[", "row", ",", "col", "]", "=", "x", ".", "value", "end", "end", "return", "m", "end" ]
The to_m method returns a simple Matrix object filled with the raw values of the original Sheet object. @return [Matrix] a collection of string values (the former #Cell::value)
[ "The", "to_m", "method", "returns", "a", "simple", "Matrix", "object", "filled", "with", "the", "raw", "values", "of", "the", "original", "Sheet", "object", "." ]
144378e62c5288781db53345ec9d400dc7a70dc3
https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/sheet.rb#L32-L40
22,575
loco2/lolsoap
lib/lolsoap/envelope.rb
LolSoap.Envelope.body
def body(klass = Builder) builder = klass.new(body_content, input_body_content_type) yield builder if block_given? builder end
ruby
def body(klass = Builder) builder = klass.new(body_content, input_body_content_type) yield builder if block_given? builder end
[ "def", "body", "(", "klass", "=", "Builder", ")", "builder", "=", "klass", ".", "new", "(", "body_content", ",", "input_body_content_type", ")", "yield", "builder", "if", "block_given?", "builder", "end" ]
Build the body of the envelope @example env.body do |b| b.some 'data' end
[ "Build", "the", "body", "of", "the", "envelope" ]
499d6db0c2f8c1b20aaa872a50442cdee90599dc
https://github.com/loco2/lolsoap/blob/499d6db0c2f8c1b20aaa872a50442cdee90599dc/lib/lolsoap/envelope.rb#L28-L32
22,576
loco2/lolsoap
lib/lolsoap/envelope.rb
LolSoap.Envelope.header
def header(klass = Builder) builder = klass.new(header_content, input_header_content_type) yield builder if block_given? builder end
ruby
def header(klass = Builder) builder = klass.new(header_content, input_header_content_type) yield builder if block_given? builder end
[ "def", "header", "(", "klass", "=", "Builder", ")", "builder", "=", "klass", ".", "new", "(", "header_content", ",", "input_header_content_type", ")", "yield", "builder", "if", "block_given?", "builder", "end" ]
Build the header of the envelope
[ "Build", "the", "header", "of", "the", "envelope" ]
499d6db0c2f8c1b20aaa872a50442cdee90599dc
https://github.com/loco2/lolsoap/blob/499d6db0c2f8c1b20aaa872a50442cdee90599dc/lib/lolsoap/envelope.rb#L35-L39
22,577
orta/gh_inspector
lib/gh_inspector/inspector.rb
GhInspector.Inspector.search_exception
def search_exception(exception, delegate = nil) query = ExceptionHound.new(exception).query search_query(query, delegate) end
ruby
def search_exception(exception, delegate = nil) query = ExceptionHound.new(exception).query search_query(query, delegate) end
[ "def", "search_exception", "(", "exception", ",", "delegate", "=", "nil", ")", "query", "=", "ExceptionHound", ".", "new", "(", "exception", ")", ".", "query", "search_query", "(", "query", ",", "delegate", ")", "end" ]
Init function with "orta", "project" Will do some magic to try and pull out a reasonable search query for an exception, then searches with that
[ "Init", "function", "with", "orta", "project", "Will", "do", "some", "magic", "to", "try", "and", "pull", "out", "a", "reasonable", "search", "query", "for", "an", "exception", "then", "searches", "with", "that" ]
f65c3c85a9bb1ad92ee595b6df122957d20cdac8
https://github.com/orta/gh_inspector/blob/f65c3c85a9bb1ad92ee595b6df122957d20cdac8/lib/gh_inspector/inspector.rb#L60-L63
22,578
orta/gh_inspector
lib/gh_inspector/inspector.rb
GhInspector.Inspector.search_query
def search_query(query, delegate = nil) delegate ||= Evidence.new sidekick.search(query, delegate) end
ruby
def search_query(query, delegate = nil) delegate ||= Evidence.new sidekick.search(query, delegate) end
[ "def", "search_query", "(", "query", ",", "delegate", "=", "nil", ")", "delegate", "||=", "Evidence", ".", "new", "sidekick", ".", "search", "(", "query", ",", "delegate", ")", "end" ]
Queries for an specific search string
[ "Queries", "for", "an", "specific", "search", "string" ]
f65c3c85a9bb1ad92ee595b6df122957d20cdac8
https://github.com/orta/gh_inspector/blob/f65c3c85a9bb1ad92ee595b6df122957d20cdac8/lib/gh_inspector/inspector.rb#L66-L69
22,579
loco2/lolsoap
lib/lolsoap/wsdl.rb
LolSoap.WSDL.type
def type(namespace, name) if @allow_abstract_types @types.fetch([namespace, name]) { abstract_type(namespace, name) } else @types.fetch([namespace, name]) { NullType.new } end end
ruby
def type(namespace, name) if @allow_abstract_types @types.fetch([namespace, name]) { abstract_type(namespace, name) } else @types.fetch([namespace, name]) { NullType.new } end end
[ "def", "type", "(", "namespace", ",", "name", ")", "if", "@allow_abstract_types", "@types", ".", "fetch", "(", "[", "namespace", ",", "name", "]", ")", "{", "abstract_type", "(", "namespace", ",", "name", ")", "}", "else", "@types", ".", "fetch", "(", "[", "namespace", ",", "name", "]", ")", "{", "NullType", ".", "new", "}", "end", "end" ]
Get a single type, or a NullType if the type doesn't exist
[ "Get", "a", "single", "type", "or", "a", "NullType", "if", "the", "type", "doesn", "t", "exist" ]
499d6db0c2f8c1b20aaa872a50442cdee90599dc
https://github.com/loco2/lolsoap/blob/499d6db0c2f8c1b20aaa872a50442cdee90599dc/lib/lolsoap/wsdl.rb#L54-L60
22,580
loco2/lolsoap
lib/lolsoap/response.rb
LolSoap.Response.fault
def fault @fault ||= begin node = doc.at_xpath('/soap:Envelope/soap:Body/soap:Fault', 'soap' => soap_namespace) Fault.new(request, node) if node end end
ruby
def fault @fault ||= begin node = doc.at_xpath('/soap:Envelope/soap:Body/soap:Fault', 'soap' => soap_namespace) Fault.new(request, node) if node end end
[ "def", "fault", "@fault", "||=", "begin", "node", "=", "doc", ".", "at_xpath", "(", "'/soap:Envelope/soap:Body/soap:Fault'", ",", "'soap'", "=>", "soap_namespace", ")", "Fault", ".", "new", "(", "request", ",", "node", ")", "if", "node", "end", "end" ]
SOAP fault, if any
[ "SOAP", "fault", "if", "any" ]
499d6db0c2f8c1b20aaa872a50442cdee90599dc
https://github.com/loco2/lolsoap/blob/499d6db0c2f8c1b20aaa872a50442cdee90599dc/lib/lolsoap/response.rb#L47-L52
22,581
orta/gh_inspector
lib/gh_inspector/sidekick.rb
GhInspector.Sidekick.search
def search(query, delegate) validate_delegate(delegate) delegate.inspector_started_query(query, inspector) url = url_for_request query begin results = get_api_results(url) rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e delegate.inspector_could_not_create_report(e, query, inspector) return end report = parse_results query, results # TODO: progress callback if report.issues.any? if self.using_deprecated_method delegate.inspector_successfully_recieved_report(report, inspector) else delegate.inspector_successfully_received_report(report, inspector) end else # rubocop:disable Style/IfInsideElse if self.using_deprecated_method delegate.inspector_recieved_empty_report(report, inspector) else delegate.inspector_received_empty_report(report, inspector) end # rubocop:enable Style/IfInsideElse end report end
ruby
def search(query, delegate) validate_delegate(delegate) delegate.inspector_started_query(query, inspector) url = url_for_request query begin results = get_api_results(url) rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e delegate.inspector_could_not_create_report(e, query, inspector) return end report = parse_results query, results # TODO: progress callback if report.issues.any? if self.using_deprecated_method delegate.inspector_successfully_recieved_report(report, inspector) else delegate.inspector_successfully_received_report(report, inspector) end else # rubocop:disable Style/IfInsideElse if self.using_deprecated_method delegate.inspector_recieved_empty_report(report, inspector) else delegate.inspector_received_empty_report(report, inspector) end # rubocop:enable Style/IfInsideElse end report end
[ "def", "search", "(", "query", ",", "delegate", ")", "validate_delegate", "(", "delegate", ")", "delegate", ".", "inspector_started_query", "(", "query", ",", "inspector", ")", "url", "=", "url_for_request", "query", "begin", "results", "=", "get_api_results", "(", "url", ")", "rescue", "Timeout", "::", "Error", ",", "Errno", "::", "EINVAL", ",", "Errno", "::", "ECONNRESET", ",", "EOFError", ",", "Net", "::", "HTTPBadResponse", ",", "Net", "::", "HTTPHeaderSyntaxError", ",", "Net", "::", "ProtocolError", "=>", "e", "delegate", ".", "inspector_could_not_create_report", "(", "e", ",", "query", ",", "inspector", ")", "return", "end", "report", "=", "parse_results", "query", ",", "results", "# TODO: progress callback", "if", "report", ".", "issues", ".", "any?", "if", "self", ".", "using_deprecated_method", "delegate", ".", "inspector_successfully_recieved_report", "(", "report", ",", "inspector", ")", "else", "delegate", ".", "inspector_successfully_received_report", "(", "report", ",", "inspector", ")", "end", "else", "# rubocop:disable Style/IfInsideElse", "if", "self", ".", "using_deprecated_method", "delegate", ".", "inspector_recieved_empty_report", "(", "report", ",", "inspector", ")", "else", "delegate", ".", "inspector_received_empty_report", "(", "report", ",", "inspector", ")", "end", "# rubocop:enable Style/IfInsideElse", "end", "report", "end" ]
Searches for a query, with a UI delegate
[ "Searches", "for", "a", "query", "with", "a", "UI", "delegate" ]
f65c3c85a9bb1ad92ee595b6df122957d20cdac8
https://github.com/orta/gh_inspector/blob/f65c3c85a9bb1ad92ee595b6df122957d20cdac8/lib/gh_inspector/sidekick.rb#L21-L55
22,582
orta/gh_inspector
lib/gh_inspector/sidekick.rb
GhInspector.Sidekick.url_for_request
def url_for_request(query, sort_by: nil, order: nil) url = "https://api.github.com/search/issues?q=" url += ERB::Util.url_encode(query) url += "+repo:#{repo_owner}/#{repo_name}" url += "&sort=#{sort_by}" if sort_by url += "&order=#{order}" if order url end
ruby
def url_for_request(query, sort_by: nil, order: nil) url = "https://api.github.com/search/issues?q=" url += ERB::Util.url_encode(query) url += "+repo:#{repo_owner}/#{repo_name}" url += "&sort=#{sort_by}" if sort_by url += "&order=#{order}" if order url end
[ "def", "url_for_request", "(", "query", ",", "sort_by", ":", "nil", ",", "order", ":", "nil", ")", "url", "=", "\"https://api.github.com/search/issues?q=\"", "url", "+=", "ERB", "::", "Util", ".", "url_encode", "(", "query", ")", "url", "+=", "\"+repo:#{repo_owner}/#{repo_name}\"", "url", "+=", "\"&sort=#{sort_by}\"", "if", "sort_by", "url", "+=", "\"&order=#{order}\"", "if", "order", "url", "end" ]
Generates a URL for the request
[ "Generates", "a", "URL", "for", "the", "request" ]
f65c3c85a9bb1ad92ee595b6df122957d20cdac8
https://github.com/orta/gh_inspector/blob/f65c3c85a9bb1ad92ee595b6df122957d20cdac8/lib/gh_inspector/sidekick.rb#L66-L74
22,583
orta/gh_inspector
lib/gh_inspector/sidekick.rb
GhInspector.Sidekick.get_api_results
def get_api_results(url) uri = URI.parse(url) puts "URL: #{url}" if self.verbose http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Get.new(uri.request_uri) response = http.request(request) JSON.parse(response.body) end
ruby
def get_api_results(url) uri = URI.parse(url) puts "URL: #{url}" if self.verbose http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Get.new(uri.request_uri) response = http.request(request) JSON.parse(response.body) end
[ "def", "get_api_results", "(", "url", ")", "uri", "=", "URI", ".", "parse", "(", "url", ")", "puts", "\"URL: #{url}\"", "if", "self", ".", "verbose", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "http", ".", "use_ssl", "=", "true", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "uri", ".", "request_uri", ")", "response", "=", "http", ".", "request", "(", "request", ")", "JSON", ".", "parse", "(", "response", ".", "body", ")", "end" ]
Gets the search results
[ "Gets", "the", "search", "results" ]
f65c3c85a9bb1ad92ee595b6df122957d20cdac8
https://github.com/orta/gh_inspector/blob/f65c3c85a9bb1ad92ee595b6df122957d20cdac8/lib/gh_inspector/sidekick.rb#L77-L87
22,584
orta/gh_inspector
lib/gh_inspector/sidekick.rb
GhInspector.Sidekick.parse_results
def parse_results(query, results) report = InspectionReport.new report.url = "https://github.com/#{repo_owner}/#{repo_name}/search?q=#{ERB::Util.url_encode(query)}&type=Issues&utf8=✓" report.query = query report.total_results = results['total_count'] report.issues = results['items'].map { |item| Issue.new(item) } report end
ruby
def parse_results(query, results) report = InspectionReport.new report.url = "https://github.com/#{repo_owner}/#{repo_name}/search?q=#{ERB::Util.url_encode(query)}&type=Issues&utf8=✓" report.query = query report.total_results = results['total_count'] report.issues = results['items'].map { |item| Issue.new(item) } report end
[ "def", "parse_results", "(", "query", ",", "results", ")", "report", "=", "InspectionReport", ".", "new", "report", ".", "url", "=", "\"https://github.com/#{repo_owner}/#{repo_name}/search?q=#{ERB::Util.url_encode(query)}&type=Issues&utf8=✓\"", "report", ".", "query", "=", "query", "report", ".", "total_results", "=", "results", "[", "'total_count'", "]", "report", ".", "issues", "=", "results", "[", "'items'", "]", ".", "map", "{", "|", "item", "|", "Issue", ".", "new", "(", "item", ")", "}", "report", "end" ]
Converts a GitHub search JSON into a InspectionReport
[ "Converts", "a", "GitHub", "search", "JSON", "into", "a", "InspectionReport" ]
f65c3c85a9bb1ad92ee595b6df122957d20cdac8
https://github.com/orta/gh_inspector/blob/f65c3c85a9bb1ad92ee595b6df122957d20cdac8/lib/gh_inspector/sidekick.rb#L90-L97
22,585
KatanaCode/blogit
app/helpers/blogit/comments_helper.rb
Blogit.CommentsHelper.name_for_comment
def name_for_comment(comment) if comment.website? link_to(comment.name, comment.website, class: "blogit_comment__name_link") else comment.name end + " " + t('wrote', scope: "blogit.comments") end
ruby
def name_for_comment(comment) if comment.website? link_to(comment.name, comment.website, class: "blogit_comment__name_link") else comment.name end + " " + t('wrote', scope: "blogit.comments") end
[ "def", "name_for_comment", "(", "comment", ")", "if", "comment", ".", "website?", "link_to", "(", "comment", ".", "name", ",", "comment", ".", "website", ",", "class", ":", "\"blogit_comment__name_link\"", ")", "else", "comment", ".", "name", "end", "+", "\" \"", "+", "t", "(", "'wrote'", ",", "scope", ":", "\"blogit.comments\"", ")", "end" ]
The commenter's name for a Comment. When the Comment has a website, includes an html link containing their name. Otherwise, just shows the name as a String. comment - A {Blogit::Comment} Returns a String containing the commenter's name.
[ "The", "commenter", "s", "name", "for", "a", "Comment", ".", "When", "the", "Comment", "has", "a", "website", "includes", "an", "html", "link", "containing", "their", "name", ".", "Otherwise", "just", "shows", "the", "name", "as", "a", "String", "." ]
93e3830bacc542970e41cee94d5d8fbb6fdefc3c
https://github.com/KatanaCode/blogit/blob/93e3830bacc542970e41cee94d5d8fbb6fdefc3c/app/helpers/blogit/comments_helper.rb#L11-L17
22,586
state-machines/state_machines-graphviz
lib/state_machines/graphviz/monkeypatch.rb
StateMachines.Machine.draw
def draw(graph_options = {}) name = graph_options.delete(:name) || "#{owner_class.name}_#{self.name}" draw_options = {:human_name => false} draw_options[:human_name] = graph_options.delete(:human_names) if graph_options.include?(:human_names) graph = Graph.new(name, graph_options) # Add nodes / edges states.by_priority.each { |state| state.draw(graph, draw_options) } events.each { |event| event.draw(graph, self, draw_options) } # Output result graph.output graph end
ruby
def draw(graph_options = {}) name = graph_options.delete(:name) || "#{owner_class.name}_#{self.name}" draw_options = {:human_name => false} draw_options[:human_name] = graph_options.delete(:human_names) if graph_options.include?(:human_names) graph = Graph.new(name, graph_options) # Add nodes / edges states.by_priority.each { |state| state.draw(graph, draw_options) } events.each { |event| event.draw(graph, self, draw_options) } # Output result graph.output graph end
[ "def", "draw", "(", "graph_options", "=", "{", "}", ")", "name", "=", "graph_options", ".", "delete", "(", ":name", ")", "||", "\"#{owner_class.name}_#{self.name}\"", "draw_options", "=", "{", ":human_name", "=>", "false", "}", "draw_options", "[", ":human_name", "]", "=", "graph_options", ".", "delete", "(", ":human_names", ")", "if", "graph_options", ".", "include?", "(", ":human_names", ")", "graph", "=", "Graph", ".", "new", "(", "name", ",", "graph_options", ")", "# Add nodes / edges", "states", ".", "by_priority", ".", "each", "{", "|", "state", "|", "state", ".", "draw", "(", "graph", ",", "draw_options", ")", "}", "events", ".", "each", "{", "|", "event", "|", "event", ".", "draw", "(", "graph", ",", "self", ",", "draw_options", ")", "}", "# Output result", "graph", ".", "output", "graph", "end" ]
Draws a directed graph of the machine for visualizing the various events, states, and their transitions. This requires both the Ruby graphviz gem and the graphviz library be installed on the system. Configuration options: * <tt>:name</tt> - The name of the file to write to (without the file extension). Default is "#{owner_class.name}_#{name}" * <tt>:path</tt> - The path to write the graph file to. Default is the current directory ("."). * <tt>:format</tt> - The image format to generate the graph in. Default is "png'. * <tt>:font</tt> - The name of the font to draw state names in. Default is "Arial". * <tt>:orientation</tt> - The direction of the graph ("portrait" or "landscape"). Default is "portrait". * <tt>:human_names</tt> - Whether to use human state / event names for node labels on the graph instead of the internal name. Default is false.
[ "Draws", "a", "directed", "graph", "of", "the", "machine", "for", "visualizing", "the", "various", "events", "states", "and", "their", "transitions", "." ]
3c61a39aaee3e804d72bbf97cfa55006506cfef2
https://github.com/state-machines/state_machines-graphviz/blob/3c61a39aaee3e804d72bbf97cfa55006506cfef2/lib/state_machines/graphviz/monkeypatch.rb#L56-L70
22,587
KatanaCode/blogit
app/helpers/blogit/application_helper.rb
Blogit.ApplicationHelper.div_tag_with_default_class
def div_tag_with_default_class(default_class, content_or_options, options, &block) if block_given? options = content_or_options content = capture(&block) else content = content_or_options end options[:class] = Array(options[:class]) + [default_class] content_tag(:div, content, options) end
ruby
def div_tag_with_default_class(default_class, content_or_options, options, &block) if block_given? options = content_or_options content = capture(&block) else content = content_or_options end options[:class] = Array(options[:class]) + [default_class] content_tag(:div, content, options) end
[ "def", "div_tag_with_default_class", "(", "default_class", ",", "content_or_options", ",", "options", ",", "&", "block", ")", "if", "block_given?", "options", "=", "content_or_options", "content", "=", "capture", "(", "block", ")", "else", "content", "=", "content_or_options", "end", "options", "[", ":class", "]", "=", "Array", "(", "options", "[", ":class", "]", ")", "+", "[", "default_class", "]", "content_tag", "(", ":div", ",", "content", ",", "options", ")", "end" ]
Creates an HTML div with a default class value added default_class - The CSS class name to add to the div content_or_options - The content to include in the div when not using a block. The options Hash when using a block options - The options when not using a block block - A block that returns HTML content to include in the div Returns an HTML safe String
[ "Creates", "an", "HTML", "div", "with", "a", "default", "class", "value", "added" ]
93e3830bacc542970e41cee94d5d8fbb6fdefc3c
https://github.com/KatanaCode/blogit/blob/93e3830bacc542970e41cee94d5d8fbb6fdefc3c/app/helpers/blogit/application_helper.rb#L82-L91
22,588
ronin/payu
lib/payu/pos.rb
Payu.Pos.validate_options!
def validate_options! raise PosInvalid.new('Missing pos_id parameter') if pos_id.nil? || pos_id == 0 raise PosInvalid.new('Missing pos_auth_key parameter') if pos_auth_key.nil? || pos_auth_key == '' raise PosInvalid.new('Missing key1 parameter') if key1.nil? || key1 == '' raise PosInvalid.new('Missing key2 parameter') if key2.nil? || key2 == '' raise PosInvalid.new("Invalid variant parameter, expected one of these: #{TYPES.join(', ')}") unless TYPES.include?(variant) raise PosInvalid.new("Invalid encoding parameter, expected one of these: #{ENCODINGS.join(', ')}") unless ENCODINGS.include?(encoding) end
ruby
def validate_options! raise PosInvalid.new('Missing pos_id parameter') if pos_id.nil? || pos_id == 0 raise PosInvalid.new('Missing pos_auth_key parameter') if pos_auth_key.nil? || pos_auth_key == '' raise PosInvalid.new('Missing key1 parameter') if key1.nil? || key1 == '' raise PosInvalid.new('Missing key2 parameter') if key2.nil? || key2 == '' raise PosInvalid.new("Invalid variant parameter, expected one of these: #{TYPES.join(', ')}") unless TYPES.include?(variant) raise PosInvalid.new("Invalid encoding parameter, expected one of these: #{ENCODINGS.join(', ')}") unless ENCODINGS.include?(encoding) end
[ "def", "validate_options!", "raise", "PosInvalid", ".", "new", "(", "'Missing pos_id parameter'", ")", "if", "pos_id", ".", "nil?", "||", "pos_id", "==", "0", "raise", "PosInvalid", ".", "new", "(", "'Missing pos_auth_key parameter'", ")", "if", "pos_auth_key", ".", "nil?", "||", "pos_auth_key", "==", "''", "raise", "PosInvalid", ".", "new", "(", "'Missing key1 parameter'", ")", "if", "key1", ".", "nil?", "||", "key1", "==", "''", "raise", "PosInvalid", ".", "new", "(", "'Missing key2 parameter'", ")", "if", "key2", ".", "nil?", "||", "key2", "==", "''", "raise", "PosInvalid", ".", "new", "(", "\"Invalid variant parameter, expected one of these: #{TYPES.join(', ')}\"", ")", "unless", "TYPES", ".", "include?", "(", "variant", ")", "raise", "PosInvalid", ".", "new", "(", "\"Invalid encoding parameter, expected one of these: #{ENCODINGS.join(', ')}\"", ")", "unless", "ENCODINGS", ".", "include?", "(", "encoding", ")", "end" ]
Creates new Pos instance @param [Hash] options options hash @return [Object] Pos object
[ "Creates", "new", "Pos", "instance" ]
62971c5b2ae61a68ef92e39244ea03fd9e575830
https://github.com/ronin/payu/blob/62971c5b2ae61a68ef92e39244ea03fd9e575830/lib/payu/pos.rb#L30-L37
22,589
ronin/payu
lib/payu/pos.rb
Payu.Pos.new_transaction
def new_transaction(options = {}) options = options.dup options.merge!({ :pos_id => @pos_id, :pos_auth_key => @pos_auth_key, :gateway_url => options[:gateway_url] || @gateway_url, :key1 => @key1, :encoding => encoding, :variant => variant }) if !options.has_key?(:add_signature) options[:add_signature] = add_signature? end if !options.has_key?(:pay_type) options[:pay_type] = test_payment? ? 't' : nil end Transaction.new(options) end
ruby
def new_transaction(options = {}) options = options.dup options.merge!({ :pos_id => @pos_id, :pos_auth_key => @pos_auth_key, :gateway_url => options[:gateway_url] || @gateway_url, :key1 => @key1, :encoding => encoding, :variant => variant }) if !options.has_key?(:add_signature) options[:add_signature] = add_signature? end if !options.has_key?(:pay_type) options[:pay_type] = test_payment? ? 't' : nil end Transaction.new(options) end
[ "def", "new_transaction", "(", "options", "=", "{", "}", ")", "options", "=", "options", ".", "dup", "options", ".", "merge!", "(", "{", ":pos_id", "=>", "@pos_id", ",", ":pos_auth_key", "=>", "@pos_auth_key", ",", ":gateway_url", "=>", "options", "[", ":gateway_url", "]", "||", "@gateway_url", ",", ":key1", "=>", "@key1", ",", ":encoding", "=>", "encoding", ",", ":variant", "=>", "variant", "}", ")", "if", "!", "options", ".", "has_key?", "(", ":add_signature", ")", "options", "[", ":add_signature", "]", "=", "add_signature?", "end", "if", "!", "options", ".", "has_key?", "(", ":pay_type", ")", "options", "[", ":pay_type", "]", "=", "test_payment?", "?", "'t'", ":", "nil", "end", "Transaction", ".", "new", "(", "options", ")", "end" ]
Creates new transaction @param [Hash] options options hash for new transaction @return [Object] Transaction object
[ "Creates", "new", "transaction" ]
62971c5b2ae61a68ef92e39244ea03fd9e575830
https://github.com/ronin/payu/blob/62971c5b2ae61a68ef92e39244ea03fd9e575830/lib/payu/pos.rb#L42-L63
22,590
ronin/payu
lib/payu/helpers.rb
Payu.Helpers.payu_hidden_fields
def payu_hidden_fields(transaction) html = "" %w(pos_id pos_auth_key pay_type session_id amount amount_netto desc order_id desc2 trsDesc first_name last_name street street_hn street_an city post_code country email phone language client_ip js payback_login sig ts ).each do |field| value = transaction.send(field) html << hidden_field_tag(field, value) unless value.blank? end html.html_safe end
ruby
def payu_hidden_fields(transaction) html = "" %w(pos_id pos_auth_key pay_type session_id amount amount_netto desc order_id desc2 trsDesc first_name last_name street street_hn street_an city post_code country email phone language client_ip js payback_login sig ts ).each do |field| value = transaction.send(field) html << hidden_field_tag(field, value) unless value.blank? end html.html_safe end
[ "def", "payu_hidden_fields", "(", "transaction", ")", "html", "=", "\"\"", "%w(", "pos_id", "pos_auth_key", "pay_type", "session_id", "amount", "amount_netto", "desc", "order_id", "desc2", "trsDesc", "first_name", "last_name", "street", "street_hn", "street_an", "city", "post_code", "country", "email", "phone", "language", "client_ip", "js", "payback_login", "sig", "ts", ")", ".", "each", "do", "|", "field", "|", "value", "=", "transaction", ".", "send", "(", "field", ")", "html", "<<", "hidden_field_tag", "(", "field", ",", "value", ")", "unless", "value", ".", "blank?", "end", "html", ".", "html_safe", "end" ]
Generates form fields for specified transaction object
[ "Generates", "form", "fields", "for", "specified", "transaction", "object" ]
62971c5b2ae61a68ef92e39244ea03fd9e575830
https://github.com/ronin/payu/blob/62971c5b2ae61a68ef92e39244ea03fd9e575830/lib/payu/helpers.rb#L6-L19
22,591
ronin/payu
lib/payu/helpers.rb
Payu.Helpers.payu_verify_params
def payu_verify_params(params) pos_id = params['pos_id'] pos = Payu[pos_id] Signature.verify!( params['sig'], params['pos_id'], params['session_id'], params['ts'], pos.key2 ) end
ruby
def payu_verify_params(params) pos_id = params['pos_id'] pos = Payu[pos_id] Signature.verify!( params['sig'], params['pos_id'], params['session_id'], params['ts'], pos.key2 ) end
[ "def", "payu_verify_params", "(", "params", ")", "pos_id", "=", "params", "[", "'pos_id'", "]", "pos", "=", "Payu", "[", "pos_id", "]", "Signature", ".", "verify!", "(", "params", "[", "'sig'", "]", ",", "params", "[", "'pos_id'", "]", ",", "params", "[", "'session_id'", "]", ",", "params", "[", "'ts'", "]", ",", "pos", ".", "key2", ")", "end" ]
Verifies signature of passed parameters from Payu request
[ "Verifies", "signature", "of", "passed", "parameters", "from", "Payu", "request" ]
62971c5b2ae61a68ef92e39244ea03fd9e575830
https://github.com/ronin/payu/blob/62971c5b2ae61a68ef92e39244ea03fd9e575830/lib/payu/helpers.rb#L22-L33
22,592
smartsheet-platform/smartsheet-ruby-sdk
lib/smartsheet/general_request.rb
Smartsheet.GeneralRequest.request
def request(method:, url_path:, body: nil, params: {}, header_overrides: {}) spec = body.nil? ? {} : {body_type: :json} endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], **spec) request_spec = Smartsheet::API::RequestSpec.new( header_overrides: header_overrides, body: body, params: params ) client.make_request(endpoint_spec, request_spec) end
ruby
def request(method:, url_path:, body: nil, params: {}, header_overrides: {}) spec = body.nil? ? {} : {body_type: :json} endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], **spec) request_spec = Smartsheet::API::RequestSpec.new( header_overrides: header_overrides, body: body, params: params ) client.make_request(endpoint_spec, request_spec) end
[ "def", "request", "(", "method", ":", ",", "url_path", ":", ",", "body", ":", "nil", ",", "params", ":", "{", "}", ",", "header_overrides", ":", "{", "}", ")", "spec", "=", "body", ".", "nil?", "?", "{", "}", ":", "{", "body_type", ":", ":json", "}", "endpoint_spec", "=", "Smartsheet", "::", "API", "::", "EndpointSpec", ".", "new", "(", "method", ",", "[", "url_path", "]", ",", "**", "spec", ")", "request_spec", "=", "Smartsheet", "::", "API", "::", "RequestSpec", ".", "new", "(", "header_overrides", ":", "header_overrides", ",", "body", ":", "body", ",", "params", ":", "params", ")", "client", ".", "make_request", "(", "endpoint_spec", ",", "request_spec", ")", "end" ]
Create a custom request using a provided method and URL path @example Make a GET request to 'https://api.smartsheet.com/2.0/sheets/list' client.request(method: :get, url_path: 'sheets/list')
[ "Create", "a", "custom", "request", "using", "a", "provided", "method", "and", "URL", "path" ]
fb8bcaed1e5c382299b1299376128b196c3b92ed
https://github.com/smartsheet-platform/smartsheet-ruby-sdk/blob/fb8bcaed1e5c382299b1299376128b196c3b92ed/lib/smartsheet/general_request.rb#L8-L17
22,593
smartsheet-platform/smartsheet-ruby-sdk
lib/smartsheet/general_request.rb
Smartsheet.GeneralRequest.request_with_file
def request_with_file( method:, url_path:, file:, file_length:, filename:, content_type: '', params: {}, header_overrides: {} ) endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], body_type: :file) request_spec = Smartsheet::API::RequestSpec.new( header_overrides: header_overrides, params: params, file_spec: Smartsheet::API::ObjectFileSpec.new(file, filename, file_length, content_type) ) client.make_request(endpoint_spec, request_spec) end
ruby
def request_with_file( method:, url_path:, file:, file_length:, filename:, content_type: '', params: {}, header_overrides: {} ) endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], body_type: :file) request_spec = Smartsheet::API::RequestSpec.new( header_overrides: header_overrides, params: params, file_spec: Smartsheet::API::ObjectFileSpec.new(file, filename, file_length, content_type) ) client.make_request(endpoint_spec, request_spec) end
[ "def", "request_with_file", "(", "method", ":", ",", "url_path", ":", ",", "file", ":", ",", "file_length", ":", ",", "filename", ":", ",", "content_type", ":", "''", ",", "params", ":", "{", "}", ",", "header_overrides", ":", "{", "}", ")", "endpoint_spec", "=", "Smartsheet", "::", "API", "::", "EndpointSpec", ".", "new", "(", "method", ",", "[", "url_path", "]", ",", "body_type", ":", ":file", ")", "request_spec", "=", "Smartsheet", "::", "API", "::", "RequestSpec", ".", "new", "(", "header_overrides", ":", "header_overrides", ",", "params", ":", "params", ",", "file_spec", ":", "Smartsheet", "::", "API", "::", "ObjectFileSpec", ".", "new", "(", "file", ",", "filename", ",", "file_length", ",", "content_type", ")", ")", "client", ".", "make_request", "(", "endpoint_spec", ",", "request_spec", ")", "end" ]
Create a custom request using a provided method, URL path, and file details @example Make a POST request to 'https://api.smartsheet.com/2.0/sheets/1/attachments' with a file client.request_with_file( method: :get, url_path: 'sheets/1/attachments', file: File.open('my-file.docx'), file_length: 1000, filename: 'my-uploaded-file.docx', content_type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' )
[ "Create", "a", "custom", "request", "using", "a", "provided", "method", "URL", "path", "and", "file", "details" ]
fb8bcaed1e5c382299b1299376128b196c3b92ed
https://github.com/smartsheet-platform/smartsheet-ruby-sdk/blob/fb8bcaed1e5c382299b1299376128b196c3b92ed/lib/smartsheet/general_request.rb#L29-L46
22,594
smartsheet-platform/smartsheet-ruby-sdk
lib/smartsheet/general_request.rb
Smartsheet.GeneralRequest.request_with_file_from_path
def request_with_file_from_path( method:, url_path:, path:, filename: nil, content_type: '', params: {}, header_overrides: {} ) endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], body_type: :file) request_spec = Smartsheet::API::RequestSpec.new( header_overrides: header_overrides, params: params, file_spec: Smartsheet::API::PathFileSpec.new(path, filename, content_type) ) client.make_request(endpoint_spec, request_spec) end
ruby
def request_with_file_from_path( method:, url_path:, path:, filename: nil, content_type: '', params: {}, header_overrides: {} ) endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], body_type: :file) request_spec = Smartsheet::API::RequestSpec.new( header_overrides: header_overrides, params: params, file_spec: Smartsheet::API::PathFileSpec.new(path, filename, content_type) ) client.make_request(endpoint_spec, request_spec) end
[ "def", "request_with_file_from_path", "(", "method", ":", ",", "url_path", ":", ",", "path", ":", ",", "filename", ":", "nil", ",", "content_type", ":", "''", ",", "params", ":", "{", "}", ",", "header_overrides", ":", "{", "}", ")", "endpoint_spec", "=", "Smartsheet", "::", "API", "::", "EndpointSpec", ".", "new", "(", "method", ",", "[", "url_path", "]", ",", "body_type", ":", ":file", ")", "request_spec", "=", "Smartsheet", "::", "API", "::", "RequestSpec", ".", "new", "(", "header_overrides", ":", "header_overrides", ",", "params", ":", "params", ",", "file_spec", ":", "Smartsheet", "::", "API", "::", "PathFileSpec", ".", "new", "(", "path", ",", "filename", ",", "content_type", ")", ")", "client", ".", "make_request", "(", "endpoint_spec", ",", "request_spec", ")", "end" ]
Create a custom request using a provided method, URL path, and filepath details @example Make a POST request to 'https://api.smartsheet.com/2.0/sheets/1/attachments' with a file client.request_with_file_from_path( method: :get, url_path: 'sheets/1/attachments', path: './my-file.docx', filename: 'my-uploaded-file.docx', content_type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' )
[ "Create", "a", "custom", "request", "using", "a", "provided", "method", "URL", "path", "and", "filepath", "details" ]
fb8bcaed1e5c382299b1299376128b196c3b92ed
https://github.com/smartsheet-platform/smartsheet-ruby-sdk/blob/fb8bcaed1e5c382299b1299376128b196c3b92ed/lib/smartsheet/general_request.rb#L57-L73
22,595
octopress/ink
lib/octopress-ink.rb
Octopress.Ink.list
def list(options={}) site = Octopress.site(options) Plugins.register options = {'minimal'=>true} if options.empty? message = "Octopress Ink - v#{VERSION}\n" if plugins.size > 0 plugins.each do |plugin| message += plugin.list(options) end else message += "You have no plugins installed." end puts message end
ruby
def list(options={}) site = Octopress.site(options) Plugins.register options = {'minimal'=>true} if options.empty? message = "Octopress Ink - v#{VERSION}\n" if plugins.size > 0 plugins.each do |plugin| message += plugin.list(options) end else message += "You have no plugins installed." end puts message end
[ "def", "list", "(", "options", "=", "{", "}", ")", "site", "=", "Octopress", ".", "site", "(", "options", ")", "Plugins", ".", "register", "options", "=", "{", "'minimal'", "=>", "true", "}", "if", "options", ".", "empty?", "message", "=", "\"Octopress Ink - v#{VERSION}\\n\"", "if", "plugins", ".", "size", ">", "0", "plugins", ".", "each", "do", "|", "plugin", "|", "message", "+=", "plugin", ".", "list", "(", "options", ")", "end", "else", "message", "+=", "\"You have no plugins installed.\"", "end", "puts", "message", "end" ]
Prints a list of plugins and details options - a Hash of options from the `list` command Note: if options are empty, this will display a list of plugin names, slugs, versions, and descriptions, but no assets, i.e. 'minimal' info.
[ "Prints", "a", "list", "of", "plugins", "and", "details" ]
7a3a796b63d361f6f60bf516dba099664e11fd80
https://github.com/octopress/ink/blob/7a3a796b63d361f6f60bf516dba099664e11fd80/lib/octopress-ink.rb#L132-L146
22,596
octopress/ink
lib/octopress-ink.rb
Octopress.Ink.copy_doc
def copy_doc(source, dest, permalink=nil) contents = File.open(source).read # Convert H1 to title and add permalink in YAML front-matter # contents.sub!(/^# (.*)$/, "#{doc_yaml('\1', permalink).strip}") FileUtils.mkdir_p File.dirname(dest) File.open(dest, 'w') {|f| f.write(contents) } puts "Updated #{dest} from #{source}" end
ruby
def copy_doc(source, dest, permalink=nil) contents = File.open(source).read # Convert H1 to title and add permalink in YAML front-matter # contents.sub!(/^# (.*)$/, "#{doc_yaml('\1', permalink).strip}") FileUtils.mkdir_p File.dirname(dest) File.open(dest, 'w') {|f| f.write(contents) } puts "Updated #{dest} from #{source}" end
[ "def", "copy_doc", "(", "source", ",", "dest", ",", "permalink", "=", "nil", ")", "contents", "=", "File", ".", "open", "(", "source", ")", ".", "read", "# Convert H1 to title and add permalink in YAML front-matter", "#", "contents", ".", "sub!", "(", "/", "/", ",", "\"#{doc_yaml('\\1', permalink).strip}\"", ")", "FileUtils", ".", "mkdir_p", "File", ".", "dirname", "(", "dest", ")", "File", ".", "open", "(", "dest", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "contents", ")", "}", "puts", "\"Updated #{dest} from #{source}\"", "end" ]
Makes it easy for Ink plugins to copy README and CHANGELOG files to doc folder to be used as a documentation asset file Usage: In rakefile require 'octopress-ink' then add task calling Octopress::Ink.copy_doc for each file
[ "Makes", "it", "easy", "for", "Ink", "plugins", "to", "copy", "README", "and", "CHANGELOG", "files", "to", "doc", "folder", "to", "be", "used", "as", "a", "documentation", "asset", "file" ]
7a3a796b63d361f6f60bf516dba099664e11fd80
https://github.com/octopress/ink/blob/7a3a796b63d361f6f60bf516dba099664e11fd80/lib/octopress-ink.rb#L216-L226
22,597
pusher-community/pusher-websocket-ruby
spec/spec_helper.rb
PusherClient.Socket.connect
def connect(async = false) @connection_thread = Thread.new do @connection = TestConnection.new @global_channel.dispatch('pusher:connection_established', JSON.dump({'socket_id' => '123abc'})) end @connection_thread.run @connection_thread.join unless async return self end
ruby
def connect(async = false) @connection_thread = Thread.new do @connection = TestConnection.new @global_channel.dispatch('pusher:connection_established', JSON.dump({'socket_id' => '123abc'})) end @connection_thread.run @connection_thread.join unless async return self end
[ "def", "connect", "(", "async", "=", "false", ")", "@connection_thread", "=", "Thread", ".", "new", "do", "@connection", "=", "TestConnection", ".", "new", "@global_channel", ".", "dispatch", "(", "'pusher:connection_established'", ",", "JSON", ".", "dump", "(", "{", "'socket_id'", "=>", "'123abc'", "}", ")", ")", "end", "@connection_thread", ".", "run", "@connection_thread", ".", "join", "unless", "async", "return", "self", "end" ]
Simulate a connection being established
[ "Simulate", "a", "connection", "being", "established" ]
205e57f97e7c0dd27a5cbff3b91040b0967c3b9c
https://github.com/pusher-community/pusher-websocket-ruby/blob/205e57f97e7c0dd27a5cbff3b91040b0967c3b9c/spec/spec_helper.rb#L25-L33
22,598
pusher-community/pusher-websocket-ruby
lib/pusher-client/socket.rb
PusherClient.Socket.authorize
def authorize(channel, callback) if is_private_channel(channel.name) auth_data = get_private_auth(channel) elsif is_presence_channel(channel.name) auth_data = get_presence_auth(channel) end # could both be nil if didn't require auth callback.call(channel, auth_data, channel.user_data) end
ruby
def authorize(channel, callback) if is_private_channel(channel.name) auth_data = get_private_auth(channel) elsif is_presence_channel(channel.name) auth_data = get_presence_auth(channel) end # could both be nil if didn't require auth callback.call(channel, auth_data, channel.user_data) end
[ "def", "authorize", "(", "channel", ",", "callback", ")", "if", "is_private_channel", "(", "channel", ".", "name", ")", "auth_data", "=", "get_private_auth", "(", "channel", ")", "elsif", "is_presence_channel", "(", "channel", ".", "name", ")", "auth_data", "=", "get_presence_auth", "(", "channel", ")", "end", "# could both be nil if didn't require auth", "callback", ".", "call", "(", "channel", ",", "auth_data", ",", "channel", ".", "user_data", ")", "end" ]
auth for private and presence
[ "auth", "for", "private", "and", "presence" ]
205e57f97e7c0dd27a5cbff3b91040b0967c3b9c
https://github.com/pusher-community/pusher-websocket-ruby/blob/205e57f97e7c0dd27a5cbff3b91040b0967c3b9c/lib/pusher-client/socket.rb#L133-L141
22,599
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/cli.rb
OneviewSDK.Cli.console
def console client_setup({}, true, true) puts "Console Connected to #{@client.url}" puts "HINT: The @client object is available to you\n\n" rescue puts "WARNING: Couldn't connect to #{@options['url'] || ENV['ONEVIEWSDK_URL']}\n\n" ensure require 'pry' Pry.config.prompt = proc { '> ' } Pry.plugins['stack_explorer'] && Pry.plugins['stack_explorer'].disable! Pry.plugins['byebug'] && Pry.plugins['byebug'].disable! Pry.start(OneviewSDK::Console.new(@client)) end
ruby
def console client_setup({}, true, true) puts "Console Connected to #{@client.url}" puts "HINT: The @client object is available to you\n\n" rescue puts "WARNING: Couldn't connect to #{@options['url'] || ENV['ONEVIEWSDK_URL']}\n\n" ensure require 'pry' Pry.config.prompt = proc { '> ' } Pry.plugins['stack_explorer'] && Pry.plugins['stack_explorer'].disable! Pry.plugins['byebug'] && Pry.plugins['byebug'].disable! Pry.start(OneviewSDK::Console.new(@client)) end
[ "def", "console", "client_setup", "(", "{", "}", ",", "true", ",", "true", ")", "puts", "\"Console Connected to #{@client.url}\"", "puts", "\"HINT: The @client object is available to you\\n\\n\"", "rescue", "puts", "\"WARNING: Couldn't connect to #{@options['url'] || ENV['ONEVIEWSDK_URL']}\\n\\n\"", "ensure", "require", "'pry'", "Pry", ".", "config", ".", "prompt", "=", "proc", "{", "'> '", "}", "Pry", ".", "plugins", "[", "'stack_explorer'", "]", "&&", "Pry", ".", "plugins", "[", "'stack_explorer'", "]", ".", "disable!", "Pry", ".", "plugins", "[", "'byebug'", "]", "&&", "Pry", ".", "plugins", "[", "'byebug'", "]", ".", "disable!", "Pry", ".", "start", "(", "OneviewSDK", "::", "Console", ".", "new", "(", "@client", ")", ")", "end" ]
Open a Ruby console with a connection to OneView
[ "Open", "a", "Ruby", "console", "with", "a", "connection", "to", "OneView" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/cli.rb#L84-L96