id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
24,300
cryptape/ruby-devp2p
lib/devp2p/command.rb
DEVp2p.Command.receive
def receive(proto, data) if structure.instance_of?(RLP::Sedes::CountableList) receive_callbacks.each {|cb| cb.call(proto, data) } else receive_callbacks.each {|cb| cb.call(proto, **data) } end end
ruby
def receive(proto, data) if structure.instance_of?(RLP::Sedes::CountableList) receive_callbacks.each {|cb| cb.call(proto, data) } else receive_callbacks.each {|cb| cb.call(proto, **data) } end end
[ "def", "receive", "(", "proto", ",", "data", ")", "if", "structure", ".", "instance_of?", "(", "RLP", "::", "Sedes", "::", "CountableList", ")", "receive_callbacks", ".", "each", "{", "|", "cb", "|", "cb", ".", "call", "(", "proto", ",", "data", ")", "}", "else", "receive_callbacks", ".", "each", "{", "|", "cb", "|", "cb", ".", "call", "(", "proto", ",", "**", "data", ")", "}", "end", "end" ]
optionally implement receive
[ "optionally", "implement", "receive" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/command.rb#L73-L79
24,301
ruby-protobuf/protobuf-core
lib/protobuf/encoder.rb
Protobuf.Encoder.write_pair
def write_pair(field, value) key = (field.tag << 3) | field.wire_type stream << ::Protobuf::Field::VarintField.encode(key) stream << field.encode(value) end
ruby
def write_pair(field, value) key = (field.tag << 3) | field.wire_type stream << ::Protobuf::Field::VarintField.encode(key) stream << field.encode(value) end
[ "def", "write_pair", "(", "field", ",", "value", ")", "key", "=", "(", "field", ".", "tag", "<<", "3", ")", "|", "field", ".", "wire_type", "stream", "<<", "::", "Protobuf", "::", "Field", "::", "VarintField", ".", "encode", "(", "key", ")", "stream", "<<", "field", ".", "encode", "(", "value", ")", "end" ]
Encode key and value, and write to +stream+.
[ "Encode", "key", "and", "value", "and", "write", "to", "+", "stream", "+", "." ]
67c37d1c54cadfe9a9e56b8df351549eed1e38bd
https://github.com/ruby-protobuf/protobuf-core/blob/67c37d1c54cadfe9a9e56b8df351549eed1e38bd/lib/protobuf/encoder.rb#L60-L64
24,302
solutious/rudy
lib/rudy/backups.rb
Rudy.Backups.get
def get(path) tmp = Rudy::Backup.new path backups = Rudy::Backups.list :path => path return nil unless backups.is_a?(Array) && !backups.empty? backups.first end
ruby
def get(path) tmp = Rudy::Backup.new path backups = Rudy::Backups.list :path => path return nil unless backups.is_a?(Array) && !backups.empty? backups.first end
[ "def", "get", "(", "path", ")", "tmp", "=", "Rudy", "::", "Backup", ".", "new", "path", "backups", "=", "Rudy", "::", "Backups", ".", "list", ":path", "=>", "path", "return", "nil", "unless", "backups", ".", "is_a?", "(", "Array", ")", "&&", "!", "backups", ".", "empty?", "backups", ".", "first", "end" ]
Returns the most recent backup object for the given path
[ "Returns", "the", "most", "recent", "backup", "object", "for", "the", "given", "path" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/backups.rb#L12-L17
24,303
cryptape/ruby-devp2p
lib/devp2p/multiplexer.rb
DEVp2p.Multiplexer.pop_frames
def pop_frames protocols = @queues.keys idx = protocols.index next_protocol protocols = protocols[idx..-1] + protocols[0,idx] protocols.each do |id| frames = pop_frames_for_protocol id return frames unless frames.empty? end [] end
ruby
def pop_frames protocols = @queues.keys idx = protocols.index next_protocol protocols = protocols[idx..-1] + protocols[0,idx] protocols.each do |id| frames = pop_frames_for_protocol id return frames unless frames.empty? end [] end
[ "def", "pop_frames", "protocols", "=", "@queues", ".", "keys", "idx", "=", "protocols", ".", "index", "next_protocol", "protocols", "=", "protocols", "[", "idx", "..", "-", "1", "]", "+", "protocols", "[", "0", ",", "idx", "]", "protocols", ".", "each", "do", "|", "id", "|", "frames", "=", "pop_frames_for_protocol", "id", "return", "frames", "unless", "frames", ".", "empty?", "end", "[", "]", "end" ]
Returns the frames for the next protocol up to protocol window size bytes.
[ "Returns", "the", "frames", "for", "the", "next", "protocol", "up", "to", "protocol", "window", "size", "bytes", "." ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/multiplexer.rb#L183-L194
24,304
keithrbennett/trick_bag
lib/trick_bag/formatters/formatters.rb
TrickBag.Formatters.array_diff
def array_diff(array1, array2, format = :text) string1 = array1.join("\n") + "\n" string2 = array2.join("\n") + "\n" Diffy::Diff.new(string1, string2).to_s(format) end
ruby
def array_diff(array1, array2, format = :text) string1 = array1.join("\n") + "\n" string2 = array2.join("\n") + "\n" Diffy::Diff.new(string1, string2).to_s(format) end
[ "def", "array_diff", "(", "array1", ",", "array2", ",", "format", "=", ":text", ")", "string1", "=", "array1", ".", "join", "(", "\"\\n\"", ")", "+", "\"\\n\"", "string2", "=", "array2", ".", "join", "(", "\"\\n\"", ")", "+", "\"\\n\"", "Diffy", "::", "Diff", ".", "new", "(", "string1", ",", "string2", ")", ".", "to_s", "(", "format", ")", "end" ]
Shows a visual diff of 2 arrays by comparing the string representations of the arrays with one element per line. @param format can be any valid Diffy option, e.g. :color see https://github.com/samg/diffy/blob/master/lib/diffy/format.rb
[ "Shows", "a", "visual", "diff", "of", "2", "arrays", "by", "comparing", "the", "string", "representations", "of", "the", "arrays", "with", "one", "element", "per", "line", "." ]
a3886a45f32588aba751d13aeba42ae680bcd203
https://github.com/keithrbennett/trick_bag/blob/a3886a45f32588aba751d13aeba42ae680bcd203/lib/trick_bag/formatters/formatters.rb#L136-L140
24,305
cryptape/ruby-devp2p
lib/devp2p/crypto.rb
DEVp2p.Crypto.encrypt
def encrypt(data, raw_pubkey) raise ArgumentError, "invalid pubkey of length #{raw_pubkey.size}" unless raw_pubkey.size == 64 Crypto::ECIES.encrypt data, raw_pubkey end
ruby
def encrypt(data, raw_pubkey) raise ArgumentError, "invalid pubkey of length #{raw_pubkey.size}" unless raw_pubkey.size == 64 Crypto::ECIES.encrypt data, raw_pubkey end
[ "def", "encrypt", "(", "data", ",", "raw_pubkey", ")", "raise", "ArgumentError", ",", "\"invalid pubkey of length #{raw_pubkey.size}\"", "unless", "raw_pubkey", ".", "size", "==", "64", "Crypto", "::", "ECIES", ".", "encrypt", "data", ",", "raw_pubkey", "end" ]
Encrypt data with ECIES method using the public key of the recipient.
[ "Encrypt", "data", "with", "ECIES", "method", "using", "the", "public", "key", "of", "the", "recipient", "." ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/crypto.rb#L67-L70
24,306
tiagopog/scrapifier
lib/scrapifier/support.rb
Scrapifier.Support.sf_eval_uri
def sf_eval_uri(uri, exts = []) doc = Nokogiri::HTML(open(uri).read) doc.encoding, meta = 'utf-8', { uri: uri } [:title, :description, :keywords, :lang, :encode, :reply_to, :author].each do |k| node = doc.xpath(sf_xpaths[k])[0] meta[k] = node.nil? ? '-' : node.text end meta[:images] = sf_fix_imgs(doc.xpath(sf_xpaths[:image]), uri, exts) meta rescue SocketError {} end
ruby
def sf_eval_uri(uri, exts = []) doc = Nokogiri::HTML(open(uri).read) doc.encoding, meta = 'utf-8', { uri: uri } [:title, :description, :keywords, :lang, :encode, :reply_to, :author].each do |k| node = doc.xpath(sf_xpaths[k])[0] meta[k] = node.nil? ? '-' : node.text end meta[:images] = sf_fix_imgs(doc.xpath(sf_xpaths[:image]), uri, exts) meta rescue SocketError {} end
[ "def", "sf_eval_uri", "(", "uri", ",", "exts", "=", "[", "]", ")", "doc", "=", "Nokogiri", "::", "HTML", "(", "open", "(", "uri", ")", ".", "read", ")", "doc", ".", "encoding", ",", "meta", "=", "'utf-8'", ",", "{", "uri", ":", "uri", "}", "[", ":title", ",", ":description", ",", ":keywords", ",", ":lang", ",", ":encode", ",", ":reply_to", ",", ":author", "]", ".", "each", "do", "|", "k", "|", "node", "=", "doc", ".", "xpath", "(", "sf_xpaths", "[", "k", "]", ")", "[", "0", "]", "meta", "[", "k", "]", "=", "node", ".", "nil?", "?", "'-'", ":", "node", ".", "text", "end", "meta", "[", ":images", "]", "=", "sf_fix_imgs", "(", "doc", ".", "xpath", "(", "sf_xpaths", "[", ":image", "]", ")", ",", "uri", ",", "exts", ")", "meta", "rescue", "SocketError", "{", "}", "end" ]
Evaluate the URI's HTML document and get its metadata. Example: >> eval_uri('http://adtangerine.com', [:png]) => { :title => "AdTangerine | Advertising Platform for Social Media", :description => "AdTangerine is an advertising platform that...", :images => [ "http://adtangerine.com/assets/logo_adt_og.png", "http://adtangerine.com/assets/logo_adt_og.png ], :uri => "http://adtangerine.com" } Arguments: uri: (String) - URI. exts: (Array) - Allowed type of images.
[ "Evaluate", "the", "URI", "s", "HTML", "document", "and", "get", "its", "metadata", "." ]
2eda1b0fac6ba58b38b8716816bd71712c7a6994
https://github.com/tiagopog/scrapifier/blob/2eda1b0fac6ba58b38b8716816bd71712c7a6994/lib/scrapifier/support.rb#L27-L40
24,307
tiagopog/scrapifier
lib/scrapifier/support.rb
Scrapifier.Support.sf_check_img_ext
def sf_check_img_ext(images, allowed = []) allowed ||= [] if images.is_a?(String) images = images.split elsif !images.is_a?(Array) images = [] end images.select { |i| i =~ sf_regex(:image, allowed) } end
ruby
def sf_check_img_ext(images, allowed = []) allowed ||= [] if images.is_a?(String) images = images.split elsif !images.is_a?(Array) images = [] end images.select { |i| i =~ sf_regex(:image, allowed) } end
[ "def", "sf_check_img_ext", "(", "images", ",", "allowed", "=", "[", "]", ")", "allowed", "||=", "[", "]", "if", "images", ".", "is_a?", "(", "String", ")", "images", "=", "images", ".", "split", "elsif", "!", "images", ".", "is_a?", "(", "Array", ")", "images", "=", "[", "]", "end", "images", ".", "select", "{", "|", "i", "|", "i", "=~", "sf_regex", "(", ":image", ",", "allowed", ")", "}", "end" ]
Filter images returning those with the allowed extentions. Example: >> sf_check_img_ext('http://source.com/image.gif', :jpg) => [] >> sf_check_img_ext( ['http://source.com/image.gif','http://source.com/image.jpg'], [:jpg, :png] ) => ['http://source.com/image.jpg'] Arguments: images: (String or Array) - Images which will be checked. allowed: (String, Symbol or Array) - Allowed types of image extension.
[ "Filter", "images", "returning", "those", "with", "the", "allowed", "extentions", "." ]
2eda1b0fac6ba58b38b8716816bd71712c7a6994
https://github.com/tiagopog/scrapifier/blob/2eda1b0fac6ba58b38b8716816bd71712c7a6994/lib/scrapifier/support.rb#L57-L65
24,308
tiagopog/scrapifier
lib/scrapifier/support.rb
Scrapifier.Support.sf_regex
def sf_regex(type, *args) type = type.to_sym unless type.is_a? Symbol type == :image && sf_img_regex(args.flatten) || sf_uri_regex[type] end
ruby
def sf_regex(type, *args) type = type.to_sym unless type.is_a? Symbol type == :image && sf_img_regex(args.flatten) || sf_uri_regex[type] end
[ "def", "sf_regex", "(", "type", ",", "*", "args", ")", "type", "=", "type", ".", "to_sym", "unless", "type", ".", "is_a?", "Symbol", "type", "==", ":image", "&&", "sf_img_regex", "(", "args", ".", "flatten", ")", "||", "sf_uri_regex", "[", "type", "]", "end" ]
Select regexes for URIs, protocols and image extensions. Example: >> sf_regex(:uri) => /\b((((ht|f)tp[s]?:\/\/).../i, >> sf_regex(:image, :jpg) => /(^http{1}[s]?:\/\/([w]{3}\.)?.+\.(jpg)(\?.+)?$)/i Arguments: type: (Symbol or String) - Regex type: :uri, :protocol, :image args: (*) - Anything.
[ "Select", "regexes", "for", "URIs", "protocols", "and", "image", "extensions", "." ]
2eda1b0fac6ba58b38b8716816bd71712c7a6994
https://github.com/tiagopog/scrapifier/blob/2eda1b0fac6ba58b38b8716816bd71712c7a6994/lib/scrapifier/support.rb#L79-L82
24,309
tiagopog/scrapifier
lib/scrapifier/support.rb
Scrapifier.Support.sf_xpaths
def sf_xpaths { title: XPath::TITLE, description: XPath::DESC, keywords: XPath::KEYWORDS, lang: XPath::LANG, encode: XPath::ENCODE, reply_to: XPath::REPLY_TO, author: XPath::AUTHOR, image: XPath::IMG } end
ruby
def sf_xpaths { title: XPath::TITLE, description: XPath::DESC, keywords: XPath::KEYWORDS, lang: XPath::LANG, encode: XPath::ENCODE, reply_to: XPath::REPLY_TO, author: XPath::AUTHOR, image: XPath::IMG } end
[ "def", "sf_xpaths", "{", "title", ":", "XPath", "::", "TITLE", ",", "description", ":", "XPath", "::", "DESC", ",", "keywords", ":", "XPath", "::", "KEYWORDS", ",", "lang", ":", "XPath", "::", "LANG", ",", "encode", ":", "XPath", "::", "ENCODE", ",", "reply_to", ":", "XPath", "::", "REPLY_TO", ",", "author", ":", "XPath", "::", "AUTHOR", ",", "image", ":", "XPath", "::", "IMG", "}", "end" ]
Organize XPaths.
[ "Organize", "XPaths", "." ]
2eda1b0fac6ba58b38b8716816bd71712c7a6994
https://github.com/tiagopog/scrapifier/blob/2eda1b0fac6ba58b38b8716816bd71712c7a6994/lib/scrapifier/support.rb#L118-L127
24,310
tiagopog/scrapifier
lib/scrapifier/support.rb
Scrapifier.Support.sf_fix_imgs
def sf_fix_imgs(imgs, uri, exts = []) sf_check_img_ext(imgs.map do |img| img = img.to_s unless img =~ sf_regex(:protocol) img = sf_fix_protocol(img, sf_domain(uri)) end img if img =~ sf_regex(:image) end.compact, exts) end
ruby
def sf_fix_imgs(imgs, uri, exts = []) sf_check_img_ext(imgs.map do |img| img = img.to_s unless img =~ sf_regex(:protocol) img = sf_fix_protocol(img, sf_domain(uri)) end img if img =~ sf_regex(:image) end.compact, exts) end
[ "def", "sf_fix_imgs", "(", "imgs", ",", "uri", ",", "exts", "=", "[", "]", ")", "sf_check_img_ext", "(", "imgs", ".", "map", "do", "|", "img", "|", "img", "=", "img", ".", "to_s", "unless", "img", "=~", "sf_regex", "(", ":protocol", ")", "img", "=", "sf_fix_protocol", "(", "img", ",", "sf_domain", "(", "uri", ")", ")", "end", "img", "if", "img", "=~", "sf_regex", "(", ":image", ")", "end", ".", "compact", ",", "exts", ")", "end" ]
Check and return only the valid image URIs. Example: >> sf_fix_imgs( ['http://adtangerine.com/image.png', '/assets/image.jpg'], 'http://adtangerine.com', :jpg ) => ['http://adtangerine/assets/image.jpg'] Arguments: imgs: (Array) - Image URIs got from the HTML doc. uri: (String) - Used as basis to the URIs that don't have any protocol/domain set. exts: (Symbol or Array) - Allowed image extesntions.
[ "Check", "and", "return", "only", "the", "valid", "image", "URIs", "." ]
2eda1b0fac6ba58b38b8716816bd71712c7a6994
https://github.com/tiagopog/scrapifier/blob/2eda1b0fac6ba58b38b8716816bd71712c7a6994/lib/scrapifier/support.rb#L145-L153
24,311
solutious/rudy
lib/rudy/huxtable.rb
Rudy.Huxtable.known_machine_group?
def known_machine_group? raise NoConfig unless @@config return true if default_machine_group? raise NoMachinesConfig unless @@config.machines return false if !@@config && !@@global zon, env, rol = @@global.zone, @@global.environment, @@global.role conf = @@config.machines.find_deferred(@@global.region, zon, [env, rol]) conf ||= @@config.machines.find_deferred(zon, [env, rol]) !conf.nil? end
ruby
def known_machine_group? raise NoConfig unless @@config return true if default_machine_group? raise NoMachinesConfig unless @@config.machines return false if !@@config && !@@global zon, env, rol = @@global.zone, @@global.environment, @@global.role conf = @@config.machines.find_deferred(@@global.region, zon, [env, rol]) conf ||= @@config.machines.find_deferred(zon, [env, rol]) !conf.nil? end
[ "def", "known_machine_group?", "raise", "NoConfig", "unless", "@@config", "return", "true", "if", "default_machine_group?", "raise", "NoMachinesConfig", "unless", "@@config", ".", "machines", "return", "false", "if", "!", "@@config", "&&", "!", "@@global", "zon", ",", "env", ",", "rol", "=", "@@global", ".", "zone", ",", "@@global", ".", "environment", ",", "@@global", ".", "role", "conf", "=", "@@config", ".", "machines", ".", "find_deferred", "(", "@@global", ".", "region", ",", "zon", ",", "[", "env", ",", "rol", "]", ")", "conf", "||=", "@@config", ".", "machines", ".", "find_deferred", "(", "zon", ",", "[", "env", ",", "rol", "]", ")", "!", "conf", ".", "nil?", "end" ]
Looks for ENV-ROLE configuration in machines. There must be at least one definition in the config for this to return true That's how Rudy knows the current group is defined.
[ "Looks", "for", "ENV", "-", "ROLE", "configuration", "in", "machines", ".", "There", "must", "be", "at", "least", "one", "definition", "in", "the", "config", "for", "this", "to", "return", "true", "That", "s", "how", "Rudy", "knows", "the", "current", "group", "is", "defined", "." ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/huxtable.rb#L246-L255
24,312
solutious/rudy
lib/rudy/huxtable.rb
Rudy.Huxtable.fetch_routine_config
def fetch_routine_config(action) raise "No action specified" unless action raise NoConfig unless @@config raise NoRoutinesConfig unless @@config.routines raise NoGlobal unless @@global action = action.to_s.tr('-:', '_') zon, env, rol = @@global.zone, @@global.environment, @@global.role disk_defs = fetch_machine_param(:disks) || {} # We want to find only one routines config with the name +action+. # This is unlike the routines config where it's okay to merge via # precedence. routine = @@config.routines.find_deferred(@@global.environment, @@global.role, action) routine ||= @@config.routines.find_deferred([@@global.environment, @@global.role], action) routine ||= @@config.routines.find_deferred(@@global.role, action) return nil unless routine return routine unless routine.has_key?(:disks) routine.disks.each_pair do |raction,disks| unless disks.kind_of?(Hash) li "#{raction} is not defined. Check your #{action} routines config.".color(:red) next end disks.each_pair do |path, props| unless disk_defs.has_key?(path) li "#{path} is not defined. Check your machines config.".color(:red) routine.disks[raction].delete(path) next end routine.disks[raction][path] = disk_defs[path].merge(props) end end routine end
ruby
def fetch_routine_config(action) raise "No action specified" unless action raise NoConfig unless @@config raise NoRoutinesConfig unless @@config.routines raise NoGlobal unless @@global action = action.to_s.tr('-:', '_') zon, env, rol = @@global.zone, @@global.environment, @@global.role disk_defs = fetch_machine_param(:disks) || {} # We want to find only one routines config with the name +action+. # This is unlike the routines config where it's okay to merge via # precedence. routine = @@config.routines.find_deferred(@@global.environment, @@global.role, action) routine ||= @@config.routines.find_deferred([@@global.environment, @@global.role], action) routine ||= @@config.routines.find_deferred(@@global.role, action) return nil unless routine return routine unless routine.has_key?(:disks) routine.disks.each_pair do |raction,disks| unless disks.kind_of?(Hash) li "#{raction} is not defined. Check your #{action} routines config.".color(:red) next end disks.each_pair do |path, props| unless disk_defs.has_key?(path) li "#{path} is not defined. Check your machines config.".color(:red) routine.disks[raction].delete(path) next end routine.disks[raction][path] = disk_defs[path].merge(props) end end routine end
[ "def", "fetch_routine_config", "(", "action", ")", "raise", "\"No action specified\"", "unless", "action", "raise", "NoConfig", "unless", "@@config", "raise", "NoRoutinesConfig", "unless", "@@config", ".", "routines", "raise", "NoGlobal", "unless", "@@global", "action", "=", "action", ".", "to_s", ".", "tr", "(", "'-:'", ",", "'_'", ")", "zon", ",", "env", ",", "rol", "=", "@@global", ".", "zone", ",", "@@global", ".", "environment", ",", "@@global", ".", "role", "disk_defs", "=", "fetch_machine_param", "(", ":disks", ")", "||", "{", "}", "# We want to find only one routines config with the name +action+. ", "# This is unlike the routines config where it's okay to merge via", "# precedence. ", "routine", "=", "@@config", ".", "routines", ".", "find_deferred", "(", "@@global", ".", "environment", ",", "@@global", ".", "role", ",", "action", ")", "routine", "||=", "@@config", ".", "routines", ".", "find_deferred", "(", "[", "@@global", ".", "environment", ",", "@@global", ".", "role", "]", ",", "action", ")", "routine", "||=", "@@config", ".", "routines", ".", "find_deferred", "(", "@@global", ".", "role", ",", "action", ")", "return", "nil", "unless", "routine", "return", "routine", "unless", "routine", ".", "has_key?", "(", ":disks", ")", "routine", ".", "disks", ".", "each_pair", "do", "|", "raction", ",", "disks", "|", "unless", "disks", ".", "kind_of?", "(", "Hash", ")", "li", "\"#{raction} is not defined. Check your #{action} routines config.\"", ".", "color", "(", ":red", ")", "next", "end", "disks", ".", "each_pair", "do", "|", "path", ",", "props", "|", "unless", "disk_defs", ".", "has_key?", "(", "path", ")", "li", "\"#{path} is not defined. Check your machines config.\"", ".", "color", "(", ":red", ")", "routine", ".", "disks", "[", "raction", "]", ".", "delete", "(", "path", ")", "next", "end", "routine", ".", "disks", "[", "raction", "]", "[", "path", "]", "=", "disk_defs", "[", "path", "]", ".", "merge", "(", "props", ")", "end", "end", "routine", "end" ]
We grab the appropriate routines config and check the paths against those defined for the matching machine group. Disks that appear in a routine but not in a machine will be removed and a warning printed. Otherwise, the routines config is merged on top of the machine config and that's what we return. This means that all the disk info is returned so we know what size they are and stuff. Return a hash: :after: - :root: !ruby/object:Proc {} - :rudy: !ruby/object:Proc {} :disks: :create: /rudy/example1: :device: /dev/sdr :size: 2 /rudy/example2: :device: /dev/sdm :size: 1 NOTE: dashes in +action+ are converted to underscores. We do this because routine names are defined by method names and valid method names don't use dashes. This way, we can use a dash on the command-line which looks nicer (underscore still works of course).
[ "We", "grab", "the", "appropriate", "routines", "config", "and", "check", "the", "paths", "against", "those", "defined", "for", "the", "matching", "machine", "group", ".", "Disks", "that", "appear", "in", "a", "routine", "but", "not", "in", "a", "machine", "will", "be", "removed", "and", "a", "warning", "printed", ".", "Otherwise", "the", "routines", "config", "is", "merged", "on", "top", "of", "the", "machine", "config", "and", "that", "s", "what", "we", "return", "." ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/huxtable.rb#L286-L325
24,313
solutious/rudy
lib/rudy/huxtable.rb
Rudy.Huxtable.default_machine_group?
def default_machine_group? default_env = @@config.defaults.environment || Rudy::DEFAULT_ENVIRONMENT default_rol = @@config.defaults.role || Rudy::DEFAULT_ROLE @@global.environment == default_env && @@global.role == default_rol end
ruby
def default_machine_group? default_env = @@config.defaults.environment || Rudy::DEFAULT_ENVIRONMENT default_rol = @@config.defaults.role || Rudy::DEFAULT_ROLE @@global.environment == default_env && @@global.role == default_rol end
[ "def", "default_machine_group?", "default_env", "=", "@@config", ".", "defaults", ".", "environment", "||", "Rudy", "::", "DEFAULT_ENVIRONMENT", "default_rol", "=", "@@config", ".", "defaults", ".", "role", "||", "Rudy", "::", "DEFAULT_ROLE", "@@global", ".", "environment", "==", "default_env", "&&", "@@global", ".", "role", "==", "default_rol", "end" ]
Returns true if this is the default machine environment and role
[ "Returns", "true", "if", "this", "is", "the", "default", "machine", "environment", "and", "role" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/huxtable.rb#L352-L356
24,314
stereocat/expectacle
lib/expectacle/thrower_base_params.rb
Expectacle.ThrowerBase.check_embed_envvar
def check_embed_envvar(param) return unless param =~ /<%=\s*ENV\[[\'\"]?(.+)[\'\"]\]?\s*%>/ envvar_name = Regexp.last_match(1) if !ENV.key?(envvar_name) @logger.error "Variable name: #{envvar_name} is not found in ENV" elsif ENV[envvar_name] =~ /^\s*$/ @logger.warn "Env var: #{envvar_name} exists, but null string" end end
ruby
def check_embed_envvar(param) return unless param =~ /<%=\s*ENV\[[\'\"]?(.+)[\'\"]\]?\s*%>/ envvar_name = Regexp.last_match(1) if !ENV.key?(envvar_name) @logger.error "Variable name: #{envvar_name} is not found in ENV" elsif ENV[envvar_name] =~ /^\s*$/ @logger.warn "Env var: #{envvar_name} exists, but null string" end end
[ "def", "check_embed_envvar", "(", "param", ")", "return", "unless", "param", "=~", "/", "\\s", "\\[", "\\'", "\\\"", "\\'", "\\\"", "\\]", "\\s", "/", "envvar_name", "=", "Regexp", ".", "last_match", "(", "1", ")", "if", "!", "ENV", ".", "key?", "(", "envvar_name", ")", "@logger", ".", "error", "\"Variable name: #{envvar_name} is not found in ENV\"", "elsif", "ENV", "[", "envvar_name", "]", "=~", "/", "\\s", "/", "@logger", ".", "warn", "\"Env var: #{envvar_name} exists, but null string\"", "end", "end" ]
Error checking of environment variable to embed @param param [String] Embedding target command
[ "Error", "checking", "of", "environment", "variable", "to", "embed" ]
a67faca42ba5f90068c69047bb6cf01c2bca1b74
https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_base_params.rb#L86-L94
24,315
stereocat/expectacle
lib/expectacle/thrower_base_params.rb
Expectacle.ThrowerBase.embed_var
def embed_var(param) check_embed_envvar(param) erb = ERB.new(param) erb.result(binding) end
ruby
def embed_var(param) check_embed_envvar(param) erb = ERB.new(param) erb.result(binding) end
[ "def", "embed_var", "(", "param", ")", "check_embed_envvar", "(", "param", ")", "erb", "=", "ERB", ".", "new", "(", "param", ")", "erb", ".", "result", "(", "binding", ")", "end" ]
Embedding environment variable to parameter @param param [String] Embedding target command @return [String] Embedded command
[ "Embedding", "environment", "variable", "to", "parameter" ]
a67faca42ba5f90068c69047bb6cf01c2bca1b74
https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_base_params.rb#L99-L103
24,316
spox/actionpool
lib/actionpool/pool.rb
ActionPool.Pool.fill_pool
def fill_pool threads = [] if(@open) @lock.synchronize do required = min - size if(required > 0) required.times do thread = ActionPool::Thread.new(:pool => self, :respond_thread => @respond_to, :a_timeout => @action_timeout, :t_timeout => @thread_timeout, :logger => @logger, :autostart => false) @threads << thread threads << thread end end end end threads.each{|t|t.start} threads end
ruby
def fill_pool threads = [] if(@open) @lock.synchronize do required = min - size if(required > 0) required.times do thread = ActionPool::Thread.new(:pool => self, :respond_thread => @respond_to, :a_timeout => @action_timeout, :t_timeout => @thread_timeout, :logger => @logger, :autostart => false) @threads << thread threads << thread end end end end threads.each{|t|t.start} threads end
[ "def", "fill_pool", "threads", "=", "[", "]", "if", "(", "@open", ")", "@lock", ".", "synchronize", "do", "required", "=", "min", "-", "size", "if", "(", "required", ">", "0", ")", "required", ".", "times", "do", "thread", "=", "ActionPool", "::", "Thread", ".", "new", "(", ":pool", "=>", "self", ",", ":respond_thread", "=>", "@respond_to", ",", ":a_timeout", "=>", "@action_timeout", ",", ":t_timeout", "=>", "@thread_timeout", ",", ":logger", "=>", "@logger", ",", ":autostart", "=>", "false", ")", "@threads", "<<", "thread", "threads", "<<", "thread", "end", "end", "end", "end", "threads", ".", "each", "{", "|", "t", "|", "t", ".", "start", "}", "threads", "end" ]
Fills the pool with the minimum number of threads Returns array of created threads
[ "Fills", "the", "pool", "with", "the", "minimum", "number", "of", "threads", "Returns", "array", "of", "created", "threads" ]
e7f1398d5ffa32654af5b0321771330ce85e2182
https://github.com/spox/actionpool/blob/e7f1398d5ffa32654af5b0321771330ce85e2182/lib/actionpool/pool.rb#L82-L100
24,317
spox/actionpool
lib/actionpool/pool.rb
ActionPool.Pool.flush
def flush mon = Splib::Monitor.new @threads.size.times{ queue{ mon.wait } } @queue.wait_empty sleep(0.01) mon.broadcast end
ruby
def flush mon = Splib::Monitor.new @threads.size.times{ queue{ mon.wait } } @queue.wait_empty sleep(0.01) mon.broadcast end
[ "def", "flush", "mon", "=", "Splib", "::", "Monitor", ".", "new", "@threads", ".", "size", ".", "times", "{", "queue", "{", "mon", ".", "wait", "}", "}", "@queue", ".", "wait_empty", "sleep", "(", "0.01", ")", "mon", ".", "broadcast", "end" ]
Flush the thread pool. Mainly used for forcibly resizing the pool if existing threads have a long thread life waiting for input.
[ "Flush", "the", "thread", "pool", ".", "Mainly", "used", "for", "forcibly", "resizing", "the", "pool", "if", "existing", "threads", "have", "a", "long", "thread", "life", "waiting", "for", "input", "." ]
e7f1398d5ffa32654af5b0321771330ce85e2182
https://github.com/spox/actionpool/blob/e7f1398d5ffa32654af5b0321771330ce85e2182/lib/actionpool/pool.rb#L277-L283
24,318
spox/actionpool
lib/actionpool/pool.rb
ActionPool.Pool.resize
def resize @logger.info("Pool is being resized to stated maximum: #{max}") until(size <= max) do t = nil t = @threads.find{|x|x.waiting?} t = @threads.shift unless t t.stop end flush nil end
ruby
def resize @logger.info("Pool is being resized to stated maximum: #{max}") until(size <= max) do t = nil t = @threads.find{|x|x.waiting?} t = @threads.shift unless t t.stop end flush nil end
[ "def", "resize", "@logger", ".", "info", "(", "\"Pool is being resized to stated maximum: #{max}\"", ")", "until", "(", "size", "<=", "max", ")", "do", "t", "=", "nil", "t", "=", "@threads", ".", "find", "{", "|", "x", "|", "x", ".", "waiting?", "}", "t", "=", "@threads", ".", "shift", "unless", "t", "t", ".", "stop", "end", "flush", "nil", "end" ]
Resize the pool
[ "Resize", "the", "pool" ]
e7f1398d5ffa32654af5b0321771330ce85e2182
https://github.com/spox/actionpool/blob/e7f1398d5ffa32654af5b0321771330ce85e2182/lib/actionpool/pool.rb#L302-L312
24,319
stereocat/expectacle
lib/expectacle/thrower_base.rb
Expectacle.ThrowerBase.open_interactive_process
def open_interactive_process(spawn_cmd) @logger.info "Begin spawn: #{spawn_cmd}" PTY.spawn(spawn_cmd) do |reader, writer, _pid| @enable_mode = false @reader = reader @writer = writer @writer.sync = true yield end end
ruby
def open_interactive_process(spawn_cmd) @logger.info "Begin spawn: #{spawn_cmd}" PTY.spawn(spawn_cmd) do |reader, writer, _pid| @enable_mode = false @reader = reader @writer = writer @writer.sync = true yield end end
[ "def", "open_interactive_process", "(", "spawn_cmd", ")", "@logger", ".", "info", "\"Begin spawn: #{spawn_cmd}\"", "PTY", ".", "spawn", "(", "spawn_cmd", ")", "do", "|", "reader", ",", "writer", ",", "_pid", "|", "@enable_mode", "=", "false", "@reader", "=", "reader", "@writer", "=", "writer", "@writer", ".", "sync", "=", "true", "yield", "end", "end" ]
Spawn interactive process @yield [] Operations for interactive process
[ "Spawn", "interactive", "process" ]
a67faca42ba5f90068c69047bb6cf01c2bca1b74
https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_base.rb#L77-L86
24,320
stereocat/expectacle
lib/expectacle/thrower_base.rb
Expectacle.ThrowerBase.do_on_interactive_process
def do_on_interactive_process until @reader.closed? || @reader.eof? @reader.expect(expect_regexp, @timeout) do |match| yield match end end rescue Errno::EIO => error # on linux, PTY raises Errno::EIO when spawned process closed. @logger.debug "PTY raises Errno::EIO, #{error.message}" end
ruby
def do_on_interactive_process until @reader.closed? || @reader.eof? @reader.expect(expect_regexp, @timeout) do |match| yield match end end rescue Errno::EIO => error # on linux, PTY raises Errno::EIO when spawned process closed. @logger.debug "PTY raises Errno::EIO, #{error.message}" end
[ "def", "do_on_interactive_process", "until", "@reader", ".", "closed?", "||", "@reader", ".", "eof?", "@reader", ".", "expect", "(", "expect_regexp", ",", "@timeout", ")", "do", "|", "match", "|", "yield", "match", "end", "end", "rescue", "Errno", "::", "EIO", "=>", "error", "# on linux, PTY raises Errno::EIO when spawned process closed.", "@logger", ".", "debug", "\"PTY raises Errno::EIO, #{error.message}\"", "end" ]
Search prompt and send command, while process is opened @yield [match] Send operations when found prompt @yieldparam match [String] Expect matches string (prompt)
[ "Search", "prompt", "and", "send", "command", "while", "process", "is", "opened" ]
a67faca42ba5f90068c69047bb6cf01c2bca1b74
https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_base.rb#L108-L117
24,321
mileszim/webpurify-gem
lib/web_purify/methods/image_filters.rb
WebPurify.ImageFilters.imgcheck
def imgcheck(imgurl, options={}) params = { :method => WebPurify::Constants.methods[:imgcheck], :imgurl => imgurl } parsed = WebPurify::Request.query(image_request_base, @query_base, params.merge(options)) return parsed[:imgid] end
ruby
def imgcheck(imgurl, options={}) params = { :method => WebPurify::Constants.methods[:imgcheck], :imgurl => imgurl } parsed = WebPurify::Request.query(image_request_base, @query_base, params.merge(options)) return parsed[:imgid] end
[ "def", "imgcheck", "(", "imgurl", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":imgcheck", "]", ",", ":imgurl", "=>", "imgurl", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "image_request_base", ",", "@query_base", ",", "params", ".", "merge", "(", "options", ")", ")", "return", "parsed", "[", ":imgid", "]", "end" ]
Check for existence of prohibited image content @param imgurl [String] URL of the image to be moderated @param options [Hash] Options hash, used to set additional parameters @return [String] Image ID that is used to return results to the callback function
[ "Check", "for", "existence", "of", "prohibited", "image", "content" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/image_filters.rb#L13-L20
24,322
mileszim/webpurify-gem
lib/web_purify/methods/image_filters.rb
WebPurify.ImageFilters.imgstatus
def imgstatus(imgid, options={}) params = { :method => WebPurify::Constants.methods[:imgstatus], :imgid => imgid } parsed = WebPurify::Request.query(image_request_base, @query_base, params.merge(options)) return parsed[:status] end
ruby
def imgstatus(imgid, options={}) params = { :method => WebPurify::Constants.methods[:imgstatus], :imgid => imgid } parsed = WebPurify::Request.query(image_request_base, @query_base, params.merge(options)) return parsed[:status] end
[ "def", "imgstatus", "(", "imgid", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":imgstatus", "]", ",", ":imgid", "=>", "imgid", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "image_request_base", ",", "@query_base", ",", "params", ".", "merge", "(", "options", ")", ")", "return", "parsed", "[", ":status", "]", "end" ]
Return status of image moderation @param imgid [String] ID of the image being moderated @param options [Hash] Options hash, used to set additional parameters @return [String] Status of image moderation
[ "Return", "status", "of", "image", "moderation" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/image_filters.rb#L28-L35
24,323
mileszim/webpurify-gem
lib/web_purify/methods/image_filters.rb
WebPurify.ImageFilters.imgaccount
def imgaccount params = { :method => WebPurify::Constants.methods[:imgaccount] } parsed = WebPurify::Request.query(image_request_base, @query_base, params) return parsed[:remaining].to_i end
ruby
def imgaccount params = { :method => WebPurify::Constants.methods[:imgaccount] } parsed = WebPurify::Request.query(image_request_base, @query_base, params) return parsed[:remaining].to_i end
[ "def", "imgaccount", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":imgaccount", "]", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "image_request_base", ",", "@query_base", ",", "params", ")", "return", "parsed", "[", ":remaining", "]", ".", "to_i", "end" ]
Return number of image submissions remaining on license @return [Integer] Number of image submissions remaining
[ "Return", "number", "of", "image", "submissions", "remaining", "on", "license" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/image_filters.rb#L41-L47
24,324
cryptape/ruby-devp2p
lib/devp2p/utils.rb
DEVp2p.Utils.sxor
def sxor(s1, s2) raise ArgumentError, "strings must have equal size" unless s1.size == s2.size s1.bytes.zip(s2.bytes).map {|a, b| (a ^ b).chr }.join end
ruby
def sxor(s1, s2) raise ArgumentError, "strings must have equal size" unless s1.size == s2.size s1.bytes.zip(s2.bytes).map {|a, b| (a ^ b).chr }.join end
[ "def", "sxor", "(", "s1", ",", "s2", ")", "raise", "ArgumentError", ",", "\"strings must have equal size\"", "unless", "s1", ".", "size", "==", "s2", ".", "size", "s1", ".", "bytes", ".", "zip", "(", "s2", ".", "bytes", ")", ".", "map", "{", "|", "a", ",", "b", "|", "(", "a", "^", "b", ")", ".", "chr", "}", ".", "join", "end" ]
String xor.
[ "String", "xor", "." ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/utils.rb#L61-L65
24,325
stjernstrom/capistrano_colors
lib/capistrano_colors/configuration.rb
Capistrano.Configuration.colorize
def colorize(options) if options.class == Array options.each do |opt| Capistrano::Logger.add_color_matcher( opt ) end else Capistrano::Logger.add_color_matcher( options ) end end
ruby
def colorize(options) if options.class == Array options.each do |opt| Capistrano::Logger.add_color_matcher( opt ) end else Capistrano::Logger.add_color_matcher( options ) end end
[ "def", "colorize", "(", "options", ")", "if", "options", ".", "class", "==", "Array", "options", ".", "each", "do", "|", "opt", "|", "Capistrano", "::", "Logger", ".", "add_color_matcher", "(", "opt", ")", "end", "else", "Capistrano", "::", "Logger", ".", "add_color_matcher", "(", "options", ")", "end", "end" ]
Add custom colormatchers Passing a hash or a array of hashes with custom colormatchers. Add the following to your deploy.rb or in your ~/.caprc == Example: require 'capistrano_colors' capistrano_color_matchers = [ { :match => /command finished/, :color => :hide, :prio => 10, :prepend => "$$$" }, { :match => /executing command/, :color => :blue, :prio => 10, :attribute => :underscore, :timestamp => true }, { :match => /^transaction: commit$/, :color => :magenta, :prio => 10, :attribute => :blink }, { :match => /git/, :color => :white, :prio => 20, :attribute => :reverse }, ] colorize( capistrano_color_matchers ) You can call colorize multiple time with either a hash or an array of hashes multiple times. == Colors: :color can have the following values: * :hide (hides the row completely) * :none * :black * :red * :green * :yellow * :blue * :magenta * :cyan * :white == Attributes: :attribute can have the following values: * :bright * :dim * :underscore * :blink * :reverse * :hidden == Text alterations :prepend gives static text to be prepended to the output :replace replaces the matched text in the output :timestamp adds the current time before the output
[ "Add", "custom", "colormatchers" ]
7b44a2c6d504ccd3db29998e8245b918609f0b08
https://github.com/stjernstrom/capistrano_colors/blob/7b44a2c6d504ccd3db29998e8245b918609f0b08/lib/capistrano_colors/configuration.rb#L58-L68
24,326
kontera-technologies/nutcracker
lib/nutcracker.rb
Nutcracker.Wrapper.start
def start *args return self if attached? or running? @pid = ::Process.spawn Nutcracker.executable, *command Process.detach(@pid) sleep 2 raise "Nutcracker failed to start" unless running? Kernel.at_exit { kill if running? } self end
ruby
def start *args return self if attached? or running? @pid = ::Process.spawn Nutcracker.executable, *command Process.detach(@pid) sleep 2 raise "Nutcracker failed to start" unless running? Kernel.at_exit { kill if running? } self end
[ "def", "start", "*", "args", "return", "self", "if", "attached?", "or", "running?", "@pid", "=", "::", "Process", ".", "spawn", "Nutcracker", ".", "executable", ",", "command", "Process", ".", "detach", "(", "@pid", ")", "sleep", "2", "raise", "\"Nutcracker failed to start\"", "unless", "running?", "Kernel", ".", "at_exit", "{", "kill", "if", "running?", "}", "self", "end" ]
Initialize a new Nutcracker process wrappper @param [Hash] options @option options [String] :config_file (conf/nutcracker.yaml) path to nutcracker's configuration file @option options [String] :stats_uri Nutcracker stats URI - tcp://localhost:22222 @option options [String] :max_memory use fixed max memory size ( ignore server configuration ) @option options [Array] :args ([]) array with additional command line arguments launching the Nutcracker service
[ "Initialize", "a", "new", "Nutcracker", "process", "wrappper" ]
c02ccd38b5a2a105b4874af7bef5c5f95526bbad
https://github.com/kontera-technologies/nutcracker/blob/c02ccd38b5a2a105b4874af7bef5c5f95526bbad/lib/nutcracker.rb#L51-L59
24,327
kontera-technologies/nutcracker
lib/nutcracker.rb
Nutcracker.Wrapper.use
def use plugin, *args Nutcracker.const_get(plugin.to_s.capitalize).start(self,*args) end
ruby
def use plugin, *args Nutcracker.const_get(plugin.to_s.capitalize).start(self,*args) end
[ "def", "use", "plugin", ",", "*", "args", "Nutcracker", ".", "const_get", "(", "plugin", ".", "to_s", ".", "capitalize", ")", ".", "start", "(", "self", ",", "args", ")", "end" ]
Syntactic sugar for initialize plugins
[ "Syntactic", "sugar", "for", "initialize", "plugins" ]
c02ccd38b5a2a105b4874af7bef5c5f95526bbad
https://github.com/kontera-technologies/nutcracker/blob/c02ccd38b5a2a105b4874af7bef5c5f95526bbad/lib/nutcracker.rb#L92-L94
24,328
kontera-technologies/nutcracker
lib/nutcracker.rb
Nutcracker.Wrapper.overview
def overview data = { :clusters => [], :config => config } stats.each do |cluster_name, cluster_data| # Setting global server attributes ( like hostname, version etc...) unless cluster_data.is_a? Hash data[cluster_name] = cluster_data next end #next unless redis? cluster_name # skip memcached clusters aliases = node_aliases cluster_name cluster = { nodes: [], name: cluster_name } cluster_data.each do |node, node_value| # Adding node if node_value.kind_of? Hash node_data = cluster_data[node] node = aliases[node] || node url = ( node =~ /redis\:\/\// ) ? node : "redis://#{node}" info = redis_info(url, config[cluster_name]["redis_auth"]) cluster[:nodes] << { server_url: url, info: info, running: info.any? }.merge(node_data) else # Cluster attribute cluster[node] = node_value end end data[:clusters].push cluster end data end
ruby
def overview data = { :clusters => [], :config => config } stats.each do |cluster_name, cluster_data| # Setting global server attributes ( like hostname, version etc...) unless cluster_data.is_a? Hash data[cluster_name] = cluster_data next end #next unless redis? cluster_name # skip memcached clusters aliases = node_aliases cluster_name cluster = { nodes: [], name: cluster_name } cluster_data.each do |node, node_value| # Adding node if node_value.kind_of? Hash node_data = cluster_data[node] node = aliases[node] || node url = ( node =~ /redis\:\/\// ) ? node : "redis://#{node}" info = redis_info(url, config[cluster_name]["redis_auth"]) cluster[:nodes] << { server_url: url, info: info, running: info.any? }.merge(node_data) else # Cluster attribute cluster[node] = node_value end end data[:clusters].push cluster end data end
[ "def", "overview", "data", "=", "{", ":clusters", "=>", "[", "]", ",", ":config", "=>", "config", "}", "stats", ".", "each", "do", "|", "cluster_name", ",", "cluster_data", "|", "# Setting global server attributes ( like hostname, version etc...)", "unless", "cluster_data", ".", "is_a?", "Hash", "data", "[", "cluster_name", "]", "=", "cluster_data", "next", "end", "#next unless redis? cluster_name # skip memcached clusters", "aliases", "=", "node_aliases", "cluster_name", "cluster", "=", "{", "nodes", ":", "[", "]", ",", "name", ":", "cluster_name", "}", "cluster_data", ".", "each", "do", "|", "node", ",", "node_value", "|", "# Adding node", "if", "node_value", ".", "kind_of?", "Hash", "node_data", "=", "cluster_data", "[", "node", "]", "node", "=", "aliases", "[", "node", "]", "||", "node", "url", "=", "(", "node", "=~", "/", "\\:", "\\/", "\\/", "/", ")", "?", "node", ":", "\"redis://#{node}\"", "info", "=", "redis_info", "(", "url", ",", "config", "[", "cluster_name", "]", "[", "\"redis_auth\"", "]", ")", "cluster", "[", ":nodes", "]", "<<", "{", "server_url", ":", "url", ",", "info", ":", "info", ",", "running", ":", "info", ".", "any?", "}", ".", "merge", "(", "node_data", ")", "else", "# Cluster attribute", "cluster", "[", "node", "]", "=", "node_value", "end", "end", "data", "[", ":clusters", "]", ".", "push", "cluster", "end", "data", "end" ]
Returns hash with server and node statistics See example.json @ project root to get details about the structure
[ "Returns", "hash", "with", "server", "and", "node", "statistics", "See", "example", ".", "json" ]
c02ccd38b5a2a105b4874af7bef5c5f95526bbad
https://github.com/kontera-technologies/nutcracker/blob/c02ccd38b5a2a105b4874af7bef5c5f95526bbad/lib/nutcracker.rb#L98-L129
24,329
kontera-technologies/nutcracker
lib/nutcracker.rb
Nutcracker.Wrapper.redis_info
def redis_info url, password begin r = Redis.new url: url, password: password info = r.info.merge 'dbsize' => r.dbsize rescue Exception => e STDERR.puts "[ERROR][#{__FILE__}:#{__LINE__}] Failed to get data from Redis - " + "#{url.inspect} (using password #{password.inspect}): #{e.message}\n#{e.backtrace.join("\n")}" return {} end begin info['maxmemory'] = @options.fetch(:max_memory) { r.config(:get, 'maxmemory')['maxmemory'] } rescue Exception info['maxmemory'] = info['used_memory_rss'] end r.quit { 'connections' => info['connected_clients'].to_i, 'used_memory' => info['used_memory'].to_f, 'used_memory_rss' => info['used_memory_rss'].to_f, 'fragmentation' => info['mem_fragmentation_ratio'].to_f, 'expired_keys' => info['expired_keys'].to_i, 'evicted_keys' => info['evicted_keys'].to_i, 'hits' => info['keyspace_hits'].to_i, 'misses' => info['keyspace_misses'].to_i, 'keys' => info['dbsize'].to_i, 'max_memory' => info['maxmemory'].to_i, 'hit_ratio' => 0 }.tap {|d| d['hit_ratio'] = d['hits'].to_f / (d['hits']+d['misses']).to_f if d['hits'] > 0 } end
ruby
def redis_info url, password begin r = Redis.new url: url, password: password info = r.info.merge 'dbsize' => r.dbsize rescue Exception => e STDERR.puts "[ERROR][#{__FILE__}:#{__LINE__}] Failed to get data from Redis - " + "#{url.inspect} (using password #{password.inspect}): #{e.message}\n#{e.backtrace.join("\n")}" return {} end begin info['maxmemory'] = @options.fetch(:max_memory) { r.config(:get, 'maxmemory')['maxmemory'] } rescue Exception info['maxmemory'] = info['used_memory_rss'] end r.quit { 'connections' => info['connected_clients'].to_i, 'used_memory' => info['used_memory'].to_f, 'used_memory_rss' => info['used_memory_rss'].to_f, 'fragmentation' => info['mem_fragmentation_ratio'].to_f, 'expired_keys' => info['expired_keys'].to_i, 'evicted_keys' => info['evicted_keys'].to_i, 'hits' => info['keyspace_hits'].to_i, 'misses' => info['keyspace_misses'].to_i, 'keys' => info['dbsize'].to_i, 'max_memory' => info['maxmemory'].to_i, 'hit_ratio' => 0 }.tap {|d| d['hit_ratio'] = d['hits'].to_f / (d['hits']+d['misses']).to_f if d['hits'] > 0 } end
[ "def", "redis_info", "url", ",", "password", "begin", "r", "=", "Redis", ".", "new", "url", ":", "url", ",", "password", ":", "password", "info", "=", "r", ".", "info", ".", "merge", "'dbsize'", "=>", "r", ".", "dbsize", "rescue", "Exception", "=>", "e", "STDERR", ".", "puts", "\"[ERROR][#{__FILE__}:#{__LINE__}] Failed to get data from Redis - \"", "+", "\"#{url.inspect} (using password #{password.inspect}): #{e.message}\\n#{e.backtrace.join(\"\\n\")}\"", "return", "{", "}", "end", "begin", "info", "[", "'maxmemory'", "]", "=", "@options", ".", "fetch", "(", ":max_memory", ")", "{", "r", ".", "config", "(", ":get", ",", "'maxmemory'", ")", "[", "'maxmemory'", "]", "}", "rescue", "Exception", "info", "[", "'maxmemory'", "]", "=", "info", "[", "'used_memory_rss'", "]", "end", "r", ".", "quit", "{", "'connections'", "=>", "info", "[", "'connected_clients'", "]", ".", "to_i", ",", "'used_memory'", "=>", "info", "[", "'used_memory'", "]", ".", "to_f", ",", "'used_memory_rss'", "=>", "info", "[", "'used_memory_rss'", "]", ".", "to_f", ",", "'fragmentation'", "=>", "info", "[", "'mem_fragmentation_ratio'", "]", ".", "to_f", ",", "'expired_keys'", "=>", "info", "[", "'expired_keys'", "]", ".", "to_i", ",", "'evicted_keys'", "=>", "info", "[", "'evicted_keys'", "]", ".", "to_i", ",", "'hits'", "=>", "info", "[", "'keyspace_hits'", "]", ".", "to_i", ",", "'misses'", "=>", "info", "[", "'keyspace_misses'", "]", ".", "to_i", ",", "'keys'", "=>", "info", "[", "'dbsize'", "]", ".", "to_i", ",", "'max_memory'", "=>", "info", "[", "'maxmemory'", "]", ".", "to_i", ",", "'hit_ratio'", "=>", "0", "}", ".", "tap", "{", "|", "d", "|", "d", "[", "'hit_ratio'", "]", "=", "d", "[", "'hits'", "]", ".", "to_f", "/", "(", "d", "[", "'hits'", "]", "+", "d", "[", "'misses'", "]", ")", ".", "to_f", "if", "d", "[", "'hits'", "]", ">", "0", "}", "end" ]
Returns hash with information about a given Redis
[ "Returns", "hash", "with", "information", "about", "a", "given", "Redis" ]
c02ccd38b5a2a105b4874af7bef5c5f95526bbad
https://github.com/kontera-technologies/nutcracker/blob/c02ccd38b5a2a105b4874af7bef5c5f95526bbad/lib/nutcracker.rb#L142-L173
24,330
mileszim/webpurify-gem
lib/web_purify/methods/text_filters.rb
WebPurify.TextFilters.check
def check(text, options={}) params = { :method => WebPurify::Constants.methods[:check], :text => text } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) return parsed[:found]=='1' end
ruby
def check(text, options={}) params = { :method => WebPurify::Constants.methods[:check], :text => text } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) return parsed[:found]=='1' end
[ "def", "check", "(", "text", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":check", "]", ",", ":text", "=>", "text", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "text_request_base", ",", "@query_base", ",", "params", ".", "merge", "(", "options", ")", ")", "return", "parsed", "[", ":found", "]", "==", "'1'", "end" ]
Check for existence of profanity @param text [String] Text to test for profanity @param options [Hash] Options hash, used to set additional parameters @return [Boolean] True if text contains profanity, false if not
[ "Check", "for", "existence", "of", "profanity" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/text_filters.rb#L13-L20
24,331
mileszim/webpurify-gem
lib/web_purify/methods/text_filters.rb
WebPurify.TextFilters.check_count
def check_count(text, options={}) params = { :method => WebPurify::Constants.methods[:check_count], :text => text } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) return parsed[:found].to_i end
ruby
def check_count(text, options={}) params = { :method => WebPurify::Constants.methods[:check_count], :text => text } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) return parsed[:found].to_i end
[ "def", "check_count", "(", "text", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":check_count", "]", ",", ":text", "=>", "text", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "text_request_base", ",", "@query_base", ",", "params", ".", "merge", "(", "options", ")", ")", "return", "parsed", "[", ":found", "]", ".", "to_i", "end" ]
Check for existence of profanity and return number of profane words found @param text [String] Text to test for profanity @param options [Hash] Options hash, used to set additional parameters @return [Integer] The number of profane words found in text
[ "Check", "for", "existence", "of", "profanity", "and", "return", "number", "of", "profane", "words", "found" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/text_filters.rb#L28-L35
24,332
mileszim/webpurify-gem
lib/web_purify/methods/text_filters.rb
WebPurify.TextFilters.replace
def replace(text, symbol, options={}) params = { :method => WebPurify::Constants.methods[:replace], :text => text, :replacesymbol => symbol } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) return parsed[:text] end
ruby
def replace(text, symbol, options={}) params = { :method => WebPurify::Constants.methods[:replace], :text => text, :replacesymbol => symbol } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) return parsed[:text] end
[ "def", "replace", "(", "text", ",", "symbol", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":replace", "]", ",", ":text", "=>", "text", ",", ":replacesymbol", "=>", "symbol", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "text_request_base", ",", "@query_base", ",", "params", ".", "merge", "(", "options", ")", ")", "return", "parsed", "[", ":text", "]", "end" ]
Replace any matched profanity with provided symbol @param text [String] Text to test for profanity @param symbol [String] The symbol to replace each character of matched profanity @param options [Hash] Options hash, used to set additional parameters @return [String] The original text, replaced with the provided symbol
[ "Replace", "any", "matched", "profanity", "with", "provided", "symbol" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/text_filters.rb#L44-L52
24,333
mileszim/webpurify-gem
lib/web_purify/methods/text_filters.rb
WebPurify.TextFilters.return
def return(text, options={}) params = { :method => WebPurify::Constants.methods[:return], :text => text } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) if parsed[:expletive].is_a?(String) return [] << parsed[:expletive] else return parsed.fetch(:expletive, []) end end
ruby
def return(text, options={}) params = { :method => WebPurify::Constants.methods[:return], :text => text } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) if parsed[:expletive].is_a?(String) return [] << parsed[:expletive] else return parsed.fetch(:expletive, []) end end
[ "def", "return", "(", "text", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":return", "]", ",", ":text", "=>", "text", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "text_request_base", ",", "@query_base", ",", "params", ".", "merge", "(", "options", ")", ")", "if", "parsed", "[", ":expletive", "]", ".", "is_a?", "(", "String", ")", "return", "[", "]", "<<", "parsed", "[", ":expletive", "]", "else", "return", "parsed", ".", "fetch", "(", ":expletive", ",", "[", "]", ")", "end", "end" ]
Return an array of matched profanity @param text [String] Text to test for profanity @param options [Hash] Options hash, used to set additional parameters @return [Array] The array of matched profane words
[ "Return", "an", "array", "of", "matched", "profanity" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/text_filters.rb#L60-L71
24,334
solutious/rudy
lib/rudy/aws/ec2/group.rb
Rudy::AWS.EC2::Group.to_s
def to_s(with_title=false) lines = [liner_note] (self.addresses || {}).each_pair do |address,rules| lines << "%18s -> %s" % [address.to_s, rules.collect { |p| p.to_s}.join(', ')] end lines.join($/) end
ruby
def to_s(with_title=false) lines = [liner_note] (self.addresses || {}).each_pair do |address,rules| lines << "%18s -> %s" % [address.to_s, rules.collect { |p| p.to_s}.join(', ')] end lines.join($/) end
[ "def", "to_s", "(", "with_title", "=", "false", ")", "lines", "=", "[", "liner_note", "]", "(", "self", ".", "addresses", "||", "{", "}", ")", ".", "each_pair", "do", "|", "address", ",", "rules", "|", "lines", "<<", "\"%18s -> %s\"", "%", "[", "address", ".", "to_s", ",", "rules", ".", "collect", "{", "|", "p", "|", "p", ".", "to_s", "}", ".", "join", "(", "', '", ")", "]", "end", "lines", ".", "join", "(", "$/", ")", "end" ]
Print info about a security group * +group+ is a Rudy::AWS::EC2::Group object
[ "Print", "info", "about", "a", "security", "group" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/aws/ec2/group.rb#L37-L43
24,335
spox/actionpool
lib/actionpool/thread.rb
ActionPool.Thread.start_thread
def start_thread begin @logger.info("New pool thread is starting (#{self})") until(@kill) do begin @action = nil if(@pool.size > @pool.min && !@thread_timeout.zero?) Timeout::timeout(@thread_timeout) do @action = @pool.action end else @action = @pool.action end run(@action[0], @action[1]) unless @action.nil? rescue Timeout::Error @kill = true rescue Wakeup @logger.info("Thread #{::Thread.current} was woken up.") rescue Retimeout @logger.warn('Thread was woken up to reset thread timeout') rescue Exception => boom @logger.error("Pool thread caught an exception: #{boom}\n#{boom.backtrace.join("\n")}") @respond_to.raise boom end end rescue Retimeout @logger.warn('Thread was woken up to reset thread timeout') retry rescue Wakeup @logger.info("Thread #{::Thread.current} was woken up.") rescue Exception => boom @logger.error("Pool thread caught an exception: #{boom}\n#{boom.backtrace.join("\n")}") @respond_to.raise boom ensure @logger.info("Pool thread is shutting down (#{self})") @pool.remove(self) end end
ruby
def start_thread begin @logger.info("New pool thread is starting (#{self})") until(@kill) do begin @action = nil if(@pool.size > @pool.min && !@thread_timeout.zero?) Timeout::timeout(@thread_timeout) do @action = @pool.action end else @action = @pool.action end run(@action[0], @action[1]) unless @action.nil? rescue Timeout::Error @kill = true rescue Wakeup @logger.info("Thread #{::Thread.current} was woken up.") rescue Retimeout @logger.warn('Thread was woken up to reset thread timeout') rescue Exception => boom @logger.error("Pool thread caught an exception: #{boom}\n#{boom.backtrace.join("\n")}") @respond_to.raise boom end end rescue Retimeout @logger.warn('Thread was woken up to reset thread timeout') retry rescue Wakeup @logger.info("Thread #{::Thread.current} was woken up.") rescue Exception => boom @logger.error("Pool thread caught an exception: #{boom}\n#{boom.backtrace.join("\n")}") @respond_to.raise boom ensure @logger.info("Pool thread is shutting down (#{self})") @pool.remove(self) end end
[ "def", "start_thread", "begin", "@logger", ".", "info", "(", "\"New pool thread is starting (#{self})\"", ")", "until", "(", "@kill", ")", "do", "begin", "@action", "=", "nil", "if", "(", "@pool", ".", "size", ">", "@pool", ".", "min", "&&", "!", "@thread_timeout", ".", "zero?", ")", "Timeout", "::", "timeout", "(", "@thread_timeout", ")", "do", "@action", "=", "@pool", ".", "action", "end", "else", "@action", "=", "@pool", ".", "action", "end", "run", "(", "@action", "[", "0", "]", ",", "@action", "[", "1", "]", ")", "unless", "@action", ".", "nil?", "rescue", "Timeout", "::", "Error", "@kill", "=", "true", "rescue", "Wakeup", "@logger", ".", "info", "(", "\"Thread #{::Thread.current} was woken up.\"", ")", "rescue", "Retimeout", "@logger", ".", "warn", "(", "'Thread was woken up to reset thread timeout'", ")", "rescue", "Exception", "=>", "boom", "@logger", ".", "error", "(", "\"Pool thread caught an exception: #{boom}\\n#{boom.backtrace.join(\"\\n\")}\"", ")", "@respond_to", ".", "raise", "boom", "end", "end", "rescue", "Retimeout", "@logger", ".", "warn", "(", "'Thread was woken up to reset thread timeout'", ")", "retry", "rescue", "Wakeup", "@logger", ".", "info", "(", "\"Thread #{::Thread.current} was woken up.\"", ")", "rescue", "Exception", "=>", "boom", "@logger", ".", "error", "(", "\"Pool thread caught an exception: #{boom}\\n#{boom.backtrace.join(\"\\n\")}\"", ")", "@respond_to", ".", "raise", "boom", "ensure", "@logger", ".", "info", "(", "\"Pool thread is shutting down (#{self})\"", ")", "@pool", ".", "remove", "(", "self", ")", "end", "end" ]
Start our thread
[ "Start", "our", "thread" ]
e7f1398d5ffa32654af5b0321771330ce85e2182
https://github.com/spox/actionpool/blob/e7f1398d5ffa32654af5b0321771330ce85e2182/lib/actionpool/thread.rb#L120-L157
24,336
dkd/paymill-ruby
lib/paymill/subscription.rb
Paymill.Subscription.parse_timestamps
def parse_timestamps super @next_capture_at = Time.at(next_capture_at) if next_capture_at @canceled_at = Time.at(canceled_at) if canceled_at @trial_start = Time.at(trial_start) if trial_start @trial_end = Time.at(trial_end) if trial_end end
ruby
def parse_timestamps super @next_capture_at = Time.at(next_capture_at) if next_capture_at @canceled_at = Time.at(canceled_at) if canceled_at @trial_start = Time.at(trial_start) if trial_start @trial_end = Time.at(trial_end) if trial_end end
[ "def", "parse_timestamps", "super", "@next_capture_at", "=", "Time", ".", "at", "(", "next_capture_at", ")", "if", "next_capture_at", "@canceled_at", "=", "Time", ".", "at", "(", "canceled_at", ")", "if", "canceled_at", "@trial_start", "=", "Time", ".", "at", "(", "trial_start", ")", "if", "trial_start", "@trial_end", "=", "Time", ".", "at", "(", "trial_end", ")", "if", "trial_end", "end" ]
Parses UNIX timestamps and creates Time objects
[ "Parses", "UNIX", "timestamps", "and", "creates", "Time", "objects" ]
4dd177faf1e5c08dae0c66fe493ccce535c9c97d
https://github.com/dkd/paymill-ruby/blob/4dd177faf1e5c08dae0c66fe493ccce535c9c97d/lib/paymill/subscription.rb#L10-L16
24,337
tobiasfeistmantl/LeSSL
lib/le_ssl/dns.rb
LeSSL.DNS.challenge_record_valid?
def challenge_record_valid?(domain, key) record = challenge_record(domain) return record && record.data == key end
ruby
def challenge_record_valid?(domain, key) record = challenge_record(domain) return record && record.data == key end
[ "def", "challenge_record_valid?", "(", "domain", ",", "key", ")", "record", "=", "challenge_record", "(", "domain", ")", "return", "record", "&&", "record", ".", "data", "==", "key", "end" ]
Checks if the TXT record for a domain is valid.
[ "Checks", "if", "the", "TXT", "record", "for", "a", "domain", "is", "valid", "." ]
7ef8b39d1ebe47534424c9c12dc6d82b54dfe8ba
https://github.com/tobiasfeistmantl/LeSSL/blob/7ef8b39d1ebe47534424c9c12dc6d82b54dfe8ba/lib/le_ssl/dns.rb#L9-L12
24,338
nofxx/yamg
lib/yamg/splash.rb
YAMG.Splash.splash_composite
def splash_composite max = size.min / 9 assets.each do |over| other = MiniMagick::Image.open(File.join(src, over)) other.resize(max) if other.dimensions.max >= max self.img = compose(other, over) end end
ruby
def splash_composite max = size.min / 9 assets.each do |over| other = MiniMagick::Image.open(File.join(src, over)) other.resize(max) if other.dimensions.max >= max self.img = compose(other, over) end end
[ "def", "splash_composite", "max", "=", "size", ".", "min", "/", "9", "assets", ".", "each", "do", "|", "over", "|", "other", "=", "MiniMagick", "::", "Image", ".", "open", "(", "File", ".", "join", "(", "src", ",", "over", ")", ")", "other", ".", "resize", "(", "max", ")", "if", "other", ".", "dimensions", ".", "max", ">=", "max", "self", ".", "img", "=", "compose", "(", "other", ",", "over", ")", "end", "end" ]
Composite 9 gravity
[ "Composite", "9", "gravity" ]
0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4
https://github.com/nofxx/yamg/blob/0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4/lib/yamg/splash.rb#L60-L67
24,339
nofxx/yamg
lib/yamg/splash.rb
YAMG.Splash.image
def image(out = nil) splash_start splash_composite return img unless out FileUtils.mkdir_p File.dirname(out) img.write(out) rescue Errno::ENOENT YAMG.puts_and_exit("Path not found '#{out}'") end
ruby
def image(out = nil) splash_start splash_composite return img unless out FileUtils.mkdir_p File.dirname(out) img.write(out) rescue Errno::ENOENT YAMG.puts_and_exit("Path not found '#{out}'") end
[ "def", "image", "(", "out", "=", "nil", ")", "splash_start", "splash_composite", "return", "img", "unless", "out", "FileUtils", ".", "mkdir_p", "File", ".", "dirname", "(", "out", ")", "img", ".", "write", "(", "out", ")", "rescue", "Errno", "::", "ENOENT", "YAMG", ".", "puts_and_exit", "(", "\"Path not found '#{out}'\"", ")", "end" ]
Outputs instance or writes image to disk
[ "Outputs", "instance", "or", "writes", "image", "to", "disk" ]
0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4
https://github.com/nofxx/yamg/blob/0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4/lib/yamg/splash.rb#L72-L80
24,340
tumblr/collins_client
lib/collins/client.rb
Collins.Client.manage_process
def manage_process name = nil name = @managed_process if name.nil? if name then begin Collins.const_get(name).new(self).run rescue Exception => e raise CollinsError.new(e.message) end else raise CollinsError.new("No managed process specified") end end
ruby
def manage_process name = nil name = @managed_process if name.nil? if name then begin Collins.const_get(name).new(self).run rescue Exception => e raise CollinsError.new(e.message) end else raise CollinsError.new("No managed process specified") end end
[ "def", "manage_process", "name", "=", "nil", "name", "=", "@managed_process", "if", "name", ".", "nil?", "if", "name", "then", "begin", "Collins", ".", "const_get", "(", "name", ")", ".", "new", "(", "self", ")", ".", "run", "rescue", "Exception", "=>", "e", "raise", "CollinsError", ".", "new", "(", "e", ".", "message", ")", "end", "else", "raise", "CollinsError", ".", "new", "(", "\"No managed process specified\"", ")", "end", "end" ]
Create a collins client instance @param [Hash] options host, username and password are required @option options [String] :host a scheme, hostname and port (e.g. https://hostname) @option options [Logger] :logger a logger to use, one is created if none is specified @option options [Fixnum] :timeout (10) timeout in seconds to wait for a response @option options [String] :username username for authentication @option options [String] :password password for authentication @option options [String] :managed_process see {#manage_process} @option options [Boolean] :strict (false) see {#strict} Interact with a collins managed process @param [String] name Name of process @raise [CollinsError] if no managed process is specified/found @return [Collins::ManagedState::Mixin] see mixin for more information
[ "Create", "a", "collins", "client", "instance" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/client.rb#L64-L75
24,341
scottwillson/tabular
lib/tabular/row.rb
Tabular.Row.[]=
def []=(key, value) if columns.key?(key) @array[columns.index(key)] = value else @array << value columns << key end hash[key] = value end
ruby
def []=(key, value) if columns.key?(key) @array[columns.index(key)] = value else @array << value columns << key end hash[key] = value end
[ "def", "[]=", "(", "key", ",", "value", ")", "if", "columns", ".", "key?", "(", "key", ")", "@array", "[", "columns", ".", "index", "(", "key", ")", "]", "=", "value", "else", "@array", "<<", "value", "columns", "<<", "key", "end", "hash", "[", "key", "]", "=", "value", "end" ]
Set cell value. Adds cell to end of Row and adds new Column if there is no Column for +key_
[ "Set", "cell", "value", ".", "Adds", "cell", "to", "end", "of", "Row", "and", "adds", "new", "Column", "if", "there", "is", "no", "Column", "for", "+", "key_" ]
a479a0d55e91eb286f16adbfe43f97d69abbbe08
https://github.com/scottwillson/tabular/blob/a479a0d55e91eb286f16adbfe43f97d69abbbe08/lib/tabular/row.rb#L42-L50
24,342
Dynamit/referee
lib/referee/codegenerator.rb
Referee.CodeGenerator.create_dictionary_representation
def create_dictionary_representation dict = { storyboards: [], table_cells: [], collection_cells: [], view_controllers: [], segues: [], prefix: @config.prefix } @project.resources.each do |group| dict[:storyboards] << group.storyboard dict[:table_cells] += group.table_cells dict[:collection_cells] += group.collection_cells dict[:view_controllers] += group.view_controllers dict[:segues] += group.segues end # Build up flags. dict[:has_table_cells] = (dict[:table_cells].count > 0) dict[:has_collection_cells] = (dict[:collection_cells].count > 0) dict[:has_segues] = (dict[:segues].count > 0) dict end
ruby
def create_dictionary_representation dict = { storyboards: [], table_cells: [], collection_cells: [], view_controllers: [], segues: [], prefix: @config.prefix } @project.resources.each do |group| dict[:storyboards] << group.storyboard dict[:table_cells] += group.table_cells dict[:collection_cells] += group.collection_cells dict[:view_controllers] += group.view_controllers dict[:segues] += group.segues end # Build up flags. dict[:has_table_cells] = (dict[:table_cells].count > 0) dict[:has_collection_cells] = (dict[:collection_cells].count > 0) dict[:has_segues] = (dict[:segues].count > 0) dict end
[ "def", "create_dictionary_representation", "dict", "=", "{", "storyboards", ":", "[", "]", ",", "table_cells", ":", "[", "]", ",", "collection_cells", ":", "[", "]", ",", "view_controllers", ":", "[", "]", ",", "segues", ":", "[", "]", ",", "prefix", ":", "@config", ".", "prefix", "}", "@project", ".", "resources", ".", "each", "do", "|", "group", "|", "dict", "[", ":storyboards", "]", "<<", "group", ".", "storyboard", "dict", "[", ":table_cells", "]", "+=", "group", ".", "table_cells", "dict", "[", ":collection_cells", "]", "+=", "group", ".", "collection_cells", "dict", "[", ":view_controllers", "]", "+=", "group", ".", "view_controllers", "dict", "[", ":segues", "]", "+=", "group", ".", "segues", "end", "# Build up flags.", "dict", "[", ":has_table_cells", "]", "=", "(", "dict", "[", ":table_cells", "]", ".", "count", ">", "0", ")", "dict", "[", ":has_collection_cells", "]", "=", "(", "dict", "[", ":collection_cells", "]", ".", "count", ">", "0", ")", "dict", "[", ":has_segues", "]", "=", "(", "dict", "[", ":segues", "]", ".", "count", ">", "0", ")", "dict", "end" ]
Converts the resources into a Mustache-compatible template dictionary.
[ "Converts", "the", "resources", "into", "a", "Mustache", "-", "compatible", "template", "dictionary", "." ]
58189bf841d0195f7f2236262a649c67cfc92bf1
https://github.com/Dynamit/referee/blob/58189bf841d0195f7f2236262a649c67cfc92bf1/lib/referee/codegenerator.rb#L51-L73
24,343
nofxx/yamg
lib/yamg/screenshot.rb
YAMG.Screenshot.work
def work(path) out = "#{path}/#{@name}.png" @fetcher.fetch(output: out, width: @size[0], height: @size[1], dpi: @dpi) rescue Screencap::Error puts "Fail to capture screenshot #{@url}" end
ruby
def work(path) out = "#{path}/#{@name}.png" @fetcher.fetch(output: out, width: @size[0], height: @size[1], dpi: @dpi) rescue Screencap::Error puts "Fail to capture screenshot #{@url}" end
[ "def", "work", "(", "path", ")", "out", "=", "\"#{path}/#{@name}.png\"", "@fetcher", ".", "fetch", "(", "output", ":", "out", ",", "width", ":", "@size", "[", "0", "]", ",", "height", ":", "@size", "[", "1", "]", ",", "dpi", ":", "@dpi", ")", "rescue", "Screencap", "::", "Error", "puts", "\"Fail to capture screenshot #{@url}\"", "end" ]
Take the screenshot Do we need pixel depth??
[ "Take", "the", "screenshot", "Do", "we", "need", "pixel", "depth??" ]
0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4
https://github.com/nofxx/yamg/blob/0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4/lib/yamg/screenshot.rb#L27-L32
24,344
scottwillson/tabular
lib/tabular/columns.rb
Tabular.Columns.<<
def <<(key) column = Column.new(@table, self, key) return if is_blank?(column.key) || key?(key) @column_indexes[column.key] = @columns.size @column_indexes[@columns.size] = column @columns_by_key[column.key] = column @columns << column end
ruby
def <<(key) column = Column.new(@table, self, key) return if is_blank?(column.key) || key?(key) @column_indexes[column.key] = @columns.size @column_indexes[@columns.size] = column @columns_by_key[column.key] = column @columns << column end
[ "def", "<<", "(", "key", ")", "column", "=", "Column", ".", "new", "(", "@table", ",", "self", ",", "key", ")", "return", "if", "is_blank?", "(", "column", ".", "key", ")", "||", "key?", "(", "key", ")", "@column_indexes", "[", "column", ".", "key", "]", "=", "@columns", ".", "size", "@column_indexes", "[", "@columns", ".", "size", "]", "=", "column", "@columns_by_key", "[", "column", ".", "key", "]", "=", "column", "@columns", "<<", "column", "end" ]
Add a new Column with +key+
[ "Add", "a", "new", "Column", "with", "+", "key", "+" ]
a479a0d55e91eb286f16adbfe43f97d69abbbe08
https://github.com/scottwillson/tabular/blob/a479a0d55e91eb286f16adbfe43f97d69abbbe08/lib/tabular/columns.rb#L77-L85
24,345
NoRedInk/elm_sprockets
lib/elm_sprockets/processor.rb
ElmSprockets.Processor.add_elm_dependencies
def add_elm_dependencies(filepath, context) # Turn e.g. ~/NoRedInk/app/assets/javascripts/Quiz/QuestionStoreAPI.js.elm # into just ~/NoRedInk/app/assets/javascripts/ dirname = context.pathname.to_s.gsub Regexp.new(context.logical_path + ".+$"), "" File.read(filepath).each_line do |line| # e.g. `import Quiz.QuestionStore exposing (..)` match = line.match(/^import\s+([^\s]+)/) next unless match # e.g. Quiz.QuestionStore module_name = match.captures[0] # e.g. Quiz/QuestionStore dependency_logical_name = module_name.tr(".", "/") # e.g. ~/NoRedInk/app/assets/javascripts/Quiz/QuestionStore.elm dependency_filepath = dirname + dependency_logical_name + ".elm" # If we don't find the dependency in our filesystem, assume it's because # it comes in through a third-party package rather than our sources. next unless File.file? dependency_filepath context.depend_on dependency_logical_name add_elm_dependencies dependency_filepath, context end end
ruby
def add_elm_dependencies(filepath, context) # Turn e.g. ~/NoRedInk/app/assets/javascripts/Quiz/QuestionStoreAPI.js.elm # into just ~/NoRedInk/app/assets/javascripts/ dirname = context.pathname.to_s.gsub Regexp.new(context.logical_path + ".+$"), "" File.read(filepath).each_line do |line| # e.g. `import Quiz.QuestionStore exposing (..)` match = line.match(/^import\s+([^\s]+)/) next unless match # e.g. Quiz.QuestionStore module_name = match.captures[0] # e.g. Quiz/QuestionStore dependency_logical_name = module_name.tr(".", "/") # e.g. ~/NoRedInk/app/assets/javascripts/Quiz/QuestionStore.elm dependency_filepath = dirname + dependency_logical_name + ".elm" # If we don't find the dependency in our filesystem, assume it's because # it comes in through a third-party package rather than our sources. next unless File.file? dependency_filepath context.depend_on dependency_logical_name add_elm_dependencies dependency_filepath, context end end
[ "def", "add_elm_dependencies", "(", "filepath", ",", "context", ")", "# Turn e.g. ~/NoRedInk/app/assets/javascripts/Quiz/QuestionStoreAPI.js.elm", "# into just ~/NoRedInk/app/assets/javascripts/", "dirname", "=", "context", ".", "pathname", ".", "to_s", ".", "gsub", "Regexp", ".", "new", "(", "context", ".", "logical_path", "+", "\".+$\"", ")", ",", "\"\"", "File", ".", "read", "(", "filepath", ")", ".", "each_line", "do", "|", "line", "|", "# e.g. `import Quiz.QuestionStore exposing (..)`", "match", "=", "line", ".", "match", "(", "/", "\\s", "\\s", "/", ")", "next", "unless", "match", "# e.g. Quiz.QuestionStore", "module_name", "=", "match", ".", "captures", "[", "0", "]", "# e.g. Quiz/QuestionStore", "dependency_logical_name", "=", "module_name", ".", "tr", "(", "\".\"", ",", "\"/\"", ")", "# e.g. ~/NoRedInk/app/assets/javascripts/Quiz/QuestionStore.elm", "dependency_filepath", "=", "dirname", "+", "dependency_logical_name", "+", "\".elm\"", "# If we don't find the dependency in our filesystem, assume it's because", "# it comes in through a third-party package rather than our sources.", "next", "unless", "File", ".", "file?", "dependency_filepath", "context", ".", "depend_on", "dependency_logical_name", "add_elm_dependencies", "dependency_filepath", ",", "context", "end", "end" ]
Add all Elm modules imported in the target file as dependencies, then recursively do the same for each of those dependent modules.
[ "Add", "all", "Elm", "modules", "imported", "in", "the", "target", "file", "as", "dependencies", "then", "recursively", "do", "the", "same", "for", "each", "of", "those", "dependent", "modules", "." ]
de697ff703d9904e48eee1a55202a8892eeefcc1
https://github.com/NoRedInk/elm_sprockets/blob/de697ff703d9904e48eee1a55202a8892eeefcc1/lib/elm_sprockets/processor.rb#L32-L59
24,346
tumblr/collins_client
lib/collins/api.rb
Collins.Api.trace
def trace(progname = nil, &block) if logger.respond_to?(:trace) then logger.trace(progname, &block) else logger.debug(progname, &block) end end
ruby
def trace(progname = nil, &block) if logger.respond_to?(:trace) then logger.trace(progname, &block) else logger.debug(progname, &block) end end
[ "def", "trace", "(", "progname", "=", "nil", ",", "&", "block", ")", "if", "logger", ".", "respond_to?", "(", ":trace", ")", "then", "logger", ".", "trace", "(", "progname", ",", "block", ")", "else", "logger", ".", "debug", "(", "progname", ",", "block", ")", "end", "end" ]
Provides a safe wrapper for our monkeypatched logger If the provided logger responds to a trace method, use that method. Otherwise fallback to using the debug method.
[ "Provides", "a", "safe", "wrapper", "for", "our", "monkeypatched", "logger" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/api.rb#L94-L100
24,347
PerfectMemory/freebase-api
lib/freebase_api/session.rb
FreebaseAPI.Session.surl
def surl(service) service_url = @env == :stable ? API_URL : SANDBOX_API_URL service_url = service_url + "/" + service service_url.gsub!('www', 'usercontent') if service.to_s == 'image' service_url end
ruby
def surl(service) service_url = @env == :stable ? API_URL : SANDBOX_API_URL service_url = service_url + "/" + service service_url.gsub!('www', 'usercontent') if service.to_s == 'image' service_url end
[ "def", "surl", "(", "service", ")", "service_url", "=", "@env", "==", ":stable", "?", "API_URL", ":", "SANDBOX_API_URL", "service_url", "=", "service_url", "+", "\"/\"", "+", "service", "service_url", ".", "gsub!", "(", "'www'", ",", "'usercontent'", ")", "if", "service", ".", "to_s", "==", "'image'", "service_url", "end" ]
Return the URL of a Freebase service @param [String] service the service @return [String] the url of the service
[ "Return", "the", "URL", "of", "a", "Freebase", "service" ]
fb9065cafce5a77d73a6c44de14bdcf4bca54be3
https://github.com/PerfectMemory/freebase-api/blob/fb9065cafce5a77d73a6c44de14bdcf4bca54be3/lib/freebase_api/session.rb#L79-L84
24,348
PerfectMemory/freebase-api
lib/freebase_api/session.rb
FreebaseAPI.Session.get
def get(url, params={}, options={}) FreebaseAPI.logger.debug("GET #{url}") params[:key] = @key if @key options = { format: options[:format], query: params } options.merge!(@proxy_options) response = self.class.get(url, options) handle_response(response) end
ruby
def get(url, params={}, options={}) FreebaseAPI.logger.debug("GET #{url}") params[:key] = @key if @key options = { format: options[:format], query: params } options.merge!(@proxy_options) response = self.class.get(url, options) handle_response(response) end
[ "def", "get", "(", "url", ",", "params", "=", "{", "}", ",", "options", "=", "{", "}", ")", "FreebaseAPI", ".", "logger", ".", "debug", "(", "\"GET #{url}\"", ")", "params", "[", ":key", "]", "=", "@key", "if", "@key", "options", "=", "{", "format", ":", "options", "[", ":format", "]", ",", "query", ":", "params", "}", "options", ".", "merge!", "(", "@proxy_options", ")", "response", "=", "self", ".", "class", ".", "get", "(", "url", ",", "options", ")", "handle_response", "(", "response", ")", "end" ]
Make a GET request @param [String] url the url to request @param [Hash] params the params of the request @return the request response
[ "Make", "a", "GET", "request" ]
fb9065cafce5a77d73a6c44de14bdcf4bca54be3
https://github.com/PerfectMemory/freebase-api/blob/fb9065cafce5a77d73a6c44de14bdcf4bca54be3/lib/freebase_api/session.rb#L91-L98
24,349
PerfectMemory/freebase-api
lib/freebase_api/session.rb
FreebaseAPI.Session.handle_response
def handle_response(response) case response.code when 200..299 response else if response.request.format == :json raise FreebaseAPI::ServiceError.new(response['error']) else raise FreebaseAPI::NetError.new('code' => response.code, 'message' => response.response.message) end end end
ruby
def handle_response(response) case response.code when 200..299 response else if response.request.format == :json raise FreebaseAPI::ServiceError.new(response['error']) else raise FreebaseAPI::NetError.new('code' => response.code, 'message' => response.response.message) end end end
[ "def", "handle_response", "(", "response", ")", "case", "response", ".", "code", "when", "200", "..", "299", "response", "else", "if", "response", ".", "request", ".", "format", "==", ":json", "raise", "FreebaseAPI", "::", "ServiceError", ".", "new", "(", "response", "[", "'error'", "]", ")", "else", "raise", "FreebaseAPI", "::", "NetError", ".", "new", "(", "'code'", "=>", "response", ".", "code", ",", "'message'", "=>", "response", ".", "response", ".", "message", ")", "end", "end", "end" ]
Handle the response If success, return the response body If failure, raise an error
[ "Handle", "the", "response" ]
fb9065cafce5a77d73a6c44de14bdcf4bca54be3
https://github.com/PerfectMemory/freebase-api/blob/fb9065cafce5a77d73a6c44de14bdcf4bca54be3/lib/freebase_api/session.rb#L104-L115
24,350
PerfectMemory/freebase-api
lib/freebase_api/session.rb
FreebaseAPI.Session.get_proxy_options
def get_proxy_options(url=nil) options = {} if url = url || ENV['HTTPS_PROXY'] || ENV['https_proxy'] || ENV['HTTP_PROXY'] || ENV['http_proxy'] proxy_uri = URI.parse(url) options[:http_proxyaddr] = proxy_uri.host options[:http_proxyport] = proxy_uri.port options[:http_proxyuser] = proxy_uri.user options[:http_proxypass] = proxy_uri.password end options end
ruby
def get_proxy_options(url=nil) options = {} if url = url || ENV['HTTPS_PROXY'] || ENV['https_proxy'] || ENV['HTTP_PROXY'] || ENV['http_proxy'] proxy_uri = URI.parse(url) options[:http_proxyaddr] = proxy_uri.host options[:http_proxyport] = proxy_uri.port options[:http_proxyuser] = proxy_uri.user options[:http_proxypass] = proxy_uri.password end options end
[ "def", "get_proxy_options", "(", "url", "=", "nil", ")", "options", "=", "{", "}", "if", "url", "=", "url", "||", "ENV", "[", "'HTTPS_PROXY'", "]", "||", "ENV", "[", "'https_proxy'", "]", "||", "ENV", "[", "'HTTP_PROXY'", "]", "||", "ENV", "[", "'http_proxy'", "]", "proxy_uri", "=", "URI", ".", "parse", "(", "url", ")", "options", "[", ":http_proxyaddr", "]", "=", "proxy_uri", ".", "host", "options", "[", ":http_proxyport", "]", "=", "proxy_uri", ".", "port", "options", "[", ":http_proxyuser", "]", "=", "proxy_uri", ".", "user", "options", "[", ":http_proxypass", "]", "=", "proxy_uri", ".", "password", "end", "options", "end" ]
Get the proxy options for HTTParty @return [Hash] the proxy options
[ "Get", "the", "proxy", "options", "for", "HTTParty" ]
fb9065cafce5a77d73a6c44de14bdcf4bca54be3
https://github.com/PerfectMemory/freebase-api/blob/fb9065cafce5a77d73a6c44de14bdcf4bca54be3/lib/freebase_api/session.rb#L120-L130
24,351
scottwillson/tabular
lib/tabular/column.rb
Tabular.Column.precision
def precision @precision ||= cells.map(&:to_f).map { |n| n.round(3) }.map { |n| n.to_s.split(".").last.gsub(/0+$/, "").length }.max end
ruby
def precision @precision ||= cells.map(&:to_f).map { |n| n.round(3) }.map { |n| n.to_s.split(".").last.gsub(/0+$/, "").length }.max end
[ "def", "precision", "@precision", "||=", "cells", ".", "map", "(", ":to_f", ")", ".", "map", "{", "|", "n", "|", "n", ".", "round", "(", "3", ")", "}", ".", "map", "{", "|", "n", "|", "n", ".", "to_s", ".", "split", "(", "\".\"", ")", ".", "last", ".", "gsub", "(", "/", "/", ",", "\"\"", ")", ".", "length", "}", ".", "max", "end" ]
Number of zeros to the right of the decimal point. Useful for formtting time data.
[ "Number", "of", "zeros", "to", "the", "right", "of", "the", "decimal", "point", ".", "Useful", "for", "formtting", "time", "data", "." ]
a479a0d55e91eb286f16adbfe43f97d69abbbe08
https://github.com/scottwillson/tabular/blob/a479a0d55e91eb286f16adbfe43f97d69abbbe08/lib/tabular/column.rb#L39-L41
24,352
r7kamura/markdiff
lib/markdiff/differ.rb
Markdiff.Differ.apply_patch
def apply_patch(operations, node) i = 0 operations.sort_by {|operation| i += 1; [-operation.priority, i] }.each do |operation| case operation when ::Markdiff::Operations::AddChildOperation operation.target_node.add_child(operation.inserted_node) mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::AddDataBeforeHrefOperation operation.target_node["data-before-href"] = operation.target_node["href"] operation.target_node["href"] = operation.after_href mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::AddDataBeforeTagNameOperation operation.target_node["data-before-tag-name"] = operation.target_node.name operation.target_node.name = operation.after_tag_name mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::AddPreviousSiblingOperation operation.target_node.add_previous_sibling(operation.inserted_node) mark_li_or_tr_as_changed(operation.target_node) if operation.target_node.name != "li" && operation.target_node.name != "tr" mark_top_level_node_as_changed(operation.target_node.parent) when ::Markdiff::Operations::RemoveOperation operation.target_node.replace(operation.inserted_node) if operation.target_node != operation.inserted_node mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::TextDiffOperation parent = operation.target_node.parent operation.target_node.replace(operation.inserted_node) mark_li_or_tr_as_changed(parent) mark_top_level_node_as_changed(parent) end end node end
ruby
def apply_patch(operations, node) i = 0 operations.sort_by {|operation| i += 1; [-operation.priority, i] }.each do |operation| case operation when ::Markdiff::Operations::AddChildOperation operation.target_node.add_child(operation.inserted_node) mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::AddDataBeforeHrefOperation operation.target_node["data-before-href"] = operation.target_node["href"] operation.target_node["href"] = operation.after_href mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::AddDataBeforeTagNameOperation operation.target_node["data-before-tag-name"] = operation.target_node.name operation.target_node.name = operation.after_tag_name mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::AddPreviousSiblingOperation operation.target_node.add_previous_sibling(operation.inserted_node) mark_li_or_tr_as_changed(operation.target_node) if operation.target_node.name != "li" && operation.target_node.name != "tr" mark_top_level_node_as_changed(operation.target_node.parent) when ::Markdiff::Operations::RemoveOperation operation.target_node.replace(operation.inserted_node) if operation.target_node != operation.inserted_node mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::TextDiffOperation parent = operation.target_node.parent operation.target_node.replace(operation.inserted_node) mark_li_or_tr_as_changed(parent) mark_top_level_node_as_changed(parent) end end node end
[ "def", "apply_patch", "(", "operations", ",", "node", ")", "i", "=", "0", "operations", ".", "sort_by", "{", "|", "operation", "|", "i", "+=", "1", ";", "[", "-", "operation", ".", "priority", ",", "i", "]", "}", ".", "each", "do", "|", "operation", "|", "case", "operation", "when", "::", "Markdiff", "::", "Operations", "::", "AddChildOperation", "operation", ".", "target_node", ".", "add_child", "(", "operation", ".", "inserted_node", ")", "mark_li_or_tr_as_changed", "(", "operation", ".", "target_node", ")", "mark_top_level_node_as_changed", "(", "operation", ".", "target_node", ")", "when", "::", "Markdiff", "::", "Operations", "::", "AddDataBeforeHrefOperation", "operation", ".", "target_node", "[", "\"data-before-href\"", "]", "=", "operation", ".", "target_node", "[", "\"href\"", "]", "operation", ".", "target_node", "[", "\"href\"", "]", "=", "operation", ".", "after_href", "mark_li_or_tr_as_changed", "(", "operation", ".", "target_node", ")", "mark_top_level_node_as_changed", "(", "operation", ".", "target_node", ")", "when", "::", "Markdiff", "::", "Operations", "::", "AddDataBeforeTagNameOperation", "operation", ".", "target_node", "[", "\"data-before-tag-name\"", "]", "=", "operation", ".", "target_node", ".", "name", "operation", ".", "target_node", ".", "name", "=", "operation", ".", "after_tag_name", "mark_li_or_tr_as_changed", "(", "operation", ".", "target_node", ")", "mark_top_level_node_as_changed", "(", "operation", ".", "target_node", ")", "when", "::", "Markdiff", "::", "Operations", "::", "AddPreviousSiblingOperation", "operation", ".", "target_node", ".", "add_previous_sibling", "(", "operation", ".", "inserted_node", ")", "mark_li_or_tr_as_changed", "(", "operation", ".", "target_node", ")", "if", "operation", ".", "target_node", ".", "name", "!=", "\"li\"", "&&", "operation", ".", "target_node", ".", "name", "!=", "\"tr\"", "mark_top_level_node_as_changed", "(", "operation", ".", "target_node", ".", "parent", ")", "when", "::", "Markdiff", "::", "Operations", "::", "RemoveOperation", "operation", ".", "target_node", ".", "replace", "(", "operation", ".", "inserted_node", ")", "if", "operation", ".", "target_node", "!=", "operation", ".", "inserted_node", "mark_li_or_tr_as_changed", "(", "operation", ".", "target_node", ")", "mark_top_level_node_as_changed", "(", "operation", ".", "target_node", ")", "when", "::", "Markdiff", "::", "Operations", "::", "TextDiffOperation", "parent", "=", "operation", ".", "target_node", ".", "parent", "operation", ".", "target_node", ".", "replace", "(", "operation", ".", "inserted_node", ")", "mark_li_or_tr_as_changed", "(", "parent", ")", "mark_top_level_node_as_changed", "(", "parent", ")", "end", "end", "node", "end" ]
Apply a given patch to a given node @param [Array<Markdiff::Operations::Base>] operations @param [Nokogiri::XML::Node] node @return [Nokogiri::XML::Node] Converted node
[ "Apply", "a", "given", "patch", "to", "a", "given", "node" ]
399fdff986771424186df65c8b25ed03b7b12305
https://github.com/r7kamura/markdiff/blob/399fdff986771424186df65c8b25ed03b7b12305/lib/markdiff/differ.rb#L16-L50
24,353
r7kamura/markdiff
lib/markdiff/differ.rb
Markdiff.Differ.create_patch
def create_patch(before_node, after_node) if before_node.to_html == after_node.to_html [] else create_patch_from_children(before_node, after_node) end end
ruby
def create_patch(before_node, after_node) if before_node.to_html == after_node.to_html [] else create_patch_from_children(before_node, after_node) end end
[ "def", "create_patch", "(", "before_node", ",", "after_node", ")", "if", "before_node", ".", "to_html", "==", "after_node", ".", "to_html", "[", "]", "else", "create_patch_from_children", "(", "before_node", ",", "after_node", ")", "end", "end" ]
Creates a patch from given two nodes @param [Nokogiri::XML::Node] before_node @param [Nokogiri::XML::Node] after_node @return [Array<Markdiff::Operations::Base>] operations
[ "Creates", "a", "patch", "from", "given", "two", "nodes" ]
399fdff986771424186df65c8b25ed03b7b12305
https://github.com/r7kamura/markdiff/blob/399fdff986771424186df65c8b25ed03b7b12305/lib/markdiff/differ.rb#L56-L62
24,354
r7kamura/markdiff
lib/markdiff/differ.rb
Markdiff.Differ.render
def render(before_string, after_string) before_node = ::Nokogiri::HTML.fragment(before_string) after_node = ::Nokogiri::HTML.fragment(after_string) patch = create_patch(before_node, after_node) apply_patch(patch, before_node) end
ruby
def render(before_string, after_string) before_node = ::Nokogiri::HTML.fragment(before_string) after_node = ::Nokogiri::HTML.fragment(after_string) patch = create_patch(before_node, after_node) apply_patch(patch, before_node) end
[ "def", "render", "(", "before_string", ",", "after_string", ")", "before_node", "=", "::", "Nokogiri", "::", "HTML", ".", "fragment", "(", "before_string", ")", "after_node", "=", "::", "Nokogiri", "::", "HTML", ".", "fragment", "(", "after_string", ")", "patch", "=", "create_patch", "(", "before_node", ",", "after_node", ")", "apply_patch", "(", "patch", ",", "before_node", ")", "end" ]
Utility method to do both creating and applying a patch @param [String] before_string @param [String] after_string @return [Nokogiri::XML::Node] Converted node
[ "Utility", "method", "to", "do", "both", "creating", "and", "applying", "a", "patch" ]
399fdff986771424186df65c8b25ed03b7b12305
https://github.com/r7kamura/markdiff/blob/399fdff986771424186df65c8b25ed03b7b12305/lib/markdiff/differ.rb#L68-L73
24,355
r7kamura/markdiff
lib/markdiff/differ.rb
Markdiff.Differ.create_patch_from_children
def create_patch_from_children(before_node, after_node) operations = [] identity_map = {} inverted_identity_map = {} ::Diff::LCS.sdiff(before_node.children.map(&:to_s), after_node.children.map(&:to_s)).each do |element| type, before, after = *element if type == "=" before_child = before_node.children[before[0]] after_child = after_node.children[after[0]] identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child end end # Partial matching before_node.children.each do |before_child| if identity_map[before_child] next end after_node.children.each do |after_child| case when identity_map[before_child] break when inverted_identity_map[after_child] when before_child.text? if after_child.text? identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child operations << ::Markdiff::Operations::TextDiffOperation.new(target_node: before_child, after_node: after_child) end when before_child.name == after_child.name if before_child.attributes == after_child.attributes identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child operations += create_patch(before_child, after_child) elsif detect_href_difference(before_child, after_child) operations << ::Markdiff::Operations::AddDataBeforeHrefOperation.new(after_href: after_child["href"], target_node: before_child) identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child operations += create_patch(before_child, after_child) end when detect_heading_level_difference(before_child, after_child) operations << ::Markdiff::Operations::AddDataBeforeTagNameOperation.new(after_tag_name: after_child.name, target_node: before_child) identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child end end end before_node.children.each do |before_child| unless identity_map[before_child] operations << ::Markdiff::Operations::RemoveOperation.new(target_node: before_child) end end after_node.children.each do |after_child| unless inverted_identity_map[after_child] right_node = after_child.next_sibling loop do case when inverted_identity_map[right_node] operations << ::Markdiff::Operations::AddPreviousSiblingOperation.new(inserted_node: after_child, target_node: inverted_identity_map[right_node]) break when right_node.nil? operations << ::Markdiff::Operations::AddChildOperation.new(inserted_node: after_child, target_node: before_node) break else right_node = right_node.next_sibling end end end end operations end
ruby
def create_patch_from_children(before_node, after_node) operations = [] identity_map = {} inverted_identity_map = {} ::Diff::LCS.sdiff(before_node.children.map(&:to_s), after_node.children.map(&:to_s)).each do |element| type, before, after = *element if type == "=" before_child = before_node.children[before[0]] after_child = after_node.children[after[0]] identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child end end # Partial matching before_node.children.each do |before_child| if identity_map[before_child] next end after_node.children.each do |after_child| case when identity_map[before_child] break when inverted_identity_map[after_child] when before_child.text? if after_child.text? identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child operations << ::Markdiff::Operations::TextDiffOperation.new(target_node: before_child, after_node: after_child) end when before_child.name == after_child.name if before_child.attributes == after_child.attributes identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child operations += create_patch(before_child, after_child) elsif detect_href_difference(before_child, after_child) operations << ::Markdiff::Operations::AddDataBeforeHrefOperation.new(after_href: after_child["href"], target_node: before_child) identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child operations += create_patch(before_child, after_child) end when detect_heading_level_difference(before_child, after_child) operations << ::Markdiff::Operations::AddDataBeforeTagNameOperation.new(after_tag_name: after_child.name, target_node: before_child) identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child end end end before_node.children.each do |before_child| unless identity_map[before_child] operations << ::Markdiff::Operations::RemoveOperation.new(target_node: before_child) end end after_node.children.each do |after_child| unless inverted_identity_map[after_child] right_node = after_child.next_sibling loop do case when inverted_identity_map[right_node] operations << ::Markdiff::Operations::AddPreviousSiblingOperation.new(inserted_node: after_child, target_node: inverted_identity_map[right_node]) break when right_node.nil? operations << ::Markdiff::Operations::AddChildOperation.new(inserted_node: after_child, target_node: before_node) break else right_node = right_node.next_sibling end end end end operations end
[ "def", "create_patch_from_children", "(", "before_node", ",", "after_node", ")", "operations", "=", "[", "]", "identity_map", "=", "{", "}", "inverted_identity_map", "=", "{", "}", "::", "Diff", "::", "LCS", ".", "sdiff", "(", "before_node", ".", "children", ".", "map", "(", ":to_s", ")", ",", "after_node", ".", "children", ".", "map", "(", ":to_s", ")", ")", ".", "each", "do", "|", "element", "|", "type", ",", "before", ",", "after", "=", "element", "if", "type", "==", "\"=\"", "before_child", "=", "before_node", ".", "children", "[", "before", "[", "0", "]", "]", "after_child", "=", "after_node", ".", "children", "[", "after", "[", "0", "]", "]", "identity_map", "[", "before_child", "]", "=", "after_child", "inverted_identity_map", "[", "after_child", "]", "=", "before_child", "end", "end", "# Partial matching", "before_node", ".", "children", ".", "each", "do", "|", "before_child", "|", "if", "identity_map", "[", "before_child", "]", "next", "end", "after_node", ".", "children", ".", "each", "do", "|", "after_child", "|", "case", "when", "identity_map", "[", "before_child", "]", "break", "when", "inverted_identity_map", "[", "after_child", "]", "when", "before_child", ".", "text?", "if", "after_child", ".", "text?", "identity_map", "[", "before_child", "]", "=", "after_child", "inverted_identity_map", "[", "after_child", "]", "=", "before_child", "operations", "<<", "::", "Markdiff", "::", "Operations", "::", "TextDiffOperation", ".", "new", "(", "target_node", ":", "before_child", ",", "after_node", ":", "after_child", ")", "end", "when", "before_child", ".", "name", "==", "after_child", ".", "name", "if", "before_child", ".", "attributes", "==", "after_child", ".", "attributes", "identity_map", "[", "before_child", "]", "=", "after_child", "inverted_identity_map", "[", "after_child", "]", "=", "before_child", "operations", "+=", "create_patch", "(", "before_child", ",", "after_child", ")", "elsif", "detect_href_difference", "(", "before_child", ",", "after_child", ")", "operations", "<<", "::", "Markdiff", "::", "Operations", "::", "AddDataBeforeHrefOperation", ".", "new", "(", "after_href", ":", "after_child", "[", "\"href\"", "]", ",", "target_node", ":", "before_child", ")", "identity_map", "[", "before_child", "]", "=", "after_child", "inverted_identity_map", "[", "after_child", "]", "=", "before_child", "operations", "+=", "create_patch", "(", "before_child", ",", "after_child", ")", "end", "when", "detect_heading_level_difference", "(", "before_child", ",", "after_child", ")", "operations", "<<", "::", "Markdiff", "::", "Operations", "::", "AddDataBeforeTagNameOperation", ".", "new", "(", "after_tag_name", ":", "after_child", ".", "name", ",", "target_node", ":", "before_child", ")", "identity_map", "[", "before_child", "]", "=", "after_child", "inverted_identity_map", "[", "after_child", "]", "=", "before_child", "end", "end", "end", "before_node", ".", "children", ".", "each", "do", "|", "before_child", "|", "unless", "identity_map", "[", "before_child", "]", "operations", "<<", "::", "Markdiff", "::", "Operations", "::", "RemoveOperation", ".", "new", "(", "target_node", ":", "before_child", ")", "end", "end", "after_node", ".", "children", ".", "each", "do", "|", "after_child", "|", "unless", "inverted_identity_map", "[", "after_child", "]", "right_node", "=", "after_child", ".", "next_sibling", "loop", "do", "case", "when", "inverted_identity_map", "[", "right_node", "]", "operations", "<<", "::", "Markdiff", "::", "Operations", "::", "AddPreviousSiblingOperation", ".", "new", "(", "inserted_node", ":", "after_child", ",", "target_node", ":", "inverted_identity_map", "[", "right_node", "]", ")", "break", "when", "right_node", ".", "nil?", "operations", "<<", "::", "Markdiff", "::", "Operations", "::", "AddChildOperation", ".", "new", "(", "inserted_node", ":", "after_child", ",", "target_node", ":", "before_node", ")", "break", "else", "right_node", "=", "right_node", ".", "next_sibling", "end", "end", "end", "end", "operations", "end" ]
1. Create identity map and collect patches from descendants 1-1. Detect exact-matched nodes 1-2. Detect partial-matched nodes and recursively walk through its children 2. Create remove operations from identity map 3. Create insert operations from identity map 4. Return operations as a patch @param [Nokogiri::XML::Node] before_node @param [Nokogiri::XML::Node] after_node @return [Array<Markdiff::Operations::Base>] operations
[ "1", ".", "Create", "identity", "map", "and", "collect", "patches", "from", "descendants", "1", "-", "1", ".", "Detect", "exact", "-", "matched", "nodes", "1", "-", "2", ".", "Detect", "partial", "-", "matched", "nodes", "and", "recursively", "walk", "through", "its", "children", "2", ".", "Create", "remove", "operations", "from", "identity", "map", "3", ".", "Create", "insert", "operations", "from", "identity", "map", "4", ".", "Return", "operations", "as", "a", "patch" ]
399fdff986771424186df65c8b25ed03b7b12305
https://github.com/r7kamura/markdiff/blob/399fdff986771424186df65c8b25ed03b7b12305/lib/markdiff/differ.rb#L87-L162
24,356
scottwillson/tabular
lib/tabular/table.rb
Tabular.Table.delete_blank_columns!
def delete_blank_columns!(*options) exceptions = extract_exceptions(options) (columns.map(&:key) - exceptions).each do |key| if rows.all? { |row| is_blank?(row[key]) || is_zero?(row[key]) } # rubocop:disable Style/IfUnlessModifier delete_column key end end end
ruby
def delete_blank_columns!(*options) exceptions = extract_exceptions(options) (columns.map(&:key) - exceptions).each do |key| if rows.all? { |row| is_blank?(row[key]) || is_zero?(row[key]) } # rubocop:disable Style/IfUnlessModifier delete_column key end end end
[ "def", "delete_blank_columns!", "(", "*", "options", ")", "exceptions", "=", "extract_exceptions", "(", "options", ")", "(", "columns", ".", "map", "(", ":key", ")", "-", "exceptions", ")", ".", "each", "do", "|", "key", "|", "if", "rows", ".", "all?", "{", "|", "row", "|", "is_blank?", "(", "row", "[", "key", "]", ")", "||", "is_zero?", "(", "row", "[", "key", "]", ")", "}", "# rubocop:disable Style/IfUnlessModifier", "delete_column", "key", "end", "end", "end" ]
Remove all columns that only contain a blank string, zero, or nil
[ "Remove", "all", "columns", "that", "only", "contain", "a", "blank", "string", "zero", "or", "nil" ]
a479a0d55e91eb286f16adbfe43f97d69abbbe08
https://github.com/scottwillson/tabular/blob/a479a0d55e91eb286f16adbfe43f97d69abbbe08/lib/tabular/table.rb#L78-L86
24,357
scottwillson/tabular
lib/tabular/table.rb
Tabular.Table.delete_homogenous_columns!
def delete_homogenous_columns!(*options) return if rows.size < 2 exceptions = extract_exceptions(options) (columns.map(&:key) - exceptions).each do |key| value = rows.first[key] delete_column key if rows.all? { |row| row[key] == value } end end
ruby
def delete_homogenous_columns!(*options) return if rows.size < 2 exceptions = extract_exceptions(options) (columns.map(&:key) - exceptions).each do |key| value = rows.first[key] delete_column key if rows.all? { |row| row[key] == value } end end
[ "def", "delete_homogenous_columns!", "(", "*", "options", ")", "return", "if", "rows", ".", "size", "<", "2", "exceptions", "=", "extract_exceptions", "(", "options", ")", "(", "columns", ".", "map", "(", ":key", ")", "-", "exceptions", ")", ".", "each", "do", "|", "key", "|", "value", "=", "rows", ".", "first", "[", "key", "]", "delete_column", "key", "if", "rows", ".", "all?", "{", "|", "row", "|", "row", "[", "key", "]", "==", "value", "}", "end", "end" ]
Remove all columns that contain the same value in all rows
[ "Remove", "all", "columns", "that", "contain", "the", "same", "value", "in", "all", "rows" ]
a479a0d55e91eb286f16adbfe43f97d69abbbe08
https://github.com/scottwillson/tabular/blob/a479a0d55e91eb286f16adbfe43f97d69abbbe08/lib/tabular/table.rb#L89-L98
24,358
scottwillson/tabular
lib/tabular/table.rb
Tabular.Table.strip!
def strip! rows.each do |row| columns.each do |column| value = row[column.key] if value.respond_to?(:strip) row[column.key] = value.strip elsif value.is_a?(Float) row[column.key] = strip_decimal(value) end end end end
ruby
def strip! rows.each do |row| columns.each do |column| value = row[column.key] if value.respond_to?(:strip) row[column.key] = value.strip elsif value.is_a?(Float) row[column.key] = strip_decimal(value) end end end end
[ "def", "strip!", "rows", ".", "each", "do", "|", "row", "|", "columns", ".", "each", "do", "|", "column", "|", "value", "=", "row", "[", "column", ".", "key", "]", "if", "value", ".", "respond_to?", "(", ":strip", ")", "row", "[", "column", ".", "key", "]", "=", "value", ".", "strip", "elsif", "value", ".", "is_a?", "(", "Float", ")", "row", "[", "column", ".", "key", "]", "=", "strip_decimal", "(", "value", ")", "end", "end", "end", "end" ]
Remove preceding and trailing whitespace from all cells. By default, Table does not strip whitespace from cells.
[ "Remove", "preceding", "and", "trailing", "whitespace", "from", "all", "cells", ".", "By", "default", "Table", "does", "not", "strip", "whitespace", "from", "cells", "." ]
a479a0d55e91eb286f16adbfe43f97d69abbbe08
https://github.com/scottwillson/tabular/blob/a479a0d55e91eb286f16adbfe43f97d69abbbe08/lib/tabular/table.rb#L109-L120
24,359
tumblr/collins_client
lib/collins/asset.rb
Collins.Asset.gateway_address
def gateway_address pool = "default" address = addresses.select{|a| a.pool == pool}.map{|a| a.gateway}.first return address if address if addresses.length > 0 then addresses.first.gateway else nil end end
ruby
def gateway_address pool = "default" address = addresses.select{|a| a.pool == pool}.map{|a| a.gateway}.first return address if address if addresses.length > 0 then addresses.first.gateway else nil end end
[ "def", "gateway_address", "pool", "=", "\"default\"", "address", "=", "addresses", ".", "select", "{", "|", "a", "|", "a", ".", "pool", "==", "pool", "}", ".", "map", "{", "|", "a", "|", "a", ".", "gateway", "}", ".", "first", "return", "address", "if", "address", "if", "addresses", ".", "length", ">", "0", "then", "addresses", ".", "first", ".", "gateway", "else", "nil", "end", "end" ]
Return the gateway address for the specified pool, or the first gateway @note If there is no address in the specified pool, the gateway of the first usable address is used, which may not be desired. @param [String] pool The address pool to find a gateway on @return [String] Gateway address, or nil
[ "Return", "the", "gateway", "address", "for", "the", "specified", "pool", "or", "the", "first", "gateway" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/asset.rb#L172-L180
24,360
tumblr/collins_client
lib/collins/util.rb
Collins.Util.deep_copy_hash
def deep_copy_hash hash require_that(hash.is_a?(Hash), "deep_copy_hash requires a hash be specified, got #{hash.class}") Marshal.load Marshal.dump(hash) end
ruby
def deep_copy_hash hash require_that(hash.is_a?(Hash), "deep_copy_hash requires a hash be specified, got #{hash.class}") Marshal.load Marshal.dump(hash) end
[ "def", "deep_copy_hash", "hash", "require_that", "(", "hash", ".", "is_a?", "(", "Hash", ")", ",", "\"deep_copy_hash requires a hash be specified, got #{hash.class}\"", ")", "Marshal", ".", "load", "Marshal", ".", "dump", "(", "hash", ")", "end" ]
Create a deep copy of a hash This is useful for copying a hash that will be mutated @note All keys and values must be serializable, Proc for instance will fail @param [Hash] hash the hash to copy @return [Hash]
[ "Create", "a", "deep", "copy", "of", "a", "hash" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/util.rb#L28-L31
24,361
tumblr/collins_client
lib/collins/util.rb
Collins.Util.require_non_empty
def require_non_empty value, message, return_value = false guard_value = if return_value == true then value elsif return_value != false then return_value else false end if value.is_a?(String) then require_that(!value.strip.empty?, message, guard_value) elsif value.respond_to?(:empty?) then require_that(!value.empty?, message, guard_value) else require_that(!value.nil?, message, guard_value) end end
ruby
def require_non_empty value, message, return_value = false guard_value = if return_value == true then value elsif return_value != false then return_value else false end if value.is_a?(String) then require_that(!value.strip.empty?, message, guard_value) elsif value.respond_to?(:empty?) then require_that(!value.empty?, message, guard_value) else require_that(!value.nil?, message, guard_value) end end
[ "def", "require_non_empty", "value", ",", "message", ",", "return_value", "=", "false", "guard_value", "=", "if", "return_value", "==", "true", "then", "value", "elsif", "return_value", "!=", "false", "then", "return_value", "else", "false", "end", "if", "value", ".", "is_a?", "(", "String", ")", "then", "require_that", "(", "!", "value", ".", "strip", ".", "empty?", ",", "message", ",", "guard_value", ")", "elsif", "value", ".", "respond_to?", "(", ":empty?", ")", "then", "require_that", "(", "!", "value", ".", "empty?", ",", "message", ",", "guard_value", ")", "else", "require_that", "(", "!", "value", ".", "nil?", ",", "message", ",", "guard_value", ")", "end", "end" ]
Require that a value not be empty If the value is a string, ensure that once stripped it's not empty. If the value responds to `:empty?`, ensure that it's not. Otherwise ensure the value isn't nil. @param [Object] value the value to check @param [String] message the exception message to use if the value is empty @param [Boolean,Object] return_value If true, returns value. If not false, returns the object @raise [ExpectationFailedError] if the value is empty @return [NilClass,Object] NilClass, or respecting return_value
[ "Require", "that", "a", "value", "not", "be", "empty" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/util.rb#L43-L58
24,362
tumblr/collins_client
lib/collins/util.rb
Collins.Util.require_that
def require_that guard, message, return_guard = false if not guard then raise ExpectationFailedError.new(message) end if return_guard == true then guard elsif return_guard != false then return_guard end end
ruby
def require_that guard, message, return_guard = false if not guard then raise ExpectationFailedError.new(message) end if return_guard == true then guard elsif return_guard != false then return_guard end end
[ "def", "require_that", "guard", ",", "message", ",", "return_guard", "=", "false", "if", "not", "guard", "then", "raise", "ExpectationFailedError", ".", "new", "(", "message", ")", "end", "if", "return_guard", "==", "true", "then", "guard", "elsif", "return_guard", "!=", "false", "then", "return_guard", "end", "end" ]
Require that a guard condition passes Simply checks that the guard is truthy, and throws an error otherwise @see #require_non_empty
[ "Require", "that", "a", "guard", "condition", "passes" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/util.rb#L64-L73
24,363
tumblr/collins_client
lib/collins/util.rb
Collins.Util.get_asset_or_tag
def get_asset_or_tag asset_or_tag asset = case asset_or_tag when Collins::Asset then asset_or_tag when String then Collins::Asset.new(asset_or_tag) when Symbol then Collins::Asset.new(asset_or_tag.to_s) else error_message = "Expected Collins::Asset, String or Symbol. Got #{asset_or_tag.class}" raise ExpectationFailedError.new(error_message) end if asset.nil? || asset.tag.nil? then raise ExpectationFailedError.new("Empty asset tag, but a tag is required") end asset end
ruby
def get_asset_or_tag asset_or_tag asset = case asset_or_tag when Collins::Asset then asset_or_tag when String then Collins::Asset.new(asset_or_tag) when Symbol then Collins::Asset.new(asset_or_tag.to_s) else error_message = "Expected Collins::Asset, String or Symbol. Got #{asset_or_tag.class}" raise ExpectationFailedError.new(error_message) end if asset.nil? || asset.tag.nil? then raise ExpectationFailedError.new("Empty asset tag, but a tag is required") end asset end
[ "def", "get_asset_or_tag", "asset_or_tag", "asset", "=", "case", "asset_or_tag", "when", "Collins", "::", "Asset", "then", "asset_or_tag", "when", "String", "then", "Collins", "::", "Asset", ".", "new", "(", "asset_or_tag", ")", "when", "Symbol", "then", "Collins", "::", "Asset", ".", "new", "(", "asset_or_tag", ".", "to_s", ")", "else", "error_message", "=", "\"Expected Collins::Asset, String or Symbol. Got #{asset_or_tag.class}\"", "raise", "ExpectationFailedError", ".", "new", "(", "error_message", ")", "end", "if", "asset", ".", "nil?", "||", "asset", ".", "tag", ".", "nil?", "then", "raise", "ExpectationFailedError", ".", "new", "(", "\"Empty asset tag, but a tag is required\"", ")", "end", "asset", "end" ]
Resolve an asset from a string tag or collins asset @note This is perhaps the only collins specific method in Util @param [Collins::Asset,String,Symbol] asset_or_tag @return [Collins::Asset] a collins asset @raise [ExpectationFailedError] if asset\_or\_tag isn't valid
[ "Resolve", "an", "asset", "from", "a", "string", "tag", "or", "collins", "asset" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/util.rb#L80-L94
24,364
tumblr/collins_client
lib/collins/util.rb
Collins.Util.symbolize_hash
def symbolize_hash hash, options = {} return {} if (hash.nil? or hash.empty?) (raise ExpectationFailedError.new("symbolize_hash called without a hash")) unless hash.is_a?(Hash) hash.inject({}) do |result, (k,v)| key = options[:downcase] ? k.to_s.downcase.to_sym : k.to_s.to_sym if v.is_a?(Hash) then result[key] = symbolize_hash(v) elsif v.is_a?(Regexp) && options[:rewrite_regex] then result[key] = v.inspect[1..-2] else result[key] = v end result end end
ruby
def symbolize_hash hash, options = {} return {} if (hash.nil? or hash.empty?) (raise ExpectationFailedError.new("symbolize_hash called without a hash")) unless hash.is_a?(Hash) hash.inject({}) do |result, (k,v)| key = options[:downcase] ? k.to_s.downcase.to_sym : k.to_s.to_sym if v.is_a?(Hash) then result[key] = symbolize_hash(v) elsif v.is_a?(Regexp) && options[:rewrite_regex] then result[key] = v.inspect[1..-2] else result[key] = v end result end end
[ "def", "symbolize_hash", "hash", ",", "options", "=", "{", "}", "return", "{", "}", "if", "(", "hash", ".", "nil?", "or", "hash", ".", "empty?", ")", "(", "raise", "ExpectationFailedError", ".", "new", "(", "\"symbolize_hash called without a hash\"", ")", ")", "unless", "hash", ".", "is_a?", "(", "Hash", ")", "hash", ".", "inject", "(", "{", "}", ")", "do", "|", "result", ",", "(", "k", ",", "v", ")", "|", "key", "=", "options", "[", ":downcase", "]", "?", "k", ".", "to_s", ".", "downcase", ".", "to_sym", ":", "k", ".", "to_s", ".", "to_sym", "if", "v", ".", "is_a?", "(", "Hash", ")", "then", "result", "[", "key", "]", "=", "symbolize_hash", "(", "v", ")", "elsif", "v", ".", "is_a?", "(", "Regexp", ")", "&&", "options", "[", ":rewrite_regex", "]", "then", "result", "[", "key", "]", "=", "v", ".", "inspect", "[", "1", "..", "-", "2", "]", "else", "result", "[", "key", "]", "=", "v", "end", "result", "end", "end" ]
Given a hash, rewrite keys to symbols @param [Hash] hash the hash to symbolize @param [Hash] options specify how to process the hash @option options [Boolean] :rewrite_regex if the value is a regex and this is true, convert it to a string @option options [Boolean] :downcase if true, downcase the keys as well @raise [ExpectationFailedError] if hash is not a hash
[ "Given", "a", "hash", "rewrite", "keys", "to", "symbols" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/util.rb#L103-L117
24,365
tumblr/collins_client
lib/collins/util.rb
Collins.Util.stringify_hash
def stringify_hash hash, options = {} (raise ExpectationFailedError.new("stringify_hash called without a hash")) unless hash.is_a?(Hash) hash.inject({}) do |result, (k,v)| key = options[:downcase] ? k.to_s.downcase : k.to_s if v.is_a?(Hash) then result[key] = stringify_hash(v) elsif v.is_a?(Regexp) && options[:rewrite_regex] then result[key] = v.inspect[1..-2] else result[key] = v end result end end
ruby
def stringify_hash hash, options = {} (raise ExpectationFailedError.new("stringify_hash called without a hash")) unless hash.is_a?(Hash) hash.inject({}) do |result, (k,v)| key = options[:downcase] ? k.to_s.downcase : k.to_s if v.is_a?(Hash) then result[key] = stringify_hash(v) elsif v.is_a?(Regexp) && options[:rewrite_regex] then result[key] = v.inspect[1..-2] else result[key] = v end result end end
[ "def", "stringify_hash", "hash", ",", "options", "=", "{", "}", "(", "raise", "ExpectationFailedError", ".", "new", "(", "\"stringify_hash called without a hash\"", ")", ")", "unless", "hash", ".", "is_a?", "(", "Hash", ")", "hash", ".", "inject", "(", "{", "}", ")", "do", "|", "result", ",", "(", "k", ",", "v", ")", "|", "key", "=", "options", "[", ":downcase", "]", "?", "k", ".", "to_s", ".", "downcase", ":", "k", ".", "to_s", "if", "v", ".", "is_a?", "(", "Hash", ")", "then", "result", "[", "key", "]", "=", "stringify_hash", "(", "v", ")", "elsif", "v", ".", "is_a?", "(", "Regexp", ")", "&&", "options", "[", ":rewrite_regex", "]", "then", "result", "[", "key", "]", "=", "v", ".", "inspect", "[", "1", "..", "-", "2", "]", "else", "result", "[", "key", "]", "=", "v", "end", "result", "end", "end" ]
Given a hash, convert all keys to strings @see #symbolize_hash
[ "Given", "a", "hash", "convert", "all", "keys", "to", "strings" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/util.rb#L121-L134
24,366
todesking/okura
lib/okura.rb
Okura.Tagger.parse
def parse str chars=str.split(//) nodes=Nodes.new(chars.length+2,@mat) nodes.add(0,Node.mk_bos_eos) nodes.add(chars.length+1,Node.mk_bos_eos) str.length.times{|i| @dic.possible_words(str,i).each{|w| nodes.add(i+1,Node.new(w)) } } nodes end
ruby
def parse str chars=str.split(//) nodes=Nodes.new(chars.length+2,@mat) nodes.add(0,Node.mk_bos_eos) nodes.add(chars.length+1,Node.mk_bos_eos) str.length.times{|i| @dic.possible_words(str,i).each{|w| nodes.add(i+1,Node.new(w)) } } nodes end
[ "def", "parse", "str", "chars", "=", "str", ".", "split", "(", "/", "/", ")", "nodes", "=", "Nodes", ".", "new", "(", "chars", ".", "length", "+", "2", ",", "@mat", ")", "nodes", ".", "add", "(", "0", ",", "Node", ".", "mk_bos_eos", ")", "nodes", ".", "add", "(", "chars", ".", "length", "+", "1", ",", "Node", ".", "mk_bos_eos", ")", "str", ".", "length", ".", "times", "{", "|", "i", "|", "@dic", ".", "possible_words", "(", "str", ",", "i", ")", ".", "each", "{", "|", "w", "|", "nodes", ".", "add", "(", "i", "+", "1", ",", "Node", ".", "new", "(", "w", ")", ")", "}", "}", "nodes", "end" ]
-> Nodes
[ "-", ">", "Nodes" ]
4e34ae7a9316bec92e06e74cadb28677f8730299
https://github.com/todesking/okura/blob/4e34ae7a9316bec92e06e74cadb28677f8730299/lib/okura.rb#L22-L33
24,367
todesking/okura
lib/okura.rb
Okura.UnkDic.define
def define type_name,left,right,cost type=@char_types.named type_name (@templates[type_name]||=[]).push Word.new '',left,right,cost end
ruby
def define type_name,left,right,cost type=@char_types.named type_name (@templates[type_name]||=[]).push Word.new '',left,right,cost end
[ "def", "define", "type_name", ",", "left", ",", "right", ",", "cost", "type", "=", "@char_types", ".", "named", "type_name", "(", "@templates", "[", "type_name", "]", "||=", "[", "]", ")", ".", "push", "Word", ".", "new", "''", ",", "left", ",", "right", ",", "cost", "end" ]
String -> Feature -> Feature -> Integer ->
[ "String", "-", ">", "Feature", "-", ">", "Feature", "-", ">", "Integer", "-", ">" ]
4e34ae7a9316bec92e06e74cadb28677f8730299
https://github.com/todesking/okura/blob/4e34ae7a9316bec92e06e74cadb28677f8730299/lib/okura.rb#L373-L376
24,368
scottwillson/tabular
lib/tabular/keys.rb
Tabular.Keys.key_to_sym
def key_to_sym(key) case key when Column key.key when String key.to_sym else key end end
ruby
def key_to_sym(key) case key when Column key.key when String key.to_sym else key end end
[ "def", "key_to_sym", "(", "key", ")", "case", "key", "when", "Column", "key", ".", "key", "when", "String", "key", ".", "to_sym", "else", "key", "end", "end" ]
Return Symbol for +key+. Translate Column and String. Return +key+ unmodified for anything else.
[ "Return", "Symbol", "for", "+", "key", "+", ".", "Translate", "Column", "and", "String", ".", "Return", "+", "key", "+", "unmodified", "for", "anything", "else", "." ]
a479a0d55e91eb286f16adbfe43f97d69abbbe08
https://github.com/scottwillson/tabular/blob/a479a0d55e91eb286f16adbfe43f97d69abbbe08/lib/tabular/keys.rb#L6-L15
24,369
tobiasfeistmantl/LeSSL
lib/le_ssl/manager.rb
LeSSL.Manager.authorize_for_domain
def authorize_for_domain(domain, options={}) authorization = client.authorize(domain: domain) # Default challenge is via HTTP # but the developer can also use # a DNS TXT record to authorize. if options[:challenge] == :dns challenge = authorization.dns01 unless options[:skip_puts] puts "====================================================================" puts "Record:" puts puts " - Name: #{challenge.record_name}.#{domain}" puts " - Type: #{challenge.record_type}" puts " - Value: #{challenge.record_content}" puts puts "Create the record; Wait a minute (or two); Request for verification!" puts "====================================================================" end # With this option the dns verification is # done automatically. LeSSL waits until a # valid record on your DNS servers was found # and requests a verification. # # CAUTION! This is a blocking the thread! if options[:automatic_verification] dns = begin if ns = options[:custom_nameservers] LeSSL::DNS.new(ns) else LeSSL::DNS.new end end puts puts 'Wait until the TXT record was set...' # Wait with verification until the # challenge record is valid. while dns.challenge_record_invalid?(domain, challenge.record_content) puts 'DNS record not valid' if options[:verbose] sleep(2) # Wait 2 seconds end puts 'Valid TXT record found. Continue with verification...' return request_verification(challenge) else return challenge end else challenge = authorization.http01 file_name = Rails.root.join('public', challenge.filename) dir = File.dirname(Rails.root.join('public', challenge.filename)) FileUtils.mkdir_p(dir) File.write(file_name, challenge.file_content) return challenge.verify_status end end
ruby
def authorize_for_domain(domain, options={}) authorization = client.authorize(domain: domain) # Default challenge is via HTTP # but the developer can also use # a DNS TXT record to authorize. if options[:challenge] == :dns challenge = authorization.dns01 unless options[:skip_puts] puts "====================================================================" puts "Record:" puts puts " - Name: #{challenge.record_name}.#{domain}" puts " - Type: #{challenge.record_type}" puts " - Value: #{challenge.record_content}" puts puts "Create the record; Wait a minute (or two); Request for verification!" puts "====================================================================" end # With this option the dns verification is # done automatically. LeSSL waits until a # valid record on your DNS servers was found # and requests a verification. # # CAUTION! This is a blocking the thread! if options[:automatic_verification] dns = begin if ns = options[:custom_nameservers] LeSSL::DNS.new(ns) else LeSSL::DNS.new end end puts puts 'Wait until the TXT record was set...' # Wait with verification until the # challenge record is valid. while dns.challenge_record_invalid?(domain, challenge.record_content) puts 'DNS record not valid' if options[:verbose] sleep(2) # Wait 2 seconds end puts 'Valid TXT record found. Continue with verification...' return request_verification(challenge) else return challenge end else challenge = authorization.http01 file_name = Rails.root.join('public', challenge.filename) dir = File.dirname(Rails.root.join('public', challenge.filename)) FileUtils.mkdir_p(dir) File.write(file_name, challenge.file_content) return challenge.verify_status end end
[ "def", "authorize_for_domain", "(", "domain", ",", "options", "=", "{", "}", ")", "authorization", "=", "client", ".", "authorize", "(", "domain", ":", "domain", ")", "# Default challenge is via HTTP", "# but the developer can also use", "# a DNS TXT record to authorize.", "if", "options", "[", ":challenge", "]", "==", ":dns", "challenge", "=", "authorization", ".", "dns01", "unless", "options", "[", ":skip_puts", "]", "puts", "\"====================================================================\"", "puts", "\"Record:\"", "puts", "puts", "\" - Name: #{challenge.record_name}.#{domain}\"", "puts", "\" - Type: #{challenge.record_type}\"", "puts", "\" - Value: #{challenge.record_content}\"", "puts", "puts", "\"Create the record; Wait a minute (or two); Request for verification!\"", "puts", "\"====================================================================\"", "end", "# With this option the dns verification is", "# done automatically. LeSSL waits until a", "# valid record on your DNS servers was found", "# and requests a verification.", "#", "# CAUTION! This is a blocking the thread!", "if", "options", "[", ":automatic_verification", "]", "dns", "=", "begin", "if", "ns", "=", "options", "[", ":custom_nameservers", "]", "LeSSL", "::", "DNS", ".", "new", "(", "ns", ")", "else", "LeSSL", "::", "DNS", ".", "new", "end", "end", "puts", "puts", "'Wait until the TXT record was set...'", "# Wait with verification until the", "# challenge record is valid.", "while", "dns", ".", "challenge_record_invalid?", "(", "domain", ",", "challenge", ".", "record_content", ")", "puts", "'DNS record not valid'", "if", "options", "[", ":verbose", "]", "sleep", "(", "2", ")", "# Wait 2 seconds", "end", "puts", "'Valid TXT record found. Continue with verification...'", "return", "request_verification", "(", "challenge", ")", "else", "return", "challenge", "end", "else", "challenge", "=", "authorization", ".", "http01", "file_name", "=", "Rails", ".", "root", ".", "join", "(", "'public'", ",", "challenge", ".", "filename", ")", "dir", "=", "File", ".", "dirname", "(", "Rails", ".", "root", ".", "join", "(", "'public'", ",", "challenge", ".", "filename", ")", ")", "FileUtils", ".", "mkdir_p", "(", "dir", ")", "File", ".", "write", "(", "file_name", ",", "challenge", ".", "file_content", ")", "return", "challenge", ".", "verify_status", "end", "end" ]
Authorize the client for a domain name. Challenge options: - HTTP (default and recommended) - DNS
[ "Authorize", "the", "client", "for", "a", "domain", "name", "." ]
7ef8b39d1ebe47534424c9c12dc6d82b54dfe8ba
https://github.com/tobiasfeistmantl/LeSSL/blob/7ef8b39d1ebe47534424c9c12dc6d82b54dfe8ba/lib/le_ssl/manager.rb#L25-L90
24,370
tumblr/collins_client
lib/collins/asset_client.rb
Collins.AssetClient.method_missing
def method_missing meth, *args, &block if @client.respond_to?(meth) then method_parameters = @client.class.instance_method(meth).parameters asset_idx = method_parameters.find_index do |item| item[1] == :asset_or_tag end if asset_idx.nil? then @client.send(meth, *args, &block) else args_with_asset = args.insert(asset_idx, @tag) logger.debug("Doing #{meth}(#{args_with_asset.join(',')}) for #{@tag}") @client.send(meth, *args_with_asset, &block) end else super end end
ruby
def method_missing meth, *args, &block if @client.respond_to?(meth) then method_parameters = @client.class.instance_method(meth).parameters asset_idx = method_parameters.find_index do |item| item[1] == :asset_or_tag end if asset_idx.nil? then @client.send(meth, *args, &block) else args_with_asset = args.insert(asset_idx, @tag) logger.debug("Doing #{meth}(#{args_with_asset.join(',')}) for #{@tag}") @client.send(meth, *args_with_asset, &block) end else super end end
[ "def", "method_missing", "meth", ",", "*", "args", ",", "&", "block", "if", "@client", ".", "respond_to?", "(", "meth", ")", "then", "method_parameters", "=", "@client", ".", "class", ".", "instance_method", "(", "meth", ")", ".", "parameters", "asset_idx", "=", "method_parameters", ".", "find_index", "do", "|", "item", "|", "item", "[", "1", "]", "==", ":asset_or_tag", "end", "if", "asset_idx", ".", "nil?", "then", "@client", ".", "send", "(", "meth", ",", "args", ",", "block", ")", "else", "args_with_asset", "=", "args", ".", "insert", "(", "asset_idx", ",", "@tag", ")", "logger", ".", "debug", "(", "\"Doing #{meth}(#{args_with_asset.join(',')}) for #{@tag}\"", ")", "@client", ".", "send", "(", "meth", ",", "args_with_asset", ",", "block", ")", "end", "else", "super", "end", "end" ]
Fill in the missing asset parameter on the dynamic method if needed If {Collins::Client} responds to the method, and the method requires an `asset_or_tag`, we insert the asset specified during initialization into the args array. If the method does not require an `asset_or_tag`, we simply proxy the method call as is. If {Collins::Client} does not respond to the method, we defer to `super`. @example collins_client.get('some_tag') # => returns that asset collins_client.with_asset('some_tag').get # => returns that same asset @note this method should never be called directly
[ "Fill", "in", "the", "missing", "asset", "parameter", "on", "the", "dynamic", "method", "if", "needed" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/asset_client.rb#L33-L49
24,371
JDHeiskell/filebound_client
lib/filebound_client.rb
FileboundClient.Client.get
def get(url, query_params = nil) JSON.parse(perform('get', url, query: query_params), symbolize_names: true, quirks_mode: true) end
ruby
def get(url, query_params = nil) JSON.parse(perform('get', url, query: query_params), symbolize_names: true, quirks_mode: true) end
[ "def", "get", "(", "url", ",", "query_params", "=", "nil", ")", "JSON", ".", "parse", "(", "perform", "(", "'get'", ",", "url", ",", "query", ":", "query_params", ")", ",", "symbolize_names", ":", "true", ",", "quirks_mode", ":", "true", ")", "end" ]
Initializes the client with the supplied Connection @param [Connection] connection the logged in Connection @return [FileboundClient::Client] an instance of FileboundClient::Client Executes a GET request on the current Filebound client session expecting JSON in the body of the response @param [String] url the resource url to request @param [Hash] query_params the optional query parameters to pass to the GET request @return [Hash] the JSON parsed hash of the response body
[ "Initializes", "the", "client", "with", "the", "supplied", "Connection" ]
cbaa56412ede796b4f088470b2b8e6dca1164d39
https://github.com/JDHeiskell/filebound_client/blob/cbaa56412ede796b4f088470b2b8e6dca1164d39/lib/filebound_client.rb#L44-L46
24,372
tumblr/collins_client
lib/collins/option.rb
Collins.Option.or_else
def or_else *default if empty? then res = if block_given? then yield else default.first end if res.is_a?(Option) then res else ::Collins::Option(res) end else self end end
ruby
def or_else *default if empty? then res = if block_given? then yield else default.first end if res.is_a?(Option) then res else ::Collins::Option(res) end else self end end
[ "def", "or_else", "*", "default", "if", "empty?", "then", "res", "=", "if", "block_given?", "then", "yield", "else", "default", ".", "first", "end", "if", "res", ".", "is_a?", "(", "Option", ")", "then", "res", "else", "::", "Collins", "::", "Option", "(", "res", ")", "end", "else", "self", "end", "end" ]
Return this `Option` if non-empty, otherwise return the result of evaluating the default @example Option(nil).or_else { "foo" } == Some("foo") @return [Option<Object>]
[ "Return", "this", "Option", "if", "non", "-", "empty", "otherwise", "return", "the", "result", "of", "evaluating", "the", "default" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/option.rb#L71-L86
24,373
tumblr/collins_client
lib/collins/option.rb
Collins.Option.map
def map &block if empty? then None.new else Some.new(block.call(get)) end end
ruby
def map &block if empty? then None.new else Some.new(block.call(get)) end end
[ "def", "map", "&", "block", "if", "empty?", "then", "None", ".", "new", "else", "Some", ".", "new", "(", "block", ".", "call", "(", "get", ")", ")", "end", "end" ]
If the option value is defined, apply the specified block to that value @example Option("15").map{|i| i.to_i}.get == 15 @yieldparam [Object] block The current value @yieldreturn [Object] The new value @return [Option<Object>] Optional value
[ "If", "the", "option", "value", "is", "defined", "apply", "the", "specified", "block", "to", "that", "value" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/option.rb#L111-L117
24,374
tumblr/collins_client
lib/collins/option.rb
Collins.Option.flat_map
def flat_map &block if empty? then None.new else res = block.call(get) if res.is_a?(Some) then res else Some.new(res) end end end
ruby
def flat_map &block if empty? then None.new else res = block.call(get) if res.is_a?(Some) then res else Some.new(res) end end end
[ "def", "flat_map", "&", "block", "if", "empty?", "then", "None", ".", "new", "else", "res", "=", "block", ".", "call", "(", "get", ")", "if", "res", ".", "is_a?", "(", "Some", ")", "then", "res", "else", "Some", ".", "new", "(", "res", ")", "end", "end", "end" ]
Same as map, but flatten the results This is useful when operating on an object that will return an `Option`. @example Option(15).flat_map {|i| Option(i).filter{|i2| i2 > 0}} == Some(15) @see #map @return [Option<Object>] Optional value
[ "Same", "as", "map", "but", "flatten", "the", "results" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/option.rb#L128-L139
24,375
jgraichen/restify
lib/restify/resource.rb
Restify.Resource.relation
def relation(name) if @relations.key? name Relation.new @context, @relations.fetch(name) else Relation.new @context, @relations.fetch(name.to_s) end end
ruby
def relation(name) if @relations.key? name Relation.new @context, @relations.fetch(name) else Relation.new @context, @relations.fetch(name.to_s) end end
[ "def", "relation", "(", "name", ")", "if", "@relations", ".", "key?", "name", "Relation", ".", "new", "@context", ",", "@relations", ".", "fetch", "(", "name", ")", "else", "Relation", ".", "new", "@context", ",", "@relations", ".", "fetch", "(", "name", ".", "to_s", ")", "end", "end" ]
Return relation with given name. @param name [String, Symbol] Relation name. @return [Relation] Relation.
[ "Return", "relation", "with", "given", "name", "." ]
6de37f17ee97a650fb30269b5b1fc836aaab4819
https://github.com/jgraichen/restify/blob/6de37f17ee97a650fb30269b5b1fc836aaab4819/lib/restify/resource.rb#L35-L41
24,376
bitaxis/annotate_models
lib/annotate_models/model_annotation_generator.rb
AnnotateModels.ModelAnnotationGenerator.apply_annotation
def apply_annotation(path, suffix=nil, extension="rb", plural=false) pn_models = Pathname.new(path) return unless pn_models.exist? suffix = "_#{suffix}" unless suffix == nil extension = (extension == nil) ? "" : ".#{extension}" @annotations.each do |model, annotation| prefix = (plural) ? model.name.pluralize : model.name pn = pn_models + "#{ActiveSupport::Inflector.underscore(prefix)}#{suffix}#{extension}" text = File.open(pn.to_path) { |fp| fp.read } re = Regexp.new("^#-(?:--)+-\n# #{model.name}.*\n(?:#.+\n)+#-(?:--)+-\n", Regexp::MULTILINE) if re =~ text text = text.sub(re, annotation) else text = "#{text}\n#{annotation}" end File.open(pn.to_path, "w") { |fp| fp.write(text) } puts " Annotated #{pn.to_path}." end end
ruby
def apply_annotation(path, suffix=nil, extension="rb", plural=false) pn_models = Pathname.new(path) return unless pn_models.exist? suffix = "_#{suffix}" unless suffix == nil extension = (extension == nil) ? "" : ".#{extension}" @annotations.each do |model, annotation| prefix = (plural) ? model.name.pluralize : model.name pn = pn_models + "#{ActiveSupport::Inflector.underscore(prefix)}#{suffix}#{extension}" text = File.open(pn.to_path) { |fp| fp.read } re = Regexp.new("^#-(?:--)+-\n# #{model.name}.*\n(?:#.+\n)+#-(?:--)+-\n", Regexp::MULTILINE) if re =~ text text = text.sub(re, annotation) else text = "#{text}\n#{annotation}" end File.open(pn.to_path, "w") { |fp| fp.write(text) } puts " Annotated #{pn.to_path}." end end
[ "def", "apply_annotation", "(", "path", ",", "suffix", "=", "nil", ",", "extension", "=", "\"rb\"", ",", "plural", "=", "false", ")", "pn_models", "=", "Pathname", ".", "new", "(", "path", ")", "return", "unless", "pn_models", ".", "exist?", "suffix", "=", "\"_#{suffix}\"", "unless", "suffix", "==", "nil", "extension", "=", "(", "extension", "==", "nil", ")", "?", "\"\"", ":", "\".#{extension}\"", "@annotations", ".", "each", "do", "|", "model", ",", "annotation", "|", "prefix", "=", "(", "plural", ")", "?", "model", ".", "name", ".", "pluralize", ":", "model", ".", "name", "pn", "=", "pn_models", "+", "\"#{ActiveSupport::Inflector.underscore(prefix)}#{suffix}#{extension}\"", "text", "=", "File", ".", "open", "(", "pn", ".", "to_path", ")", "{", "|", "fp", "|", "fp", ".", "read", "}", "re", "=", "Regexp", ".", "new", "(", "\"^#-(?:--)+-\\n# #{model.name}.*\\n(?:#.+\\n)+#-(?:--)+-\\n\"", ",", "Regexp", "::", "MULTILINE", ")", "if", "re", "=~", "text", "text", "=", "text", ".", "sub", "(", "re", ",", "annotation", ")", "else", "text", "=", "\"#{text}\\n#{annotation}\"", "end", "File", ".", "open", "(", "pn", ".", "to_path", ",", "\"w\"", ")", "{", "|", "fp", "|", "fp", ".", "write", "(", "text", ")", "}", "puts", "\" Annotated #{pn.to_path}.\"", "end", "end" ]
Apply annotations to a file @param path [String] Relative path (from root of application) of directory to apply annotations to. @param suffix [String] Optionally specify suffix of files to apply annotation to (e.g. "<model.name>_<suffix>.rb"). @param extension [String] Optionally specify extension of files to apply annotaations to (e.g. "<model.name>_<suffix>.<extension>").
[ "Apply", "annotations", "to", "a", "file" ]
0fe3e47973c01016ced9a28ad56ab417169478c7
https://github.com/bitaxis/annotate_models/blob/0fe3e47973c01016ced9a28ad56ab417169478c7/lib/annotate_models/model_annotation_generator.rb#L20-L38
24,377
bitaxis/annotate_models
lib/annotate_models/model_annotation_generator.rb
AnnotateModels.ModelAnnotationGenerator.generate
def generate Dir["app/models/*.rb"].each do |path| result = File.basename(path).scan(/^(.+)\.rb/)[0][0] model = eval(ActiveSupport::Inflector.camelize(result)) next if model.respond_to?(:abstract_class) && model.abstract_class next unless model < ActiveRecord::Base @annotations[model] = generate_annotation(model) unless @annotations.keys.include?(model) end end
ruby
def generate Dir["app/models/*.rb"].each do |path| result = File.basename(path).scan(/^(.+)\.rb/)[0][0] model = eval(ActiveSupport::Inflector.camelize(result)) next if model.respond_to?(:abstract_class) && model.abstract_class next unless model < ActiveRecord::Base @annotations[model] = generate_annotation(model) unless @annotations.keys.include?(model) end end
[ "def", "generate", "Dir", "[", "\"app/models/*.rb\"", "]", ".", "each", "do", "|", "path", "|", "result", "=", "File", ".", "basename", "(", "path", ")", ".", "scan", "(", "/", "\\.", "/", ")", "[", "0", "]", "[", "0", "]", "model", "=", "eval", "(", "ActiveSupport", "::", "Inflector", ".", "camelize", "(", "result", ")", ")", "next", "if", "model", ".", "respond_to?", "(", ":abstract_class", ")", "&&", "model", ".", "abstract_class", "next", "unless", "model", "<", "ActiveRecord", "::", "Base", "@annotations", "[", "model", "]", "=", "generate_annotation", "(", "model", ")", "unless", "@annotations", ".", "keys", ".", "include?", "(", "model", ")", "end", "end" ]
Gather model classes and generate annotation for each one.
[ "Gather", "model", "classes", "and", "generate", "annotation", "for", "each", "one", "." ]
0fe3e47973c01016ced9a28ad56ab417169478c7
https://github.com/bitaxis/annotate_models/blob/0fe3e47973c01016ced9a28ad56ab417169478c7/lib/annotate_models/model_annotation_generator.rb#L59-L67
24,378
bitaxis/annotate_models
lib/annotate_models/model_annotation_generator.rb
AnnotateModels.ModelAnnotationGenerator.generate_annotation
def generate_annotation(model) max_column_length = model.columns.collect { |c| c.name.length }.max annotation = [] annotation << "#-#{'--' * 38}-" annotation << "# #{model.name}" annotation << "#" annotation << sprintf("# %-#{max_column_length}s SQL Type Null Primary Default", "Name") annotation << sprintf("# %s -------------------- ------- ------- ----------", "-" * max_column_length) format = "# %-#{max_column_length}s %-20s %-7s %-7s %-10s" model.columns.each do |column| annotation << sprintf( format, column.name, column.sql_type, column.null, column.name == model.primary_key, (column.default || "") ) end annotation << "#" annotation << "#-#{'--' * 38}-" annotation.join("\n") + "\n" end
ruby
def generate_annotation(model) max_column_length = model.columns.collect { |c| c.name.length }.max annotation = [] annotation << "#-#{'--' * 38}-" annotation << "# #{model.name}" annotation << "#" annotation << sprintf("# %-#{max_column_length}s SQL Type Null Primary Default", "Name") annotation << sprintf("# %s -------------------- ------- ------- ----------", "-" * max_column_length) format = "# %-#{max_column_length}s %-20s %-7s %-7s %-10s" model.columns.each do |column| annotation << sprintf( format, column.name, column.sql_type, column.null, column.name == model.primary_key, (column.default || "") ) end annotation << "#" annotation << "#-#{'--' * 38}-" annotation.join("\n") + "\n" end
[ "def", "generate_annotation", "(", "model", ")", "max_column_length", "=", "model", ".", "columns", ".", "collect", "{", "|", "c", "|", "c", ".", "name", ".", "length", "}", ".", "max", "annotation", "=", "[", "]", "annotation", "<<", "\"#-#{'--' * 38}-\"", "annotation", "<<", "\"# #{model.name}\"", "annotation", "<<", "\"#\"", "annotation", "<<", "sprintf", "(", "\"# %-#{max_column_length}s SQL Type Null Primary Default\"", ",", "\"Name\"", ")", "annotation", "<<", "sprintf", "(", "\"# %s -------------------- ------- ------- ----------\"", ",", "\"-\"", "*", "max_column_length", ")", "format", "=", "\"# %-#{max_column_length}s %-20s %-7s %-7s %-10s\"", "model", ".", "columns", ".", "each", "do", "|", "column", "|", "annotation", "<<", "sprintf", "(", "format", ",", "column", ".", "name", ",", "column", ".", "sql_type", ",", "column", ".", "null", ",", "column", ".", "name", "==", "model", ".", "primary_key", ",", "(", "column", ".", "default", "||", "\"\"", ")", ")", "end", "annotation", "<<", "\"#\"", "annotation", "<<", "\"#-#{'--' * 38}-\"", "annotation", ".", "join", "(", "\"\\n\"", ")", "+", "\"\\n\"", "end" ]
Generate annotation text. @param model [Class] An ActiveRecord model class.
[ "Generate", "annotation", "text", "." ]
0fe3e47973c01016ced9a28ad56ab417169478c7
https://github.com/bitaxis/annotate_models/blob/0fe3e47973c01016ced9a28ad56ab417169478c7/lib/annotate_models/model_annotation_generator.rb#L85-L107
24,379
JDHeiskell/filebound_client
lib/filebound_client/connection.rb
FileboundClient.Connection.get
def get(url, params) request = HTTPI::Request.new(resource_url(url, query_params(params[:query]))) execute_request(:get, request, params) end
ruby
def get(url, params) request = HTTPI::Request.new(resource_url(url, query_params(params[:query]))) execute_request(:get, request, params) end
[ "def", "get", "(", "url", ",", "params", ")", "request", "=", "HTTPI", "::", "Request", ".", "new", "(", "resource_url", "(", "url", ",", "query_params", "(", "params", "[", ":query", "]", ")", ")", ")", "execute_request", "(", ":get", ",", "request", ",", "params", ")", "end" ]
Sends a GET request to the supplied resource using the supplied params hash @param [String] url the url that represents the resource @param [Hash] params the params Hash that will be sent in the request (keys: query, headers, body) @return [Net::HTTPResponse] the response from the GET request
[ "Sends", "a", "GET", "request", "to", "the", "supplied", "resource", "using", "the", "supplied", "params", "hash" ]
cbaa56412ede796b4f088470b2b8e6dca1164d39
https://github.com/JDHeiskell/filebound_client/blob/cbaa56412ede796b4f088470b2b8e6dca1164d39/lib/filebound_client/connection.rb#L105-L108
24,380
JDHeiskell/filebound_client
lib/filebound_client/connection.rb
FileboundClient.Connection.put
def put(url, params) request = HTTPI::Request.new(resource_url(url, query_params(params[:query]))) request.body = params[:body].to_json execute_request(:put, request, params) end
ruby
def put(url, params) request = HTTPI::Request.new(resource_url(url, query_params(params[:query]))) request.body = params[:body].to_json execute_request(:put, request, params) end
[ "def", "put", "(", "url", ",", "params", ")", "request", "=", "HTTPI", "::", "Request", ".", "new", "(", "resource_url", "(", "url", ",", "query_params", "(", "params", "[", ":query", "]", ")", ")", ")", "request", ".", "body", "=", "params", "[", ":body", "]", ".", "to_json", "execute_request", "(", ":put", ",", "request", ",", "params", ")", "end" ]
Sends a PUT request to the supplied resource using the supplied params hash @param [String] url the url that represents the resource @param [Hash] params the params Hash that will be sent in the request (keys: query, headers, body) @return [Net::HTTPResponse] the response from the PUT request
[ "Sends", "a", "PUT", "request", "to", "the", "supplied", "resource", "using", "the", "supplied", "params", "hash" ]
cbaa56412ede796b4f088470b2b8e6dca1164d39
https://github.com/JDHeiskell/filebound_client/blob/cbaa56412ede796b4f088470b2b8e6dca1164d39/lib/filebound_client/connection.rb#L114-L118
24,381
JDHeiskell/filebound_client
lib/filebound_client/connection.rb
FileboundClient.Connection.login
def login response = post('/login', body: { username: configuration.username, password: configuration.password }, headers: { 'Content-Type' => 'application/json' }) if response.code == 200 @token = JSON.parse(response.body, symbolize_names: true, quirks_mode: true) true else false end end
ruby
def login response = post('/login', body: { username: configuration.username, password: configuration.password }, headers: { 'Content-Type' => 'application/json' }) if response.code == 200 @token = JSON.parse(response.body, symbolize_names: true, quirks_mode: true) true else false end end
[ "def", "login", "response", "=", "post", "(", "'/login'", ",", "body", ":", "{", "username", ":", "configuration", ".", "username", ",", "password", ":", "configuration", ".", "password", "}", ",", "headers", ":", "{", "'Content-Type'", "=>", "'application/json'", "}", ")", "if", "response", ".", "code", "==", "200", "@token", "=", "JSON", ".", "parse", "(", "response", ".", "body", ",", "symbolize_names", ":", "true", ",", "quirks_mode", ":", "true", ")", "true", "else", "false", "end", "end" ]
Sends a POST request to the Filebound API's login endpoint to request a new security token @return [true, false] returns true if the login was successful and the token was set
[ "Sends", "a", "POST", "request", "to", "the", "Filebound", "API", "s", "login", "endpoint", "to", "request", "a", "new", "security", "token" ]
cbaa56412ede796b4f088470b2b8e6dca1164d39
https://github.com/JDHeiskell/filebound_client/blob/cbaa56412ede796b4f088470b2b8e6dca1164d39/lib/filebound_client/connection.rb#L141-L150
24,382
nofxx/yamg
lib/yamg/icon.rb
YAMG.Icon.write_out
def write_out(path = nil) return img unless path FileUtils.mkdir_p File.dirname(path) img.write(path) path rescue Errno::ENOENT puts_and_exit("Path not found '#{path}'") end
ruby
def write_out(path = nil) return img unless path FileUtils.mkdir_p File.dirname(path) img.write(path) path rescue Errno::ENOENT puts_and_exit("Path not found '#{path}'") end
[ "def", "write_out", "(", "path", "=", "nil", ")", "return", "img", "unless", "path", "FileUtils", ".", "mkdir_p", "File", ".", "dirname", "(", "path", ")", "img", ".", "write", "(", "path", ")", "path", "rescue", "Errno", "::", "ENOENT", "puts_and_exit", "(", "\"Path not found '#{path}'\"", ")", "end" ]
Writes image to disk
[ "Writes", "image", "to", "disk" ]
0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4
https://github.com/nofxx/yamg/blob/0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4/lib/yamg/icon.rb#L138-L145
24,383
jgraichen/restify
lib/restify/error.rb
Restify.ResponseError.errors
def errors if response.decoded_body response.decoded_body['errors'] || response.decoded_body[:errors] || response.decoded_body else response.body end end
ruby
def errors if response.decoded_body response.decoded_body['errors'] || response.decoded_body[:errors] || response.decoded_body else response.body end end
[ "def", "errors", "if", "response", ".", "decoded_body", "response", ".", "decoded_body", "[", "'errors'", "]", "||", "response", ".", "decoded_body", "[", ":errors", "]", "||", "response", ".", "decoded_body", "else", "response", ".", "body", "end", "end" ]
Return hash or array of errors if response included such a thing otherwise it returns nil.
[ "Return", "hash", "or", "array", "of", "errors", "if", "response", "included", "such", "a", "thing", "otherwise", "it", "returns", "nil", "." ]
6de37f17ee97a650fb30269b5b1fc836aaab4819
https://github.com/jgraichen/restify/blob/6de37f17ee97a650fb30269b5b1fc836aaab4819/lib/restify/error.rb#L71-L79
24,384
pillowfactory/csv-mapper
lib/csv-mapper/row_map.rb
CsvMapper.RowMap.read_attributes_from_file
def read_attributes_from_file aliases = {} attributes = FasterCSV.new(@csv_data, @parser_options).readline @start_at_row = [ @start_at_row, 1 ].max @csv_data.rewind attributes.each_with_index do |name, index| name.strip! use_name = aliases[name] || name.gsub(/\s+/, '_').gsub(/[\W]+/, '').downcase add_attribute use_name, index end end
ruby
def read_attributes_from_file aliases = {} attributes = FasterCSV.new(@csv_data, @parser_options).readline @start_at_row = [ @start_at_row, 1 ].max @csv_data.rewind attributes.each_with_index do |name, index| name.strip! use_name = aliases[name] || name.gsub(/\s+/, '_').gsub(/[\W]+/, '').downcase add_attribute use_name, index end end
[ "def", "read_attributes_from_file", "aliases", "=", "{", "}", "attributes", "=", "FasterCSV", ".", "new", "(", "@csv_data", ",", "@parser_options", ")", ".", "readline", "@start_at_row", "=", "[", "@start_at_row", ",", "1", "]", ".", "max", "@csv_data", ".", "rewind", "attributes", ".", "each_with_index", "do", "|", "name", ",", "index", "|", "name", ".", "strip!", "use_name", "=", "aliases", "[", "name", "]", "||", "name", ".", "gsub", "(", "/", "\\s", "/", ",", "'_'", ")", ".", "gsub", "(", "/", "\\W", "/", ",", "''", ")", ".", "downcase", "add_attribute", "use_name", ",", "index", "end", "end" ]
Allow us to read the first line of a csv file to automatically generate the attribute names. Spaces are replaced with underscores and non-word characters are removed. Keep in mind that there is potential for overlap in using this (i.e. you have a field named files+ and one named files- and they both get named 'files'). You can specify aliases to rename fields to prevent conflicts and/or improve readability and compatibility. i.e. read_attributes_from_file('files+' => 'files_plus', 'files-' => 'files_minus)
[ "Allow", "us", "to", "read", "the", "first", "line", "of", "a", "csv", "file", "to", "automatically", "generate", "the", "attribute", "names", ".", "Spaces", "are", "replaced", "with", "underscores", "and", "non", "-", "word", "characters", "are", "removed", "." ]
4eb58109cd9f70e29312d150e39a5d18fe1813e6
https://github.com/pillowfactory/csv-mapper/blob/4eb58109cd9f70e29312d150e39a5d18fe1813e6/lib/csv-mapper/row_map.rb#L51-L60
24,385
pillowfactory/csv-mapper
lib/csv-mapper/row_map.rb
CsvMapper.RowMap.parse
def parse(csv_row) target = self.map_to_class.new @before_filters.each {|filter| filter.call(csv_row, target) } self.mapped_attributes.each do |attr_map| target.send("#{attr_map.name}=", attr_map.parse(csv_row)) end @after_filters.each {|filter| filter.call(csv_row, target) } return target end
ruby
def parse(csv_row) target = self.map_to_class.new @before_filters.each {|filter| filter.call(csv_row, target) } self.mapped_attributes.each do |attr_map| target.send("#{attr_map.name}=", attr_map.parse(csv_row)) end @after_filters.each {|filter| filter.call(csv_row, target) } return target end
[ "def", "parse", "(", "csv_row", ")", "target", "=", "self", ".", "map_to_class", ".", "new", "@before_filters", ".", "each", "{", "|", "filter", "|", "filter", ".", "call", "(", "csv_row", ",", "target", ")", "}", "self", ".", "mapped_attributes", ".", "each", "do", "|", "attr_map", "|", "target", ".", "send", "(", "\"#{attr_map.name}=\"", ",", "attr_map", ".", "parse", "(", "csv_row", ")", ")", "end", "@after_filters", ".", "each", "{", "|", "filter", "|", "filter", ".", "call", "(", "csv_row", ",", "target", ")", "}", "return", "target", "end" ]
Given a CSV row return an instance of an object defined by this mapping
[ "Given", "a", "CSV", "row", "return", "an", "instance", "of", "an", "object", "defined", "by", "this", "mapping" ]
4eb58109cd9f70e29312d150e39a5d18fe1813e6
https://github.com/pillowfactory/csv-mapper/blob/4eb58109cd9f70e29312d150e39a5d18fe1813e6/lib/csv-mapper/row_map.rb#L127-L138
24,386
substancelab/rconomic
lib/economic/proxies/current_invoice_proxy.rb
Economic.CurrentInvoiceProxy.initialize_properties_with_values_from_owner
def initialize_properties_with_values_from_owner(invoice) if owner.is_a?(Debtor) invoice.debtor = owner invoice.debtor_name ||= owner.name invoice.debtor_address ||= owner.address invoice.debtor_postal_code ||= owner.postal_code invoice.debtor_city ||= owner.city invoice.term_of_payment_handle ||= owner.term_of_payment_handle invoice.layout_handle ||= owner.layout_handle invoice.currency_handle ||= owner.currency_handle end end
ruby
def initialize_properties_with_values_from_owner(invoice) if owner.is_a?(Debtor) invoice.debtor = owner invoice.debtor_name ||= owner.name invoice.debtor_address ||= owner.address invoice.debtor_postal_code ||= owner.postal_code invoice.debtor_city ||= owner.city invoice.term_of_payment_handle ||= owner.term_of_payment_handle invoice.layout_handle ||= owner.layout_handle invoice.currency_handle ||= owner.currency_handle end end
[ "def", "initialize_properties_with_values_from_owner", "(", "invoice", ")", "if", "owner", ".", "is_a?", "(", "Debtor", ")", "invoice", ".", "debtor", "=", "owner", "invoice", ".", "debtor_name", "||=", "owner", ".", "name", "invoice", ".", "debtor_address", "||=", "owner", ".", "address", "invoice", ".", "debtor_postal_code", "||=", "owner", ".", "postal_code", "invoice", ".", "debtor_city", "||=", "owner", ".", "city", "invoice", ".", "term_of_payment_handle", "||=", "owner", ".", "term_of_payment_handle", "invoice", ".", "layout_handle", "||=", "owner", ".", "layout_handle", "invoice", ".", "currency_handle", "||=", "owner", ".", "currency_handle", "end", "end" ]
Initialize properties in invoice with values from owner
[ "Initialize", "properties", "in", "invoice", "with", "values", "from", "owner" ]
cae2dcafd640707a5d42d657b080a066efd19dc0
https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/current_invoice_proxy.rb#L13-L26
24,387
substancelab/rconomic
lib/economic/proxies/current_invoice_line_proxy.rb
Economic.CurrentInvoiceLineProxy.find
def find(handle) handle = Entity::Handle.build(:number => handle) unless handle.is_a?(Entity::Handle) super(handle) end
ruby
def find(handle) handle = Entity::Handle.build(:number => handle) unless handle.is_a?(Entity::Handle) super(handle) end
[ "def", "find", "(", "handle", ")", "handle", "=", "Entity", "::", "Handle", ".", "build", "(", ":number", "=>", "handle", ")", "unless", "handle", ".", "is_a?", "(", "Entity", "::", "Handle", ")", "super", "(", "handle", ")", "end" ]
Gets data for CurrentInvoiceLine from the API
[ "Gets", "data", "for", "CurrentInvoiceLine", "from", "the", "API" ]
cae2dcafd640707a5d42d657b080a066efd19dc0
https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/current_invoice_line_proxy.rb#L8-L11
24,388
livingsocial/imprint
lib/imprint/log_helpers.rb
Imprint.LogHelpers.log_entrypoint
def log_entrypoint raise "you must call Imprint.configuration and configure the gem before using LogHelpers" if Imprint.configuration.nil? log_filter = ActionDispatch::Http::ParameterFilter.new(Imprint.configuration[:log_filters] || Rails.application.config.filter_parameters) # I should probably switch this to be a whitelist as well, or support both white and black lists for both cookies and headers header_blacklist = Imprint.configuration[:header_blacklist] || [] cookies_whitelist = Imprint.configuration[:cookies_whitelist] || [] param_level = Imprint.configuration[:param_level] || Imprint::QUERY_PARAMS http_request_headers = request.headers.select{|header_name, header_value| header_name.match("^HTTP.*") && !header_blacklist.include?(header_name) } data_append = "headers: " if http_request_headers.respond_to?(:each_pair) http_request_headers.each_pair{|k,v| data_append << " #{k}=\"#{v}\"" } else http_request_headers.each{|el| data_append << " #{el.first}=\"#{el.last}\"" } end data_append << " params: " if param_level==Imprint::FULL_PARAMS set_full_params(log_filter, data_append) elsif param_level==Imprint::FULL_GET_PARAMS if request.get? set_full_params(log_filter, data_append) else set_query_params(log_filter, data_append) end else set_query_params(log_filter, data_append) end if defined? cookies cookies_whitelist.each do |cookie_key| cookie_val = cookies[cookie_key] ? cookies[cookie_key] : 'nil' data_append << " #{cookie_key}=\"#{cookie_val}\"" end end logger.info "Started request_method=#{request.method.inspect} request_url=\"#{request.path}\" request_time=\"#{Time.now.to_default_s}\" request_ip=#{request.remote_ip.inspect} #{data_append}" rescue => e logger.error "error logging log_entrypoint for request: #{e.inspect}" logger.error e.backtrace.take(10).join("\n") end
ruby
def log_entrypoint raise "you must call Imprint.configuration and configure the gem before using LogHelpers" if Imprint.configuration.nil? log_filter = ActionDispatch::Http::ParameterFilter.new(Imprint.configuration[:log_filters] || Rails.application.config.filter_parameters) # I should probably switch this to be a whitelist as well, or support both white and black lists for both cookies and headers header_blacklist = Imprint.configuration[:header_blacklist] || [] cookies_whitelist = Imprint.configuration[:cookies_whitelist] || [] param_level = Imprint.configuration[:param_level] || Imprint::QUERY_PARAMS http_request_headers = request.headers.select{|header_name, header_value| header_name.match("^HTTP.*") && !header_blacklist.include?(header_name) } data_append = "headers: " if http_request_headers.respond_to?(:each_pair) http_request_headers.each_pair{|k,v| data_append << " #{k}=\"#{v}\"" } else http_request_headers.each{|el| data_append << " #{el.first}=\"#{el.last}\"" } end data_append << " params: " if param_level==Imprint::FULL_PARAMS set_full_params(log_filter, data_append) elsif param_level==Imprint::FULL_GET_PARAMS if request.get? set_full_params(log_filter, data_append) else set_query_params(log_filter, data_append) end else set_query_params(log_filter, data_append) end if defined? cookies cookies_whitelist.each do |cookie_key| cookie_val = cookies[cookie_key] ? cookies[cookie_key] : 'nil' data_append << " #{cookie_key}=\"#{cookie_val}\"" end end logger.info "Started request_method=#{request.method.inspect} request_url=\"#{request.path}\" request_time=\"#{Time.now.to_default_s}\" request_ip=#{request.remote_ip.inspect} #{data_append}" rescue => e logger.error "error logging log_entrypoint for request: #{e.inspect}" logger.error e.backtrace.take(10).join("\n") end
[ "def", "log_entrypoint", "raise", "\"you must call Imprint.configuration and configure the gem before using LogHelpers\"", "if", "Imprint", ".", "configuration", ".", "nil?", "log_filter", "=", "ActionDispatch", "::", "Http", "::", "ParameterFilter", ".", "new", "(", "Imprint", ".", "configuration", "[", ":log_filters", "]", "||", "Rails", ".", "application", ".", "config", ".", "filter_parameters", ")", "# I should probably switch this to be a whitelist as well, or support both white and black lists for both cookies and headers", "header_blacklist", "=", "Imprint", ".", "configuration", "[", ":header_blacklist", "]", "||", "[", "]", "cookies_whitelist", "=", "Imprint", ".", "configuration", "[", ":cookies_whitelist", "]", "||", "[", "]", "param_level", "=", "Imprint", ".", "configuration", "[", ":param_level", "]", "||", "Imprint", "::", "QUERY_PARAMS", "http_request_headers", "=", "request", ".", "headers", ".", "select", "{", "|", "header_name", ",", "header_value", "|", "header_name", ".", "match", "(", "\"^HTTP.*\"", ")", "&&", "!", "header_blacklist", ".", "include?", "(", "header_name", ")", "}", "data_append", "=", "\"headers: \"", "if", "http_request_headers", ".", "respond_to?", "(", ":each_pair", ")", "http_request_headers", ".", "each_pair", "{", "|", "k", ",", "v", "|", "data_append", "<<", "\" #{k}=\\\"#{v}\\\"\"", "}", "else", "http_request_headers", ".", "each", "{", "|", "el", "|", "data_append", "<<", "\" #{el.first}=\\\"#{el.last}\\\"\"", "}", "end", "data_append", "<<", "\" params: \"", "if", "param_level", "==", "Imprint", "::", "FULL_PARAMS", "set_full_params", "(", "log_filter", ",", "data_append", ")", "elsif", "param_level", "==", "Imprint", "::", "FULL_GET_PARAMS", "if", "request", ".", "get?", "set_full_params", "(", "log_filter", ",", "data_append", ")", "else", "set_query_params", "(", "log_filter", ",", "data_append", ")", "end", "else", "set_query_params", "(", "log_filter", ",", "data_append", ")", "end", "if", "defined?", "cookies", "cookies_whitelist", ".", "each", "do", "|", "cookie_key", "|", "cookie_val", "=", "cookies", "[", "cookie_key", "]", "?", "cookies", "[", "cookie_key", "]", ":", "'nil'", "data_append", "<<", "\" #{cookie_key}=\\\"#{cookie_val}\\\"\"", "end", "end", "logger", ".", "info", "\"Started request_method=#{request.method.inspect} request_url=\\\"#{request.path}\\\" request_time=\\\"#{Time.now.to_default_s}\\\" request_ip=#{request.remote_ip.inspect} #{data_append}\"", "rescue", "=>", "e", "logger", ".", "error", "\"error logging log_entrypoint for request: #{e.inspect}\"", "logger", ".", "error", "e", ".", "backtrace", ".", "take", "(", "10", ")", ".", "join", "(", "\"\\n\"", ")", "end" ]
Not relying on default rails logging, we more often use lograge. We still want to log incoming params safely, which lograge doesn't include this does the same sensative param filtering as rails defaults It also allows for logging headers and cookies
[ "Not", "relying", "on", "default", "rails", "logging", "we", "more", "often", "use", "lograge", ".", "We", "still", "want", "to", "log", "incoming", "params", "safely", "which", "lograge", "doesn", "t", "include", "this", "does", "the", "same", "sensative", "param", "filtering", "as", "rails", "defaults", "It", "also", "allows", "for", "logging", "headers", "and", "cookies" ]
51a4cd9c96f9e06e98be68666f421d927965edc5
https://github.com/livingsocial/imprint/blob/51a4cd9c96f9e06e98be68666f421d927965edc5/lib/imprint/log_helpers.rb#L8-L49
24,389
substancelab/rconomic
lib/economic/proxies/actions/find_by_date_interval.rb
Economic.FindByDateInterval.find_by_date_interval
def find_by_date_interval(from, unto) response = request(:find_by_date_interval, "first" => from.iso8601, "last" => unto.iso8601) handle_key = "#{Support::String.underscore(entity_class_name)}_handle".intern handles = [response[handle_key]].flatten.reject(&:blank?).collect do |handle| Entity::Handle.build(handle) end get_data_array(handles).collect do |entity_hash| entity = build(entity_hash) entity.persisted = true entity end end
ruby
def find_by_date_interval(from, unto) response = request(:find_by_date_interval, "first" => from.iso8601, "last" => unto.iso8601) handle_key = "#{Support::String.underscore(entity_class_name)}_handle".intern handles = [response[handle_key]].flatten.reject(&:blank?).collect do |handle| Entity::Handle.build(handle) end get_data_array(handles).collect do |entity_hash| entity = build(entity_hash) entity.persisted = true entity end end
[ "def", "find_by_date_interval", "(", "from", ",", "unto", ")", "response", "=", "request", "(", ":find_by_date_interval", ",", "\"first\"", "=>", "from", ".", "iso8601", ",", "\"last\"", "=>", "unto", ".", "iso8601", ")", "handle_key", "=", "\"#{Support::String.underscore(entity_class_name)}_handle\"", ".", "intern", "handles", "=", "[", "response", "[", "handle_key", "]", "]", ".", "flatten", ".", "reject", "(", ":blank?", ")", ".", "collect", "do", "|", "handle", "|", "Entity", "::", "Handle", ".", "build", "(", "handle", ")", "end", "get_data_array", "(", "handles", ")", ".", "collect", "do", "|", "entity_hash", "|", "entity", "=", "build", "(", "entity_hash", ")", "entity", ".", "persisted", "=", "true", "entity", "end", "end" ]
Returns entity objects for a given interval of days.
[ "Returns", "entity", "objects", "for", "a", "given", "interval", "of", "days", "." ]
cae2dcafd640707a5d42d657b080a066efd19dc0
https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/actions/find_by_date_interval.rb#L6-L20
24,390
substancelab/rconomic
lib/economic/entity.rb
Economic.Entity.get_data
def get_data response = proxy.get_data(handle) update_properties(response) self.partial = false self.persisted = true end
ruby
def get_data response = proxy.get_data(handle) update_properties(response) self.partial = false self.persisted = true end
[ "def", "get_data", "response", "=", "proxy", ".", "get_data", "(", "handle", ")", "update_properties", "(", "response", ")", "self", ".", "partial", "=", "false", "self", ".", "persisted", "=", "true", "end" ]
Updates Entity with its data from the API
[ "Updates", "Entity", "with", "its", "data", "from", "the", "API" ]
cae2dcafd640707a5d42d657b080a066efd19dc0
https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/entity.rb#L111-L116
24,391
substancelab/rconomic
lib/economic/entity.rb
Economic.Entity.destroy
def destroy handleKey = "#{Support::String.camel_back(class_name)}Handle" response = request(:delete, handleKey => handle.to_hash) @persisted = false @partial = true response end
ruby
def destroy handleKey = "#{Support::String.camel_back(class_name)}Handle" response = request(:delete, handleKey => handle.to_hash) @persisted = false @partial = true response end
[ "def", "destroy", "handleKey", "=", "\"#{Support::String.camel_back(class_name)}Handle\"", "response", "=", "request", "(", ":delete", ",", "handleKey", "=>", "handle", ".", "to_hash", ")", "@persisted", "=", "false", "@partial", "=", "true", "response", "end" ]
Deletes entity permanently from E-conomic.
[ "Deletes", "entity", "permanently", "from", "E", "-", "conomic", "." ]
cae2dcafd640707a5d42d657b080a066efd19dc0
https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/entity.rb#L160-L168
24,392
substancelab/rconomic
lib/economic/entity.rb
Economic.Entity.update_properties
def update_properties(hash) hash.each do |key, value| setter_method = "#{key}=" if respond_to?(setter_method) send(setter_method, value) end end end
ruby
def update_properties(hash) hash.each do |key, value| setter_method = "#{key}=" if respond_to?(setter_method) send(setter_method, value) end end end
[ "def", "update_properties", "(", "hash", ")", "hash", ".", "each", "do", "|", "key", ",", "value", "|", "setter_method", "=", "\"#{key}=\"", "if", "respond_to?", "(", "setter_method", ")", "send", "(", "setter_method", ",", "value", ")", "end", "end", "end" ]
Updates properties of Entity with the values from hash
[ "Updates", "properties", "of", "Entity", "with", "the", "values", "from", "hash" ]
cae2dcafd640707a5d42d657b080a066efd19dc0
https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/entity.rb#L171-L178
24,393
errorstudio/voipfone_client
lib/voipfone_client/sms.rb
VoipfoneClient.SMS.send
def send if @to.nil? || @from.nil? || @message.nil? raise ArgumentError, "You need to include 'to' and 'from' numbers and a message to send an SMS" end to = @to.gsub(" ","") from = @from.gsub(" ","") parameters = { "sms-send-to" => to, "sms-send-from" => from, "sms-message" => @message[0..159] } request = @browser.post("#{VoipfoneClient::API_POST_URL}?smsSend", parameters) response = parse_response(request) if response == "ok" return true else raise VoipfoneAPIError, response end end
ruby
def send if @to.nil? || @from.nil? || @message.nil? raise ArgumentError, "You need to include 'to' and 'from' numbers and a message to send an SMS" end to = @to.gsub(" ","") from = @from.gsub(" ","") parameters = { "sms-send-to" => to, "sms-send-from" => from, "sms-message" => @message[0..159] } request = @browser.post("#{VoipfoneClient::API_POST_URL}?smsSend", parameters) response = parse_response(request) if response == "ok" return true else raise VoipfoneAPIError, response end end
[ "def", "send", "if", "@to", ".", "nil?", "||", "@from", ".", "nil?", "||", "@message", ".", "nil?", "raise", "ArgumentError", ",", "\"You need to include 'to' and 'from' numbers and a message to send an SMS\"", "end", "to", "=", "@to", ".", "gsub", "(", "\" \"", ",", "\"\"", ")", "from", "=", "@from", ".", "gsub", "(", "\" \"", ",", "\"\"", ")", "parameters", "=", "{", "\"sms-send-to\"", "=>", "to", ",", "\"sms-send-from\"", "=>", "from", ",", "\"sms-message\"", "=>", "@message", "[", "0", "..", "159", "]", "}", "request", "=", "@browser", ".", "post", "(", "\"#{VoipfoneClient::API_POST_URL}?smsSend\"", ",", "parameters", ")", "response", "=", "parse_response", "(", "request", ")", "if", "response", "==", "\"ok\"", "return", "true", "else", "raise", "VoipfoneAPIError", ",", "response", "end", "end" ]
Constructor to create an SMS - optionally pass in to, from and message @param to [String] the phone number to send the SMS to, as a string. Spaces will be stripped; + symbol allowed. @param from [String] the phone number to send the SMS from, as a string. Spaces will be stripped; + symbol allowed. @param message [String] the message to send. The first 160 characters only will be sent. Send an sms from your account.
[ "Constructor", "to", "create", "an", "SMS", "-", "optionally", "pass", "in", "to", "from", "and", "message" ]
83bd19fdbaffd7d5029e445faf3456126bb4ca11
https://github.com/errorstudio/voipfone_client/blob/83bd19fdbaffd7d5029e445faf3456126bb4ca11/lib/voipfone_client/sms.rb#L17-L35
24,394
substancelab/rconomic
lib/economic/proxies/entity_proxy.rb
Economic.EntityProxy.all
def all response = request(:get_all) handles = response.values.flatten.collect { |handle| Entity::Handle.build(handle) } get_data_for_handles(handles) self end
ruby
def all response = request(:get_all) handles = response.values.flatten.collect { |handle| Entity::Handle.build(handle) } get_data_for_handles(handles) self end
[ "def", "all", "response", "=", "request", "(", ":get_all", ")", "handles", "=", "response", ".", "values", ".", "flatten", ".", "collect", "{", "|", "handle", "|", "Entity", "::", "Handle", ".", "build", "(", "handle", ")", "}", "get_data_for_handles", "(", "handles", ")", "self", "end" ]
Fetches all entities from the API.
[ "Fetches", "all", "entities", "from", "the", "API", "." ]
cae2dcafd640707a5d42d657b080a066efd19dc0
https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/entity_proxy.rb#L36-L42
24,395
substancelab/rconomic
lib/economic/proxies/entity_proxy.rb
Economic.EntityProxy.find
def find(handle) handle = build_handle(handle) entity_hash = get_data(handle) entity = build(entity_hash) entity.persisted = true entity end
ruby
def find(handle) handle = build_handle(handle) entity_hash = get_data(handle) entity = build(entity_hash) entity.persisted = true entity end
[ "def", "find", "(", "handle", ")", "handle", "=", "build_handle", "(", "handle", ")", "entity_hash", "=", "get_data", "(", "handle", ")", "entity", "=", "build", "(", "entity_hash", ")", "entity", ".", "persisted", "=", "true", "entity", "end" ]
Fetches Entity data from API and returns an Entity initialized with that data added to Proxy
[ "Fetches", "Entity", "data", "from", "API", "and", "returns", "an", "Entity", "initialized", "with", "that", "data", "added", "to", "Proxy" ]
cae2dcafd640707a5d42d657b080a066efd19dc0
https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/entity_proxy.rb#L69-L75
24,396
substancelab/rconomic
lib/economic/proxies/entity_proxy.rb
Economic.EntityProxy.get_data
def get_data(handle) handle = Entity::Handle.new(handle) entity_hash = request(:get_data, "entityHandle" => handle.to_hash) entity_hash end
ruby
def get_data(handle) handle = Entity::Handle.new(handle) entity_hash = request(:get_data, "entityHandle" => handle.to_hash) entity_hash end
[ "def", "get_data", "(", "handle", ")", "handle", "=", "Entity", "::", "Handle", ".", "new", "(", "handle", ")", "entity_hash", "=", "request", "(", ":get_data", ",", "\"entityHandle\"", "=>", "handle", ".", "to_hash", ")", "entity_hash", "end" ]
Gets data for Entity from the API. Returns Hash with the response data
[ "Gets", "data", "for", "Entity", "from", "the", "API", ".", "Returns", "Hash", "with", "the", "response", "data" ]
cae2dcafd640707a5d42d657b080a066efd19dc0
https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/entity_proxy.rb#L78-L82
24,397
substancelab/rconomic
lib/economic/proxies/entity_proxy.rb
Economic.EntityProxy.get_data_array
def get_data_array(handles) return [] unless handles && handles.any? entity_class_name_for_soap_request = entity_class.name.split("::").last response = request(:get_data_array, "entityHandles" => {"#{entity_class_name_for_soap_request}Handle" => handles.collect(&:to_hash)}) [response["#{entity_class.key}_data".intern]].flatten end
ruby
def get_data_array(handles) return [] unless handles && handles.any? entity_class_name_for_soap_request = entity_class.name.split("::").last response = request(:get_data_array, "entityHandles" => {"#{entity_class_name_for_soap_request}Handle" => handles.collect(&:to_hash)}) [response["#{entity_class.key}_data".intern]].flatten end
[ "def", "get_data_array", "(", "handles", ")", "return", "[", "]", "unless", "handles", "&&", "handles", ".", "any?", "entity_class_name_for_soap_request", "=", "entity_class", ".", "name", ".", "split", "(", "\"::\"", ")", ".", "last", "response", "=", "request", "(", ":get_data_array", ",", "\"entityHandles\"", "=>", "{", "\"#{entity_class_name_for_soap_request}Handle\"", "=>", "handles", ".", "collect", "(", ":to_hash", ")", "}", ")", "[", "response", "[", "\"#{entity_class.key}_data\"", ".", "intern", "]", "]", ".", "flatten", "end" ]
Fetches all data for the given handles. Returns Array with hashes of entity data
[ "Fetches", "all", "data", "for", "the", "given", "handles", ".", "Returns", "Array", "with", "hashes", "of", "entity", "data" ]
cae2dcafd640707a5d42d657b080a066efd19dc0
https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/entity_proxy.rb#L112-L118
24,398
substancelab/rconomic
lib/economic/proxies/entity_proxy.rb
Economic.EntityProxy.request
def request(action, data = nil) session.request( Endpoint.new.soap_action_name(entity_class, action), data ) end
ruby
def request(action, data = nil) session.request( Endpoint.new.soap_action_name(entity_class, action), data ) end
[ "def", "request", "(", "action", ",", "data", "=", "nil", ")", "session", ".", "request", "(", "Endpoint", ".", "new", ".", "soap_action_name", "(", "entity_class", ",", "action", ")", ",", "data", ")", "end" ]
Requests an action from the API endpoint
[ "Requests", "an", "action", "from", "the", "API", "endpoint" ]
cae2dcafd640707a5d42d657b080a066efd19dc0
https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/entity_proxy.rb#L147-L152
24,399
substancelab/rconomic
lib/economic/proxies/order_proxy.rb
Economic.OrderProxy.current
def current response = request(:get_all_current) handles = response.values.flatten.collect { |handle| Entity::Handle.build(handle) } initialize_items get_data_for_handles(handles) self end
ruby
def current response = request(:get_all_current) handles = response.values.flatten.collect { |handle| Entity::Handle.build(handle) } initialize_items get_data_for_handles(handles) self end
[ "def", "current", "response", "=", "request", "(", ":get_all_current", ")", "handles", "=", "response", ".", "values", ".", "flatten", ".", "collect", "{", "|", "handle", "|", "Entity", "::", "Handle", ".", "build", "(", "handle", ")", "}", "initialize_items", "get_data_for_handles", "(", "handles", ")", "self", "end" ]
Fetches all current orders from the API.
[ "Fetches", "all", "current", "orders", "from", "the", "API", "." ]
cae2dcafd640707a5d42d657b080a066efd19dc0
https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/order_proxy.rb#L13-L20