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
partition
stringclasses
1 value
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.fetch_items_from_filesystem_or_zip
def fetch_items_from_filesystem_or_zip unless in_zip? @items = Dir.foreach(current_dir).map {|fn| load_item dir: current_dir, name: fn }.to_a.partition {|i| %w(. ..).include? i.name}.flatten else @items = [load_item(dir: current_dir, name: '.', stat: File.stat(current_dir)), load_item(dir: current_dir, name: '..', stat: File.stat(File.dirname(current_dir)))] zf = Zip::File.new current_dir zf.each {|entry| next if entry.name_is_directory? stat = zf.file.stat entry.name @items << load_item(dir: current_dir, name: entry.name, stat: stat) } end end
ruby
def fetch_items_from_filesystem_or_zip unless in_zip? @items = Dir.foreach(current_dir).map {|fn| load_item dir: current_dir, name: fn }.to_a.partition {|i| %w(. ..).include? i.name}.flatten else @items = [load_item(dir: current_dir, name: '.', stat: File.stat(current_dir)), load_item(dir: current_dir, name: '..', stat: File.stat(File.dirname(current_dir)))] zf = Zip::File.new current_dir zf.each {|entry| next if entry.name_is_directory? stat = zf.file.stat entry.name @items << load_item(dir: current_dir, name: entry.name, stat: stat) } end end
[ "def", "fetch_items_from_filesystem_or_zip", "unless", "in_zip?", "@items", "=", "Dir", ".", "foreach", "(", "current_dir", ")", ".", "map", "{", "|", "fn", "|", "load_item", "dir", ":", "current_dir", ",", "name", ":", "fn", "}", ".", "to_a", ".", "partition", "{", "|", "i", "|", "%w(", ".", "..", ")", ".", "include?", "i", ".", "name", "}", ".", "flatten", "else", "@items", "=", "[", "load_item", "(", "dir", ":", "current_dir", ",", "name", ":", "'.'", ",", "stat", ":", "File", ".", "stat", "(", "current_dir", ")", ")", ",", "load_item", "(", "dir", ":", "current_dir", ",", "name", ":", "'..'", ",", "stat", ":", "File", ".", "stat", "(", "File", ".", "dirname", "(", "current_dir", ")", ")", ")", "]", "zf", "=", "Zip", "::", "File", ".", "new", "current_dir", "zf", ".", "each", "{", "|", "entry", "|", "next", "if", "entry", ".", "name_is_directory?", "stat", "=", "zf", ".", "file", ".", "stat", "entry", ".", "name", "@items", "<<", "load_item", "(", "dir", ":", "current_dir", ",", "name", ":", "entry", ".", "name", ",", "stat", ":", "stat", ")", "}", "end", "end" ]
Fetch files from current directory or current .zip file.
[ "Fetch", "files", "from", "current", "directory", "or", "current", ".", "zip", "file", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L258-L273
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.find
def find(str) index = items.index {|i| i.index > current_row && i.name.start_with?(str)} || items.index {|i| i.name.start_with? str} move_cursor index if index end
ruby
def find(str) index = items.index {|i| i.index > current_row && i.name.start_with?(str)} || items.index {|i| i.name.start_with? str} move_cursor index if index end
[ "def", "find", "(", "str", ")", "index", "=", "items", ".", "index", "{", "|", "i", "|", "i", ".", "index", ">", "current_row", "&&", "i", ".", "name", ".", "start_with?", "(", "str", ")", "}", "||", "items", ".", "index", "{", "|", "i", "|", "i", ".", "name", ".", "start_with?", "str", "}", "move_cursor", "index", "if", "index", "end" ]
Focus at the first file or directory of which name starts with the given String.
[ "Focus", "at", "the", "first", "file", "or", "directory", "of", "which", "name", "starts", "with", "the", "given", "String", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L276-L279
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.find_reverse
def find_reverse(str) index = items.reverse.index {|i| i.index < current_row && i.name.start_with?(str)} || items.reverse.index {|i| i.name.start_with? str} move_cursor items.size - index - 1 if index end
ruby
def find_reverse(str) index = items.reverse.index {|i| i.index < current_row && i.name.start_with?(str)} || items.reverse.index {|i| i.name.start_with? str} move_cursor items.size - index - 1 if index end
[ "def", "find_reverse", "(", "str", ")", "index", "=", "items", ".", "reverse", ".", "index", "{", "|", "i", "|", "i", ".", "index", "<", "current_row", "&&", "i", ".", "name", ".", "start_with?", "(", "str", ")", "}", "||", "items", ".", "reverse", ".", "index", "{", "|", "i", "|", "i", ".", "name", ".", "start_with?", "str", "}", "move_cursor", "items", ".", "size", "-", "index", "-", "1", "if", "index", "end" ]
Focus at the last file or directory of which name starts with the given String.
[ "Focus", "at", "the", "last", "file", "or", "directory", "of", "which", "name", "starts", "with", "the", "given", "String", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L282-L285
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.draw_items
def draw_items main.newpad items @displayed_items = items[current_page * max_items, max_items] main.display current_page header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages end
ruby
def draw_items main.newpad items @displayed_items = items[current_page * max_items, max_items] main.display current_page header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages end
[ "def", "draw_items", "main", ".", "newpad", "items", "@displayed_items", "=", "items", "[", "current_page", "*", "max_items", ",", "max_items", "]", "main", ".", "display", "current_page", "header_l", ".", "draw_path_and_page_number", "path", ":", "current_dir", ".", "path", ",", "current", ":", "current_page", "+", "1", ",", "total", ":", "total_pages", "end" ]
Update the main window with the loaded files and directories. Also update the header.
[ "Update", "the", "main", "window", "with", "the", "loaded", "files", "and", "directories", ".", "Also", "update", "the", "header", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L298-L303
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.sort_items_according_to_current_direction
def sort_items_according_to_current_direction case @direction when nil @items = items.shift(2) + items.partition(&:directory?).flat_map(&:sort) when 'r' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort.reverse} when 'S', 's' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by {|i| -i.size}} when 'Sr', 'sr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:size)} when 't' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.mtime <=> x.mtime}} when 'tr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:mtime)} when 'c' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.ctime <=> x.ctime}} when 'cr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:ctime)} when 'u' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.atime <=> x.atime}} when 'ur' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:atime)} when 'e' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.extname <=> x.extname}} when 'er' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:extname)} end items.each.with_index {|item, index| item.index = index} end
ruby
def sort_items_according_to_current_direction case @direction when nil @items = items.shift(2) + items.partition(&:directory?).flat_map(&:sort) when 'r' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort.reverse} when 'S', 's' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by {|i| -i.size}} when 'Sr', 'sr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:size)} when 't' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.mtime <=> x.mtime}} when 'tr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:mtime)} when 'c' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.ctime <=> x.ctime}} when 'cr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:ctime)} when 'u' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.atime <=> x.atime}} when 'ur' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:atime)} when 'e' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.extname <=> x.extname}} when 'er' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:extname)} end items.each.with_index {|item, index| item.index = index} end
[ "def", "sort_items_according_to_current_direction", "case", "@direction", "when", "nil", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", "&", ":directory?", ")", ".", "flat_map", "(", "&", ":sort", ")", "when", "'r'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", "&", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort", ".", "reverse", "}", "when", "'S'", ",", "'s'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", "&", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort_by", "{", "|", "i", "|", "-", "i", ".", "size", "}", "}", "when", "'Sr'", ",", "'sr'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", "&", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort_by", "(", "&", ":size", ")", "}", "when", "'t'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", "&", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort", "{", "|", "x", ",", "y", "|", "y", ".", "mtime", "<=>", "x", ".", "mtime", "}", "}", "when", "'tr'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", "&", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort_by", "(", "&", ":mtime", ")", "}", "when", "'c'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", "&", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort", "{", "|", "x", ",", "y", "|", "y", ".", "ctime", "<=>", "x", ".", "ctime", "}", "}", "when", "'cr'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", "&", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort_by", "(", "&", ":ctime", ")", "}", "when", "'u'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", "&", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort", "{", "|", "x", ",", "y", "|", "y", ".", "atime", "<=>", "x", ".", "atime", "}", "}", "when", "'ur'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", "&", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort_by", "(", "&", ":atime", ")", "}", "when", "'e'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", "&", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort", "{", "|", "x", ",", "y", "|", "y", ".", "extname", "<=>", "x", ".", "extname", "}", "}", "when", "'er'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", "&", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort_by", "(", "&", ":extname", ")", "}", "end", "items", ".", "each", ".", "with_index", "{", "|", "item", ",", "index", "|", "item", ".", "index", "=", "index", "}", "end" ]
Sort the loaded files and directories in already given sort order.
[ "Sort", "the", "loaded", "files", "and", "directories", "in", "already", "given", "sort", "order", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L306-L334
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.grep
def grep(pattern = '.*') regexp = Regexp.new(pattern) fetch_items_from_filesystem_or_zip @items = items.shift(2) + items.select {|i| i.name =~ regexp} sort_items_according_to_current_direction draw_items draw_total_items switch_page 0 move_cursor 0 end
ruby
def grep(pattern = '.*') regexp = Regexp.new(pattern) fetch_items_from_filesystem_or_zip @items = items.shift(2) + items.select {|i| i.name =~ regexp} sort_items_according_to_current_direction draw_items draw_total_items switch_page 0 move_cursor 0 end
[ "def", "grep", "(", "pattern", "=", "'.*'", ")", "regexp", "=", "Regexp", ".", "new", "(", "pattern", ")", "fetch_items_from_filesystem_or_zip", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "select", "{", "|", "i", "|", "i", ".", "name", "=~", "regexp", "}", "sort_items_according_to_current_direction", "draw_items", "draw_total_items", "switch_page", "0", "move_cursor", "0", "end" ]
Search files and directories from the current directory, and update the screen. * +pattern+ - Search pattern against file names in Ruby Regexp string. === Example a : Search files that contains the letter "a" in their file name .*\.pdf$ : Search PDF files
[ "Search", "files", "and", "directories", "from", "the", "current", "directory", "and", "update", "the", "screen", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L344-L353
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.cp
def cp(dest) unless in_zip? src = (m = marked_items).any? ? m.map(&:path) : current_item FileUtils.cp_r src, expand_path(dest) else raise 'cping multiple items in .zip is not supported.' if selected_items.size > 1 Zip::File.open(current_zip) do |zip| entry = zip.find_entry(selected_items.first.name).dup entry.name, entry.name_length = dest, dest.size zip.instance_variable_get(:@entry_set) << entry end end ls end
ruby
def cp(dest) unless in_zip? src = (m = marked_items).any? ? m.map(&:path) : current_item FileUtils.cp_r src, expand_path(dest) else raise 'cping multiple items in .zip is not supported.' if selected_items.size > 1 Zip::File.open(current_zip) do |zip| entry = zip.find_entry(selected_items.first.name).dup entry.name, entry.name_length = dest, dest.size zip.instance_variable_get(:@entry_set) << entry end end ls end
[ "def", "cp", "(", "dest", ")", "unless", "in_zip?", "src", "=", "(", "m", "=", "marked_items", ")", ".", "any?", "?", "m", ".", "map", "(", "&", ":path", ")", ":", "current_item", "FileUtils", ".", "cp_r", "src", ",", "expand_path", "(", "dest", ")", "else", "raise", "'cping multiple items in .zip is not supported.'", "if", "selected_items", ".", "size", ">", "1", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "entry", "=", "zip", ".", "find_entry", "(", "selected_items", ".", "first", ".", "name", ")", ".", "dup", "entry", ".", "name", ",", "entry", ".", "name_length", "=", "dest", ",", "dest", ".", "size", "zip", ".", "instance_variable_get", "(", ":@entry_set", ")", "<<", "entry", "end", "end", "ls", "end" ]
Copy selected files and directories to the destination.
[ "Copy", "selected", "files", "and", "directories", "to", "the", "destination", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L356-L369
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.mv
def mv(dest) unless in_zip? src = (m = marked_items).any? ? m.map(&:path) : current_item FileUtils.mv src, expand_path(dest) else raise 'mving multiple items in .zip is not supported.' if selected_items.size > 1 rename "#{selected_items.first.name}/#{dest}" end ls end
ruby
def mv(dest) unless in_zip? src = (m = marked_items).any? ? m.map(&:path) : current_item FileUtils.mv src, expand_path(dest) else raise 'mving multiple items in .zip is not supported.' if selected_items.size > 1 rename "#{selected_items.first.name}/#{dest}" end ls end
[ "def", "mv", "(", "dest", ")", "unless", "in_zip?", "src", "=", "(", "m", "=", "marked_items", ")", ".", "any?", "?", "m", ".", "map", "(", "&", ":path", ")", ":", "current_item", "FileUtils", ".", "mv", "src", ",", "expand_path", "(", "dest", ")", "else", "raise", "'mving multiple items in .zip is not supported.'", "if", "selected_items", ".", "size", ">", "1", "rename", "\"#{selected_items.first.name}/#{dest}\"", "end", "ls", "end" ]
Move selected files and directories to the destination.
[ "Move", "selected", "files", "and", "directories", "to", "the", "destination", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L372-L381
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.rename
def rename(pattern) from, to = pattern.sub(/^\//, '').sub(/\/$/, '').split '/' if to.nil? from, to = current_item.name, from else from = Regexp.new from end unless in_zip? selected_items.each do |item| name = item.name.gsub from, to FileUtils.mv item, current_dir.join(name) if item.name != name end else Zip::File.open(current_zip) do |zip| selected_items.each do |item| name = item.name.gsub from, to zip.rename item.name, name end end end ls end
ruby
def rename(pattern) from, to = pattern.sub(/^\//, '').sub(/\/$/, '').split '/' if to.nil? from, to = current_item.name, from else from = Regexp.new from end unless in_zip? selected_items.each do |item| name = item.name.gsub from, to FileUtils.mv item, current_dir.join(name) if item.name != name end else Zip::File.open(current_zip) do |zip| selected_items.each do |item| name = item.name.gsub from, to zip.rename item.name, name end end end ls end
[ "def", "rename", "(", "pattern", ")", "from", ",", "to", "=", "pattern", ".", "sub", "(", "/", "\\/", "/", ",", "''", ")", ".", "sub", "(", "/", "\\/", "/", ",", "''", ")", ".", "split", "'/'", "if", "to", ".", "nil?", "from", ",", "to", "=", "current_item", ".", "name", ",", "from", "else", "from", "=", "Regexp", ".", "new", "from", "end", "unless", "in_zip?", "selected_items", ".", "each", "do", "|", "item", "|", "name", "=", "item", ".", "name", ".", "gsub", "from", ",", "to", "FileUtils", ".", "mv", "item", ",", "current_dir", ".", "join", "(", "name", ")", "if", "item", ".", "name", "!=", "name", "end", "else", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "selected_items", ".", "each", "do", "|", "item", "|", "name", "=", "item", ".", "name", ".", "gsub", "from", ",", "to", "zip", ".", "rename", "item", ".", "name", ",", "name", "end", "end", "end", "ls", "end" ]
Rename selected files and directories. ==== Parameters * +pattern+ - new filename, or a shash separated Regexp like string
[ "Rename", "selected", "files", "and", "directories", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L387-L408
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.trash
def trash unless in_zip? if osx? FileUtils.mv selected_items.map(&:path), File.expand_path('~/.Trash/') else #TODO support other OS FileUtils.rm_rf selected_items.map(&:path) end else return unless ask %Q[Trashing zip entries is not supported. Actually the files will be deleted. Are you sure want to proceed? (y/n)] delete end @current_row -= selected_items.count {|i| i.index <= current_row} ls end
ruby
def trash unless in_zip? if osx? FileUtils.mv selected_items.map(&:path), File.expand_path('~/.Trash/') else #TODO support other OS FileUtils.rm_rf selected_items.map(&:path) end else return unless ask %Q[Trashing zip entries is not supported. Actually the files will be deleted. Are you sure want to proceed? (y/n)] delete end @current_row -= selected_items.count {|i| i.index <= current_row} ls end
[ "def", "trash", "unless", "in_zip?", "if", "osx?", "FileUtils", ".", "mv", "selected_items", ".", "map", "(", "&", ":path", ")", ",", "File", ".", "expand_path", "(", "'~/.Trash/'", ")", "else", "FileUtils", ".", "rm_rf", "selected_items", ".", "map", "(", "&", ":path", ")", "end", "else", "return", "unless", "ask", "%Q[Trashing zip entries is not supported. Actually the files will be deleted. Are you sure want to proceed? (y/n)]", "delete", "end", "@current_row", "-=", "selected_items", ".", "count", "{", "|", "i", "|", "i", ".", "index", "<=", "current_row", "}", "ls", "end" ]
Soft delete selected files and directories. If the OS is not OSX, performs the same as `delete` command.
[ "Soft", "delete", "selected", "files", "and", "directories", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L413-L427
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.delete
def delete unless in_zip? FileUtils.rm_rf selected_items.map(&:path) else Zip::File.open(current_zip) do |zip| zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry| if entry.name_is_directory? zip.dir.delete entry.to_s else zip.file.delete entry.to_s end end end end @current_row -= selected_items.count {|i| i.index <= current_row} ls end
ruby
def delete unless in_zip? FileUtils.rm_rf selected_items.map(&:path) else Zip::File.open(current_zip) do |zip| zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry| if entry.name_is_directory? zip.dir.delete entry.to_s else zip.file.delete entry.to_s end end end end @current_row -= selected_items.count {|i| i.index <= current_row} ls end
[ "def", "delete", "unless", "in_zip?", "FileUtils", ".", "rm_rf", "selected_items", ".", "map", "(", "&", ":path", ")", "else", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "zip", ".", "select", "{", "|", "e", "|", "selected_items", ".", "map", "(", "&", ":name", ")", ".", "include?", "e", ".", "to_s", "}", ".", "each", "do", "|", "entry", "|", "if", "entry", ".", "name_is_directory?", "zip", ".", "dir", ".", "delete", "entry", ".", "to_s", "else", "zip", ".", "file", ".", "delete", "entry", ".", "to_s", "end", "end", "end", "end", "@current_row", "-=", "selected_items", ".", "count", "{", "|", "i", "|", "i", ".", "index", "<=", "current_row", "}", "ls", "end" ]
Delete selected files and directories.
[ "Delete", "selected", "files", "and", "directories", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L430-L446
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.mkdir
def mkdir(dir) unless in_zip? FileUtils.mkdir_p current_dir.join(dir) else Zip::File.open(current_zip) do |zip| zip.dir.mkdir dir end end ls end
ruby
def mkdir(dir) unless in_zip? FileUtils.mkdir_p current_dir.join(dir) else Zip::File.open(current_zip) do |zip| zip.dir.mkdir dir end end ls end
[ "def", "mkdir", "(", "dir", ")", "unless", "in_zip?", "FileUtils", ".", "mkdir_p", "current_dir", ".", "join", "(", "dir", ")", "else", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "zip", ".", "dir", ".", "mkdir", "dir", "end", "end", "ls", "end" ]
Create a new directory.
[ "Create", "a", "new", "directory", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L449-L458
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.touch
def touch(filename) unless in_zip? FileUtils.touch current_dir.join(filename) else Zip::File.open(current_zip) do |zip| # zip.file.open(filename, 'w') {|_f| } #HAXX this code creates an unneeded temporary file zip.instance_variable_get(:@entry_set) << Zip::Entry.new(current_zip, filename) end end ls end
ruby
def touch(filename) unless in_zip? FileUtils.touch current_dir.join(filename) else Zip::File.open(current_zip) do |zip| # zip.file.open(filename, 'w') {|_f| } #HAXX this code creates an unneeded temporary file zip.instance_variable_get(:@entry_set) << Zip::Entry.new(current_zip, filename) end end ls end
[ "def", "touch", "(", "filename", ")", "unless", "in_zip?", "FileUtils", ".", "touch", "current_dir", ".", "join", "(", "filename", ")", "else", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "zip", ".", "instance_variable_get", "(", ":@entry_set", ")", "<<", "Zip", "::", "Entry", ".", "new", "(", "current_zip", ",", "filename", ")", "end", "end", "ls", "end" ]
Create a new empty file.
[ "Create", "a", "new", "empty", "file", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L461-L471
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.zip
def zip(zipfile_name) return unless zipfile_name zipfile_name += '.zip' unless zipfile_name.end_with? '.zip' Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile| selected_items.each do |item| next if item.symlink? if item.directory? Dir[item.join('**/**')].each do |file| zipfile.add file.sub("#{current_dir}/", ''), file end else zipfile.add item.name, item end end end ls end
ruby
def zip(zipfile_name) return unless zipfile_name zipfile_name += '.zip' unless zipfile_name.end_with? '.zip' Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile| selected_items.each do |item| next if item.symlink? if item.directory? Dir[item.join('**/**')].each do |file| zipfile.add file.sub("#{current_dir}/", ''), file end else zipfile.add item.name, item end end end ls end
[ "def", "zip", "(", "zipfile_name", ")", "return", "unless", "zipfile_name", "zipfile_name", "+=", "'.zip'", "unless", "zipfile_name", ".", "end_with?", "'.zip'", "Zip", "::", "File", ".", "open", "(", "zipfile_name", ",", "Zip", "::", "File", "::", "CREATE", ")", "do", "|", "zipfile", "|", "selected_items", ".", "each", "do", "|", "item", "|", "next", "if", "item", ".", "symlink?", "if", "item", ".", "directory?", "Dir", "[", "item", ".", "join", "(", "'**/**'", ")", "]", ".", "each", "do", "|", "file", "|", "zipfile", ".", "add", "file", ".", "sub", "(", "\"#{current_dir}/\"", ",", "''", ")", ",", "file", "end", "else", "zipfile", ".", "add", "item", ".", "name", ",", "item", "end", "end", "end", "ls", "end" ]
Archive selected files and directories into a .zip file.
[ "Archive", "selected", "files", "and", "directories", "into", "a", ".", "zip", "file", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L513-L530
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.unarchive
def unarchive unless in_zip? zips, gzs = selected_items.partition(&:zip?).tap {|z, others| break [z, *others.partition(&:gz?)]} zips.each do |item| FileUtils.mkdir_p current_dir.join(item.basename) Zip::File.open(item) do |zip| zip.each do |entry| FileUtils.mkdir_p File.join(item.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(item.basename, entry.to_s)) { true } end end end gzs.each do |item| Zlib::GzipReader.open(item) do |gz| Gem::Package::TarReader.new(gz) do |tar| dest_dir = current_dir.join (gz.orig_name || item.basename).sub(/\.tar$/, '') tar.each do |entry| dest = nil if entry.full_name == '././@LongLink' dest = File.join dest_dir, entry.read.strip next end dest ||= File.join dest_dir, entry.full_name if entry.directory? FileUtils.mkdir_p dest, :mode => entry.header.mode elsif entry.file? FileUtils.mkdir_p dest_dir File.open(dest, 'wb') {|f| f.print entry.read} FileUtils.chmod entry.header.mode, dest elsif entry.header.typeflag == '2' # symlink File.symlink entry.header.linkname, dest end unless Dir.exist? dest_dir FileUtils.mkdir_p dest_dir File.open(File.join(dest_dir, gz.orig_name || item.basename), 'wb') {|f| f.print gz.read} end end end end end else Zip::File.open(current_zip) do |zip| zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry| FileUtils.mkdir_p File.join(current_zip.dir, current_zip.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(current_zip.dir, current_zip.basename, entry.to_s)) { true } end end end ls end
ruby
def unarchive unless in_zip? zips, gzs = selected_items.partition(&:zip?).tap {|z, others| break [z, *others.partition(&:gz?)]} zips.each do |item| FileUtils.mkdir_p current_dir.join(item.basename) Zip::File.open(item) do |zip| zip.each do |entry| FileUtils.mkdir_p File.join(item.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(item.basename, entry.to_s)) { true } end end end gzs.each do |item| Zlib::GzipReader.open(item) do |gz| Gem::Package::TarReader.new(gz) do |tar| dest_dir = current_dir.join (gz.orig_name || item.basename).sub(/\.tar$/, '') tar.each do |entry| dest = nil if entry.full_name == '././@LongLink' dest = File.join dest_dir, entry.read.strip next end dest ||= File.join dest_dir, entry.full_name if entry.directory? FileUtils.mkdir_p dest, :mode => entry.header.mode elsif entry.file? FileUtils.mkdir_p dest_dir File.open(dest, 'wb') {|f| f.print entry.read} FileUtils.chmod entry.header.mode, dest elsif entry.header.typeflag == '2' # symlink File.symlink entry.header.linkname, dest end unless Dir.exist? dest_dir FileUtils.mkdir_p dest_dir File.open(File.join(dest_dir, gz.orig_name || item.basename), 'wb') {|f| f.print gz.read} end end end end end else Zip::File.open(current_zip) do |zip| zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry| FileUtils.mkdir_p File.join(current_zip.dir, current_zip.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(current_zip.dir, current_zip.basename, entry.to_s)) { true } end end end ls end
[ "def", "unarchive", "unless", "in_zip?", "zips", ",", "gzs", "=", "selected_items", ".", "partition", "(", "&", ":zip?", ")", ".", "tap", "{", "|", "z", ",", "others", "|", "break", "[", "z", ",", "*", "others", ".", "partition", "(", "&", ":gz?", ")", "]", "}", "zips", ".", "each", "do", "|", "item", "|", "FileUtils", ".", "mkdir_p", "current_dir", ".", "join", "(", "item", ".", "basename", ")", "Zip", "::", "File", ".", "open", "(", "item", ")", "do", "|", "zip", "|", "zip", ".", "each", "do", "|", "entry", "|", "FileUtils", ".", "mkdir_p", "File", ".", "join", "(", "item", ".", "basename", ",", "File", ".", "dirname", "(", "entry", ".", "to_s", ")", ")", "zip", ".", "extract", "(", "entry", ",", "File", ".", "join", "(", "item", ".", "basename", ",", "entry", ".", "to_s", ")", ")", "{", "true", "}", "end", "end", "end", "gzs", ".", "each", "do", "|", "item", "|", "Zlib", "::", "GzipReader", ".", "open", "(", "item", ")", "do", "|", "gz", "|", "Gem", "::", "Package", "::", "TarReader", ".", "new", "(", "gz", ")", "do", "|", "tar", "|", "dest_dir", "=", "current_dir", ".", "join", "(", "gz", ".", "orig_name", "||", "item", ".", "basename", ")", ".", "sub", "(", "/", "\\.", "/", ",", "''", ")", "tar", ".", "each", "do", "|", "entry", "|", "dest", "=", "nil", "if", "entry", ".", "full_name", "==", "'././@LongLink'", "dest", "=", "File", ".", "join", "dest_dir", ",", "entry", ".", "read", ".", "strip", "next", "end", "dest", "||=", "File", ".", "join", "dest_dir", ",", "entry", ".", "full_name", "if", "entry", ".", "directory?", "FileUtils", ".", "mkdir_p", "dest", ",", ":mode", "=>", "entry", ".", "header", ".", "mode", "elsif", "entry", ".", "file?", "FileUtils", ".", "mkdir_p", "dest_dir", "File", ".", "open", "(", "dest", ",", "'wb'", ")", "{", "|", "f", "|", "f", ".", "print", "entry", ".", "read", "}", "FileUtils", ".", "chmod", "entry", ".", "header", ".", "mode", ",", "dest", "elsif", "entry", ".", "header", ".", "typeflag", "==", "'2'", "File", ".", "symlink", "entry", ".", "header", ".", "linkname", ",", "dest", "end", "unless", "Dir", ".", "exist?", "dest_dir", "FileUtils", ".", "mkdir_p", "dest_dir", "File", ".", "open", "(", "File", ".", "join", "(", "dest_dir", ",", "gz", ".", "orig_name", "||", "item", ".", "basename", ")", ",", "'wb'", ")", "{", "|", "f", "|", "f", ".", "print", "gz", ".", "read", "}", "end", "end", "end", "end", "end", "else", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "zip", ".", "select", "{", "|", "e", "|", "selected_items", ".", "map", "(", "&", ":name", ")", ".", "include?", "e", ".", "to_s", "}", ".", "each", "do", "|", "entry", "|", "FileUtils", ".", "mkdir_p", "File", ".", "join", "(", "current_zip", ".", "dir", ",", "current_zip", ".", "basename", ",", "File", ".", "dirname", "(", "entry", ".", "to_s", ")", ")", "zip", ".", "extract", "(", "entry", ",", "File", ".", "join", "(", "current_zip", ".", "dir", ",", "current_zip", ".", "basename", ",", "entry", ".", "to_s", ")", ")", "{", "true", "}", "end", "end", "end", "ls", "end" ]
Unarchive .zip and .tar.gz files within selected files and directories into current_directory.
[ "Unarchive", ".", "zip", "and", ".", "tar", ".", "gz", "files", "within", "selected", "files", "and", "directories", "into", "current_directory", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L533-L582
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.switch_page
def switch_page(page) main.display (@current_page = page) @displayed_items = items[current_page * max_items, max_items] header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages end
ruby
def switch_page(page) main.display (@current_page = page) @displayed_items = items[current_page * max_items, max_items] header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages end
[ "def", "switch_page", "(", "page", ")", "main", ".", "display", "(", "@current_page", "=", "page", ")", "@displayed_items", "=", "items", "[", "current_page", "*", "max_items", ",", "max_items", "]", "header_l", ".", "draw_path_and_page_number", "path", ":", "current_dir", ".", "path", ",", "current", ":", "current_page", "+", "1", ",", "total", ":", "total_pages", "end" ]
Move to the given page number. ==== Parameters * +page+ - Target page number
[ "Move", "to", "the", "given", "page", "number", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L603-L607
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.draw_marked_items
def draw_marked_items items = marked_items header_r.draw_marked_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size} end
ruby
def draw_marked_items items = marked_items header_r.draw_marked_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size} end
[ "def", "draw_marked_items", "items", "=", "marked_items", "header_r", ".", "draw_marked_items", "count", ":", "items", ".", "size", ",", "size", ":", "items", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "i", "|", "sum", "+=", "i", ".", "size", "}", "end" ]
Update the header information concerning currently marked files or directories.
[ "Update", "the", "header", "information", "concerning", "currently", "marked", "files", "or", "directories", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L610-L613
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.draw_total_items
def draw_total_items header_r.draw_total_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size} end
ruby
def draw_total_items header_r.draw_total_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size} end
[ "def", "draw_total_items", "header_r", ".", "draw_total_items", "count", ":", "items", ".", "size", ",", "size", ":", "items", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "i", "|", "sum", "+=", "i", ".", "size", "}", "end" ]
Update the header information concerning total files and directories in the current directory.
[ "Update", "the", "header", "information", "concerning", "total", "files", "and", "directories", "in", "the", "current", "directory", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L616-L618
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.process_command_line
def process_command_line(preset_command: nil) prompt = preset_command ? ":#{preset_command} " : ':' command_line.set_prompt prompt cmd, *args = command_line.get_command(prompt: prompt).split(' ') if cmd && !cmd.empty? && respond_to?(cmd) ret = self.public_send cmd, *args clear_command_line ret end rescue Interrupt clear_command_line end
ruby
def process_command_line(preset_command: nil) prompt = preset_command ? ":#{preset_command} " : ':' command_line.set_prompt prompt cmd, *args = command_line.get_command(prompt: prompt).split(' ') if cmd && !cmd.empty? && respond_to?(cmd) ret = self.public_send cmd, *args clear_command_line ret end rescue Interrupt clear_command_line end
[ "def", "process_command_line", "(", "preset_command", ":", "nil", ")", "prompt", "=", "preset_command", "?", "\":#{preset_command} \"", ":", "':'", "command_line", ".", "set_prompt", "prompt", "cmd", ",", "*", "args", "=", "command_line", ".", "get_command", "(", "prompt", ":", "prompt", ")", ".", "split", "(", "' '", ")", "if", "cmd", "&&", "!", "cmd", ".", "empty?", "&&", "respond_to?", "(", "cmd", ")", "ret", "=", "self", ".", "public_send", "cmd", ",", "*", "args", "clear_command_line", "ret", "end", "rescue", "Interrupt", "clear_command_line", "end" ]
Accept user input, and directly execute it as a Ruby method call to the controller. ==== Parameters * +preset_command+ - A command that would be displayed at the command line before user input.
[ "Accept", "user", "input", "and", "directly", "execute", "it", "as", "a", "Ruby", "method", "call", "to", "the", "controller", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L641-L652
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.process_shell_command
def process_shell_command command_line.set_prompt ':!' cmd = command_line.get_command(prompt: ':!')[1..-1] execute_external_command pause: true do system cmd end rescue Interrupt ensure command_line.clear command_line.noutrefresh end
ruby
def process_shell_command command_line.set_prompt ':!' cmd = command_line.get_command(prompt: ':!')[1..-1] execute_external_command pause: true do system cmd end rescue Interrupt ensure command_line.clear command_line.noutrefresh end
[ "def", "process_shell_command", "command_line", ".", "set_prompt", "':!'", "cmd", "=", "command_line", ".", "get_command", "(", "prompt", ":", "':!'", ")", "[", "1", "..", "-", "1", "]", "execute_external_command", "pause", ":", "true", "do", "system", "cmd", "end", "rescue", "Interrupt", "ensure", "command_line", ".", "clear", "command_line", ".", "noutrefresh", "end" ]
Accept user input, and directly execute it in an external shell.
[ "Accept", "user", "input", "and", "directly", "execute", "it", "in", "an", "external", "shell", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L655-L665
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.ask
def ask(prompt = '(y/n)') command_line.set_prompt prompt command_line.refresh while (c = Curses.getch) next unless [?N, ?Y, ?n, ?y, 3, 27] .include? c # N, Y, n, y, ^c, esc command_line.clear command_line.noutrefresh break (c == 'y') || (c == 'Y') end end
ruby
def ask(prompt = '(y/n)') command_line.set_prompt prompt command_line.refresh while (c = Curses.getch) next unless [?N, ?Y, ?n, ?y, 3, 27] .include? c # N, Y, n, y, ^c, esc command_line.clear command_line.noutrefresh break (c == 'y') || (c == 'Y') end end
[ "def", "ask", "(", "prompt", "=", "'(y/n)'", ")", "command_line", ".", "set_prompt", "prompt", "command_line", ".", "refresh", "while", "(", "c", "=", "Curses", ".", "getch", ")", "next", "unless", "[", "?N", ",", "?Y", ",", "?n", ",", "?y", ",", "3", ",", "27", "]", ".", "include?", "c", "command_line", ".", "clear", "command_line", ".", "noutrefresh", "break", "(", "c", "==", "'y'", ")", "||", "(", "c", "==", "'Y'", ")", "end", "end" ]
Let the user answer y or n. ==== Parameters * +prompt+ - Prompt message
[ "Let", "the", "user", "answer", "y", "or", "n", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L671-L680
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.edit
def edit execute_external_command do editor = ENV['EDITOR'] || 'vim' unless in_zip? system %Q[#{editor} "#{current_item.path}"] else begin tmpdir, tmpfile_name = nil Zip::File.open(current_zip) do |zip| tmpdir = Dir.mktmpdir FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name)) tmpfile_name = File.join(tmpdir, current_item.name) File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)} system %Q[#{editor} "#{tmpfile_name}"] zip.add(current_item.name, tmpfile_name) { true } end ls ensure FileUtils.remove_entry_secure tmpdir if tmpdir end end end end
ruby
def edit execute_external_command do editor = ENV['EDITOR'] || 'vim' unless in_zip? system %Q[#{editor} "#{current_item.path}"] else begin tmpdir, tmpfile_name = nil Zip::File.open(current_zip) do |zip| tmpdir = Dir.mktmpdir FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name)) tmpfile_name = File.join(tmpdir, current_item.name) File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)} system %Q[#{editor} "#{tmpfile_name}"] zip.add(current_item.name, tmpfile_name) { true } end ls ensure FileUtils.remove_entry_secure tmpdir if tmpdir end end end end
[ "def", "edit", "execute_external_command", "do", "editor", "=", "ENV", "[", "'EDITOR'", "]", "||", "'vim'", "unless", "in_zip?", "system", "%Q[#{editor} \"#{current_item.path}\"]", "else", "begin", "tmpdir", ",", "tmpfile_name", "=", "nil", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "tmpdir", "=", "Dir", ".", "mktmpdir", "FileUtils", ".", "mkdir_p", "File", ".", "join", "(", "tmpdir", ",", "File", ".", "dirname", "(", "current_item", ".", "name", ")", ")", "tmpfile_name", "=", "File", ".", "join", "(", "tmpdir", ",", "current_item", ".", "name", ")", "File", ".", "open", "(", "tmpfile_name", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "puts", "zip", ".", "file", ".", "read", "(", "current_item", ".", "name", ")", "}", "system", "%Q[#{editor} \"#{tmpfile_name}\"]", "zip", ".", "add", "(", "current_item", ".", "name", ",", "tmpfile_name", ")", "{", "true", "}", "end", "ls", "ensure", "FileUtils", ".", "remove_entry_secure", "tmpdir", "if", "tmpdir", "end", "end", "end", "end" ]
Open current file or directory with the editor.
[ "Open", "current", "file", "or", "directory", "with", "the", "editor", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L683-L705
train
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.view
def view pager = ENV['PAGER'] || 'less' execute_external_command do unless in_zip? system %Q[#{pager} "#{current_item.path}"] else begin tmpdir, tmpfile_name = nil Zip::File.open(current_zip) do |zip| tmpdir = Dir.mktmpdir FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name)) tmpfile_name = File.join(tmpdir, current_item.name) File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)} end system %Q[#{pager} "#{tmpfile_name}"] ensure FileUtils.remove_entry_secure tmpdir if tmpdir end end end end
ruby
def view pager = ENV['PAGER'] || 'less' execute_external_command do unless in_zip? system %Q[#{pager} "#{current_item.path}"] else begin tmpdir, tmpfile_name = nil Zip::File.open(current_zip) do |zip| tmpdir = Dir.mktmpdir FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name)) tmpfile_name = File.join(tmpdir, current_item.name) File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)} end system %Q[#{pager} "#{tmpfile_name}"] ensure FileUtils.remove_entry_secure tmpdir if tmpdir end end end end
[ "def", "view", "pager", "=", "ENV", "[", "'PAGER'", "]", "||", "'less'", "execute_external_command", "do", "unless", "in_zip?", "system", "%Q[#{pager} \"#{current_item.path}\"]", "else", "begin", "tmpdir", ",", "tmpfile_name", "=", "nil", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "tmpdir", "=", "Dir", ".", "mktmpdir", "FileUtils", ".", "mkdir_p", "File", ".", "join", "(", "tmpdir", ",", "File", ".", "dirname", "(", "current_item", ".", "name", ")", ")", "tmpfile_name", "=", "File", ".", "join", "(", "tmpdir", ",", "current_item", ".", "name", ")", "File", ".", "open", "(", "tmpfile_name", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "puts", "zip", ".", "file", ".", "read", "(", "current_item", ".", "name", ")", "}", "end", "system", "%Q[#{pager} \"#{tmpfile_name}\"]", "ensure", "FileUtils", ".", "remove_entry_secure", "tmpdir", "if", "tmpdir", "end", "end", "end", "end" ]
Open current file or directory with the viewer.
[ "Open", "current", "file", "or", "directory", "with", "the", "viewer", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L708-L728
train
thumblemonks/riot
lib/riot/assertion.rb
Riot.Assertion.run
def run(situation) @expectings << situation.evaluate(&@expectation_block) if @expectation_block actual = situation.evaluate(&definition) assert((@macro.expects_exception? ? nil : actual), *@expectings) rescue Exception => e @macro.expects_exception? ? assert(e, *@expectings) : @macro.error(e) end
ruby
def run(situation) @expectings << situation.evaluate(&@expectation_block) if @expectation_block actual = situation.evaluate(&definition) assert((@macro.expects_exception? ? nil : actual), *@expectings) rescue Exception => e @macro.expects_exception? ? assert(e, *@expectings) : @macro.error(e) end
[ "def", "run", "(", "situation", ")", "@expectings", "<<", "situation", ".", "evaluate", "(", "&", "@expectation_block", ")", "if", "@expectation_block", "actual", "=", "situation", ".", "evaluate", "(", "&", "definition", ")", "assert", "(", "(", "@macro", ".", "expects_exception?", "?", "nil", ":", "actual", ")", ",", "*", "@expectings", ")", "rescue", "Exception", "=>", "e", "@macro", ".", "expects_exception?", "?", "assert", "(", "e", ",", "*", "@expectings", ")", ":", "@macro", ".", "error", "(", "e", ")", "end" ]
Setups a new Assertion. By default, the assertion will be a "positive" one, which means +evaluate+ will be call on the associated assertion macro. If +negative+ is true, +devaluate+ will be called instead. Not providing a definition block is just kind of silly since it's used to generate the +actual+ value for evaluation by a macro. @param [String] definition A small description of what this assertion is testing @param [Boolean] negative Determines whether this is a positive or negative assertion @param [lambda] definition The block that will return the +actual+ value when eval'ed Given a {Riot::Situation}, execute the assertion definition provided to this Assertion, hand off to an assertion macro for evaluation, and then return a status tuple. If the macro to be used expects any exception, catch the exception and send to the macro; else just return it back. Currently supporting 3 evaluation states: :pass, :fail, and :error @param [Riot::Situation] situation An instance of a {Riot::Situation} @return [Array<Symbol, String>] array containing evaluation state and a descriptive explanation
[ "Setups", "a", "new", "Assertion", ".", "By", "default", "the", "assertion", "will", "be", "a", "positive", "one", "which", "means", "+", "evaluate", "+", "will", "be", "call", "on", "the", "associated", "assertion", "macro", ".", "If", "+", "negative", "+", "is", "true", "+", "devaluate", "+", "will", "be", "called", "instead", ".", "Not", "providing", "a", "definition", "block", "is", "just", "kind", "of", "silly", "since", "it", "s", "used", "to", "generate", "the", "+", "actual", "+", "value", "for", "evaluation", "by", "a", "macro", "." ]
e99a8965f2d28730fc863c647ca40b3bffb9e562
https://github.com/thumblemonks/riot/blob/e99a8965f2d28730fc863c647ca40b3bffb9e562/lib/riot/assertion.rb#L49-L55
train
thumblemonks/riot
lib/riot/reporter/io.rb
Riot.IOReporter.format_error
def format_error(e) format = [" #{e.class.name} occurred", "#{e.to_s}"] filter_backtrace(e.backtrace) { |line| format << " at #{line}" } format.join("\n") end
ruby
def format_error(e) format = [" #{e.class.name} occurred", "#{e.to_s}"] filter_backtrace(e.backtrace) { |line| format << " at #{line}" } format.join("\n") end
[ "def", "format_error", "(", "e", ")", "format", "=", "[", "\" #{e.class.name} occurred\"", ",", "\"#{e.to_s}\"", "]", "filter_backtrace", "(", "e", ".", "backtrace", ")", "{", "|", "line", "|", "format", "<<", "\" at #{line}\"", "}", "format", ".", "join", "(", "\"\\n\"", ")", "end" ]
Generates a message for assertions that error out. However, in the additional stacktrace, any mentions of Riot and Rake framework methods calls are removed. Makes for a more readable error response. @param [Exception] e the exception to generate the backtrace from @return [String] the error response message
[ "Generates", "a", "message", "for", "assertions", "that", "error", "out", ".", "However", "in", "the", "additional", "stacktrace", "any", "mentions", "of", "Riot", "and", "Rake", "framework", "methods", "calls", "are", "removed", ".", "Makes", "for", "a", "more", "readable", "error", "response", "." ]
e99a8965f2d28730fc863c647ca40b3bffb9e562
https://github.com/thumblemonks/riot/blob/e99a8965f2d28730fc863c647ca40b3bffb9e562/lib/riot/reporter/io.rb#L53-L57
train
amatsuda/rfd
lib/rfd/commands.rb
Rfd.Commands.O
def O dir = current_item.directory? ? current_item.path : current_dir.path system %Q[osascript -e 'tell app "Terminal" do script "cd #{dir}" end tell'] if osx? end
ruby
def O dir = current_item.directory? ? current_item.path : current_dir.path system %Q[osascript -e 'tell app "Terminal" do script "cd #{dir}" end tell'] if osx? end
[ "def", "O", "dir", "=", "current_item", ".", "directory?", "?", "current_item", ".", "path", ":", "current_dir", ".", "path", "system", "%Q[osascript -e 'tell app \"Terminal\" do script \"cd #{dir}\" end tell']", "if", "osx?", "end" ]
"O"pen terminal here.
[ "O", "pen", "terminal", "here", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd/commands.rb#L177-L182
train
amatsuda/rfd
lib/rfd/commands.rb
Rfd.Commands.ctrl_a
def ctrl_a mark = marked_items.size != (items.size - 2) # exclude . and .. items.each {|i| i.toggle_mark unless i.marked? == mark} draw_items draw_marked_items move_cursor current_row end
ruby
def ctrl_a mark = marked_items.size != (items.size - 2) # exclude . and .. items.each {|i| i.toggle_mark unless i.marked? == mark} draw_items draw_marked_items move_cursor current_row end
[ "def", "ctrl_a", "mark", "=", "marked_items", ".", "size", "!=", "(", "items", ".", "size", "-", "2", ")", "items", ".", "each", "{", "|", "i", "|", "i", ".", "toggle_mark", "unless", "i", ".", "marked?", "==", "mark", "}", "draw_items", "draw_marked_items", "move_cursor", "current_row", "end" ]
Mark or unmark "a"ll files and directories.
[ "Mark", "or", "unmark", "a", "ll", "files", "and", "directories", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd/commands.rb#L190-L196
train
amatsuda/rfd
lib/rfd/commands.rb
Rfd.Commands.enter
def enter if current_item.name == '.' # do nothing elsif current_item.name == '..' cd '..' elsif in_zip? v elsif current_item.directory? || current_item.zip? cd current_item else v end end
ruby
def enter if current_item.name == '.' # do nothing elsif current_item.name == '..' cd '..' elsif in_zip? v elsif current_item.directory? || current_item.zip? cd current_item else v end end
[ "def", "enter", "if", "current_item", ".", "name", "==", "'.'", "elsif", "current_item", ".", "name", "==", "'..'", "cd", "'..'", "elsif", "in_zip?", "v", "elsif", "current_item", ".", "directory?", "||", "current_item", ".", "zip?", "cd", "current_item", "else", "v", "end", "end" ]
cd into a directory, or view a file.
[ "cd", "into", "a", "directory", "or", "view", "a", "file", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd/commands.rb#L265-L276
train
amatsuda/rfd
lib/rfd/commands.rb
Rfd.Commands.del
def del if current_dir.path != '/' dir_was = times == 1 ? current_dir.name : File.basename(current_dir.join(['..'] * (times - 1))) cd File.expand_path(current_dir.join(['..'] * times)) find dir_was end end
ruby
def del if current_dir.path != '/' dir_was = times == 1 ? current_dir.name : File.basename(current_dir.join(['..'] * (times - 1))) cd File.expand_path(current_dir.join(['..'] * times)) find dir_was end end
[ "def", "del", "if", "current_dir", ".", "path", "!=", "'/'", "dir_was", "=", "times", "==", "1", "?", "current_dir", ".", "name", ":", "File", ".", "basename", "(", "current_dir", ".", "join", "(", "[", "'..'", "]", "*", "(", "times", "-", "1", ")", ")", ")", "cd", "File", ".", "expand_path", "(", "current_dir", ".", "join", "(", "[", "'..'", "]", "*", "times", ")", ")", "find", "dir_was", "end", "end" ]
cd to the upper hierarchy.
[ "cd", "to", "the", "upper", "hierarchy", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd/commands.rb#L286-L292
train
thumblemonks/riot
lib/riot/message.rb
Riot.Message.method_missing
def method_missing(meth, *phrases, &block) push(meth.to_s.gsub('_', ' ')) _inspect(phrases) end
ruby
def method_missing(meth, *phrases, &block) push(meth.to_s.gsub('_', ' ')) _inspect(phrases) end
[ "def", "method_missing", "(", "meth", ",", "*", "phrases", ",", "&", "block", ")", "push", "(", "meth", ".", "to_s", ".", "gsub", "(", "'_'", ",", "' '", ")", ")", "_inspect", "(", "phrases", ")", "end" ]
Converts any method call into a more readable string by replacing underscores with spaces. Any arguments to the method are inspected and appended to the final message. Blocks are currently ignored. @param [String, Symbol] meth the method name to be converted into a more readable form @param [Array<Object>] *phrases an array of objects to be inspected @return [Riot::Message] this instance for use in chaining calls
[ "Converts", "any", "method", "call", "into", "a", "more", "readable", "string", "by", "replacing", "underscores", "with", "spaces", ".", "Any", "arguments", "to", "the", "method", "are", "inspected", "and", "appended", "to", "the", "final", "message", ".", "Blocks", "are", "currently", "ignored", "." ]
e99a8965f2d28730fc863c647ca40b3bffb9e562
https://github.com/thumblemonks/riot/blob/e99a8965f2d28730fc863c647ca40b3bffb9e562/lib/riot/message.rb#L53-L56
train
thumblemonks/riot
lib/riot/reporter.rb
Riot.Reporter.report
def report(description, response) code, result = *response case code when :pass then @passes += 1 pass(description, result) when :fail then @failures += 1 message, line, file = *response[1..-1] fail(description, message, line, file) when :error, :setup_error, :context_error then @errors += 1 error(description, result) end end
ruby
def report(description, response) code, result = *response case code when :pass then @passes += 1 pass(description, result) when :fail then @failures += 1 message, line, file = *response[1..-1] fail(description, message, line, file) when :error, :setup_error, :context_error then @errors += 1 error(description, result) end end
[ "def", "report", "(", "description", ",", "response", ")", "code", ",", "result", "=", "*", "response", "case", "code", "when", ":pass", "then", "@passes", "+=", "1", "pass", "(", "description", ",", "result", ")", "when", ":fail", "then", "@failures", "+=", "1", "message", ",", "line", ",", "file", "=", "*", "response", "[", "1", "..", "-", "1", "]", "fail", "(", "description", ",", "message", ",", "line", ",", "file", ")", "when", ":error", ",", ":setup_error", ",", ":context_error", "then", "@errors", "+=", "1", "error", "(", "description", ",", "result", ")", "end", "end" ]
Called immediately after an assertion has been evaluated. From this method either +pass+, +fail+, or +error+ will be called. @param [String] description the description of the assertion @param [Array<Symbol, *[Object]>] response the evaluation response from the assertion
[ "Called", "immediately", "after", "an", "assertion", "has", "been", "evaluated", ".", "From", "this", "method", "either", "+", "pass", "+", "+", "fail", "+", "or", "+", "error", "+", "will", "be", "called", "." ]
e99a8965f2d28730fc863c647ca40b3bffb9e562
https://github.com/thumblemonks/riot/blob/e99a8965f2d28730fc863c647ca40b3bffb9e562/lib/riot/reporter.rb#L63-L77
train
singlebrook/utf8-cleaner
lib/utf8-cleaner/uri_string.rb
UTF8Cleaner.URIString.encoded_char_array
def encoded_char_array char_array = [] index = 0 while (index < data.length) do char = data[index] if char == '%' # Skip the next two characters, which are the encoded byte # indicates by this %. (We'll change this later for multibyte characters.) skip_next = 2 # If the next character is not a hex char, drop the percent and it unless data[index + 1] =~ HEX_CHARS_REGEX index += 2 next end # If the character after that is not a hex char, drop the percent and # both of the following chars. unless data[index + 2] =~ HEX_CHARS_REGEX index += 3 next end # How long is this character? first_byte = '0x' + (data[index + 1] + data[index + 2]).upcase bytes = utf8_char_length_in_bytes(first_byte) # Grab the specified number of encoded bytes utf8_char_encoded_bytes = next_n_bytes_from(index, bytes) # Did we get the right number of bytes? if utf8_char_encoded_bytes.length == bytes # We did. Is it a valid character? utf8_char_encoded = utf8_char_encoded_bytes.join if valid_uri_encoded_utf8(utf8_char_encoded) # It's valid! char_array << utf8_char_encoded # If we're dealing with a multibyte character, skip more than two # of the next characters, which have already been processed. skip_next = bytes * 3 - 1 end end index += skip_next else # This was not an encoded character, so just add it and move to the next. char_array << char end index += 1 end char_array end
ruby
def encoded_char_array char_array = [] index = 0 while (index < data.length) do char = data[index] if char == '%' # Skip the next two characters, which are the encoded byte # indicates by this %. (We'll change this later for multibyte characters.) skip_next = 2 # If the next character is not a hex char, drop the percent and it unless data[index + 1] =~ HEX_CHARS_REGEX index += 2 next end # If the character after that is not a hex char, drop the percent and # both of the following chars. unless data[index + 2] =~ HEX_CHARS_REGEX index += 3 next end # How long is this character? first_byte = '0x' + (data[index + 1] + data[index + 2]).upcase bytes = utf8_char_length_in_bytes(first_byte) # Grab the specified number of encoded bytes utf8_char_encoded_bytes = next_n_bytes_from(index, bytes) # Did we get the right number of bytes? if utf8_char_encoded_bytes.length == bytes # We did. Is it a valid character? utf8_char_encoded = utf8_char_encoded_bytes.join if valid_uri_encoded_utf8(utf8_char_encoded) # It's valid! char_array << utf8_char_encoded # If we're dealing with a multibyte character, skip more than two # of the next characters, which have already been processed. skip_next = bytes * 3 - 1 end end index += skip_next else # This was not an encoded character, so just add it and move to the next. char_array << char end index += 1 end char_array end
[ "def", "encoded_char_array", "char_array", "=", "[", "]", "index", "=", "0", "while", "(", "index", "<", "data", ".", "length", ")", "do", "char", "=", "data", "[", "index", "]", "if", "char", "==", "'%'", "skip_next", "=", "2", "unless", "data", "[", "index", "+", "1", "]", "=~", "HEX_CHARS_REGEX", "index", "+=", "2", "next", "end", "unless", "data", "[", "index", "+", "2", "]", "=~", "HEX_CHARS_REGEX", "index", "+=", "3", "next", "end", "first_byte", "=", "'0x'", "+", "(", "data", "[", "index", "+", "1", "]", "+", "data", "[", "index", "+", "2", "]", ")", ".", "upcase", "bytes", "=", "utf8_char_length_in_bytes", "(", "first_byte", ")", "utf8_char_encoded_bytes", "=", "next_n_bytes_from", "(", "index", ",", "bytes", ")", "if", "utf8_char_encoded_bytes", ".", "length", "==", "bytes", "utf8_char_encoded", "=", "utf8_char_encoded_bytes", ".", "join", "if", "valid_uri_encoded_utf8", "(", "utf8_char_encoded", ")", "char_array", "<<", "utf8_char_encoded", "skip_next", "=", "bytes", "*", "3", "-", "1", "end", "end", "index", "+=", "skip_next", "else", "char_array", "<<", "char", "end", "index", "+=", "1", "end", "char_array", "end" ]
Returns an array of valid URI-encoded UTF-8 characters.
[ "Returns", "an", "array", "of", "valid", "URI", "-", "encoded", "UTF", "-", "8", "characters", "." ]
adc8db208ed8a390240a087cce3cdabda2d1afa3
https://github.com/singlebrook/utf8-cleaner/blob/adc8db208ed8a390240a087cce3cdabda2d1afa3/lib/utf8-cleaner/uri_string.rb#L31-L87
train
singlebrook/utf8-cleaner
lib/utf8-cleaner/uri_string.rb
UTF8Cleaner.URIString.utf8_char_length_in_bytes
def utf8_char_length_in_bytes(first_byte) if first_byte.hex < 'C0'.hex 1 elsif first_byte.hex < 'DF'.hex 2 elsif first_byte.hex < 'EF'.hex 3 else 4 end end
ruby
def utf8_char_length_in_bytes(first_byte) if first_byte.hex < 'C0'.hex 1 elsif first_byte.hex < 'DF'.hex 2 elsif first_byte.hex < 'EF'.hex 3 else 4 end end
[ "def", "utf8_char_length_in_bytes", "(", "first_byte", ")", "if", "first_byte", ".", "hex", "<", "'C0'", ".", "hex", "1", "elsif", "first_byte", ".", "hex", "<", "'DF'", ".", "hex", "2", "elsif", "first_byte", ".", "hex", "<", "'EF'", ".", "hex", "3", "else", "4", "end", "end" ]
If the first byte is between 0xC0 and 0xDF, the UTF-8 character has two bytes; if it is between 0xE0 and 0xEF, the UTF-8 character has 3 bytes; and if it is 0xF0 and 0xFF, the UTF-8 character has 4 bytes. first_byte is a string like "0x13"
[ "If", "the", "first", "byte", "is", "between", "0xC0", "and", "0xDF", "the", "UTF", "-", "8", "character", "has", "two", "bytes", ";", "if", "it", "is", "between", "0xE0", "and", "0xEF", "the", "UTF", "-", "8", "character", "has", "3", "bytes", ";", "and", "if", "it", "is", "0xF0", "and", "0xFF", "the", "UTF", "-", "8", "character", "has", "4", "bytes", ".", "first_byte", "is", "a", "string", "like", "0x13" ]
adc8db208ed8a390240a087cce3cdabda2d1afa3
https://github.com/singlebrook/utf8-cleaner/blob/adc8db208ed8a390240a087cce3cdabda2d1afa3/lib/utf8-cleaner/uri_string.rb#L121-L131
train
rlister/stax
lib/stax/mixin/ecs.rb
Stax.Ecs.ecs_services_with_ids
def ecs_services_with_ids(*ids) if ids.empty? ecs_services else ecs_services.select do |s| ids.include?(s.logical_resource_id) end end end
ruby
def ecs_services_with_ids(*ids) if ids.empty? ecs_services else ecs_services.select do |s| ids.include?(s.logical_resource_id) end end end
[ "def", "ecs_services_with_ids", "(", "*", "ids", ")", "if", "ids", ".", "empty?", "ecs_services", "else", "ecs_services", ".", "select", "do", "|", "s", "|", "ids", ".", "include?", "(", "s", ".", "logical_resource_id", ")", "end", "end", "end" ]
get services with a list of logical ids
[ "get", "services", "with", "a", "list", "of", "logical", "ids" ]
450b4431627a6751f911410f996e6f24cd814272
https://github.com/rlister/stax/blob/450b4431627a6751f911410f996e6f24cd814272/lib/stax/mixin/ecs.rb#L28-L36
train
maestrano/maestrano-connector-rails
app/jobs/maestrano/connector/rails/all_synchronizations_job.rb
Maestrano::Connector::Rails.AllSynchronizationsJob.perform
def perform(name = nil, count = nil) Maestrano::Connector::Rails::Organization .where.not(oauth_provider: nil, encrypted_oauth_token: nil) .where(sync_enabled: true) .select(:id) .find_each do |organization| Maestrano::Connector::Rails::SynchronizationJob.set(wait: rand(3600)).perform_later(organization.id, {}) end end
ruby
def perform(name = nil, count = nil) Maestrano::Connector::Rails::Organization .where.not(oauth_provider: nil, encrypted_oauth_token: nil) .where(sync_enabled: true) .select(:id) .find_each do |organization| Maestrano::Connector::Rails::SynchronizationJob.set(wait: rand(3600)).perform_later(organization.id, {}) end end
[ "def", "perform", "(", "name", "=", "nil", ",", "count", "=", "nil", ")", "Maestrano", "::", "Connector", "::", "Rails", "::", "Organization", ".", "where", ".", "not", "(", "oauth_provider", ":", "nil", ",", "encrypted_oauth_token", ":", "nil", ")", ".", "where", "(", "sync_enabled", ":", "true", ")", ".", "select", "(", ":id", ")", ".", "find_each", "do", "|", "organization", "|", "Maestrano", "::", "Connector", "::", "Rails", "::", "SynchronizationJob", ".", "set", "(", "wait", ":", "rand", "(", "3600", ")", ")", ".", "perform_later", "(", "organization", ".", "id", ",", "{", "}", ")", "end", "end" ]
Trigger synchronization of all active organizations
[ "Trigger", "synchronization", "of", "all", "active", "organizations" ]
c7f0e9591c1065f1ee0eca318869757da7c3bc04
https://github.com/maestrano/maestrano-connector-rails/blob/c7f0e9591c1065f1ee0eca318869757da7c3bc04/app/jobs/maestrano/connector/rails/all_synchronizations_job.rb#L6-L14
train
aasmith/feed-normalizer
lib/structures.rb
FeedNormalizer.ElementCleaner.clean!
def clean! self.class::SIMPLE_ELEMENTS.each do |element| val = self.send(element) send("#{element}=", (val.is_a?(Array) ? val.collect{|v| HtmlCleaner.flatten(v.to_s)} : HtmlCleaner.flatten(val.to_s))) end self.class::HTML_ELEMENTS.each do |element| send("#{element}=", HtmlCleaner.clean(self.send(element).to_s)) end self.class::BLENDED_ELEMENTS.each do |element| self.send(element).collect{|v| v.clean!} end end
ruby
def clean! self.class::SIMPLE_ELEMENTS.each do |element| val = self.send(element) send("#{element}=", (val.is_a?(Array) ? val.collect{|v| HtmlCleaner.flatten(v.to_s)} : HtmlCleaner.flatten(val.to_s))) end self.class::HTML_ELEMENTS.each do |element| send("#{element}=", HtmlCleaner.clean(self.send(element).to_s)) end self.class::BLENDED_ELEMENTS.each do |element| self.send(element).collect{|v| v.clean!} end end
[ "def", "clean!", "self", ".", "class", "::", "SIMPLE_ELEMENTS", ".", "each", "do", "|", "element", "|", "val", "=", "self", ".", "send", "(", "element", ")", "send", "(", "\"#{element}=\"", ",", "(", "val", ".", "is_a?", "(", "Array", ")", "?", "val", ".", "collect", "{", "|", "v", "|", "HtmlCleaner", ".", "flatten", "(", "v", ".", "to_s", ")", "}", ":", "HtmlCleaner", ".", "flatten", "(", "val", ".", "to_s", ")", ")", ")", "end", "self", ".", "class", "::", "HTML_ELEMENTS", ".", "each", "do", "|", "element", "|", "send", "(", "\"#{element}=\"", ",", "HtmlCleaner", ".", "clean", "(", "self", ".", "send", "(", "element", ")", ".", "to_s", ")", ")", "end", "self", ".", "class", "::", "BLENDED_ELEMENTS", ".", "each", "do", "|", "element", "|", "self", ".", "send", "(", "element", ")", ".", "collect", "{", "|", "v", "|", "v", ".", "clean!", "}", "end", "end" ]
Recursively cleans all elements in place. Only allow tags in whitelist. Always parse the html with a parser and delete all tags that arent on the list. For feed elements that can contain HTML: - feed.(title|description) - feed.entries[n].(title|description|content)
[ "Recursively", "cleans", "all", "elements", "in", "place", "." ]
afa7765c08481d38729a71bd5dfd5ef95736f026
https://github.com/aasmith/feed-normalizer/blob/afa7765c08481d38729a71bd5dfd5ef95736f026/lib/structures.rb#L102-L117
train
rlister/stax
lib/stax/mixin/ssm.rb
Stax.Ssm.ssm_parameter_tmpfile
def ssm_parameter_tmpfile(name) Tempfile.new(stack_name).tap do |file| file.write(ssm_parameter_get(name)) File.chmod(0400, file.path) file.close end end
ruby
def ssm_parameter_tmpfile(name) Tempfile.new(stack_name).tap do |file| file.write(ssm_parameter_get(name)) File.chmod(0400, file.path) file.close end end
[ "def", "ssm_parameter_tmpfile", "(", "name", ")", "Tempfile", ".", "new", "(", "stack_name", ")", ".", "tap", "do", "|", "file", "|", "file", ".", "write", "(", "ssm_parameter_get", "(", "name", ")", ")", "File", ".", "chmod", "(", "0400", ",", "file", ".", "path", ")", "file", ".", "close", "end", "end" ]
get a parameter from the store to a Tmpfile
[ "get", "a", "parameter", "from", "the", "store", "to", "a", "Tmpfile" ]
450b4431627a6751f911410f996e6f24cd814272
https://github.com/rlister/stax/blob/450b4431627a6751f911410f996e6f24cd814272/lib/stax/mixin/ssm.rb#L37-L43
train
rlister/stax
lib/stax/mixin/ssm.rb
Stax.Ssm.ssm_run_shellscript
def ssm_run_shellscript(*cmd) Aws::Ssm.run( document_name: 'AWS-RunShellScript', targets: [{key: 'tag:aws:cloudformation:stack-name', values: [stack_name]}], parameters: {commands: cmd} )&.command_id.tap(&method(:puts)) end
ruby
def ssm_run_shellscript(*cmd) Aws::Ssm.run( document_name: 'AWS-RunShellScript', targets: [{key: 'tag:aws:cloudformation:stack-name', values: [stack_name]}], parameters: {commands: cmd} )&.command_id.tap(&method(:puts)) end
[ "def", "ssm_run_shellscript", "(", "*", "cmd", ")", "Aws", "::", "Ssm", ".", "run", "(", "document_name", ":", "'AWS-RunShellScript'", ",", "targets", ":", "[", "{", "key", ":", "'tag:aws:cloudformation:stack-name'", ",", "values", ":", "[", "stack_name", "]", "}", "]", ",", "parameters", ":", "{", "commands", ":", "cmd", "}", ")", "&.", "command_id", ".", "tap", "(", "&", "method", "(", ":puts", ")", ")", "end" ]
run a command on stack instances
[ "run", "a", "command", "on", "stack", "instances" ]
450b4431627a6751f911410f996e6f24cd814272
https://github.com/rlister/stax/blob/450b4431627a6751f911410f996e6f24cd814272/lib/stax/mixin/ssm.rb#L50-L56
train
kddeisz/snip_snip
lib/snip_snip/reporter.rb
SnipSnip.Reporter.report
def report(controller) return if results.empty? action_display = "#{controller.controller_name}##{controller.action_name}" SnipSnip.logger.info(action_display) results.sort_by(&:report).each do |result| SnipSnip.logger.info(" #{result.report}") end ensure Registry.clear end
ruby
def report(controller) return if results.empty? action_display = "#{controller.controller_name}##{controller.action_name}" SnipSnip.logger.info(action_display) results.sort_by(&:report).each do |result| SnipSnip.logger.info(" #{result.report}") end ensure Registry.clear end
[ "def", "report", "(", "controller", ")", "return", "if", "results", ".", "empty?", "action_display", "=", "\"#{controller.controller_name}##{controller.action_name}\"", "SnipSnip", ".", "logger", ".", "info", "(", "action_display", ")", "results", ".", "sort_by", "(", "&", ":report", ")", ".", "each", "do", "|", "result", "|", "SnipSnip", ".", "logger", ".", "info", "(", "\" #{result.report}\"", ")", "end", "ensure", "Registry", ".", "clear", "end" ]
Report on the unused columns that were selected during the course of the processing the action on the given controller.
[ "Report", "on", "the", "unused", "columns", "that", "were", "selected", "during", "the", "course", "of", "the", "processing", "the", "action", "on", "the", "given", "controller", "." ]
432879a18560d2ea3bf158293d92b386da095a80
https://github.com/kddeisz/snip_snip/blob/432879a18560d2ea3bf158293d92b386da095a80/lib/snip_snip/reporter.rb#L23-L34
train
maestrano/maestrano-connector-rails
app/models/maestrano/connector/rails/concerns/connec_helper.rb
Maestrano::Connector::Rails::Concerns::ConnecHelper.ClassMethods.fold_references
def fold_references(mapped_external_entity, references, organization) references = format_references(references) mapped_external_entity = mapped_external_entity.with_indifferent_access # Use both record_references and id_references + the id (references.values.flatten + ['id']).each do |reference| fold_references_helper(mapped_external_entity, reference.split('/'), organization) end mapped_external_entity end
ruby
def fold_references(mapped_external_entity, references, organization) references = format_references(references) mapped_external_entity = mapped_external_entity.with_indifferent_access # Use both record_references and id_references + the id (references.values.flatten + ['id']).each do |reference| fold_references_helper(mapped_external_entity, reference.split('/'), organization) end mapped_external_entity end
[ "def", "fold_references", "(", "mapped_external_entity", ",", "references", ",", "organization", ")", "references", "=", "format_references", "(", "references", ")", "mapped_external_entity", "=", "mapped_external_entity", ".", "with_indifferent_access", "(", "references", ".", "values", ".", "flatten", "+", "[", "'id'", "]", ")", ".", "each", "do", "|", "reference", "|", "fold_references_helper", "(", "mapped_external_entity", ",", "reference", ".", "split", "(", "'/'", ")", ",", "organization", ")", "end", "mapped_external_entity", "end" ]
Replaces ids from the external application by arrays containing them
[ "Replaces", "ids", "from", "the", "external", "application", "by", "arrays", "containing", "them" ]
c7f0e9591c1065f1ee0eca318869757da7c3bc04
https://github.com/maestrano/maestrano-connector-rails/blob/c7f0e9591c1065f1ee0eca318869757da7c3bc04/app/models/maestrano/connector/rails/concerns/connec_helper.rb#L73-L83
train
maestrano/maestrano-connector-rails
app/models/maestrano/connector/rails/concerns/connec_helper.rb
Maestrano::Connector::Rails::Concerns::ConnecHelper.ClassMethods.id_hash
def id_hash(id, organization) { id: id, provider: organization.oauth_provider, realm: organization.oauth_uid } end
ruby
def id_hash(id, organization) { id: id, provider: organization.oauth_provider, realm: organization.oauth_uid } end
[ "def", "id_hash", "(", "id", ",", "organization", ")", "{", "id", ":", "id", ",", "provider", ":", "organization", ".", "oauth_provider", ",", "realm", ":", "organization", ".", "oauth_uid", "}", "end" ]
Builds an id_hash from the id and organization
[ "Builds", "an", "id_hash", "from", "the", "id", "and", "organization" ]
c7f0e9591c1065f1ee0eca318869757da7c3bc04
https://github.com/maestrano/maestrano-connector-rails/blob/c7f0e9591c1065f1ee0eca318869757da7c3bc04/app/models/maestrano/connector/rails/concerns/connec_helper.rb#L86-L92
train
maestrano/maestrano-connector-rails
app/models/maestrano/connector/rails/concerns/connec_helper.rb
Maestrano::Connector::Rails::Concerns::ConnecHelper.ClassMethods.fold_references_helper
def fold_references_helper(entity, array_of_refs, organization) ref = array_of_refs.shift field = entity[ref] return if field.blank? # Follow embedment path, remplace if it's not an array or a hash case field when Array field.each do |f| fold_references_helper(f, array_of_refs.dup, organization) end when Hash fold_references_helper(entity[ref], array_of_refs, organization) else id = field entity[ref] = [id_hash(id, organization)] end end
ruby
def fold_references_helper(entity, array_of_refs, organization) ref = array_of_refs.shift field = entity[ref] return if field.blank? # Follow embedment path, remplace if it's not an array or a hash case field when Array field.each do |f| fold_references_helper(f, array_of_refs.dup, organization) end when Hash fold_references_helper(entity[ref], array_of_refs, organization) else id = field entity[ref] = [id_hash(id, organization)] end end
[ "def", "fold_references_helper", "(", "entity", ",", "array_of_refs", ",", "organization", ")", "ref", "=", "array_of_refs", ".", "shift", "field", "=", "entity", "[", "ref", "]", "return", "if", "field", ".", "blank?", "case", "field", "when", "Array", "field", ".", "each", "do", "|", "f", "|", "fold_references_helper", "(", "f", ",", "array_of_refs", ".", "dup", ",", "organization", ")", "end", "when", "Hash", "fold_references_helper", "(", "entity", "[", "ref", "]", ",", "array_of_refs", ",", "organization", ")", "else", "id", "=", "field", "entity", "[", "ref", "]", "=", "[", "id_hash", "(", "id", ",", "organization", ")", "]", "end", "end" ]
Recursive method for folding references
[ "Recursive", "method", "for", "folding", "references" ]
c7f0e9591c1065f1ee0eca318869757da7c3bc04
https://github.com/maestrano/maestrano-connector-rails/blob/c7f0e9591c1065f1ee0eca318869757da7c3bc04/app/models/maestrano/connector/rails/concerns/connec_helper.rb#L95-L112
train
maestrano/maestrano-connector-rails
app/models/maestrano/connector/rails/concerns/connec_helper.rb
Maestrano::Connector::Rails::Concerns::ConnecHelper.ClassMethods.unfold_references_helper
def unfold_references_helper(entity, array_of_refs, organization) ref = array_of_refs.shift field = entity[ref] # Unfold the id if array_of_refs.empty? && field return entity.delete(ref) if field.is_a?(String) # ~retro-compatibility to ease transition aroud Connec! idmaps rework. Should be removed eventually. id_hash = field.find { |id| id[:provider] == organization.oauth_provider && id[:realm] == organization.oauth_uid } if id_hash entity[ref] = id_hash['id'] elsif field.find { |id| id[:provider] == 'connec' } # Should always be true as ids will always contain a connec id # We may enqueue a fetch on the endpoint of the missing association, followed by a re-fetch on this one. # However it's expected to be an edge case, so for now we rely on the fact that the webhooks should be relativly in order. # Worst case it'll be done on following sync entity.delete(ref) return nil end true # Follow embedment path else return true if field.blank? case field when Array bool = true field.each do |f| bool &= unfold_references_helper(f, array_of_refs.dup, organization) end bool when Hash unfold_references_helper(entity[ref], array_of_refs, organization) end end end
ruby
def unfold_references_helper(entity, array_of_refs, organization) ref = array_of_refs.shift field = entity[ref] # Unfold the id if array_of_refs.empty? && field return entity.delete(ref) if field.is_a?(String) # ~retro-compatibility to ease transition aroud Connec! idmaps rework. Should be removed eventually. id_hash = field.find { |id| id[:provider] == organization.oauth_provider && id[:realm] == organization.oauth_uid } if id_hash entity[ref] = id_hash['id'] elsif field.find { |id| id[:provider] == 'connec' } # Should always be true as ids will always contain a connec id # We may enqueue a fetch on the endpoint of the missing association, followed by a re-fetch on this one. # However it's expected to be an edge case, so for now we rely on the fact that the webhooks should be relativly in order. # Worst case it'll be done on following sync entity.delete(ref) return nil end true # Follow embedment path else return true if field.blank? case field when Array bool = true field.each do |f| bool &= unfold_references_helper(f, array_of_refs.dup, organization) end bool when Hash unfold_references_helper(entity[ref], array_of_refs, organization) end end end
[ "def", "unfold_references_helper", "(", "entity", ",", "array_of_refs", ",", "organization", ")", "ref", "=", "array_of_refs", ".", "shift", "field", "=", "entity", "[", "ref", "]", "if", "array_of_refs", ".", "empty?", "&&", "field", "return", "entity", ".", "delete", "(", "ref", ")", "if", "field", ".", "is_a?", "(", "String", ")", "id_hash", "=", "field", ".", "find", "{", "|", "id", "|", "id", "[", ":provider", "]", "==", "organization", ".", "oauth_provider", "&&", "id", "[", ":realm", "]", "==", "organization", ".", "oauth_uid", "}", "if", "id_hash", "entity", "[", "ref", "]", "=", "id_hash", "[", "'id'", "]", "elsif", "field", ".", "find", "{", "|", "id", "|", "id", "[", ":provider", "]", "==", "'connec'", "}", "entity", ".", "delete", "(", "ref", ")", "return", "nil", "end", "true", "else", "return", "true", "if", "field", ".", "blank?", "case", "field", "when", "Array", "bool", "=", "true", "field", ".", "each", "do", "|", "f", "|", "bool", "&=", "unfold_references_helper", "(", "f", ",", "array_of_refs", ".", "dup", ",", "organization", ")", "end", "bool", "when", "Hash", "unfold_references_helper", "(", "entity", "[", "ref", "]", ",", "array_of_refs", ",", "organization", ")", "end", "end", "end" ]
Recursive method for unfolding references
[ "Recursive", "method", "for", "unfolding", "references" ]
c7f0e9591c1065f1ee0eca318869757da7c3bc04
https://github.com/maestrano/maestrano-connector-rails/blob/c7f0e9591c1065f1ee0eca318869757da7c3bc04/app/models/maestrano/connector/rails/concerns/connec_helper.rb#L115-L150
train
maestrano/maestrano-connector-rails
app/models/maestrano/connector/rails/concerns/connec_helper.rb
Maestrano::Connector::Rails::Concerns::ConnecHelper.ClassMethods.filter_connec_entity_for_id_refs
def filter_connec_entity_for_id_refs(connec_entity, id_references) return {} if id_references.empty? entity = connec_entity.dup.with_indifferent_access tree = build_id_references_tree(id_references) filter_connec_entity_for_id_refs_helper(entity, tree) # TODO, improve performance by returning an empty hash if all the id_references have their id in the connec hash # We should still return all of them if at least one is missing as we are relying on the id entity end
ruby
def filter_connec_entity_for_id_refs(connec_entity, id_references) return {} if id_references.empty? entity = connec_entity.dup.with_indifferent_access tree = build_id_references_tree(id_references) filter_connec_entity_for_id_refs_helper(entity, tree) # TODO, improve performance by returning an empty hash if all the id_references have their id in the connec hash # We should still return all of them if at least one is missing as we are relying on the id entity end
[ "def", "filter_connec_entity_for_id_refs", "(", "connec_entity", ",", "id_references", ")", "return", "{", "}", "if", "id_references", ".", "empty?", "entity", "=", "connec_entity", ".", "dup", ".", "with_indifferent_access", "tree", "=", "build_id_references_tree", "(", "id_references", ")", "filter_connec_entity_for_id_refs_helper", "(", "entity", ",", "tree", ")", "entity", "end" ]
Returns the connec_entity without all the fields that are not id_references
[ "Returns", "the", "connec_entity", "without", "all", "the", "fields", "that", "are", "not", "id_references" ]
c7f0e9591c1065f1ee0eca318869757da7c3bc04
https://github.com/maestrano/maestrano-connector-rails/blob/c7f0e9591c1065f1ee0eca318869757da7c3bc04/app/models/maestrano/connector/rails/concerns/connec_helper.rb#L163-L174
train
maestrano/maestrano-connector-rails
app/models/maestrano/connector/rails/concerns/connec_helper.rb
Maestrano::Connector::Rails::Concerns::ConnecHelper.ClassMethods.filter_connec_entity_for_id_refs_helper
def filter_connec_entity_for_id_refs_helper(entity_hash, tree) return if tree.empty? entity_hash.slice!(*tree.keys) tree.each do |key, children| case entity_hash[key] when Array entity_hash[key].each do |hash| filter_connec_entity_for_id_refs_helper(hash, children) end when Hash filter_connec_entity_for_id_refs_helper(entity_hash[key], children) end end end
ruby
def filter_connec_entity_for_id_refs_helper(entity_hash, tree) return if tree.empty? entity_hash.slice!(*tree.keys) tree.each do |key, children| case entity_hash[key] when Array entity_hash[key].each do |hash| filter_connec_entity_for_id_refs_helper(hash, children) end when Hash filter_connec_entity_for_id_refs_helper(entity_hash[key], children) end end end
[ "def", "filter_connec_entity_for_id_refs_helper", "(", "entity_hash", ",", "tree", ")", "return", "if", "tree", ".", "empty?", "entity_hash", ".", "slice!", "(", "*", "tree", ".", "keys", ")", "tree", ".", "each", "do", "|", "key", ",", "children", "|", "case", "entity_hash", "[", "key", "]", "when", "Array", "entity_hash", "[", "key", "]", ".", "each", "do", "|", "hash", "|", "filter_connec_entity_for_id_refs_helper", "(", "hash", ",", "children", ")", "end", "when", "Hash", "filter_connec_entity_for_id_refs_helper", "(", "entity_hash", "[", "key", "]", ",", "children", ")", "end", "end", "end" ]
Recursive method for filtering connec entities
[ "Recursive", "method", "for", "filtering", "connec", "entities" ]
c7f0e9591c1065f1ee0eca318869757da7c3bc04
https://github.com/maestrano/maestrano-connector-rails/blob/c7f0e9591c1065f1ee0eca318869757da7c3bc04/app/models/maestrano/connector/rails/concerns/connec_helper.rb#L177-L192
train
maestrano/maestrano-connector-rails
app/models/maestrano/connector/rails/concerns/connec_helper.rb
Maestrano::Connector::Rails::Concerns::ConnecHelper.ClassMethods.merge_id_hashes
def merge_id_hashes(dist, src, id_references) dist = dist.with_indifferent_access src = src.with_indifferent_access id_references.each do |id_reference| array_of_refs = id_reference.split('/') merge_id_hashes_helper(dist, array_of_refs, src) end dist end
ruby
def merge_id_hashes(dist, src, id_references) dist = dist.with_indifferent_access src = src.with_indifferent_access id_references.each do |id_reference| array_of_refs = id_reference.split('/') merge_id_hashes_helper(dist, array_of_refs, src) end dist end
[ "def", "merge_id_hashes", "(", "dist", ",", "src", ",", "id_references", ")", "dist", "=", "dist", ".", "with_indifferent_access", "src", "=", "src", ".", "with_indifferent_access", "id_references", ".", "each", "do", "|", "id_reference", "|", "array_of_refs", "=", "id_reference", ".", "split", "(", "'/'", ")", "merge_id_hashes_helper", "(", "dist", ",", "array_of_refs", ",", "src", ")", "end", "dist", "end" ]
Merges the id arrays from two hashes while keeping only the id_references fields
[ "Merges", "the", "id", "arrays", "from", "two", "hashes", "while", "keeping", "only", "the", "id_references", "fields" ]
c7f0e9591c1065f1ee0eca318869757da7c3bc04
https://github.com/maestrano/maestrano-connector-rails/blob/c7f0e9591c1065f1ee0eca318869757da7c3bc04/app/models/maestrano/connector/rails/concerns/connec_helper.rb#L214-L225
train
maestrano/maestrano-connector-rails
app/models/maestrano/connector/rails/concerns/connec_helper.rb
Maestrano::Connector::Rails::Concerns::ConnecHelper.ClassMethods.merge_id_hashes_helper
def merge_id_hashes_helper(hash, array_of_refs, src, path = []) ref = array_of_refs.shift field = hash[ref] if array_of_refs.empty? && field value = value_from_hash(src, path + [ref]) if value.is_a?(Array) hash[ref] = (field + value).uniq else hash.delete(ref) end else case field when Array field.each_with_index do |f, index| merge_id_hashes_helper(f, array_of_refs.dup, src, path + [ref, index]) end when Hash merge_id_hashes_helper(field, array_of_refs, src, path + [ref]) end end end
ruby
def merge_id_hashes_helper(hash, array_of_refs, src, path = []) ref = array_of_refs.shift field = hash[ref] if array_of_refs.empty? && field value = value_from_hash(src, path + [ref]) if value.is_a?(Array) hash[ref] = (field + value).uniq else hash.delete(ref) end else case field when Array field.each_with_index do |f, index| merge_id_hashes_helper(f, array_of_refs.dup, src, path + [ref, index]) end when Hash merge_id_hashes_helper(field, array_of_refs, src, path + [ref]) end end end
[ "def", "merge_id_hashes_helper", "(", "hash", ",", "array_of_refs", ",", "src", ",", "path", "=", "[", "]", ")", "ref", "=", "array_of_refs", ".", "shift", "field", "=", "hash", "[", "ref", "]", "if", "array_of_refs", ".", "empty?", "&&", "field", "value", "=", "value_from_hash", "(", "src", ",", "path", "+", "[", "ref", "]", ")", "if", "value", ".", "is_a?", "(", "Array", ")", "hash", "[", "ref", "]", "=", "(", "field", "+", "value", ")", ".", "uniq", "else", "hash", ".", "delete", "(", "ref", ")", "end", "else", "case", "field", "when", "Array", "field", ".", "each_with_index", "do", "|", "f", ",", "index", "|", "merge_id_hashes_helper", "(", "f", ",", "array_of_refs", ".", "dup", ",", "src", ",", "path", "+", "[", "ref", ",", "index", "]", ")", "end", "when", "Hash", "merge_id_hashes_helper", "(", "field", ",", "array_of_refs", ",", "src", ",", "path", "+", "[", "ref", "]", ")", "end", "end", "end" ]
Recursive helper for merging id hashes
[ "Recursive", "helper", "for", "merging", "id", "hashes" ]
c7f0e9591c1065f1ee0eca318869757da7c3bc04
https://github.com/maestrano/maestrano-connector-rails/blob/c7f0e9591c1065f1ee0eca318869757da7c3bc04/app/models/maestrano/connector/rails/concerns/connec_helper.rb#L228-L249
train
rlister/stax
lib/stax/mixin/ecs/deploy.rb
Stax.Ecs.taskdef_to_hash
def taskdef_to_hash(taskdef) args = %i[family cpu memory requires_compatibilities task_role_arn execution_role_arn network_mode container_definitions volumes placement_constraints] taskdef.to_hash.slice(*args) end
ruby
def taskdef_to_hash(taskdef) args = %i[family cpu memory requires_compatibilities task_role_arn execution_role_arn network_mode container_definitions volumes placement_constraints] taskdef.to_hash.slice(*args) end
[ "def", "taskdef_to_hash", "(", "taskdef", ")", "args", "=", "%i[", "family", "cpu", "memory", "requires_compatibilities", "task_role_arn", "execution_role_arn", "network_mode", "container_definitions", "volumes", "placement_constraints", "]", "taskdef", ".", "to_hash", ".", "slice", "(", "*", "args", ")", "end" ]
convert to hash for registering new taskdef
[ "convert", "to", "hash", "for", "registering", "new", "taskdef" ]
450b4431627a6751f911410f996e6f24cd814272
https://github.com/rlister/stax/blob/450b4431627a6751f911410f996e6f24cd814272/lib/stax/mixin/ecs/deploy.rb#L5-L8
train
rlister/stax
lib/stax/mixin/ecs/deploy.rb
Stax.Ecs.ecs_deploy
def ecs_deploy(id, &block) service = Aws::Ecs.services(ecs_cluster_name, [resource(id)]).first taskdef = get_taskdef(service) ## convert to a hash and modify in block hash = taskdef_to_hash(taskdef) yield(hash) if block_given? taskdef = register_taskdef(hash) update_service(service, taskdef) end
ruby
def ecs_deploy(id, &block) service = Aws::Ecs.services(ecs_cluster_name, [resource(id)]).first taskdef = get_taskdef(service) ## convert to a hash and modify in block hash = taskdef_to_hash(taskdef) yield(hash) if block_given? taskdef = register_taskdef(hash) update_service(service, taskdef) end
[ "def", "ecs_deploy", "(", "id", ",", "&", "block", ")", "service", "=", "Aws", "::", "Ecs", ".", "services", "(", "ecs_cluster_name", ",", "[", "resource", "(", "id", ")", "]", ")", ".", "first", "taskdef", "=", "get_taskdef", "(", "service", ")", "hash", "=", "taskdef_to_hash", "(", "taskdef", ")", "yield", "(", "hash", ")", "if", "block_given?", "taskdef", "=", "register_taskdef", "(", "hash", ")", "update_service", "(", "service", ",", "taskdef", ")", "end" ]
update taskdef for a service, triggering a deploy modify current taskdef in block
[ "update", "taskdef", "for", "a", "service", "triggering", "a", "deploy", "modify", "current", "taskdef", "in", "block" ]
450b4431627a6751f911410f996e6f24cd814272
https://github.com/rlister/stax/blob/450b4431627a6751f911410f996e6f24cd814272/lib/stax/mixin/ecs/deploy.rb#L36-L46
train
avdgaag/rpub
lib/rpub/compressor.rb
Rpub.Compressor.store_file
def store_file(filename, content) zip.put_next_entry filename, nil, nil, Zip::Entry::STORED, Zlib::NO_COMPRESSION zip.write content.to_s end
ruby
def store_file(filename, content) zip.put_next_entry filename, nil, nil, Zip::Entry::STORED, Zlib::NO_COMPRESSION zip.write content.to_s end
[ "def", "store_file", "(", "filename", ",", "content", ")", "zip", ".", "put_next_entry", "filename", ",", "nil", ",", "nil", ",", "Zip", "::", "Entry", "::", "STORED", ",", "Zlib", "::", "NO_COMPRESSION", "zip", ".", "write", "content", ".", "to_s", "end" ]
Store a file in the archive without any compression. @param [String] filename under the which the data should be stored @param [#to_s] content to be compressed
[ "Store", "a", "file", "in", "the", "archive", "without", "any", "compression", "." ]
9ab682ea5a20e3e6c1d6ce16c71149db0476f6c2
https://github.com/avdgaag/rpub/blob/9ab682ea5a20e3e6c1d6ce16c71149db0476f6c2/lib/rpub/compressor.rb#L32-L35
train
avdgaag/rpub
lib/rpub/compressor.rb
Rpub.Compressor.compress_file
def compress_file(filename, content) zip.put_next_entry filename, nil, nil, Zip::Entry::DEFLATED, Zlib::BEST_COMPRESSION zip.write content.to_s end
ruby
def compress_file(filename, content) zip.put_next_entry filename, nil, nil, Zip::Entry::DEFLATED, Zlib::BEST_COMPRESSION zip.write content.to_s end
[ "def", "compress_file", "(", "filename", ",", "content", ")", "zip", ".", "put_next_entry", "filename", ",", "nil", ",", "nil", ",", "Zip", "::", "Entry", "::", "DEFLATED", ",", "Zlib", "::", "BEST_COMPRESSION", "zip", ".", "write", "content", ".", "to_s", "end" ]
Store a file with maximum compression in the archive. @param [String] filename under the which the data should be stored @param [#to_s] content to be compressed
[ "Store", "a", "file", "with", "maximum", "compression", "in", "the", "archive", "." ]
9ab682ea5a20e3e6c1d6ce16c71149db0476f6c2
https://github.com/avdgaag/rpub/blob/9ab682ea5a20e3e6c1d6ce16c71149db0476f6c2/lib/rpub/compressor.rb#L41-L44
train
afair/postgresql_cursor
lib/postgresql_cursor/cursor.rb
PostgreSQLCursor.Cursor.pluck
def pluck(*cols) options = cols.last.is_a?(Hash) ? cols.pop : {} @options.merge!(options) @options[:symbolize_keys] = true self.iterate_type(options[:class]) if options[:class] cols = cols.map {|c| c.to_sym } result = [] self.each() do |row| row = row.symbolize_keys if row.is_a?(Hash) result << cols.map { |c| row[c] } end result.flatten! if cols.size == 1 result end
ruby
def pluck(*cols) options = cols.last.is_a?(Hash) ? cols.pop : {} @options.merge!(options) @options[:symbolize_keys] = true self.iterate_type(options[:class]) if options[:class] cols = cols.map {|c| c.to_sym } result = [] self.each() do |row| row = row.symbolize_keys if row.is_a?(Hash) result << cols.map { |c| row[c] } end result.flatten! if cols.size == 1 result end
[ "def", "pluck", "(", "*", "cols", ")", "options", "=", "cols", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "cols", ".", "pop", ":", "{", "}", "@options", ".", "merge!", "(", "options", ")", "@options", "[", ":symbolize_keys", "]", "=", "true", "self", ".", "iterate_type", "(", "options", "[", ":class", "]", ")", "if", "options", "[", ":class", "]", "cols", "=", "cols", ".", "map", "{", "|", "c", "|", "c", ".", "to_sym", "}", "result", "=", "[", "]", "self", ".", "each", "(", ")", "do", "|", "row", "|", "row", "=", "row", ".", "symbolize_keys", "if", "row", ".", "is_a?", "(", "Hash", ")", "result", "<<", "cols", ".", "map", "{", "|", "c", "|", "row", "[", "c", "]", "}", "end", "result", ".", "flatten!", "if", "cols", ".", "size", "==", "1", "result", "end" ]
Returns an array of columns plucked from the result rows. Experimental function, as this could still use too much memory and negate the purpose of this libarary. Should this return a lazy enumerator instead?
[ "Returns", "an", "array", "of", "columns", "plucked", "from", "the", "result", "rows", ".", "Experimental", "function", "as", "this", "could", "still", "use", "too", "much", "memory", "and", "negate", "the", "purpose", "of", "this", "libarary", ".", "Should", "this", "return", "a", "lazy", "enumerator", "instead?" ]
92224ba8e33df8da85b9c31ffdb56feb29390887
https://github.com/afair/postgresql_cursor/blob/92224ba8e33df8da85b9c31ffdb56feb29390887/lib/postgresql_cursor/cursor.rb#L165-L180
train
cantino/reckon
lib/reckon/app.rb
Reckon.App.weighted_account_match
def weighted_account_match( row ) query_tokens = tokenize(row[:description]) search_vector = [] account_vectors = {} query_tokens.each do |token| idf = Math.log((accounts.keys.length + 1) / ((tokens[token] || {}).keys.length.to_f + 1)) tf = 1.0 / query_tokens.length.to_f search_vector << tf*idf accounts.each do |account, total_terms| tf = (tokens[token] && tokens[token][account]) ? tokens[token][account] / total_terms.to_f : 0 account_vectors[account] ||= [] account_vectors[account] << tf*idf end end # Should I normalize the vectors? Probably unnecessary due to tf-idf and short documents. account_vectors = account_vectors.to_a.map do |account, account_vector| { :cosine => (0...account_vector.length).to_a.inject(0) { |m, i| m + search_vector[i] * account_vector[i] }, :account => account } end account_vectors.sort! {|a, b| b[:cosine] <=> a[:cosine] } # Return empty set if no accounts matched so that we can fallback to the defaults in the unattended mode if options[:unattended] if account_vectors.first && account_vectors.first[:account] account_vectors = [] if account_vectors.first[:cosine] == 0 end end return account_vectors end
ruby
def weighted_account_match( row ) query_tokens = tokenize(row[:description]) search_vector = [] account_vectors = {} query_tokens.each do |token| idf = Math.log((accounts.keys.length + 1) / ((tokens[token] || {}).keys.length.to_f + 1)) tf = 1.0 / query_tokens.length.to_f search_vector << tf*idf accounts.each do |account, total_terms| tf = (tokens[token] && tokens[token][account]) ? tokens[token][account] / total_terms.to_f : 0 account_vectors[account] ||= [] account_vectors[account] << tf*idf end end # Should I normalize the vectors? Probably unnecessary due to tf-idf and short documents. account_vectors = account_vectors.to_a.map do |account, account_vector| { :cosine => (0...account_vector.length).to_a.inject(0) { |m, i| m + search_vector[i] * account_vector[i] }, :account => account } end account_vectors.sort! {|a, b| b[:cosine] <=> a[:cosine] } # Return empty set if no accounts matched so that we can fallback to the defaults in the unattended mode if options[:unattended] if account_vectors.first && account_vectors.first[:account] account_vectors = [] if account_vectors.first[:cosine] == 0 end end return account_vectors end
[ "def", "weighted_account_match", "(", "row", ")", "query_tokens", "=", "tokenize", "(", "row", "[", ":description", "]", ")", "search_vector", "=", "[", "]", "account_vectors", "=", "{", "}", "query_tokens", ".", "each", "do", "|", "token", "|", "idf", "=", "Math", ".", "log", "(", "(", "accounts", ".", "keys", ".", "length", "+", "1", ")", "/", "(", "(", "tokens", "[", "token", "]", "||", "{", "}", ")", ".", "keys", ".", "length", ".", "to_f", "+", "1", ")", ")", "tf", "=", "1.0", "/", "query_tokens", ".", "length", ".", "to_f", "search_vector", "<<", "tf", "*", "idf", "accounts", ".", "each", "do", "|", "account", ",", "total_terms", "|", "tf", "=", "(", "tokens", "[", "token", "]", "&&", "tokens", "[", "token", "]", "[", "account", "]", ")", "?", "tokens", "[", "token", "]", "[", "account", "]", "/", "total_terms", ".", "to_f", ":", "0", "account_vectors", "[", "account", "]", "||=", "[", "]", "account_vectors", "[", "account", "]", "<<", "tf", "*", "idf", "end", "end", "account_vectors", "=", "account_vectors", ".", "to_a", ".", "map", "do", "|", "account", ",", "account_vector", "|", "{", ":cosine", "=>", "(", "0", "...", "account_vector", ".", "length", ")", ".", "to_a", ".", "inject", "(", "0", ")", "{", "|", "m", ",", "i", "|", "m", "+", "search_vector", "[", "i", "]", "*", "account_vector", "[", "i", "]", "}", ",", ":account", "=>", "account", "}", "end", "account_vectors", ".", "sort!", "{", "|", "a", ",", "b", "|", "b", "[", ":cosine", "]", "<=>", "a", "[", ":cosine", "]", "}", "if", "options", "[", ":unattended", "]", "if", "account_vectors", ".", "first", "&&", "account_vectors", ".", "first", "[", ":account", "]", "account_vectors", "=", "[", "]", "if", "account_vectors", ".", "first", "[", ":cosine", "]", "==", "0", "end", "end", "return", "account_vectors", "end" ]
Weigh accounts by how well they match the row
[ "Weigh", "accounts", "by", "how", "well", "they", "match", "the", "row" ]
781a80f3fa213656d19909e3f42d0e469e5d8d47
https://github.com/cantino/reckon/blob/781a80f3fa213656d19909e3f42d0e469e5d8d47/lib/reckon/app.rb#L180-L214
train
Kesin11/danger-textlint
lib/textlint/plugin.rb
Danger.DangerTextlint.lint
def lint return if target_files.empty? bin = textlint_path result_json = run_textlint(bin, target_files) errors = parse(result_json) send_comment(errors) end
ruby
def lint return if target_files.empty? bin = textlint_path result_json = run_textlint(bin, target_files) errors = parse(result_json) send_comment(errors) end
[ "def", "lint", "return", "if", "target_files", ".", "empty?", "bin", "=", "textlint_path", "result_json", "=", "run_textlint", "(", "bin", ",", "target_files", ")", "errors", "=", "parse", "(", "result_json", ")", "send_comment", "(", "errors", ")", "end" ]
Execute textlint and send comment @return [void]
[ "Execute", "textlint", "and", "send", "comment" ]
bdc5826c0726ccc418034d30d3184f824f2d4035
https://github.com/Kesin11/danger-textlint/blob/bdc5826c0726ccc418034d30d3184f824f2d4035/lib/textlint/plugin.rb#L42-L49
train
karafka/capistrano-karafka
lib/capistrano/karafka.rb
Capistrano.Karafka.set_defaults
def set_defaults set_if_empty :karafka_role, :karafka set_if_empty :karafka_processes, 1 set_if_empty :karafka_consumer_groups, [] set_if_empty :karafka_default_hooks, -> { true } set_if_empty :karafka_env, -> { fetch(:karafka_env, fetch(:environment)) } set_if_empty :karafka_pid, -> { File.join(shared_path, 'tmp', 'pids', 'karafka.pid') } end
ruby
def set_defaults set_if_empty :karafka_role, :karafka set_if_empty :karafka_processes, 1 set_if_empty :karafka_consumer_groups, [] set_if_empty :karafka_default_hooks, -> { true } set_if_empty :karafka_env, -> { fetch(:karafka_env, fetch(:environment)) } set_if_empty :karafka_pid, -> { File.join(shared_path, 'tmp', 'pids', 'karafka.pid') } end
[ "def", "set_defaults", "set_if_empty", ":karafka_role", ",", ":karafka", "set_if_empty", ":karafka_processes", ",", "1", "set_if_empty", ":karafka_consumer_groups", ",", "[", "]", "set_if_empty", ":karafka_default_hooks", ",", "->", "{", "true", "}", "set_if_empty", ":karafka_env", ",", "->", "{", "fetch", "(", ":karafka_env", ",", "fetch", "(", ":environment", ")", ")", "}", "set_if_empty", ":karafka_pid", ",", "->", "{", "File", ".", "join", "(", "shared_path", ",", "'tmp'", ",", "'pids'", ",", "'karafka.pid'", ")", "}", "end" ]
Default values for Karafka settings
[ "Default", "values", "for", "Karafka", "settings" ]
984e07d5ab6d3de9a434b539c1cd92b34bbdd999
https://github.com/karafka/capistrano-karafka/blob/984e07d5ab6d3de9a434b539c1cd92b34bbdd999/lib/capistrano/karafka.rb#L20-L27
train
mwunsch/weary
lib/weary/resource.rb
Weary.Resource.meets_requirements?
def meets_requirements?(params) requirements.reject {|k| params.keys.map(&:to_s).include? k.to_s }.empty? end
ruby
def meets_requirements?(params) requirements.reject {|k| params.keys.map(&:to_s).include? k.to_s }.empty? end
[ "def", "meets_requirements?", "(", "params", ")", "requirements", ".", "reject", "{", "|", "k", "|", "params", ".", "keys", ".", "map", "(", "&", ":to_s", ")", ".", "include?", "k", ".", "to_s", "}", ".", "empty?", "end" ]
Given a hash of Request parameters, do they meet the requirements?
[ "Given", "a", "hash", "of", "Request", "parameters", "do", "they", "meet", "the", "requirements?" ]
e36ce4f82d83cbc3d826eaa427acc5e66a0f849b
https://github.com/mwunsch/weary/blob/e36ce4f82d83cbc3d826eaa427acc5e66a0f849b/lib/weary/resource.rb#L97-L99
train
mwunsch/weary
lib/weary/resource.rb
Weary.Resource.request
def request(params={}) normalize_parameters params raise UnmetRequirementsError, "Required parameters: #{requirements}" \ unless meets_requirements? params credentials = pull_credentials params pairs = pull_url_pairs params request = construct_request expand_url(pairs), params, credentials yield request if block_given? request end
ruby
def request(params={}) normalize_parameters params raise UnmetRequirementsError, "Required parameters: #{requirements}" \ unless meets_requirements? params credentials = pull_credentials params pairs = pull_url_pairs params request = construct_request expand_url(pairs), params, credentials yield request if block_given? request end
[ "def", "request", "(", "params", "=", "{", "}", ")", "normalize_parameters", "params", "raise", "UnmetRequirementsError", ",", "\"Required parameters: #{requirements}\"", "unless", "meets_requirements?", "params", "credentials", "=", "pull_credentials", "params", "pairs", "=", "pull_url_pairs", "params", "request", "=", "construct_request", "expand_url", "(", "pairs", ")", ",", "params", ",", "credentials", "yield", "request", "if", "block_given?", "request", "end" ]
Construct the request from the given parameters. Yields the Request Returns the Request. Raises a Weary::Resource::UnmetRequirementsError if the requirements are not met.
[ "Construct", "the", "request", "from", "the", "given", "parameters", "." ]
e36ce4f82d83cbc3d826eaa427acc5e66a0f849b
https://github.com/mwunsch/weary/blob/e36ce4f82d83cbc3d826eaa427acc5e66a0f849b/lib/weary/resource.rb#L108-L117
train
capicue/pgn
lib/pgn/move_calculator.rb
PGN.MoveCalculator.compute_origin
def compute_origin return nil if move.castle possibilities = case move.piece when /[brq]/i then direction_origins when /[kn]/i then move_origins when /p/i then pawn_origins end if possibilities.length > 1 possibilities = disambiguate(possibilities) end self.board.position_for(possibilities.first) end
ruby
def compute_origin return nil if move.castle possibilities = case move.piece when /[brq]/i then direction_origins when /[kn]/i then move_origins when /p/i then pawn_origins end if possibilities.length > 1 possibilities = disambiguate(possibilities) end self.board.position_for(possibilities.first) end
[ "def", "compute_origin", "return", "nil", "if", "move", ".", "castle", "possibilities", "=", "case", "move", ".", "piece", "when", "/", "/i", "then", "direction_origins", "when", "/", "/i", "then", "move_origins", "when", "/", "/i", "then", "pawn_origins", "end", "if", "possibilities", ".", "length", ">", "1", "possibilities", "=", "disambiguate", "(", "possibilities", ")", "end", "self", ".", "board", ".", "position_for", "(", "possibilities", ".", "first", ")", "end" ]
Using the current position and move, figure out where the piece came from.
[ "Using", "the", "current", "position", "and", "move", "figure", "out", "where", "the", "piece", "came", "from", "." ]
d7e3a0839bbf7e4216409b419bd85f171a840c87
https://github.com/capicue/pgn/blob/d7e3a0839bbf7e4216409b419bd85f171a840c87/lib/pgn/move_calculator.rb#L181-L195
train
capicue/pgn
lib/pgn/move_calculator.rb
PGN.MoveCalculator.direction_origins
def direction_origins directions = DIRECTIONS[move.piece.downcase] possibilities = [] directions.each do |dir| piece, square = first_piece(destination_coords, dir) possibilities << square if piece == self.move.piece end possibilities end
ruby
def direction_origins directions = DIRECTIONS[move.piece.downcase] possibilities = [] directions.each do |dir| piece, square = first_piece(destination_coords, dir) possibilities << square if piece == self.move.piece end possibilities end
[ "def", "direction_origins", "directions", "=", "DIRECTIONS", "[", "move", ".", "piece", ".", "downcase", "]", "possibilities", "=", "[", "]", "directions", ".", "each", "do", "|", "dir", "|", "piece", ",", "square", "=", "first_piece", "(", "destination_coords", ",", "dir", ")", "possibilities", "<<", "square", "if", "piece", "==", "self", ".", "move", ".", "piece", "end", "possibilities", "end" ]
From the destination square, move in each direction stopping if we reach the end of the board. If we encounter a piece, add it to the list of origin possibilities if it is the moving piece, or else check the next direction.
[ "From", "the", "destination", "square", "move", "in", "each", "direction", "stopping", "if", "we", "reach", "the", "end", "of", "the", "board", ".", "If", "we", "encounter", "a", "piece", "add", "it", "to", "the", "list", "of", "origin", "possibilities", "if", "it", "is", "the", "moving", "piece", "or", "else", "check", "the", "next", "direction", "." ]
d7e3a0839bbf7e4216409b419bd85f171a840c87
https://github.com/capicue/pgn/blob/d7e3a0839bbf7e4216409b419bd85f171a840c87/lib/pgn/move_calculator.rb#L202-L212
train
capicue/pgn
lib/pgn/move_calculator.rb
PGN.MoveCalculator.move_origins
def move_origins(moves = nil) moves ||= MOVES[move.piece.downcase] possibilities = [] file, rank = destination_coords moves.each do |i, j| f = file + i r = rank + j if valid_square?(f, r) && self.board.at(f, r) == move.piece possibilities << [f, r] end end possibilities end
ruby
def move_origins(moves = nil) moves ||= MOVES[move.piece.downcase] possibilities = [] file, rank = destination_coords moves.each do |i, j| f = file + i r = rank + j if valid_square?(f, r) && self.board.at(f, r) == move.piece possibilities << [f, r] end end possibilities end
[ "def", "move_origins", "(", "moves", "=", "nil", ")", "moves", "||=", "MOVES", "[", "move", ".", "piece", ".", "downcase", "]", "possibilities", "=", "[", "]", "file", ",", "rank", "=", "destination_coords", "moves", ".", "each", "do", "|", "i", ",", "j", "|", "f", "=", "file", "+", "i", "r", "=", "rank", "+", "j", "if", "valid_square?", "(", "f", ",", "r", ")", "&&", "self", ".", "board", ".", "at", "(", "f", ",", "r", ")", "==", "move", ".", "piece", "possibilities", "<<", "[", "f", ",", "r", "]", "end", "end", "possibilities", "end" ]
From the destination square, make each move. If it is a valid square and matches the moving piece, add it to the list of origin possibilities.
[ "From", "the", "destination", "square", "make", "each", "move", ".", "If", "it", "is", "a", "valid", "square", "and", "matches", "the", "moving", "piece", "add", "it", "to", "the", "list", "of", "origin", "possibilities", "." ]
d7e3a0839bbf7e4216409b419bd85f171a840c87
https://github.com/capicue/pgn/blob/d7e3a0839bbf7e4216409b419bd85f171a840c87/lib/pgn/move_calculator.rb#L218-L233
train
capicue/pgn
lib/pgn/move_calculator.rb
PGN.MoveCalculator.pawn_origins
def pawn_origins _, rank = destination_coords double_rank = (rank == 3 && self.move.white?) || (rank == 4 && self.move.black?) pawn_moves = PAWN_MOVES[self.move.piece] moves = self.move.capture ? pawn_moves[:capture] : pawn_moves[:normal] moves += pawn_moves[:double] if double_rank move_origins(moves) end
ruby
def pawn_origins _, rank = destination_coords double_rank = (rank == 3 && self.move.white?) || (rank == 4 && self.move.black?) pawn_moves = PAWN_MOVES[self.move.piece] moves = self.move.capture ? pawn_moves[:capture] : pawn_moves[:normal] moves += pawn_moves[:double] if double_rank move_origins(moves) end
[ "def", "pawn_origins", "_", ",", "rank", "=", "destination_coords", "double_rank", "=", "(", "rank", "==", "3", "&&", "self", ".", "move", ".", "white?", ")", "||", "(", "rank", "==", "4", "&&", "self", ".", "move", ".", "black?", ")", "pawn_moves", "=", "PAWN_MOVES", "[", "self", ".", "move", ".", "piece", "]", "moves", "=", "self", ".", "move", ".", "capture", "?", "pawn_moves", "[", ":capture", "]", ":", "pawn_moves", "[", ":normal", "]", "moves", "+=", "pawn_moves", "[", ":double", "]", "if", "double_rank", "move_origins", "(", "moves", ")", "end" ]
Computes the possbile pawn origins based on the destination square and whether or not the move is a capture.
[ "Computes", "the", "possbile", "pawn", "origins", "based", "on", "the", "destination", "square", "and", "whether", "or", "not", "the", "move", "is", "a", "capture", "." ]
d7e3a0839bbf7e4216409b419bd85f171a840c87
https://github.com/capicue/pgn/blob/d7e3a0839bbf7e4216409b419bd85f171a840c87/lib/pgn/move_calculator.rb#L238-L248
train
capicue/pgn
lib/pgn/move_calculator.rb
PGN.MoveCalculator.disambiguate_san
def disambiguate_san(possibilities) move.disambiguation ? possibilities.select {|p| self.board.position_for(p).match(move.disambiguation) } : possibilities end
ruby
def disambiguate_san(possibilities) move.disambiguation ? possibilities.select {|p| self.board.position_for(p).match(move.disambiguation) } : possibilities end
[ "def", "disambiguate_san", "(", "possibilities", ")", "move", ".", "disambiguation", "?", "possibilities", ".", "select", "{", "|", "p", "|", "self", ".", "board", ".", "position_for", "(", "p", ")", ".", "match", "(", "move", ".", "disambiguation", ")", "}", ":", "possibilities", "end" ]
Try to disambiguate based on the standard algebraic notation.
[ "Try", "to", "disambiguate", "based", "on", "the", "standard", "algebraic", "notation", "." ]
d7e3a0839bbf7e4216409b419bd85f171a840c87
https://github.com/capicue/pgn/blob/d7e3a0839bbf7e4216409b419bd85f171a840c87/lib/pgn/move_calculator.rb#L260-L264
train
capicue/pgn
lib/pgn/move_calculator.rb
PGN.MoveCalculator.disambiguate_pawns
def disambiguate_pawns(possibilities) self.move.piece.match(/p/i) && !self.move.capture ? possibilities.reject {|p| self.board.position_for(p).match(/2|7/) } : possibilities end
ruby
def disambiguate_pawns(possibilities) self.move.piece.match(/p/i) && !self.move.capture ? possibilities.reject {|p| self.board.position_for(p).match(/2|7/) } : possibilities end
[ "def", "disambiguate_pawns", "(", "possibilities", ")", "self", ".", "move", ".", "piece", ".", "match", "(", "/", "/i", ")", "&&", "!", "self", ".", "move", ".", "capture", "?", "possibilities", ".", "reject", "{", "|", "p", "|", "self", ".", "board", ".", "position_for", "(", "p", ")", ".", "match", "(", "/", "/", ")", "}", ":", "possibilities", "end" ]
A pawn can't move two spaces if there is a pawn in front of it.
[ "A", "pawn", "can", "t", "move", "two", "spaces", "if", "there", "is", "a", "pawn", "in", "front", "of", "it", "." ]
d7e3a0839bbf7e4216409b419bd85f171a840c87
https://github.com/capicue/pgn/blob/d7e3a0839bbf7e4216409b419bd85f171a840c87/lib/pgn/move_calculator.rb#L268-L272
train
capicue/pgn
lib/pgn/move_calculator.rb
PGN.MoveCalculator.disambiguate_discovered_check
def disambiguate_discovered_check(possibilities) DIRECTIONS.each do |attacking_piece, directions| attacking_piece = attacking_piece.upcase if self.move.black? directions.each do |dir| piece, square = first_piece(king_position, dir) next unless piece == self.move.piece && possibilities.include?(square) piece, _ = first_piece(square, dir) possibilities.reject! {|p| p == square } if piece == attacking_piece end end possibilities end
ruby
def disambiguate_discovered_check(possibilities) DIRECTIONS.each do |attacking_piece, directions| attacking_piece = attacking_piece.upcase if self.move.black? directions.each do |dir| piece, square = first_piece(king_position, dir) next unless piece == self.move.piece && possibilities.include?(square) piece, _ = first_piece(square, dir) possibilities.reject! {|p| p == square } if piece == attacking_piece end end possibilities end
[ "def", "disambiguate_discovered_check", "(", "possibilities", ")", "DIRECTIONS", ".", "each", "do", "|", "attacking_piece", ",", "directions", "|", "attacking_piece", "=", "attacking_piece", ".", "upcase", "if", "self", ".", "move", ".", "black?", "directions", ".", "each", "do", "|", "dir", "|", "piece", ",", "square", "=", "first_piece", "(", "king_position", ",", "dir", ")", "next", "unless", "piece", "==", "self", ".", "move", ".", "piece", "&&", "possibilities", ".", "include?", "(", "square", ")", "piece", ",", "_", "=", "first_piece", "(", "square", ",", "dir", ")", "possibilities", ".", "reject!", "{", "|", "p", "|", "p", "==", "square", "}", "if", "piece", "==", "attacking_piece", "end", "end", "possibilities", "end" ]
A piece can't move if it would result in a discovered check.
[ "A", "piece", "can", "t", "move", "if", "it", "would", "result", "in", "a", "discovered", "check", "." ]
d7e3a0839bbf7e4216409b419bd85f171a840c87
https://github.com/capicue/pgn/blob/d7e3a0839bbf7e4216409b419bd85f171a840c87/lib/pgn/move_calculator.rb#L276-L290
train
capicue/pgn
lib/pgn/move_calculator.rb
PGN.MoveCalculator.en_passant_capture
def en_passant_capture return nil if self.move.castle if !self.board.at(self.move.destination) && self.move.capture self.move.destination[0] + self.origin[1] end end
ruby
def en_passant_capture return nil if self.move.castle if !self.board.at(self.move.destination) && self.move.capture self.move.destination[0] + self.origin[1] end end
[ "def", "en_passant_capture", "return", "nil", "if", "self", ".", "move", ".", "castle", "if", "!", "self", ".", "board", ".", "at", "(", "self", ".", "move", ".", "destination", ")", "&&", "self", ".", "move", ".", "capture", "self", ".", "move", ".", "destination", "[", "0", "]", "+", "self", ".", "origin", "[", "1", "]", "end", "end" ]
If the move is a capture and there is no piece on the destination square, it must be an en passant capture.
[ "If", "the", "move", "is", "a", "capture", "and", "there", "is", "no", "piece", "on", "the", "destination", "square", "it", "must", "be", "an", "en", "passant", "capture", "." ]
d7e3a0839bbf7e4216409b419bd85f171a840c87
https://github.com/capicue/pgn/blob/d7e3a0839bbf7e4216409b419bd85f171a840c87/lib/pgn/move_calculator.rb#L308-L314
train
mwunsch/weary
lib/weary/request.rb
Weary.Request.call
def call(environment) app = adapter.new middlewares = @middlewares || [] stack = Rack::Builder.new do middlewares.each do |middleware| klass, *args = middleware use klass, *args[0...-1].flatten, &args.last end run app end stack.call rack_env_defaults.merge(environment.update(env)) end
ruby
def call(environment) app = adapter.new middlewares = @middlewares || [] stack = Rack::Builder.new do middlewares.each do |middleware| klass, *args = middleware use klass, *args[0...-1].flatten, &args.last end run app end stack.call rack_env_defaults.merge(environment.update(env)) end
[ "def", "call", "(", "environment", ")", "app", "=", "adapter", ".", "new", "middlewares", "=", "@middlewares", "||", "[", "]", "stack", "=", "Rack", "::", "Builder", ".", "new", "do", "middlewares", ".", "each", "do", "|", "middleware", "|", "klass", ",", "*", "args", "=", "middleware", "use", "klass", ",", "*", "args", "[", "0", "...", "-", "1", "]", ".", "flatten", ",", "&", "args", ".", "last", "end", "run", "app", "end", "stack", ".", "call", "rack_env_defaults", ".", "merge", "(", "environment", ".", "update", "(", "env", ")", ")", "end" ]
A Rack interface for the Request. Applies itself and whatever middlewares to the env and passes the new env into the adapter. environment - A Hash for the Rack env. Returns an Array of three items; a Rack tuple.
[ "A", "Rack", "interface", "for", "the", "Request", ".", "Applies", "itself", "and", "whatever", "middlewares", "to", "the", "env", "and", "passes", "the", "new", "env", "into", "the", "adapter", "." ]
e36ce4f82d83cbc3d826eaa427acc5e66a0f849b
https://github.com/mwunsch/weary/blob/e36ce4f82d83cbc3d826eaa427acc5e66a0f849b/lib/weary/request.rb#L42-L53
train
mwunsch/weary
lib/weary/request.rb
Weary.Request.perform
def perform future do status, headers, body = call(rack_env_defaults) response = Weary::Response.new body, status, headers yield response if block_given? response end end
ruby
def perform future do status, headers, body = call(rack_env_defaults) response = Weary::Response.new body, status, headers yield response if block_given? response end end
[ "def", "perform", "future", "do", "status", ",", "headers", ",", "body", "=", "call", "(", "rack_env_defaults", ")", "response", "=", "Weary", "::", "Response", ".", "new", "body", ",", "status", ",", "headers", "yield", "response", "if", "block_given?", "response", "end", "end" ]
Returns a future-wrapped Response.
[ "Returns", "a", "future", "-", "wrapped", "Response", "." ]
e36ce4f82d83cbc3d826eaa427acc5e66a0f849b
https://github.com/mwunsch/weary/blob/e36ce4f82d83cbc3d826eaa427acc5e66a0f849b/lib/weary/request.rb#L115-L122
train
mwunsch/weary
lib/weary/request.rb
Weary.Request.query_params_from_hash
def query_params_from_hash(value, prefix = nil) case value when Array value.map { |v| query_params_from_hash(v, "#{prefix}%5B%5D") }.join("&") when Hash value.map { |k, v| query_params_from_hash(v, prefix ? "#{prefix}%5B#{Rack::Utils.escape_path(k)}%5D" : Rack::Utils.escape_path(k)) }.join("&") when NilClass prefix else raise ArgumentError, "value must be a Hash" if prefix.nil? "#{prefix}=#{Rack::Utils.escape_path(value)}" end end
ruby
def query_params_from_hash(value, prefix = nil) case value when Array value.map { |v| query_params_from_hash(v, "#{prefix}%5B%5D") }.join("&") when Hash value.map { |k, v| query_params_from_hash(v, prefix ? "#{prefix}%5B#{Rack::Utils.escape_path(k)}%5D" : Rack::Utils.escape_path(k)) }.join("&") when NilClass prefix else raise ArgumentError, "value must be a Hash" if prefix.nil? "#{prefix}=#{Rack::Utils.escape_path(value)}" end end
[ "def", "query_params_from_hash", "(", "value", ",", "prefix", "=", "nil", ")", "case", "value", "when", "Array", "value", ".", "map", "{", "|", "v", "|", "query_params_from_hash", "(", "v", ",", "\"#{prefix}%5B%5D\"", ")", "}", ".", "join", "(", "\"&\"", ")", "when", "Hash", "value", ".", "map", "{", "|", "k", ",", "v", "|", "query_params_from_hash", "(", "v", ",", "prefix", "?", "\"#{prefix}%5B#{Rack::Utils.escape_path(k)}%5D\"", ":", "Rack", "::", "Utils", ".", "escape_path", "(", "k", ")", ")", "}", ".", "join", "(", "\"&\"", ")", "when", "NilClass", "prefix", "else", "raise", "ArgumentError", ",", "\"value must be a Hash\"", "if", "prefix", ".", "nil?", "\"#{prefix}=#{Rack::Utils.escape_path(value)}\"", "end", "end" ]
Stolen from Faraday
[ "Stolen", "from", "Faraday" ]
e36ce4f82d83cbc3d826eaa427acc5e66a0f849b
https://github.com/mwunsch/weary/blob/e36ce4f82d83cbc3d826eaa427acc5e66a0f849b/lib/weary/request.rb#L127-L141
train
meplato/sapoci
lib/sapoci/document.rb
SAPOCI.Document.to_html
def to_html(options = {}) html = [] self.items.each do |item| html << item.to_html(options) end html.join end
ruby
def to_html(options = {}) html = [] self.items.each do |item| html << item.to_html(options) end html.join end
[ "def", "to_html", "(", "options", "=", "{", "}", ")", "html", "=", "[", "]", "self", ".", "items", ".", "each", "do", "|", "item", "|", "html", "<<", "item", ".", "to_html", "(", "options", ")", "end", "html", ".", "join", "end" ]
Returns all +items+ as HTML hidden field tags.
[ "Returns", "all", "+", "items", "+", "as", "HTML", "hidden", "field", "tags", "." ]
013f6b141d1697f45af624ffbcdc0f1779f9783c
https://github.com/meplato/sapoci/blob/013f6b141d1697f45af624ffbcdc0f1779f9783c/lib/sapoci/document.rb#L44-L50
train
ticketevolution/ticketevolution-ruby
lib/ticket_evolution/affiliate_commissions.rb
TicketEvolution.AffiliateCommissions.find_by_office_order
def find_by_office_order(office_id, order_link_id, params=nil) request(:GET, "/#{office_id}/orders/#{order_link_id}", params) do |response| singular_class.new(response.body.merge({ :status_code => response.response_code, :server_message => response.server_message, :connection => response.body[:connection] })) end end
ruby
def find_by_office_order(office_id, order_link_id, params=nil) request(:GET, "/#{office_id}/orders/#{order_link_id}", params) do |response| singular_class.new(response.body.merge({ :status_code => response.response_code, :server_message => response.server_message, :connection => response.body[:connection] })) end end
[ "def", "find_by_office_order", "(", "office_id", ",", "order_link_id", ",", "params", "=", "nil", ")", "request", "(", ":GET", ",", "\"/#{office_id}/orders/#{order_link_id}\"", ",", "params", ")", "do", "|", "response", "|", "singular_class", ".", "new", "(", "response", ".", "body", ".", "merge", "(", "{", ":status_code", "=>", "response", ".", "response_code", ",", ":server_message", "=>", "response", ".", "server_message", ",", ":connection", "=>", "response", ".", "body", "[", ":connection", "]", "}", ")", ")", "end", "end" ]
Find affiliate commission of the office at the time the order was created
[ "Find", "affiliate", "commission", "of", "the", "office", "at", "the", "time", "the", "order", "was", "created" ]
8666c645144ceaf546236b3977c665b3191a483e
https://github.com/ticketevolution/ticketevolution-ruby/blob/8666c645144ceaf546236b3977c665b3191a483e/lib/ticket_evolution/affiliate_commissions.rb#L8-L16
train
capicue/pgn
lib/pgn/game.rb
PGN.Game.play
def play index = 0 hist = Array.new(3, "") loop do puts "\e[H\e[2J" puts self.positions[index].inspect hist[0..2] = (hist[1..2] << STDIN.getch) case hist.join when LEFT index -= 1 if index > 0 when RIGHT index += 1 if index < self.moves.length when EXIT break end end end
ruby
def play index = 0 hist = Array.new(3, "") loop do puts "\e[H\e[2J" puts self.positions[index].inspect hist[0..2] = (hist[1..2] << STDIN.getch) case hist.join when LEFT index -= 1 if index > 0 when RIGHT index += 1 if index < self.moves.length when EXIT break end end end
[ "def", "play", "index", "=", "0", "hist", "=", "Array", ".", "new", "(", "3", ",", "\"\"", ")", "loop", "do", "puts", "\"\\e[H\\e[2J\"", "puts", "self", ".", "positions", "[", "index", "]", ".", "inspect", "hist", "[", "0", "..", "2", "]", "=", "(", "hist", "[", "1", "..", "2", "]", "<<", "STDIN", ".", "getch", ")", "case", "hist", ".", "join", "when", "LEFT", "index", "-=", "1", "if", "index", ">", "0", "when", "RIGHT", "index", "+=", "1", "if", "index", "<", "self", ".", "moves", ".", "length", "when", "EXIT", "break", "end", "end", "end" ]
Interactively step through the game Use +d+ to move forward, +a+ to move backward, and +^C+ to exit.
[ "Interactively", "step", "through", "the", "game" ]
d7e3a0839bbf7e4216409b419bd85f171a840c87
https://github.com/capicue/pgn/blob/d7e3a0839bbf7e4216409b419bd85f171a840c87/lib/pgn/game.rb#L116-L134
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.url_to_animation
def url_to_animation(url, options = nil) if options == nil options = AnimationOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLGet + "takeanimation.ashx", false, options, url) return nil end
ruby
def url_to_animation(url, options = nil) if options == nil options = AnimationOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLGet + "takeanimation.ashx", false, options, url) return nil end
[ "def", "url_to_animation", "(", "url", ",", "options", "=", "nil", ")", "if", "options", "==", "nil", "options", "=", "AnimationOptions", ".", "new", "(", ")", "end", "@request", "=", "Request", ".", "new", "(", "@protocol", "+", "WebServicesBaseURLGet", "+", "\"takeanimation.ashx\"", ",", "false", ",", "options", ",", "url", ")", "return", "nil", "end" ]
Create a new instance of the Client class in order to access the GrabzIt API. @param applicationKey [String] your application key @param applicationSecret [String] your application secret @see http://grabz.it/register.aspx You can get an application key and secret by registering for free with GrabzIt This method specifies the URL of the online video that should be converted into a animated GIF @param url [String] The URL of the video to convert into a animated GIF @param options [AnimationOptions, nil] a instance of the AnimationOptions class that defines any special options to use when creating the animated GIF @return [void]
[ "Create", "a", "new", "instance", "of", "the", "Client", "class", "in", "order", "to", "access", "the", "GrabzIt", "API", "." ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L69-L77
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.url_to_image
def url_to_image(url, options = nil) if options == nil options = ImageOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLGet + TakePicture, false, options, url) return nil end
ruby
def url_to_image(url, options = nil) if options == nil options = ImageOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLGet + TakePicture, false, options, url) return nil end
[ "def", "url_to_image", "(", "url", ",", "options", "=", "nil", ")", "if", "options", "==", "nil", "options", "=", "ImageOptions", ".", "new", "(", ")", "end", "@request", "=", "Request", ".", "new", "(", "@protocol", "+", "WebServicesBaseURLGet", "+", "TakePicture", ",", "false", ",", "options", ",", "url", ")", "return", "nil", "end" ]
This method specifies the URL that should be converted into a image screenshot @param url [String] the URL to capture as a screenshot @param options [ImageOptions, nil] a instance of the ImageOptions class that defines any special options to use when creating the screenshot @return [void]
[ "This", "method", "specifies", "the", "URL", "that", "should", "be", "converted", "into", "a", "image", "screenshot" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L84-L92
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.html_to_image
def html_to_image(html, options = nil) if options == nil options = ImageOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLPost + TakePicture, true, options, html) return nil end
ruby
def html_to_image(html, options = nil) if options == nil options = ImageOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLPost + TakePicture, true, options, html) return nil end
[ "def", "html_to_image", "(", "html", ",", "options", "=", "nil", ")", "if", "options", "==", "nil", "options", "=", "ImageOptions", ".", "new", "(", ")", "end", "@request", "=", "Request", ".", "new", "(", "@protocol", "+", "WebServicesBaseURLPost", "+", "TakePicture", ",", "true", ",", "options", ",", "html", ")", "return", "nil", "end" ]
This method specifies the HTML that should be converted into a image @param html [String] the HTML to convert into a image @param options [ImageOptions, nil] a instance of the ImageOptions class that defines any special options to use when creating the image @return [void]
[ "This", "method", "specifies", "the", "HTML", "that", "should", "be", "converted", "into", "a", "image" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L99-L107
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.url_to_table
def url_to_table(url, options = nil) if options == nil options = TableOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLGet + TakeTable, false, options, url) return nil end
ruby
def url_to_table(url, options = nil) if options == nil options = TableOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLGet + TakeTable, false, options, url) return nil end
[ "def", "url_to_table", "(", "url", ",", "options", "=", "nil", ")", "if", "options", "==", "nil", "options", "=", "TableOptions", ".", "new", "(", ")", "end", "@request", "=", "Request", ".", "new", "(", "@protocol", "+", "WebServicesBaseURLGet", "+", "TakeTable", ",", "false", ",", "options", ",", "url", ")", "return", "nil", "end" ]
This method specifies the URL that the HTML tables should be extracted from @param url [String] the URL to extract HTML tables from @param options [TableOptions, nil] a instance of the TableOptions class that defines any special options to use when converting the HTML table @return [void]
[ "This", "method", "specifies", "the", "URL", "that", "the", "HTML", "tables", "should", "be", "extracted", "from" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L123-L131
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.html_to_table
def html_to_table(html, options = nil) if options == nil options = TableOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLPost + TakeTable, true, options, html) return nil end
ruby
def html_to_table(html, options = nil) if options == nil options = TableOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLPost + TakeTable, true, options, html) return nil end
[ "def", "html_to_table", "(", "html", ",", "options", "=", "nil", ")", "if", "options", "==", "nil", "options", "=", "TableOptions", ".", "new", "(", ")", "end", "@request", "=", "Request", ".", "new", "(", "@protocol", "+", "WebServicesBaseURLPost", "+", "TakeTable", ",", "true", ",", "options", ",", "html", ")", "return", "nil", "end" ]
This method specifies the HTML that the HTML tables should be extracted from @param html [String] the HTML to extract HTML tables from @param options [TableOptions, nil] a instance of the TableOptions class that defines any special options to use when converting the HTML table @return [void]
[ "This", "method", "specifies", "the", "HTML", "that", "the", "HTML", "tables", "should", "be", "extracted", "from" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L138-L146
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.url_to_pdf
def url_to_pdf(url, options = nil) if options == nil options = PDFOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLGet + TakePDF, false, options, url) return nil end
ruby
def url_to_pdf(url, options = nil) if options == nil options = PDFOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLGet + TakePDF, false, options, url) return nil end
[ "def", "url_to_pdf", "(", "url", ",", "options", "=", "nil", ")", "if", "options", "==", "nil", "options", "=", "PDFOptions", ".", "new", "(", ")", "end", "@request", "=", "Request", ".", "new", "(", "@protocol", "+", "WebServicesBaseURLGet", "+", "TakePDF", ",", "false", ",", "options", ",", "url", ")", "return", "nil", "end" ]
This method specifies the URL that should be converted into a PDF @param url [String] the URL to capture as a PDF @param options [PDFOptions, nil] a instance of the PDFOptions class that defines any special options to use when creating the PDF @return [void]
[ "This", "method", "specifies", "the", "URL", "that", "should", "be", "converted", "into", "a", "PDF" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L162-L170
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.html_to_pdf
def html_to_pdf(html, options = nil) if options == nil options = PDFOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLPost + TakePDF, true, options, html) return nil end
ruby
def html_to_pdf(html, options = nil) if options == nil options = PDFOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLPost + TakePDF, true, options, html) return nil end
[ "def", "html_to_pdf", "(", "html", ",", "options", "=", "nil", ")", "if", "options", "==", "nil", "options", "=", "PDFOptions", ".", "new", "(", ")", "end", "@request", "=", "Request", ".", "new", "(", "@protocol", "+", "WebServicesBaseURLPost", "+", "TakePDF", ",", "true", ",", "options", ",", "html", ")", "return", "nil", "end" ]
This method specifies the HTML that should be converted into a PDF @param html [String] the HTML to convert into a PDF @param options [PDFOptions, nil] a instance of the PDFOptions class that defines any special options to use when creating the PDF @return [void]
[ "This", "method", "specifies", "the", "HTML", "that", "should", "be", "converted", "into", "a", "PDF" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L177-L185
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.url_to_docx
def url_to_docx(url, options = nil) if options == nil options = DOCXOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLGet + TakeDOCX, false, options, url) return nil end
ruby
def url_to_docx(url, options = nil) if options == nil options = DOCXOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLGet + TakeDOCX, false, options, url) return nil end
[ "def", "url_to_docx", "(", "url", ",", "options", "=", "nil", ")", "if", "options", "==", "nil", "options", "=", "DOCXOptions", ".", "new", "(", ")", "end", "@request", "=", "Request", ".", "new", "(", "@protocol", "+", "WebServicesBaseURLGet", "+", "TakeDOCX", ",", "false", ",", "options", ",", "url", ")", "return", "nil", "end" ]
This method specifies the URL that should be converted into a DOCX @param url [String] the URL to capture as a DOCX @param options [DOCXOptions, nil] a instance of the DOCXOptions class that defines any special options to use when creating the DOCX @return [void]
[ "This", "method", "specifies", "the", "URL", "that", "should", "be", "converted", "into", "a", "DOCX" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L201-L209
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.html_to_docx
def html_to_docx(html, options = nil) if options == nil options = DOCXOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLPost + TakeDOCX, true, options, html) return nil end
ruby
def html_to_docx(html, options = nil) if options == nil options = DOCXOptions.new() end @request = Request.new(@protocol + WebServicesBaseURLPost + TakeDOCX, true, options, html) return nil end
[ "def", "html_to_docx", "(", "html", ",", "options", "=", "nil", ")", "if", "options", "==", "nil", "options", "=", "DOCXOptions", ".", "new", "(", ")", "end", "@request", "=", "Request", ".", "new", "(", "@protocol", "+", "WebServicesBaseURLPost", "+", "TakeDOCX", ",", "true", ",", "options", ",", "html", ")", "return", "nil", "end" ]
This method specifies the HTML that should be converted into a DOCX @param html [String] the HTML to convert into a DOCX @param options [DOCXOptions, nil] a instance of the DOCXOptions class that defines any special options to use when creating the DOCX @return [void]
[ "This", "method", "specifies", "the", "HTML", "that", "should", "be", "converted", "into", "a", "DOCX" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L216-L224
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.save
def save(callBackURL = nil) if @request == nil raise GrabzItException.new("No parameters have been set.", GrabzItException::PARAMETER_MISSING_PARAMETERS) end sig = encode(@request.options()._getSignatureString(GrabzIt::Utility.nil_check(@applicationSecret), callBackURL, @request.getTargetUrl())) data = take(sig, callBackURL) if data == nil || data == "" data = take(sig, callBackURL) end if data == nil || data == "" raise GrabzItException.new("An unknown network error occurred, please try calling this method again.", GrabzItException::NETWORK_GENERAL_ERROR) end return get_result_value(data, "ID") end
ruby
def save(callBackURL = nil) if @request == nil raise GrabzItException.new("No parameters have been set.", GrabzItException::PARAMETER_MISSING_PARAMETERS) end sig = encode(@request.options()._getSignatureString(GrabzIt::Utility.nil_check(@applicationSecret), callBackURL, @request.getTargetUrl())) data = take(sig, callBackURL) if data == nil || data == "" data = take(sig, callBackURL) end if data == nil || data == "" raise GrabzItException.new("An unknown network error occurred, please try calling this method again.", GrabzItException::NETWORK_GENERAL_ERROR) end return get_result_value(data, "ID") end
[ "def", "save", "(", "callBackURL", "=", "nil", ")", "if", "@request", "==", "nil", "raise", "GrabzItException", ".", "new", "(", "\"No parameters have been set.\"", ",", "GrabzItException", "::", "PARAMETER_MISSING_PARAMETERS", ")", "end", "sig", "=", "encode", "(", "@request", ".", "options", "(", ")", ".", "_getSignatureString", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "@applicationSecret", ")", ",", "callBackURL", ",", "@request", ".", "getTargetUrl", "(", ")", ")", ")", "data", "=", "take", "(", "sig", ",", "callBackURL", ")", "if", "data", "==", "nil", "||", "data", "==", "\"\"", "data", "=", "take", "(", "sig", ",", "callBackURL", ")", "end", "if", "data", "==", "nil", "||", "data", "==", "\"\"", "raise", "GrabzItException", ".", "new", "(", "\"An unknown network error occurred, please try calling this method again.\"", ",", "GrabzItException", "::", "NETWORK_GENERAL_ERROR", ")", "end", "return", "get_result_value", "(", "data", ",", "\"ID\"", ")", "end" ]
Calls the GrabzIt web service to take the screenshot The handler will be passed a URL with the following query string parameters: - message (is any error message associated with the screenshot) - customId (is a custom id you may have specified in the [AnimationOptions], [ImageOptions], [PDFOptions] or [TableOptions] classes) - id (is the unique id of the screenshot which can be used to retrieve the screenshot with the {#get_result} method) - filename (is the filename of the screenshot) - format (is the format of the screenshot) @note This is the recommended method of saving a screenshot @param callBackURL [String, nil] the handler the GrabzIt web service should call after it has completed its work @return [String] the unique identifier of the screenshot. This can be used to get the screenshot with the {#get_result} method @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
[ "Calls", "the", "GrabzIt", "web", "service", "to", "take", "the", "screenshot" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L247-L265
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.save_to
def save_to(saveToFile = nil) id = save() if id == nil || id == "" return false end #Wait for it to be possibly ready sleep((@request.options().startDelay() / 1000) + 3) #Wait for it to be ready. while true do status = get_status(id) if !status.cached && !status.processing raise GrabzItException.new("The capture did not complete with the error: " + status.message, GrabzItException::RENDERING_ERROR) break elsif status.cached result = get_result(id) if !result raise GrabzItException.new("The capture could not be found on GrabzIt.", GrabzItException::RENDERING_MISSING_SCREENSHOT) break end if saveToFile == nil || saveToFile == "" return result end screenshot = File.new(saveToFile, "wb") screenshot.write(result) screenshot.close break end sleep(3) end return true end
ruby
def save_to(saveToFile = nil) id = save() if id == nil || id == "" return false end #Wait for it to be possibly ready sleep((@request.options().startDelay() / 1000) + 3) #Wait for it to be ready. while true do status = get_status(id) if !status.cached && !status.processing raise GrabzItException.new("The capture did not complete with the error: " + status.message, GrabzItException::RENDERING_ERROR) break elsif status.cached result = get_result(id) if !result raise GrabzItException.new("The capture could not be found on GrabzIt.", GrabzItException::RENDERING_MISSING_SCREENSHOT) break end if saveToFile == nil || saveToFile == "" return result end screenshot = File.new(saveToFile, "wb") screenshot.write(result) screenshot.close break end sleep(3) end return true end
[ "def", "save_to", "(", "saveToFile", "=", "nil", ")", "id", "=", "save", "(", ")", "if", "id", "==", "nil", "||", "id", "==", "\"\"", "return", "false", "end", "sleep", "(", "(", "@request", ".", "options", "(", ")", ".", "startDelay", "(", ")", "/", "1000", ")", "+", "3", ")", "while", "true", "do", "status", "=", "get_status", "(", "id", ")", "if", "!", "status", ".", "cached", "&&", "!", "status", ".", "processing", "raise", "GrabzItException", ".", "new", "(", "\"The capture did not complete with the error: \"", "+", "status", ".", "message", ",", "GrabzItException", "::", "RENDERING_ERROR", ")", "break", "elsif", "status", ".", "cached", "result", "=", "get_result", "(", "id", ")", "if", "!", "result", "raise", "GrabzItException", ".", "new", "(", "\"The capture could not be found on GrabzIt.\"", ",", "GrabzItException", "::", "RENDERING_MISSING_SCREENSHOT", ")", "break", "end", "if", "saveToFile", "==", "nil", "||", "saveToFile", "==", "\"\"", "return", "result", "end", "screenshot", "=", "File", ".", "new", "(", "saveToFile", ",", "\"wb\"", ")", "screenshot", ".", "write", "(", "result", ")", "screenshot", ".", "close", "break", "end", "sleep", "(", "3", ")", "end", "return", "true", "end" ]
Calls the GrabzIt web service to take the screenshot and saves it to the target path provided. if no target path is provided it returns the screenshot byte data. @note Warning, this is a SYNCHONOUS method and can take up to 5 minutes before a response @param saveToFile [String, nil] the file path that the screenshot should saved to. @example Synchronously save the screenshot to test.jpg save_to('images/test.jpg') @raise [RuntimeError] if the screenshot cannot be saved a RuntimeError will be raised that will contain an explanation @return [Boolean] returns the true if it is successfully saved to a file, otherwise if a target path is not provided it returns the screenshot's byte data.
[ "Calls", "the", "GrabzIt", "web", "service", "to", "take", "the", "screenshot", "and", "saves", "it", "to", "the", "target", "path", "provided", ".", "if", "no", "target", "path", "is", "provided", "it", "returns", "the", "screenshot", "byte", "data", "." ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L276-L315
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.get_status
def get_status(id) if id == nil || id == "" return nil end result = get(@protocol + WebServicesBaseURLGet + "getstatus.ashx?id=" + GrabzIt::Utility.nil_check(id)) doc = REXML::Document.new(result) processing = doc.root.elements["Processing"].text() cached = doc.root.elements["Cached"].text() expired = doc.root.elements["Expired"].text() message = doc.root.elements["Message"].text() return ScreenShotStatus.new((processing == TrueString), (cached == TrueString), (expired == TrueString), message) end
ruby
def get_status(id) if id == nil || id == "" return nil end result = get(@protocol + WebServicesBaseURLGet + "getstatus.ashx?id=" + GrabzIt::Utility.nil_check(id)) doc = REXML::Document.new(result) processing = doc.root.elements["Processing"].text() cached = doc.root.elements["Cached"].text() expired = doc.root.elements["Expired"].text() message = doc.root.elements["Message"].text() return ScreenShotStatus.new((processing == TrueString), (cached == TrueString), (expired == TrueString), message) end
[ "def", "get_status", "(", "id", ")", "if", "id", "==", "nil", "||", "id", "==", "\"\"", "return", "nil", "end", "result", "=", "get", "(", "@protocol", "+", "WebServicesBaseURLGet", "+", "\"getstatus.ashx?id=\"", "+", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "id", ")", ")", "doc", "=", "REXML", "::", "Document", ".", "new", "(", "result", ")", "processing", "=", "doc", ".", "root", ".", "elements", "[", "\"Processing\"", "]", ".", "text", "(", ")", "cached", "=", "doc", ".", "root", ".", "elements", "[", "\"Cached\"", "]", ".", "text", "(", ")", "expired", "=", "doc", ".", "root", ".", "elements", "[", "\"Expired\"", "]", ".", "text", "(", ")", "message", "=", "doc", ".", "root", ".", "elements", "[", "\"Message\"", "]", ".", "text", "(", ")", "return", "ScreenShotStatus", ".", "new", "(", "(", "processing", "==", "TrueString", ")", ",", "(", "cached", "==", "TrueString", ")", ",", "(", "expired", "==", "TrueString", ")", ",", "message", ")", "end" ]
Get the current status of a GrabzIt screenshot @param id [String] the id of the screenshot @return [ScreenShotStatus] a object representing the status of the screenshot
[ "Get", "the", "current", "status", "of", "a", "GrabzIt", "screenshot" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L321-L337
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.get_result
def get_result(id) if id == nil || id == "" return nil end return get(@protocol + WebServicesBaseURLGet + "getfile.ashx?id=" + GrabzIt::Utility.nil_check(id)) end
ruby
def get_result(id) if id == nil || id == "" return nil end return get(@protocol + WebServicesBaseURLGet + "getfile.ashx?id=" + GrabzIt::Utility.nil_check(id)) end
[ "def", "get_result", "(", "id", ")", "if", "id", "==", "nil", "||", "id", "==", "\"\"", "return", "nil", "end", "return", "get", "(", "@protocol", "+", "WebServicesBaseURLGet", "+", "\"getfile.ashx?id=\"", "+", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "id", ")", ")", "end" ]
This method returns the screenshot itself. If nothing is returned then something has gone wrong or the screenshot is not ready yet @param id [String] the id of the screenshot @return [Object] returns the screenshot @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
[ "This", "method", "returns", "the", "screenshot", "itself", ".", "If", "nothing", "is", "returned", "then", "something", "has", "gone", "wrong", "or", "the", "screenshot", "is", "not", "ready", "yet" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L344-L350
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.get_cookies
def get_cookies(domain) sig = encode(GrabzIt::Utility.nil_check(@applicationSecret)+"|"+GrabzIt::Utility.nil_check(domain)) qs = "key=" qs.concat(CGI.escape(GrabzIt::Utility.nil_check(@applicationKey))) qs.concat("&domain=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(domain))) qs.concat("&sig=") qs.concat(sig) result = get(@protocol + WebServicesBaseURLGet + "getcookies.ashx?" + qs) doc = REXML::Document.new(result) check_for_exception(doc) cookies = Array.new xml_cookies = doc.elements.to_a("//WebResult/Cookies/Cookie") xml_cookies.each do |cookie| expires = nil if cookie.elements["Expires"] != nil expires = cookie.elements["Expires"].text end grabzItCookie = GrabzIt::Cookie.new(cookie.elements["Name"].text, cookie.elements["Domain"].text, cookie.elements["Value"].text, cookie.elements["Path"].text, (cookie.elements["HttpOnly"].text == TrueString), expires, cookie.elements["Type"].text) cookies << grabzItCookie end return cookies end
ruby
def get_cookies(domain) sig = encode(GrabzIt::Utility.nil_check(@applicationSecret)+"|"+GrabzIt::Utility.nil_check(domain)) qs = "key=" qs.concat(CGI.escape(GrabzIt::Utility.nil_check(@applicationKey))) qs.concat("&domain=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(domain))) qs.concat("&sig=") qs.concat(sig) result = get(@protocol + WebServicesBaseURLGet + "getcookies.ashx?" + qs) doc = REXML::Document.new(result) check_for_exception(doc) cookies = Array.new xml_cookies = doc.elements.to_a("//WebResult/Cookies/Cookie") xml_cookies.each do |cookie| expires = nil if cookie.elements["Expires"] != nil expires = cookie.elements["Expires"].text end grabzItCookie = GrabzIt::Cookie.new(cookie.elements["Name"].text, cookie.elements["Domain"].text, cookie.elements["Value"].text, cookie.elements["Path"].text, (cookie.elements["HttpOnly"].text == TrueString), expires, cookie.elements["Type"].text) cookies << grabzItCookie end return cookies end
[ "def", "get_cookies", "(", "domain", ")", "sig", "=", "encode", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "@applicationSecret", ")", "+", "\"|\"", "+", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "domain", ")", ")", "qs", "=", "\"key=\"", "qs", ".", "concat", "(", "CGI", ".", "escape", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "@applicationKey", ")", ")", ")", "qs", ".", "concat", "(", "\"&domain=\"", ")", "qs", ".", "concat", "(", "CGI", ".", "escape", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "domain", ")", ")", ")", "qs", ".", "concat", "(", "\"&sig=\"", ")", "qs", ".", "concat", "(", "sig", ")", "result", "=", "get", "(", "@protocol", "+", "WebServicesBaseURLGet", "+", "\"getcookies.ashx?\"", "+", "qs", ")", "doc", "=", "REXML", "::", "Document", ".", "new", "(", "result", ")", "check_for_exception", "(", "doc", ")", "cookies", "=", "Array", ".", "new", "xml_cookies", "=", "doc", ".", "elements", ".", "to_a", "(", "\"//WebResult/Cookies/Cookie\"", ")", "xml_cookies", ".", "each", "do", "|", "cookie", "|", "expires", "=", "nil", "if", "cookie", ".", "elements", "[", "\"Expires\"", "]", "!=", "nil", "expires", "=", "cookie", ".", "elements", "[", "\"Expires\"", "]", ".", "text", "end", "grabzItCookie", "=", "GrabzIt", "::", "Cookie", ".", "new", "(", "cookie", ".", "elements", "[", "\"Name\"", "]", ".", "text", ",", "cookie", ".", "elements", "[", "\"Domain\"", "]", ".", "text", ",", "cookie", ".", "elements", "[", "\"Value\"", "]", ".", "text", ",", "cookie", ".", "elements", "[", "\"Path\"", "]", ".", "text", ",", "(", "cookie", ".", "elements", "[", "\"HttpOnly\"", "]", ".", "text", "==", "TrueString", ")", ",", "expires", ",", "cookie", ".", "elements", "[", "\"Type\"", "]", ".", "text", ")", "cookies", "<<", "grabzItCookie", "end", "return", "cookies", "end" ]
Get all the cookies that GrabzIt is using for a particular domain. This may include your user set cookies as well @param domain [String] the domain to return cookies for @return [Array<Cookie>] an array of cookies @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
[ "Get", "all", "the", "cookies", "that", "GrabzIt", "is", "using", "for", "a", "particular", "domain", ".", "This", "may", "include", "your", "user", "set", "cookies", "as", "well" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L357-L386
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.set_cookie
def set_cookie(name, domain, value = "", path = "/", httponly = false, expires = "") sig = encode(GrabzIt::Utility.nil_check(@applicationSecret)+"|"+GrabzIt::Utility.nil_check(name)+"|"+GrabzIt::Utility.nil_check(domain)+ "|"+GrabzIt::Utility.nil_check(value)+"|"+GrabzIt::Utility.nil_check(path)+"|"+GrabzIt::Utility.b_to_str(httponly)+ "|"+GrabzIt::Utility.nil_check(expires)+"|0") qs = "key=" qs.concat(CGI.escape(GrabzIt::Utility.nil_check(@applicationKey))) qs.concat("&domain=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(domain))) qs.concat("&name=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(name))) qs.concat("&value=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(value))) qs.concat("&path=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(path))) qs.concat("&httponly=") qs.concat(GrabzIt::Utility.b_to_str(httponly)) qs.concat("&expires=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(expires))) qs.concat("&sig=") qs.concat(sig) return (get_result_value(get(@protocol + WebServicesBaseURLGet + "setcookie.ashx?" + qs), "Result") == TrueString) end
ruby
def set_cookie(name, domain, value = "", path = "/", httponly = false, expires = "") sig = encode(GrabzIt::Utility.nil_check(@applicationSecret)+"|"+GrabzIt::Utility.nil_check(name)+"|"+GrabzIt::Utility.nil_check(domain)+ "|"+GrabzIt::Utility.nil_check(value)+"|"+GrabzIt::Utility.nil_check(path)+"|"+GrabzIt::Utility.b_to_str(httponly)+ "|"+GrabzIt::Utility.nil_check(expires)+"|0") qs = "key=" qs.concat(CGI.escape(GrabzIt::Utility.nil_check(@applicationKey))) qs.concat("&domain=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(domain))) qs.concat("&name=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(name))) qs.concat("&value=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(value))) qs.concat("&path=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(path))) qs.concat("&httponly=") qs.concat(GrabzIt::Utility.b_to_str(httponly)) qs.concat("&expires=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(expires))) qs.concat("&sig=") qs.concat(sig) return (get_result_value(get(@protocol + WebServicesBaseURLGet + "setcookie.ashx?" + qs), "Result") == TrueString) end
[ "def", "set_cookie", "(", "name", ",", "domain", ",", "value", "=", "\"\"", ",", "path", "=", "\"/\"", ",", "httponly", "=", "false", ",", "expires", "=", "\"\"", ")", "sig", "=", "encode", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "@applicationSecret", ")", "+", "\"|\"", "+", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "name", ")", "+", "\"|\"", "+", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "domain", ")", "+", "\"|\"", "+", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "value", ")", "+", "\"|\"", "+", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "path", ")", "+", "\"|\"", "+", "GrabzIt", "::", "Utility", ".", "b_to_str", "(", "httponly", ")", "+", "\"|\"", "+", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "expires", ")", "+", "\"|0\"", ")", "qs", "=", "\"key=\"", "qs", ".", "concat", "(", "CGI", ".", "escape", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "@applicationKey", ")", ")", ")", "qs", ".", "concat", "(", "\"&domain=\"", ")", "qs", ".", "concat", "(", "CGI", ".", "escape", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "domain", ")", ")", ")", "qs", ".", "concat", "(", "\"&name=\"", ")", "qs", ".", "concat", "(", "CGI", ".", "escape", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "name", ")", ")", ")", "qs", ".", "concat", "(", "\"&value=\"", ")", "qs", ".", "concat", "(", "CGI", ".", "escape", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "value", ")", ")", ")", "qs", ".", "concat", "(", "\"&path=\"", ")", "qs", ".", "concat", "(", "CGI", ".", "escape", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "path", ")", ")", ")", "qs", ".", "concat", "(", "\"&httponly=\"", ")", "qs", ".", "concat", "(", "GrabzIt", "::", "Utility", ".", "b_to_str", "(", "httponly", ")", ")", "qs", ".", "concat", "(", "\"&expires=\"", ")", "qs", ".", "concat", "(", "CGI", ".", "escape", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "expires", ")", ")", ")", "qs", ".", "concat", "(", "\"&sig=\"", ")", "qs", ".", "concat", "(", "sig", ")", "return", "(", "get_result_value", "(", "get", "(", "@protocol", "+", "WebServicesBaseURLGet", "+", "\"setcookie.ashx?\"", "+", "qs", ")", ",", "\"Result\"", ")", "==", "TrueString", ")", "end" ]
Sets a new custom cookie on GrabzIt, if the custom cookie has the same name and domain as a global cookie the global cookie is overridden @note This can be useful if a websites functionality is controlled by cookies @param name [String] the name of the cookie to set @param domain [String] the domain of the website to set the cookie for @param value [String, ''] the value of the cookie @param path [String, '/'] the website path the cookie relates to @param httponly [Boolean, false] is the cookie only used on HTTP @param expires [String, ''] when the cookie expires. Pass a nil value if it does not expire @return [Boolean] returns true if the cookie was successfully set @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
[ "Sets", "a", "new", "custom", "cookie", "on", "GrabzIt", "if", "the", "custom", "cookie", "has", "the", "same", "name", "and", "domain", "as", "a", "global", "cookie", "the", "global" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L400-L423
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.delete_cookie
def delete_cookie(name, domain) sig = encode(GrabzIt::Utility.nil_check(@applicationSecret)+"|"+GrabzIt::Utility.nil_check(name)+ "|"+GrabzIt::Utility.nil_check(domain)+"|1") qs = "key=" qs.concat(CGI.escape(GrabzIt::Utility.nil_check(@applicationKey))) qs.concat("&domain=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(domain))) qs.concat("&name=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(name))) qs.concat("&delete=1&sig=") qs.concat(sig) return (get_result_value(get(@protocol + WebServicesBaseURLGet + "setcookie.ashx?" + qs), "Result") == TrueString) end
ruby
def delete_cookie(name, domain) sig = encode(GrabzIt::Utility.nil_check(@applicationSecret)+"|"+GrabzIt::Utility.nil_check(name)+ "|"+GrabzIt::Utility.nil_check(domain)+"|1") qs = "key=" qs.concat(CGI.escape(GrabzIt::Utility.nil_check(@applicationKey))) qs.concat("&domain=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(domain))) qs.concat("&name=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(name))) qs.concat("&delete=1&sig=") qs.concat(sig) return (get_result_value(get(@protocol + WebServicesBaseURLGet + "setcookie.ashx?" + qs), "Result") == TrueString) end
[ "def", "delete_cookie", "(", "name", ",", "domain", ")", "sig", "=", "encode", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "@applicationSecret", ")", "+", "\"|\"", "+", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "name", ")", "+", "\"|\"", "+", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "domain", ")", "+", "\"|1\"", ")", "qs", "=", "\"key=\"", "qs", ".", "concat", "(", "CGI", ".", "escape", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "@applicationKey", ")", ")", ")", "qs", ".", "concat", "(", "\"&domain=\"", ")", "qs", ".", "concat", "(", "CGI", ".", "escape", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "domain", ")", ")", ")", "qs", ".", "concat", "(", "\"&name=\"", ")", "qs", ".", "concat", "(", "CGI", ".", "escape", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "name", ")", ")", ")", "qs", ".", "concat", "(", "\"&delete=1&sig=\"", ")", "qs", ".", "concat", "(", "sig", ")", "return", "(", "get_result_value", "(", "get", "(", "@protocol", "+", "WebServicesBaseURLGet", "+", "\"setcookie.ashx?\"", "+", "qs", ")", ",", "\"Result\"", ")", "==", "TrueString", ")", "end" ]
Delete a custom cookie or block a global cookie from being used @param name [String] the name of the cookie to delete @param domain [String] the website the cookie belongs to @return [Boolean] returns true if the cookie was successfully set @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
[ "Delete", "a", "custom", "cookie", "or", "block", "a", "global", "cookie", "from", "being", "used" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L431-L445
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.add_watermark
def add_watermark(identifier, path, xpos, ypos) if !File.file?(path) raise "File: " + path + " does not exist" end sig = encode(GrabzIt::Utility.nil_check(@applicationSecret)+"|"+GrabzIt::Utility.nil_check(identifier)+"|"+GrabzIt::Utility.nil_int_check(xpos)+ "|"+GrabzIt::Utility.nil_int_check(ypos)) boundary = '--------------------------'+Time.now.to_f.to_s url = @protocol + "://grabz.it/services/addwatermark.ashx" uri = URI.parse(url) file = File.open(path, "rb") data = file.read post_body = Array.new post_body << "\r\n--"+boundary+"\r\n" post_body << "Content-Disposition: form-data; name=\"watermark\"; filename=\""+File.basename(path)+"\"\r\nContent-Type: image/jpeg\r\n\r\n" post_body << data post_body << "\r\n--"+boundary+"\r\n" post_body << "Content-Disposition: form-data; name=\"key\"\r\n\r\n" post_body << GrabzIt::Utility.nil_check(@applicationKey) post_body << "\r\n--"+boundary+"\r\n" post_body << "Content-Disposition: form-data; name=\"identifier\"\r\n\r\n" post_body << GrabzIt::Utility.nil_check(identifier) post_body << "\r\n--"+boundary+"\r\n" post_body << "Content-Disposition: form-data; name=\"xpos\"\r\n\r\n" post_body << GrabzIt::Utility.nil_check(xpos) post_body << "\r\n--"+boundary+"\r\n" post_body << "Content-Disposition: form-data; name=\"ypos\"\r\n\r\n" post_body << GrabzIt::Utility.nil_check(ypos) post_body << "\r\n--"+boundary+"\r\n" post_body << "Content-Disposition: form-data; name=\"sig\"\r\n\r\n" post_body << sig post_body << "\r\n--"+boundary+"--\r\n" request = Net::HTTP::Post.new(url) request.content_type = "multipart/form-data, boundary="+boundary request.body = post_body.join caller = Net::HTTP.new(uri.host, uri.port) caller.use_ssl = uri.scheme == 'https' response = caller.start {|http| http.request(request)} response_check(response) return (get_result_value(response.body(), "Result") == TrueString) end
ruby
def add_watermark(identifier, path, xpos, ypos) if !File.file?(path) raise "File: " + path + " does not exist" end sig = encode(GrabzIt::Utility.nil_check(@applicationSecret)+"|"+GrabzIt::Utility.nil_check(identifier)+"|"+GrabzIt::Utility.nil_int_check(xpos)+ "|"+GrabzIt::Utility.nil_int_check(ypos)) boundary = '--------------------------'+Time.now.to_f.to_s url = @protocol + "://grabz.it/services/addwatermark.ashx" uri = URI.parse(url) file = File.open(path, "rb") data = file.read post_body = Array.new post_body << "\r\n--"+boundary+"\r\n" post_body << "Content-Disposition: form-data; name=\"watermark\"; filename=\""+File.basename(path)+"\"\r\nContent-Type: image/jpeg\r\n\r\n" post_body << data post_body << "\r\n--"+boundary+"\r\n" post_body << "Content-Disposition: form-data; name=\"key\"\r\n\r\n" post_body << GrabzIt::Utility.nil_check(@applicationKey) post_body << "\r\n--"+boundary+"\r\n" post_body << "Content-Disposition: form-data; name=\"identifier\"\r\n\r\n" post_body << GrabzIt::Utility.nil_check(identifier) post_body << "\r\n--"+boundary+"\r\n" post_body << "Content-Disposition: form-data; name=\"xpos\"\r\n\r\n" post_body << GrabzIt::Utility.nil_check(xpos) post_body << "\r\n--"+boundary+"\r\n" post_body << "Content-Disposition: form-data; name=\"ypos\"\r\n\r\n" post_body << GrabzIt::Utility.nil_check(ypos) post_body << "\r\n--"+boundary+"\r\n" post_body << "Content-Disposition: form-data; name=\"sig\"\r\n\r\n" post_body << sig post_body << "\r\n--"+boundary+"--\r\n" request = Net::HTTP::Post.new(url) request.content_type = "multipart/form-data, boundary="+boundary request.body = post_body.join caller = Net::HTTP.new(uri.host, uri.port) caller.use_ssl = uri.scheme == 'https' response = caller.start {|http| http.request(request)} response_check(response) return (get_result_value(response.body(), "Result") == TrueString) end
[ "def", "add_watermark", "(", "identifier", ",", "path", ",", "xpos", ",", "ypos", ")", "if", "!", "File", ".", "file?", "(", "path", ")", "raise", "\"File: \"", "+", "path", "+", "\" does not exist\"", "end", "sig", "=", "encode", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "@applicationSecret", ")", "+", "\"|\"", "+", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "identifier", ")", "+", "\"|\"", "+", "GrabzIt", "::", "Utility", ".", "nil_int_check", "(", "xpos", ")", "+", "\"|\"", "+", "GrabzIt", "::", "Utility", ".", "nil_int_check", "(", "ypos", ")", ")", "boundary", "=", "'--------------------------'", "+", "Time", ".", "now", ".", "to_f", ".", "to_s", "url", "=", "@protocol", "+", "\"://grabz.it/services/addwatermark.ashx\"", "uri", "=", "URI", ".", "parse", "(", "url", ")", "file", "=", "File", ".", "open", "(", "path", ",", "\"rb\"", ")", "data", "=", "file", ".", "read", "post_body", "=", "Array", ".", "new", "post_body", "<<", "\"\\r\\n--\"", "+", "boundary", "+", "\"\\r\\n\"", "post_body", "<<", "\"Content-Disposition: form-data; name=\\\"watermark\\\"; filename=\\\"\"", "+", "File", ".", "basename", "(", "path", ")", "+", "\"\\\"\\r\\nContent-Type: image/jpeg\\r\\n\\r\\n\"", "post_body", "<<", "data", "post_body", "<<", "\"\\r\\n--\"", "+", "boundary", "+", "\"\\r\\n\"", "post_body", "<<", "\"Content-Disposition: form-data; name=\\\"key\\\"\\r\\n\\r\\n\"", "post_body", "<<", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "@applicationKey", ")", "post_body", "<<", "\"\\r\\n--\"", "+", "boundary", "+", "\"\\r\\n\"", "post_body", "<<", "\"Content-Disposition: form-data; name=\\\"identifier\\\"\\r\\n\\r\\n\"", "post_body", "<<", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "identifier", ")", "post_body", "<<", "\"\\r\\n--\"", "+", "boundary", "+", "\"\\r\\n\"", "post_body", "<<", "\"Content-Disposition: form-data; name=\\\"xpos\\\"\\r\\n\\r\\n\"", "post_body", "<<", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "xpos", ")", "post_body", "<<", "\"\\r\\n--\"", "+", "boundary", "+", "\"\\r\\n\"", "post_body", "<<", "\"Content-Disposition: form-data; name=\\\"ypos\\\"\\r\\n\\r\\n\"", "post_body", "<<", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "ypos", ")", "post_body", "<<", "\"\\r\\n--\"", "+", "boundary", "+", "\"\\r\\n\"", "post_body", "<<", "\"Content-Disposition: form-data; name=\\\"sig\\\"\\r\\n\\r\\n\"", "post_body", "<<", "sig", "post_body", "<<", "\"\\r\\n--\"", "+", "boundary", "+", "\"--\\r\\n\"", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "url", ")", "request", ".", "content_type", "=", "\"multipart/form-data, boundary=\"", "+", "boundary", "request", ".", "body", "=", "post_body", ".", "join", "caller", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "caller", ".", "use_ssl", "=", "uri", ".", "scheme", "==", "'https'", "response", "=", "caller", ".", "start", "{", "|", "http", "|", "http", ".", "request", "(", "request", ")", "}", "response_check", "(", "response", ")", "return", "(", "get_result_value", "(", "response", ".", "body", "(", ")", ",", "\"Result\"", ")", "==", "TrueString", ")", "end" ]
Add a new custom watermark @param identifier [String] the identifier you want to give the custom watermark. It is important that this identifier is unique. @param path [String] the absolute path of the watermark on your server. For instance C:/watermark/1.png @param xpos [Integer] the horizontal position you want the screenshot to appear at: Left = 0, Center = 1, Right = 2 @param ypos [Integer] the vertical position you want the screenshot to appear at: Top = 0, Middle = 1, Bottom = 2 @return [Boolean] returns true if the watermark was successfully set @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
[ "Add", "a", "new", "custom", "watermark" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L475-L527
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.delete_watermark
def delete_watermark(identifier) sig = encode(GrabzIt::Utility.nil_check(@applicationSecret)+"|"+GrabzIt::Utility.nil_check(identifier)) qs = "key=" qs.concat(CGI.escape(GrabzIt::Utility.nil_check(@applicationKey))) qs.concat("&identifier=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(identifier))) qs.concat("&sig=") qs.concat(sig) return (get_result_value(get(@protocol + WebServicesBaseURLGet + "deletewatermark.ashx?" + qs), "Result") == TrueString) end
ruby
def delete_watermark(identifier) sig = encode(GrabzIt::Utility.nil_check(@applicationSecret)+"|"+GrabzIt::Utility.nil_check(identifier)) qs = "key=" qs.concat(CGI.escape(GrabzIt::Utility.nil_check(@applicationKey))) qs.concat("&identifier=") qs.concat(CGI.escape(GrabzIt::Utility.nil_check(identifier))) qs.concat("&sig=") qs.concat(sig) return (get_result_value(get(@protocol + WebServicesBaseURLGet + "deletewatermark.ashx?" + qs), "Result") == TrueString) end
[ "def", "delete_watermark", "(", "identifier", ")", "sig", "=", "encode", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "@applicationSecret", ")", "+", "\"|\"", "+", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "identifier", ")", ")", "qs", "=", "\"key=\"", "qs", ".", "concat", "(", "CGI", ".", "escape", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "@applicationKey", ")", ")", ")", "qs", ".", "concat", "(", "\"&identifier=\"", ")", "qs", ".", "concat", "(", "CGI", ".", "escape", "(", "GrabzIt", "::", "Utility", ".", "nil_check", "(", "identifier", ")", ")", ")", "qs", ".", "concat", "(", "\"&sig=\"", ")", "qs", ".", "concat", "(", "sig", ")", "return", "(", "get_result_value", "(", "get", "(", "@protocol", "+", "WebServicesBaseURLGet", "+", "\"deletewatermark.ashx?\"", "+", "qs", ")", ",", "\"Result\"", ")", "==", "TrueString", ")", "end" ]
Delete a custom watermark @param identifier [String] the identifier of the custom watermark you want to delete @return [Boolean] returns true if the watermark was successfully deleted @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
[ "Delete", "a", "custom", "watermark" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L534-L545
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.set_local_proxy
def set_local_proxy(value) if value uri = URI.parse(value) @proxy = Proxy.new(uri.host, uri.port, uri.user, uri.password) else @proxy = Proxy.new() end end
ruby
def set_local_proxy(value) if value uri = URI.parse(value) @proxy = Proxy.new(uri.host, uri.port, uri.user, uri.password) else @proxy = Proxy.new() end end
[ "def", "set_local_proxy", "(", "value", ")", "if", "value", "uri", "=", "URI", ".", "parse", "(", "value", ")", "@proxy", "=", "Proxy", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ",", "uri", ".", "user", ",", "uri", ".", "password", ")", "else", "@proxy", "=", "Proxy", ".", "new", "(", ")", "end", "end" ]
This method enables a local proxy server to be used for all requests @param value [String] the URL, which can include a port if required, of the proxy. Providing a null will remove any previously set proxy
[ "This", "method", "enables", "a", "local", "proxy", "server", "to", "be", "used", "for", "all", "requests" ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L561-L568
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.decrypt_file
def decrypt_file(path, key) data = read_file(path) decryptedFile = File.new(path, "wb") decryptedFile.write(decrypt(data, key)) decryptedFile.close end
ruby
def decrypt_file(path, key) data = read_file(path) decryptedFile = File.new(path, "wb") decryptedFile.write(decrypt(data, key)) decryptedFile.close end
[ "def", "decrypt_file", "(", "path", ",", "key", ")", "data", "=", "read_file", "(", "path", ")", "decryptedFile", "=", "File", ".", "new", "(", "path", ",", "\"wb\"", ")", "decryptedFile", ".", "write", "(", "decrypt", "(", "data", ",", "key", ")", ")", "decryptedFile", ".", "close", "end" ]
This method will decrypt a encrypted capture file, using the key you passed to the encryption key parameter. @param path [String] the path of the encrypted capture @param key [String] the encryption key
[ "This", "method", "will", "decrypt", "a", "encrypted", "capture", "file", "using", "the", "key", "you", "passed", "to", "the", "encryption", "key", "parameter", "." ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L581-L586
train
GrabzIt/grabzit
ruby/GrabzIt/lib/grabzit/client.rb
GrabzIt.Client.decrypt
def decrypt(data, key) if data == nil return nil end iv = data[0..15] payload = data[16..-1] cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc") cipher.padding = 0 cipher.key = Base64.strict_decode64(key); cipher.iv = iv decrypted = cipher.update(payload); decrypted << cipher.final(); return decrypted end
ruby
def decrypt(data, key) if data == nil return nil end iv = data[0..15] payload = data[16..-1] cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc") cipher.padding = 0 cipher.key = Base64.strict_decode64(key); cipher.iv = iv decrypted = cipher.update(payload); decrypted << cipher.final(); return decrypted end
[ "def", "decrypt", "(", "data", ",", "key", ")", "if", "data", "==", "nil", "return", "nil", "end", "iv", "=", "data", "[", "0", "..", "15", "]", "payload", "=", "data", "[", "16", "..", "-", "1", "]", "cipher", "=", "OpenSSL", "::", "Cipher", "::", "Cipher", ".", "new", "(", "\"aes-256-cbc\"", ")", "cipher", ".", "padding", "=", "0", "cipher", ".", "key", "=", "Base64", ".", "strict_decode64", "(", "key", ")", ";", "cipher", ".", "iv", "=", "iv", "decrypted", "=", "cipher", ".", "update", "(", "payload", ")", ";", "decrypted", "<<", "cipher", ".", "final", "(", ")", ";", "return", "decrypted", "end" ]
This method will decrypt a encrypted capture, using the key you passed to the encryption key parameter. @param path [String] the encrypted bytes @param key [String] the encryption key @return [Array<Byte>] an array of decrypted bytes
[ "This", "method", "will", "decrypt", "a", "encrypted", "capture", "using", "the", "key", "you", "passed", "to", "the", "encryption", "key", "parameter", "." ]
9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c
https://github.com/GrabzIt/grabzit/blob/9ab5dfd32ae7cf3c5fcd29f13e980fd5d266391c/ruby/GrabzIt/lib/grabzit/client.rb#L593-L606
train
notEthan/api_hammer
lib/api_hammer/halt_methods.rb
ApiHammer.HaltMethods.halt_error
def halt_error(status, errors, options = {}) errors_as_json = errors.respond_to?(:as_json) ? errors.as_json : errors unless errors_as_json.is_a?(Hash) raise ArgumentError, "errors be an object representable in JSON as a Hash; got errors = #{errors.inspect}" end unless errors_as_json.keys.all? { |k| k.is_a?(String) || k.is_a?(Symbol) } raise ArgumentError, "errors keys must all be string or symbol; got errors = #{errors.inspect}" end unless errors_as_json.values.all? { |v| v.is_a?(Array) && v.all? { |e| e.is_a?(String) } } raise ArgumentError, "errors values must all be arrays of strings; got errors = #{errors.inspect}" end error_message = nil halt_options = options.reject do |k,v| (k.to_s == 'error_message').tap do |is_error_message| if is_error_message error_message = v end end end body = {'errors' => errors} error_message ||= begin error_values = errors.values.inject([], &:+) if error_values.size <= 1 error_values.first else # sentencify with periods error_values.map { |v| v =~ /\.\s*\z/ ? v : v + '.' }.join(' ') end end body['error_message'] = error_message if error_message if Object.const_defined?(:Rollbar) and status != 404 and Object.const_defined?(:DEBUG_4XX) and DEBUG_4XX['enabled'] Rollbar.debug "Service halted with status #{status}", status: status, body: body, halt_options: halt_options end halt(status, body, halt_options) end
ruby
def halt_error(status, errors, options = {}) errors_as_json = errors.respond_to?(:as_json) ? errors.as_json : errors unless errors_as_json.is_a?(Hash) raise ArgumentError, "errors be an object representable in JSON as a Hash; got errors = #{errors.inspect}" end unless errors_as_json.keys.all? { |k| k.is_a?(String) || k.is_a?(Symbol) } raise ArgumentError, "errors keys must all be string or symbol; got errors = #{errors.inspect}" end unless errors_as_json.values.all? { |v| v.is_a?(Array) && v.all? { |e| e.is_a?(String) } } raise ArgumentError, "errors values must all be arrays of strings; got errors = #{errors.inspect}" end error_message = nil halt_options = options.reject do |k,v| (k.to_s == 'error_message').tap do |is_error_message| if is_error_message error_message = v end end end body = {'errors' => errors} error_message ||= begin error_values = errors.values.inject([], &:+) if error_values.size <= 1 error_values.first else # sentencify with periods error_values.map { |v| v =~ /\.\s*\z/ ? v : v + '.' }.join(' ') end end body['error_message'] = error_message if error_message if Object.const_defined?(:Rollbar) and status != 404 and Object.const_defined?(:DEBUG_4XX) and DEBUG_4XX['enabled'] Rollbar.debug "Service halted with status #{status}", status: status, body: body, halt_options: halt_options end halt(status, body, halt_options) end
[ "def", "halt_error", "(", "status", ",", "errors", ",", "options", "=", "{", "}", ")", "errors_as_json", "=", "errors", ".", "respond_to?", "(", ":as_json", ")", "?", "errors", ".", "as_json", ":", "errors", "unless", "errors_as_json", ".", "is_a?", "(", "Hash", ")", "raise", "ArgumentError", ",", "\"errors be an object representable in JSON as a Hash; got errors = #{errors.inspect}\"", "end", "unless", "errors_as_json", ".", "keys", ".", "all?", "{", "|", "k", "|", "k", ".", "is_a?", "(", "String", ")", "||", "k", ".", "is_a?", "(", "Symbol", ")", "}", "raise", "ArgumentError", ",", "\"errors keys must all be string or symbol; got errors = #{errors.inspect}\"", "end", "unless", "errors_as_json", ".", "values", ".", "all?", "{", "|", "v", "|", "v", ".", "is_a?", "(", "Array", ")", "&&", "v", ".", "all?", "{", "|", "e", "|", "e", ".", "is_a?", "(", "String", ")", "}", "}", "raise", "ArgumentError", ",", "\"errors values must all be arrays of strings; got errors = #{errors.inspect}\"", "end", "error_message", "=", "nil", "halt_options", "=", "options", ".", "reject", "do", "|", "k", ",", "v", "|", "(", "k", ".", "to_s", "==", "'error_message'", ")", ".", "tap", "do", "|", "is_error_message", "|", "if", "is_error_message", "error_message", "=", "v", "end", "end", "end", "body", "=", "{", "'errors'", "=>", "errors", "}", "error_message", "||=", "begin", "error_values", "=", "errors", ".", "values", ".", "inject", "(", "[", "]", ",", "&", ":+", ")", "if", "error_values", ".", "size", "<=", "1", "error_values", ".", "first", "else", "error_values", ".", "map", "{", "|", "v", "|", "v", "=~", "/", "\\.", "\\s", "\\z", "/", "?", "v", ":", "v", "+", "'.'", "}", ".", "join", "(", "' '", ")", "end", "end", "body", "[", "'error_message'", "]", "=", "error_message", "if", "error_message", "if", "Object", ".", "const_defined?", "(", ":Rollbar", ")", "and", "status", "!=", "404", "and", "Object", ".", "const_defined?", "(", ":DEBUG_4XX", ")", "and", "DEBUG_4XX", "[", "'enabled'", "]", "Rollbar", ".", "debug", "\"Service halted with status #{status}\"", ",", "status", ":", "status", ",", "body", ":", "body", ",", "halt_options", ":", "halt_options", "end", "halt", "(", "status", ",", "body", ",", "halt_options", ")", "end" ]
halt and render the given errors in the body on the 'errors' key
[ "halt", "and", "render", "the", "given", "errors", "in", "the", "body", "on", "the", "errors", "key" ]
a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e
https://github.com/notEthan/api_hammer/blob/a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e/lib/api_hammer/halt_methods.rb#L4-L38
train
notEthan/api_hammer
lib/api_hammer/sinatra.rb
ApiHammer.Sinatra.format_response
def format_response(status, body_object, headers={}) if status == 204 body = '' else body = case response_media_type when 'application/json' JSON.pretty_generate(body_object) when 'application/x-www-form-urlencoded' URI.encode_www_form(body_object) when 'application/xml' body_object.to_s when 'text/plain' body_object else # :nocov: raise NotImplementedError, "unsupported response media type #{response_media_type}" # :nocov: end end [status, headers.merge({'Content-Type' => response_media_type}), [body]] end
ruby
def format_response(status, body_object, headers={}) if status == 204 body = '' else body = case response_media_type when 'application/json' JSON.pretty_generate(body_object) when 'application/x-www-form-urlencoded' URI.encode_www_form(body_object) when 'application/xml' body_object.to_s when 'text/plain' body_object else # :nocov: raise NotImplementedError, "unsupported response media type #{response_media_type}" # :nocov: end end [status, headers.merge({'Content-Type' => response_media_type}), [body]] end
[ "def", "format_response", "(", "status", ",", "body_object", ",", "headers", "=", "{", "}", ")", "if", "status", "==", "204", "body", "=", "''", "else", "body", "=", "case", "response_media_type", "when", "'application/json'", "JSON", ".", "pretty_generate", "(", "body_object", ")", "when", "'application/x-www-form-urlencoded'", "URI", ".", "encode_www_form", "(", "body_object", ")", "when", "'application/xml'", "body_object", ".", "to_s", "when", "'text/plain'", "body_object", "else", "raise", "NotImplementedError", ",", "\"unsupported response media type #{response_media_type}\"", "end", "end", "[", "status", ",", "headers", ".", "merge", "(", "{", "'Content-Type'", "=>", "response_media_type", "}", ")", ",", "[", "body", "]", "]", "end" ]
returns a rack response with the given object encoded in the appropriate format for the requests. arguments are in the order of what tends to vary most frequently rather than rack's way, so headers come last
[ "returns", "a", "rack", "response", "with", "the", "given", "object", "encoded", "in", "the", "appropriate", "format", "for", "the", "requests", "." ]
a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e
https://github.com/notEthan/api_hammer/blob/a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e/lib/api_hammer/sinatra.rb#L107-L127
train
notEthan/api_hammer
lib/api_hammer/sinatra.rb
ApiHammer.Sinatra.request_body
def request_body # rewind in case anything in the past has left this un-rewound request.body.rewind request.body.read.tap do # rewind in case anything in the future expects this to have been left rewound request.body.rewind end end
ruby
def request_body # rewind in case anything in the past has left this un-rewound request.body.rewind request.body.read.tap do # rewind in case anything in the future expects this to have been left rewound request.body.rewind end end
[ "def", "request_body", "request", ".", "body", ".", "rewind", "request", ".", "body", ".", "read", ".", "tap", "do", "request", ".", "body", ".", "rewind", "end", "end" ]
reads the request body
[ "reads", "the", "request", "body" ]
a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e
https://github.com/notEthan/api_hammer/blob/a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e/lib/api_hammer/sinatra.rb#L130-L137
train
notEthan/api_hammer
lib/api_hammer/sinatra.rb
ApiHammer.Sinatra.parsed_body
def parsed_body request_media_type = request.media_type unless request_media_type =~ /\S/ fallback = true request_media_type = supported_media_types.first end case request_media_type when 'application/json' begin return JSON.parse(request_body) rescue JSON::ParserError if fallback t_key = 'app.errors.request.body_parse_fallback_json' default = "Error encountered attempting to parse the request body. No Content-Type was specified and parsing as JSON failed. Supported media types are %{supported_media_types}. JSON parser error: %{error_class}: %{error_message}" else t_key = 'app.errors.request.body_parse_indicated_json' default = "Error encountered attempting to parse the JSON request body: %{error_class}: %{error_message}" end message = I18n.t(t_key, :default => default, :error_class => $!.class, :error_message => $!.message, :supported_media_types => supported_media_types.join(', ') ) errors = {'json' => [message]} halt_error(400, errors) end else if supported_media_types.include?(request_media_type) # :nocov: raise NotImplementedError, "handling request body with media type #{request_media_type} not implemented" # :nocov: end logger.error "received Content-Type of #{request.content_type.inspect}; halting with 415" message = I18n.t('app.errors.request.content_type', :default => "Unsupported Content-Type of %{content_type} given for the request body. Supported media types are %{supported_media_types}", :content_type => request.content_type, :supported_media_types => supported_media_types.join(', ') ) errors = {'Content-Type' => [message]} halt_error(415, errors) end end
ruby
def parsed_body request_media_type = request.media_type unless request_media_type =~ /\S/ fallback = true request_media_type = supported_media_types.first end case request_media_type when 'application/json' begin return JSON.parse(request_body) rescue JSON::ParserError if fallback t_key = 'app.errors.request.body_parse_fallback_json' default = "Error encountered attempting to parse the request body. No Content-Type was specified and parsing as JSON failed. Supported media types are %{supported_media_types}. JSON parser error: %{error_class}: %{error_message}" else t_key = 'app.errors.request.body_parse_indicated_json' default = "Error encountered attempting to parse the JSON request body: %{error_class}: %{error_message}" end message = I18n.t(t_key, :default => default, :error_class => $!.class, :error_message => $!.message, :supported_media_types => supported_media_types.join(', ') ) errors = {'json' => [message]} halt_error(400, errors) end else if supported_media_types.include?(request_media_type) # :nocov: raise NotImplementedError, "handling request body with media type #{request_media_type} not implemented" # :nocov: end logger.error "received Content-Type of #{request.content_type.inspect}; halting with 415" message = I18n.t('app.errors.request.content_type', :default => "Unsupported Content-Type of %{content_type} given for the request body. Supported media types are %{supported_media_types}", :content_type => request.content_type, :supported_media_types => supported_media_types.join(', ') ) errors = {'Content-Type' => [message]} halt_error(415, errors) end end
[ "def", "parsed_body", "request_media_type", "=", "request", ".", "media_type", "unless", "request_media_type", "=~", "/", "\\S", "/", "fallback", "=", "true", "request_media_type", "=", "supported_media_types", ".", "first", "end", "case", "request_media_type", "when", "'application/json'", "begin", "return", "JSON", ".", "parse", "(", "request_body", ")", "rescue", "JSON", "::", "ParserError", "if", "fallback", "t_key", "=", "'app.errors.request.body_parse_fallback_json'", "default", "=", "\"Error encountered attempting to parse the request body. No Content-Type was specified and parsing as JSON failed. Supported media types are %{supported_media_types}. JSON parser error: %{error_class}: %{error_message}\"", "else", "t_key", "=", "'app.errors.request.body_parse_indicated_json'", "default", "=", "\"Error encountered attempting to parse the JSON request body: %{error_class}: %{error_message}\"", "end", "message", "=", "I18n", ".", "t", "(", "t_key", ",", ":default", "=>", "default", ",", ":error_class", "=>", "$!", ".", "class", ",", ":error_message", "=>", "$!", ".", "message", ",", ":supported_media_types", "=>", "supported_media_types", ".", "join", "(", "', '", ")", ")", "errors", "=", "{", "'json'", "=>", "[", "message", "]", "}", "halt_error", "(", "400", ",", "errors", ")", "end", "else", "if", "supported_media_types", ".", "include?", "(", "request_media_type", ")", "raise", "NotImplementedError", ",", "\"handling request body with media type #{request_media_type} not implemented\"", "end", "logger", ".", "error", "\"received Content-Type of #{request.content_type.inspect}; halting with 415\"", "message", "=", "I18n", ".", "t", "(", "'app.errors.request.content_type'", ",", ":default", "=>", "\"Unsupported Content-Type of %{content_type} given for the request body. Supported media types are %{supported_media_types}\"", ",", ":content_type", "=>", "request", ".", "content_type", ",", ":supported_media_types", "=>", "supported_media_types", ".", "join", "(", "', '", ")", ")", "errors", "=", "{", "'Content-Type'", "=>", "[", "message", "]", "}", "halt_error", "(", "415", ",", "errors", ")", "end", "end" ]
returns the parsed contents of the request body. checks the Content-Type of the request, and unless it's supported (or omitted - in which case assumed to be the first supported media type), halts with 415. if the body is not parseable, then halts with 400.
[ "returns", "the", "parsed", "contents", "of", "the", "request", "body", "." ]
a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e
https://github.com/notEthan/api_hammer/blob/a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e/lib/api_hammer/sinatra.rb#L145-L187
train
notEthan/api_hammer
lib/api_hammer/sinatra.rb
ApiHammer.Sinatra.check_params_and_object_consistent
def check_params_and_object_consistent(path_params, object) errors = {} path_params.each do |(k, v)| if object.key?(k) && object[k] != v errors[k] = [I18n.t('app.errors.inconsistent_uri_and_entity', :key => k, :uri_value => v, :entity_value => object[k], :default => "Inconsistent data given in the request URI and request entity: %{key} was specified as %{uri_value} in the URI but %{entity_value} in the entity", )] end end if errors.any? halt_error(422, errors) end end
ruby
def check_params_and_object_consistent(path_params, object) errors = {} path_params.each do |(k, v)| if object.key?(k) && object[k] != v errors[k] = [I18n.t('app.errors.inconsistent_uri_and_entity', :key => k, :uri_value => v, :entity_value => object[k], :default => "Inconsistent data given in the request URI and request entity: %{key} was specified as %{uri_value} in the URI but %{entity_value} in the entity", )] end end if errors.any? halt_error(422, errors) end end
[ "def", "check_params_and_object_consistent", "(", "path_params", ",", "object", ")", "errors", "=", "{", "}", "path_params", ".", "each", "do", "|", "(", "k", ",", "v", ")", "|", "if", "object", ".", "key?", "(", "k", ")", "&&", "object", "[", "k", "]", "!=", "v", "errors", "[", "k", "]", "=", "[", "I18n", ".", "t", "(", "'app.errors.inconsistent_uri_and_entity'", ",", ":key", "=>", "k", ",", ":uri_value", "=>", "v", ",", ":entity_value", "=>", "object", "[", "k", "]", ",", ":default", "=>", "\"Inconsistent data given in the request URI and request entity: %{key} was specified as %{uri_value} in the URI but %{entity_value} in the entity\"", ",", ")", "]", "end", "end", "if", "errors", ".", "any?", "halt_error", "(", "422", ",", "errors", ")", "end", "end" ]
for methods where parameters which are required in the path may also be specified in the body, this takes the path_params and the body object and ensures that they are consistent any place they are specified in the body.
[ "for", "methods", "where", "parameters", "which", "are", "required", "in", "the", "path", "may", "also", "be", "specified", "in", "the", "body", "this", "takes", "the", "path_params", "and", "the", "body", "object", "and", "ensures", "that", "they", "are", "consistent", "any", "place", "they", "are", "specified", "in", "the", "body", "." ]
a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e
https://github.com/notEthan/api_hammer/blob/a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e/lib/api_hammer/sinatra.rb#L192-L207
train
notEthan/api_hammer
lib/api_hammer/body.rb
ApiHammer.Body.object
def object instance_variable_defined?(:@object) ? @object : @object = begin if media_type == 'application/json' JSON.parse(body) rescue nil elsif media_type == 'application/x-www-form-urlencoded' CGI.parse(body).map { |k, vs| {k => vs.last} }.inject({}, &:update) end end end
ruby
def object instance_variable_defined?(:@object) ? @object : @object = begin if media_type == 'application/json' JSON.parse(body) rescue nil elsif media_type == 'application/x-www-form-urlencoded' CGI.parse(body).map { |k, vs| {k => vs.last} }.inject({}, &:update) end end end
[ "def", "object", "instance_variable_defined?", "(", ":@object", ")", "?", "@object", ":", "@object", "=", "begin", "if", "media_type", "==", "'application/json'", "JSON", ".", "parse", "(", "body", ")", "rescue", "nil", "elsif", "media_type", "==", "'application/x-www-form-urlencoded'", "CGI", ".", "parse", "(", "body", ")", ".", "map", "{", "|", "k", ",", "vs", "|", "{", "k", "=>", "vs", ".", "last", "}", "}", ".", "inject", "(", "{", "}", ",", "&", ":update", ")", "end", "end", "end" ]
parses the body to an object
[ "parses", "the", "body", "to", "an", "object" ]
a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e
https://github.com/notEthan/api_hammer/blob/a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e/lib/api_hammer/body.rb#L13-L21
train
notEthan/api_hammer
lib/api_hammer/body.rb
ApiHammer.Body.jsonifiable
def jsonifiable @jsonifiable ||= Body.new(catch(:jsonifiable) do original_body = self.body unless original_body.is_a?(String) begin # if the response body is not a string, but JSON doesn't complain # about dumping whatever it is, go ahead and use it JSON.generate([original_body]) throw :jsonifiable, original_body rescue # otherwise return nil - don't know what to do with whatever this object is throw :jsonifiable, nil end end # first try to change the string's encoding per the Content-Type header body = original_body.dup unless body.valid_encoding? # I think this always comes in as ASCII-8BIT anyway so may never get here. hopefully. body.force_encoding('ASCII-8BIT') end content_type_attrs = ContentTypeAttrs.new(content_type) if content_type_attrs.parsed? charset = content_type_attrs['charset'].first if charset && Encoding.list.any? { |enc| enc.to_s.downcase == charset.downcase } if body.dup.force_encoding(charset).valid_encoding? body.force_encoding(charset) else # I guess just ignore the specified encoding if the result is not valid. fall back to # something else below. end end end begin JSON.generate([body]) rescue Encoding::UndefinedConversionError # if updating by content-type didn't do it, try UTF8 since JSON wants that - but only # if it seems to be valid utf8. # don't try utf8 if the response content-type indicated something else. try_utf8 = !(content_type_attrs && content_type_attrs.parsed? && content_type_attrs['charset'].any? { |cs| !['utf8', ''].include?(cs.downcase) }) if try_utf8 && body.dup.force_encoding('UTF-8').valid_encoding? body.force_encoding('UTF-8') else # I'm not sure if there is a way in this situation to get JSON gem to generate the # string correctly. fall back to an array of codepoints I guess? this is a weird # solution but the best I've got for now. body = body.codepoints.to_a end end body end, content_type) end
ruby
def jsonifiable @jsonifiable ||= Body.new(catch(:jsonifiable) do original_body = self.body unless original_body.is_a?(String) begin # if the response body is not a string, but JSON doesn't complain # about dumping whatever it is, go ahead and use it JSON.generate([original_body]) throw :jsonifiable, original_body rescue # otherwise return nil - don't know what to do with whatever this object is throw :jsonifiable, nil end end # first try to change the string's encoding per the Content-Type header body = original_body.dup unless body.valid_encoding? # I think this always comes in as ASCII-8BIT anyway so may never get here. hopefully. body.force_encoding('ASCII-8BIT') end content_type_attrs = ContentTypeAttrs.new(content_type) if content_type_attrs.parsed? charset = content_type_attrs['charset'].first if charset && Encoding.list.any? { |enc| enc.to_s.downcase == charset.downcase } if body.dup.force_encoding(charset).valid_encoding? body.force_encoding(charset) else # I guess just ignore the specified encoding if the result is not valid. fall back to # something else below. end end end begin JSON.generate([body]) rescue Encoding::UndefinedConversionError # if updating by content-type didn't do it, try UTF8 since JSON wants that - but only # if it seems to be valid utf8. # don't try utf8 if the response content-type indicated something else. try_utf8 = !(content_type_attrs && content_type_attrs.parsed? && content_type_attrs['charset'].any? { |cs| !['utf8', ''].include?(cs.downcase) }) if try_utf8 && body.dup.force_encoding('UTF-8').valid_encoding? body.force_encoding('UTF-8') else # I'm not sure if there is a way in this situation to get JSON gem to generate the # string correctly. fall back to an array of codepoints I guess? this is a weird # solution but the best I've got for now. body = body.codepoints.to_a end end body end, content_type) end
[ "def", "jsonifiable", "@jsonifiable", "||=", "Body", ".", "new", "(", "catch", "(", ":jsonifiable", ")", "do", "original_body", "=", "self", ".", "body", "unless", "original_body", ".", "is_a?", "(", "String", ")", "begin", "JSON", ".", "generate", "(", "[", "original_body", "]", ")", "throw", ":jsonifiable", ",", "original_body", "rescue", "throw", ":jsonifiable", ",", "nil", "end", "end", "body", "=", "original_body", ".", "dup", "unless", "body", ".", "valid_encoding?", "body", ".", "force_encoding", "(", "'ASCII-8BIT'", ")", "end", "content_type_attrs", "=", "ContentTypeAttrs", ".", "new", "(", "content_type", ")", "if", "content_type_attrs", ".", "parsed?", "charset", "=", "content_type_attrs", "[", "'charset'", "]", ".", "first", "if", "charset", "&&", "Encoding", ".", "list", ".", "any?", "{", "|", "enc", "|", "enc", ".", "to_s", ".", "downcase", "==", "charset", ".", "downcase", "}", "if", "body", ".", "dup", ".", "force_encoding", "(", "charset", ")", ".", "valid_encoding?", "body", ".", "force_encoding", "(", "charset", ")", "else", "end", "end", "end", "begin", "JSON", ".", "generate", "(", "[", "body", "]", ")", "rescue", "Encoding", "::", "UndefinedConversionError", "try_utf8", "=", "!", "(", "content_type_attrs", "&&", "content_type_attrs", ".", "parsed?", "&&", "content_type_attrs", "[", "'charset'", "]", ".", "any?", "{", "|", "cs", "|", "!", "[", "'utf8'", ",", "''", "]", ".", "include?", "(", "cs", ".", "downcase", ")", "}", ")", "if", "try_utf8", "&&", "body", ".", "dup", ".", "force_encoding", "(", "'UTF-8'", ")", ".", "valid_encoding?", "body", ".", "force_encoding", "(", "'UTF-8'", ")", "else", "body", "=", "body", ".", "codepoints", ".", "to_a", "end", "end", "body", "end", ",", "content_type", ")", "end" ]
deal with the vagaries of getting the response body in a form which JSON gem will not cry about generating
[ "deal", "with", "the", "vagaries", "of", "getting", "the", "response", "body", "in", "a", "form", "which", "JSON", "gem", "will", "not", "cry", "about", "generating" ]
a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e
https://github.com/notEthan/api_hammer/blob/a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e/lib/api_hammer/body.rb#L49-L101
train
notEthan/api_hammer
lib/api_hammer/faraday/outputter.rb
ApiHammer.FaradayCurlVOutputter.alter_body_by_content_type
def alter_body_by_content_type(body, content_type) return body unless body.is_a?(String) content_type_attrs = ApiHammer::ContentTypeAttrs.new(content_type) if @options[:text].nil? ? content_type_attrs.text? : @options[:text] if pretty? case content_type_attrs.media_type when 'application/json' require 'json' begin body = JSON.pretty_generate(JSON.parse(body)) rescue JSON::ParserError end end end if color? coderay_scanner = CodeRayForMediaTypes.reject{|k,v| !v.any?{|type| type === content_type_attrs.media_type} }.keys.first if coderay_scanner require 'coderay' body = CodeRay.scan(body, coderay_scanner).encode(:terminal) end end else body = omitted_body("[[omitted binary body (size = #{body.size})]]") end body end
ruby
def alter_body_by_content_type(body, content_type) return body unless body.is_a?(String) content_type_attrs = ApiHammer::ContentTypeAttrs.new(content_type) if @options[:text].nil? ? content_type_attrs.text? : @options[:text] if pretty? case content_type_attrs.media_type when 'application/json' require 'json' begin body = JSON.pretty_generate(JSON.parse(body)) rescue JSON::ParserError end end end if color? coderay_scanner = CodeRayForMediaTypes.reject{|k,v| !v.any?{|type| type === content_type_attrs.media_type} }.keys.first if coderay_scanner require 'coderay' body = CodeRay.scan(body, coderay_scanner).encode(:terminal) end end else body = omitted_body("[[omitted binary body (size = #{body.size})]]") end body end
[ "def", "alter_body_by_content_type", "(", "body", ",", "content_type", ")", "return", "body", "unless", "body", ".", "is_a?", "(", "String", ")", "content_type_attrs", "=", "ApiHammer", "::", "ContentTypeAttrs", ".", "new", "(", "content_type", ")", "if", "@options", "[", ":text", "]", ".", "nil?", "?", "content_type_attrs", ".", "text?", ":", "@options", "[", ":text", "]", "if", "pretty?", "case", "content_type_attrs", ".", "media_type", "when", "'application/json'", "require", "'json'", "begin", "body", "=", "JSON", ".", "pretty_generate", "(", "JSON", ".", "parse", "(", "body", ")", ")", "rescue", "JSON", "::", "ParserError", "end", "end", "end", "if", "color?", "coderay_scanner", "=", "CodeRayForMediaTypes", ".", "reject", "{", "|", "k", ",", "v", "|", "!", "v", ".", "any?", "{", "|", "type", "|", "type", "===", "content_type_attrs", ".", "media_type", "}", "}", ".", "keys", ".", "first", "if", "coderay_scanner", "require", "'coderay'", "body", "=", "CodeRay", ".", "scan", "(", "body", ",", "coderay_scanner", ")", ".", "encode", "(", ":terminal", ")", "end", "end", "else", "body", "=", "omitted_body", "(", "\"[[omitted binary body (size = #{body.size})]]\"", ")", "end", "body", "end" ]
takes a body and a content type; returns the body, altered according to options. - with coloring (ansi colors for terminals) possibly added, if it's a recognized content type and #color? is true - formatted prettily if #pretty? is true
[ "takes", "a", "body", "and", "a", "content", "type", ";", "returns", "the", "body", "altered", "according", "to", "options", "." ]
a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e
https://github.com/notEthan/api_hammer/blob/a5ebc1b9e8c1635035a6b600a81b3d52cc673a8e/lib/api_hammer/faraday/outputter.rb#L129-L154
train