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
2,300
LIFX/lifx-gem
lib/lifx/light_target.rb
LIFX.LightTarget.set_power
def set_power(state) level = case state when :on 1 when :off 0 else raise ArgumentError.new("Must pass in either :on or :off") end send_message(Protocol::Device::SetPower.new(level: level)) self end
ruby
def set_power(state) level = case state when :on 1 when :off 0 else raise ArgumentError.new("Must pass in either :on or :off") end send_message(Protocol::Device::SetPower.new(level: level)) self end
[ "def", "set_power", "(", "state", ")", "level", "=", "case", "state", "when", ":on", "1", "when", ":off", "0", "else", "raise", "ArgumentError", ".", "new", "(", "\"Must pass in either :on or :off\"", ")", "end", "send_message", "(", "Protocol", "::", "Device", "::", "SetPower", ".", "new", "(", "level", ":", "level", ")", ")", "self", "end" ]
Attempts to set the power state to `state` asynchronously. This method cannot guarantee the message was received. @param state [:on, :off] @return [Light, LightCollection] self for chaining
[ "Attempts", "to", "set", "the", "power", "state", "to", "state", "asynchronously", ".", "This", "method", "cannot", "guarantee", "the", "message", "was", "received", "." ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light_target.rb#L139-L150
2,301
LIFX/lifx-gem
lib/lifx/light_target.rb
LIFX.LightTarget.set_site_id
def set_site_id(site_id) send_message(Protocol::Device::SetSite.new(site: [site_id].pack('H*'))) end
ruby
def set_site_id(site_id) send_message(Protocol::Device::SetSite.new(site: [site_id].pack('H*'))) end
[ "def", "set_site_id", "(", "site_id", ")", "send_message", "(", "Protocol", "::", "Device", "::", "SetSite", ".", "new", "(", "site", ":", "[", "site_id", "]", ".", "pack", "(", "'H*'", ")", ")", ")", "end" ]
Attempts to set the site id of the light. Will clear label and tags. This method cannot guarantee message receipt. @note Don't use this unless you know what you're doing. @api private @param site_id [String] Site ID @return [void]
[ "Attempts", "to", "set", "the", "site", "id", "of", "the", "light", ".", "Will", "clear", "label", "and", "tags", ".", "This", "method", "cannot", "guarantee", "message", "receipt", "." ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light_target.rb#L180-L182
2,302
LIFX/lifx-gem
lib/lifx/light_target.rb
LIFX.LightTarget.set_time
def set_time(time = Time.now) send_message(Protocol::Device::SetTime.new(time: (time.to_f * NSEC_IN_SEC).round)) end
ruby
def set_time(time = Time.now) send_message(Protocol::Device::SetTime.new(time: (time.to_f * NSEC_IN_SEC).round)) end
[ "def", "set_time", "(", "time", "=", "Time", ".", "now", ")", "send_message", "(", "Protocol", "::", "Device", "::", "SetTime", ".", "new", "(", "time", ":", "(", "time", ".", "to_f", "*", "NSEC_IN_SEC", ")", ".", "round", ")", ")", "end" ]
Attempts to set the device time on the targets @api private @param time [Time] The time to set @return [void]
[ "Attempts", "to", "set", "the", "device", "time", "on", "the", "targets" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light_target.rb#L189-L191
2,303
MaximeD/gem_updater
lib/gem_updater/ruby_gems_fetcher.rb
GemUpdater.RubyGemsFetcher.query_rubygems
def query_rubygems(tries = 0) JSON.parse(open("https://rubygems.org/api/v1/gems/#{gem_name}.json").read) rescue OpenURI::HTTPError => e # We may trigger too many requests, in which case give rubygems a break if e.io.status.include?(HTTP_TOO_MANY_REQUESTS) if (tries += 1) < 2 sleep 1 && retry end end end
ruby
def query_rubygems(tries = 0) JSON.parse(open("https://rubygems.org/api/v1/gems/#{gem_name}.json").read) rescue OpenURI::HTTPError => e # We may trigger too many requests, in which case give rubygems a break if e.io.status.include?(HTTP_TOO_MANY_REQUESTS) if (tries += 1) < 2 sleep 1 && retry end end end
[ "def", "query_rubygems", "(", "tries", "=", "0", ")", "JSON", ".", "parse", "(", "open", "(", "\"https://rubygems.org/api/v1/gems/#{gem_name}.json\"", ")", ".", "read", ")", "rescue", "OpenURI", "::", "HTTPError", "=>", "e", "# We may trigger too many requests, in which case give rubygems a break", "if", "e", ".", "io", ".", "status", ".", "include?", "(", "HTTP_TOO_MANY_REQUESTS", ")", "if", "(", "tries", "+=", "1", ")", "<", "2", "sleep", "1", "&&", "retry", "end", "end", "end" ]
Make the real query to rubygems It may fail in case we trigger too many requests @param tries [Integer|nil] (optional) how many times we tried
[ "Make", "the", "real", "query", "to", "rubygems", "It", "may", "fail", "in", "case", "we", "trigger", "too", "many", "requests" ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater/ruby_gems_fetcher.rb#L49-L58
2,304
MaximeD/gem_updater
lib/gem_updater/ruby_gems_fetcher.rb
GemUpdater.RubyGemsFetcher.uri_from_other_sources
def uri_from_other_sources uri = nil source.remotes.each do |remote| break if uri uri = case remote.host when 'rubygems.org' then next # already checked when 'rails-assets.org' uri_from_railsassets else Bundler.ui.error "Source #{remote} is not supported, ' \ 'feel free to open a PR or an issue on https://github.com/MaximeD/gem_updater" end end uri end
ruby
def uri_from_other_sources uri = nil source.remotes.each do |remote| break if uri uri = case remote.host when 'rubygems.org' then next # already checked when 'rails-assets.org' uri_from_railsassets else Bundler.ui.error "Source #{remote} is not supported, ' \ 'feel free to open a PR or an issue on https://github.com/MaximeD/gem_updater" end end uri end
[ "def", "uri_from_other_sources", "uri", "=", "nil", "source", ".", "remotes", ".", "each", "do", "|", "remote", "|", "break", "if", "uri", "uri", "=", "case", "remote", ".", "host", "when", "'rubygems.org'", "then", "next", "# already checked", "when", "'rails-assets.org'", "uri_from_railsassets", "else", "Bundler", ".", "ui", ".", "error", "\"Source #{remote} is not supported, ' \\\n 'feel free to open a PR or an issue on https://github.com/MaximeD/gem_updater\"", "end", "end", "uri", "end" ]
Look if gem can be found in another remote @return [String|nil] uri of source code rubocop:disable Metrics/MethodLength
[ "Look", "if", "gem", "can", "be", "found", "in", "another", "remote" ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater/ruby_gems_fetcher.rb#L64-L80
2,305
MrPowers/directed_graph
lib/directed_graph/graphml.rb
DirectedGraph.Graph.compute_key
def compute_key(external_identifier) x = [external_identifier].flatten x.map! {|xx| xx.to_s} x.join("_") end
ruby
def compute_key(external_identifier) x = [external_identifier].flatten x.map! {|xx| xx.to_s} x.join("_") end
[ "def", "compute_key", "(", "external_identifier", ")", "x", "=", "[", "external_identifier", "]", ".", "flatten", "x", ".", "map!", "{", "|", "xx", "|", "xx", ".", "to_s", "}", "x", ".", "join", "(", "\"_\"", ")", "end" ]
Generate a string key from an array of identifiers
[ "Generate", "a", "string", "key", "from", "an", "array", "of", "identifiers" ]
eb0f607e555a068cca2a7927d2b81aadae9c743a
https://github.com/MrPowers/directed_graph/blob/eb0f607e555a068cca2a7927d2b81aadae9c743a/lib/directed_graph/graphml.rb#L7-L11
2,306
MrPowers/directed_graph
lib/directed_graph/graphml.rb
DirectedGraph.Graph.to_graphml
def to_graphml() builder = Builder::XmlMarkup.new(:indent => 1) builder.instruct! :xml, :version => "1.0" graphml_attribs = { "xmlns" => "http://graphml.graphdrawing.org/xmlns", "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", "xmlns:y" => "http://www.yworks.com/xml/graphml", "xmlns:yed" => "http://www.yworks.com/xml/yed/3", "xsi:schemaLocation" => "http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd", :directed => "1", :label => "test" } builder.graphml(graphml_attribs) do # Define key id's at top of graphml file builder.key({:for=>"node", :id=>"d3", "yfiles.type"=>"nodegraphics"}) # Build Graph # builder.graph({:id=>"G"}) do vertices.each do |vertex| builder.node(:id => compute_key([vertex.name, vertex.object_id])) do builder.data({:key=>"d3"}) do builder.tag!("y:ShapeNode") do graphics = vertex.data.fetch(:graphics, {}) graphics.fetch(:fill, []).each {|f| builder.tag! "y:Fill", {:color=>f, :transparent=>"false"}} graphics.fetch(:shape,[]).each {|s| builder.tag! "y:Shape", {:type=>s}} graphics.fetch(:geometry,[]).each {|s| builder.tag! "y:Geometry", s} graphics.fetch(:label,[]).each {|l| builder.tag! "y:NodeLabel", l} end end end end edges.each do |edge| source = edge.origin_vertex target = edge.destination_vertex options = edge.data[:options] label = "" builder.edge( :source => s = compute_key([source.name, source.object_id]), :target => t = compute_key([target.name, target.object_id]), :id => compute_key([source.name, target.name, edge.object_id]), :label => "#{label}" ) do #edge[:attributes].each_pair { |k, v| # id_str = compute_key([k,:edge_attr]) # builder.data(v.to_s, {:key=>@guid[id_str]}) #} end end end end builder.target! end
ruby
def to_graphml() builder = Builder::XmlMarkup.new(:indent => 1) builder.instruct! :xml, :version => "1.0" graphml_attribs = { "xmlns" => "http://graphml.graphdrawing.org/xmlns", "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", "xmlns:y" => "http://www.yworks.com/xml/graphml", "xmlns:yed" => "http://www.yworks.com/xml/yed/3", "xsi:schemaLocation" => "http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd", :directed => "1", :label => "test" } builder.graphml(graphml_attribs) do # Define key id's at top of graphml file builder.key({:for=>"node", :id=>"d3", "yfiles.type"=>"nodegraphics"}) # Build Graph # builder.graph({:id=>"G"}) do vertices.each do |vertex| builder.node(:id => compute_key([vertex.name, vertex.object_id])) do builder.data({:key=>"d3"}) do builder.tag!("y:ShapeNode") do graphics = vertex.data.fetch(:graphics, {}) graphics.fetch(:fill, []).each {|f| builder.tag! "y:Fill", {:color=>f, :transparent=>"false"}} graphics.fetch(:shape,[]).each {|s| builder.tag! "y:Shape", {:type=>s}} graphics.fetch(:geometry,[]).each {|s| builder.tag! "y:Geometry", s} graphics.fetch(:label,[]).each {|l| builder.tag! "y:NodeLabel", l} end end end end edges.each do |edge| source = edge.origin_vertex target = edge.destination_vertex options = edge.data[:options] label = "" builder.edge( :source => s = compute_key([source.name, source.object_id]), :target => t = compute_key([target.name, target.object_id]), :id => compute_key([source.name, target.name, edge.object_id]), :label => "#{label}" ) do #edge[:attributes].each_pair { |k, v| # id_str = compute_key([k,:edge_attr]) # builder.data(v.to_s, {:key=>@guid[id_str]}) #} end end end end builder.target! end
[ "def", "to_graphml", "(", ")", "builder", "=", "Builder", "::", "XmlMarkup", ".", "new", "(", ":indent", "=>", "1", ")", "builder", ".", "instruct!", ":xml", ",", ":version", "=>", "\"1.0\"", "graphml_attribs", "=", "{", "\"xmlns\"", "=>", "\"http://graphml.graphdrawing.org/xmlns\"", ",", "\"xmlns:xsi\"", "=>", "\"http://www.w3.org/2001/XMLSchema-instance\"", ",", "\"xmlns:y\"", "=>", "\"http://www.yworks.com/xml/graphml\"", ",", "\"xmlns:yed\"", "=>", "\"http://www.yworks.com/xml/yed/3\"", ",", "\"xsi:schemaLocation\"", "=>", "\"http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd\"", ",", ":directed", "=>", "\"1\"", ",", ":label", "=>", "\"test\"", "}", "builder", ".", "graphml", "(", "graphml_attribs", ")", "do", "# Define key id's at top of graphml file", "builder", ".", "key", "(", "{", ":for", "=>", "\"node\"", ",", ":id", "=>", "\"d3\"", ",", "\"yfiles.type\"", "=>", "\"nodegraphics\"", "}", ")", "# Build Graph ", "#", "builder", ".", "graph", "(", "{", ":id", "=>", "\"G\"", "}", ")", "do", "vertices", ".", "each", "do", "|", "vertex", "|", "builder", ".", "node", "(", ":id", "=>", "compute_key", "(", "[", "vertex", ".", "name", ",", "vertex", ".", "object_id", "]", ")", ")", "do", "builder", ".", "data", "(", "{", ":key", "=>", "\"d3\"", "}", ")", "do", "builder", ".", "tag!", "(", "\"y:ShapeNode\"", ")", "do", "graphics", "=", "vertex", ".", "data", ".", "fetch", "(", ":graphics", ",", "{", "}", ")", "graphics", ".", "fetch", "(", ":fill", ",", "[", "]", ")", ".", "each", "{", "|", "f", "|", "builder", ".", "tag!", "\"y:Fill\"", ",", "{", ":color", "=>", "f", ",", ":transparent", "=>", "\"false\"", "}", "}", "graphics", ".", "fetch", "(", ":shape", ",", "[", "]", ")", ".", "each", "{", "|", "s", "|", "builder", ".", "tag!", "\"y:Shape\"", ",", "{", ":type", "=>", "s", "}", "}", "graphics", ".", "fetch", "(", ":geometry", ",", "[", "]", ")", ".", "each", "{", "|", "s", "|", "builder", ".", "tag!", "\"y:Geometry\"", ",", "s", "}", "graphics", ".", "fetch", "(", ":label", ",", "[", "]", ")", ".", "each", "{", "|", "l", "|", "builder", ".", "tag!", "\"y:NodeLabel\"", ",", "l", "}", "end", "end", "end", "end", "edges", ".", "each", "do", "|", "edge", "|", "source", "=", "edge", ".", "origin_vertex", "target", "=", "edge", ".", "destination_vertex", "options", "=", "edge", ".", "data", "[", ":options", "]", "label", "=", "\"\"", "builder", ".", "edge", "(", ":source", "=>", "s", "=", "compute_key", "(", "[", "source", ".", "name", ",", "source", ".", "object_id", "]", ")", ",", ":target", "=>", "t", "=", "compute_key", "(", "[", "target", ".", "name", ",", "target", ".", "object_id", "]", ")", ",", ":id", "=>", "compute_key", "(", "[", "source", ".", "name", ",", "target", ".", "name", ",", "edge", ".", "object_id", "]", ")", ",", ":label", "=>", "\"#{label}\"", ")", "do", "#edge[:attributes].each_pair { |k, v| ", "# id_str = compute_key([k,:edge_attr])", "# builder.data(v.to_s, {:key=>@guid[id_str]})", "#}", "end", "end", "end", "end", "builder", ".", "target!", "end" ]
Return graph as graphml text
[ "Return", "graph", "as", "graphml", "text" ]
eb0f607e555a068cca2a7927d2b81aadae9c743a
https://github.com/MrPowers/directed_graph/blob/eb0f607e555a068cca2a7927d2b81aadae9c743a/lib/directed_graph/graphml.rb#L14-L76
2,307
LIFX/lifx-gem
lib/lifx/color.rb
LIFX.Color.to_hsbk
def to_hsbk Protocol::Light::Hsbk.new( hue: (hue / 360.0 * UINT16_MAX).to_i, saturation: (saturation * UINT16_MAX).to_i, brightness: (brightness * UINT16_MAX).to_i, kelvin: [KELVIN_MIN, kelvin.to_i, KELVIN_MAX].sort[1] ) end
ruby
def to_hsbk Protocol::Light::Hsbk.new( hue: (hue / 360.0 * UINT16_MAX).to_i, saturation: (saturation * UINT16_MAX).to_i, brightness: (brightness * UINT16_MAX).to_i, kelvin: [KELVIN_MIN, kelvin.to_i, KELVIN_MAX].sort[1] ) end
[ "def", "to_hsbk", "Protocol", "::", "Light", "::", "Hsbk", ".", "new", "(", "hue", ":", "(", "hue", "/", "360.0", "*", "UINT16_MAX", ")", ".", "to_i", ",", "saturation", ":", "(", "saturation", "*", "UINT16_MAX", ")", ".", "to_i", ",", "brightness", ":", "(", "brightness", "*", "UINT16_MAX", ")", ".", "to_i", ",", "kelvin", ":", "[", "KELVIN_MIN", ",", "kelvin", ".", "to_i", ",", "KELVIN_MAX", "]", ".", "sort", "[", "1", "]", ")", "end" ]
Returns a struct for use by the protocol @api private @return [Protocol::Light::Hsbk]
[ "Returns", "a", "struct", "for", "use", "by", "the", "protocol" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/color.rb#L162-L169
2,308
LIFX/lifx-gem
lib/lifx/color.rb
LIFX.Color.similar_to?
def similar_to?(other, threshold: DEFAULT_SIMILAR_THRESHOLD) return false unless other.is_a?(Color) conditions = [] conditions << (((hue - other.hue).abs < (threshold * 360)) || begin # FIXME: Surely there's a better way. hues = [hue, other.hue].sort hues[0] += 360 (hues[0] - hues[1]).abs < (threshold * 360) end) conditions << ((saturation - other.saturation).abs < threshold) conditions << ((brightness - other.brightness).abs < threshold) conditions.all? end
ruby
def similar_to?(other, threshold: DEFAULT_SIMILAR_THRESHOLD) return false unless other.is_a?(Color) conditions = [] conditions << (((hue - other.hue).abs < (threshold * 360)) || begin # FIXME: Surely there's a better way. hues = [hue, other.hue].sort hues[0] += 360 (hues[0] - hues[1]).abs < (threshold * 360) end) conditions << ((saturation - other.saturation).abs < threshold) conditions << ((brightness - other.brightness).abs < threshold) conditions.all? end
[ "def", "similar_to?", "(", "other", ",", "threshold", ":", "DEFAULT_SIMILAR_THRESHOLD", ")", "return", "false", "unless", "other", ".", "is_a?", "(", "Color", ")", "conditions", "=", "[", "]", "conditions", "<<", "(", "(", "(", "hue", "-", "other", ".", "hue", ")", ".", "abs", "<", "(", "threshold", "*", "360", ")", ")", "||", "begin", "# FIXME: Surely there's a better way.", "hues", "=", "[", "hue", ",", "other", ".", "hue", "]", ".", "sort", "hues", "[", "0", "]", "+=", "360", "(", "hues", "[", "0", "]", "-", "hues", "[", "1", "]", ")", ".", "abs", "<", "(", "threshold", "*", "360", ")", "end", ")", "conditions", "<<", "(", "(", "saturation", "-", "other", ".", "saturation", ")", ".", "abs", "<", "threshold", ")", "conditions", "<<", "(", "(", "brightness", "-", "other", ".", "brightness", ")", ".", "abs", "<", "threshold", ")", "conditions", ".", "all?", "end" ]
0.1% variance Checks if colours are equal to 0.1% variance @param other [Color] Color to compare to @param threshold: [Float] 0..1. Threshold to consider it similar @return [Boolean]
[ "0", ".", "1%", "variance", "Checks", "if", "colours", "are", "equal", "to", "0", ".", "1%", "variance" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/color.rb#L182-L195
2,309
jakubsvehla/nominatim
lib/nominatim/reverse.rb
Nominatim.Reverse.fetch
def fetch body = get(Nominatim.config.reverse_url, @criteria).body return nil if body.empty? Nominatim::Place.new(body) end
ruby
def fetch body = get(Nominatim.config.reverse_url, @criteria).body return nil if body.empty? Nominatim::Place.new(body) end
[ "def", "fetch", "body", "=", "get", "(", "Nominatim", ".", "config", ".", "reverse_url", ",", "@criteria", ")", ".", "body", "return", "nil", "if", "body", ".", "empty?", "Nominatim", "::", "Place", ".", "new", "(", "body", ")", "end" ]
Returns search result or nil if no results received.
[ "Returns", "search", "result", "or", "nil", "if", "no", "results", "received", "." ]
1457ae8a1ea036efe5bd85eb81a77356d9ceaf06
https://github.com/jakubsvehla/nominatim/blob/1457ae8a1ea036efe5bd85eb81a77356d9ceaf06/lib/nominatim/reverse.rb#L10-L14
2,310
mloughran/signature
lib/signature.rb
Signature.Request.sign
def sign(token) @auth_hash = { :auth_version => "1.0", :auth_key => token.key, :auth_timestamp => Time.now.to_i.to_s } @auth_hash[:auth_signature] = signature(token) @signed = true return @auth_hash end
ruby
def sign(token) @auth_hash = { :auth_version => "1.0", :auth_key => token.key, :auth_timestamp => Time.now.to_i.to_s } @auth_hash[:auth_signature] = signature(token) @signed = true return @auth_hash end
[ "def", "sign", "(", "token", ")", "@auth_hash", "=", "{", ":auth_version", "=>", "\"1.0\"", ",", ":auth_key", "=>", "token", ".", "key", ",", ":auth_timestamp", "=>", "Time", ".", "now", ".", "to_i", ".", "to_s", "}", "@auth_hash", "[", ":auth_signature", "]", "=", "signature", "(", "token", ")", "@signed", "=", "true", "return", "@auth_hash", "end" ]
Sign the request with the given token, and return the computed authentication parameters
[ "Sign", "the", "request", "with", "the", "given", "token", "and", "return", "the", "computed", "authentication", "parameters" ]
9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20
https://github.com/mloughran/signature/blob/9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20/lib/signature.rb#L47-L58
2,311
mloughran/signature
lib/signature.rb
Signature.Request.authenticate_by_token!
def authenticate_by_token!(token, timestamp_grace = 600) # Validate that your code has provided a valid token. This does not # raise an AuthenticationError since passing tokens with empty secret is # a code error which should be fixed, not reported to the API's consumer if token.secret.nil? || token.secret.empty? raise "Provided token is missing secret" end validate_version! validate_timestamp!(timestamp_grace) validate_signature!(token) true end
ruby
def authenticate_by_token!(token, timestamp_grace = 600) # Validate that your code has provided a valid token. This does not # raise an AuthenticationError since passing tokens with empty secret is # a code error which should be fixed, not reported to the API's consumer if token.secret.nil? || token.secret.empty? raise "Provided token is missing secret" end validate_version! validate_timestamp!(timestamp_grace) validate_signature!(token) true end
[ "def", "authenticate_by_token!", "(", "token", ",", "timestamp_grace", "=", "600", ")", "# Validate that your code has provided a valid token. This does not", "# raise an AuthenticationError since passing tokens with empty secret is", "# a code error which should be fixed, not reported to the API's consumer", "if", "token", ".", "secret", ".", "nil?", "||", "token", ".", "secret", ".", "empty?", "raise", "\"Provided token is missing secret\"", "end", "validate_version!", "validate_timestamp!", "(", "timestamp_grace", ")", "validate_signature!", "(", "token", ")", "true", "end" ]
Authenticates the request with a token Raises an AuthenticationError if the request is invalid. AuthenticationError exception messages are designed to be exposed to API consumers, and should help them correct errors generating signatures Timestamp: Unless timestamp_grace is set to nil (which allows this check to be skipped), AuthenticationError will be raised if the timestamp is missing or further than timestamp_grace period away from the real time (defaults to 10 minutes) Signature: Raises AuthenticationError if the signature does not match the computed HMAC. The error contains a hint for how to sign.
[ "Authenticates", "the", "request", "with", "a", "token" ]
9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20
https://github.com/mloughran/signature/blob/9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20/lib/signature.rb#L74-L86
2,312
mloughran/signature
lib/signature.rb
Signature.Request.authenticate
def authenticate(timestamp_grace = 600) raise ArgumentError, "Block required" unless block_given? key = @auth_hash['auth_key'] raise AuthenticationError, "Missing parameter: auth_key" unless key token = yield key unless token raise AuthenticationError, "Unknown auth_key" end authenticate_by_token!(token, timestamp_grace) return token end
ruby
def authenticate(timestamp_grace = 600) raise ArgumentError, "Block required" unless block_given? key = @auth_hash['auth_key'] raise AuthenticationError, "Missing parameter: auth_key" unless key token = yield key unless token raise AuthenticationError, "Unknown auth_key" end authenticate_by_token!(token, timestamp_grace) return token end
[ "def", "authenticate", "(", "timestamp_grace", "=", "600", ")", "raise", "ArgumentError", ",", "\"Block required\"", "unless", "block_given?", "key", "=", "@auth_hash", "[", "'auth_key'", "]", "raise", "AuthenticationError", ",", "\"Missing parameter: auth_key\"", "unless", "key", "token", "=", "yield", "key", "unless", "token", "raise", "AuthenticationError", ",", "\"Unknown auth_key\"", "end", "authenticate_by_token!", "(", "token", ",", "timestamp_grace", ")", "return", "token", "end" ]
Authenticate a request Takes a block which will be called with the auth_key from the request, and which should return a Signature::Token (or nil if no token can be found for the key) Raises errors in the same way as authenticate_by_token!
[ "Authenticate", "a", "request" ]
9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20
https://github.com/mloughran/signature/blob/9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20/lib/signature.rb#L105-L115
2,313
mloughran/signature
lib/signature.rb
Signature.Request.authenticate_async
def authenticate_async(timestamp_grace = 600) raise ArgumentError, "Block required" unless block_given? df = EM::DefaultDeferrable.new key = @auth_hash['auth_key'] unless key df.fail(AuthenticationError.new("Missing parameter: auth_key")) return end token_df = yield key token_df.callback { |token| begin authenticate_by_token!(token, timestamp_grace) df.succeed(token) rescue AuthenticationError => e df.fail(e) end } token_df.errback { df.fail(AuthenticationError.new("Unknown auth_key")) } ensure return df end
ruby
def authenticate_async(timestamp_grace = 600) raise ArgumentError, "Block required" unless block_given? df = EM::DefaultDeferrable.new key = @auth_hash['auth_key'] unless key df.fail(AuthenticationError.new("Missing parameter: auth_key")) return end token_df = yield key token_df.callback { |token| begin authenticate_by_token!(token, timestamp_grace) df.succeed(token) rescue AuthenticationError => e df.fail(e) end } token_df.errback { df.fail(AuthenticationError.new("Unknown auth_key")) } ensure return df end
[ "def", "authenticate_async", "(", "timestamp_grace", "=", "600", ")", "raise", "ArgumentError", ",", "\"Block required\"", "unless", "block_given?", "df", "=", "EM", "::", "DefaultDeferrable", ".", "new", "key", "=", "@auth_hash", "[", "'auth_key'", "]", "unless", "key", "df", ".", "fail", "(", "AuthenticationError", ".", "new", "(", "\"Missing parameter: auth_key\"", ")", ")", "return", "end", "token_df", "=", "yield", "key", "token_df", ".", "callback", "{", "|", "token", "|", "begin", "authenticate_by_token!", "(", "token", ",", "timestamp_grace", ")", "df", ".", "succeed", "(", "token", ")", "rescue", "AuthenticationError", "=>", "e", "df", ".", "fail", "(", "e", ")", "end", "}", "token_df", ".", "errback", "{", "df", ".", "fail", "(", "AuthenticationError", ".", "new", "(", "\"Unknown auth_key\"", ")", ")", "}", "ensure", "return", "df", "end" ]
Authenticate a request asynchronously This method is useful it you're running a server inside eventmachine and need to lookup the token asynchronously. The block is passed an auth key and a deferrable which should succeed with the token, or fail if the token cannot be found This method returns a deferrable which succeeds with the valid token, or fails with an AuthenticationError which can be used to pass the error back to the user
[ "Authenticate", "a", "request", "asynchronously" ]
9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20
https://github.com/mloughran/signature/blob/9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20/lib/signature.rb#L129-L154
2,314
mloughran/signature
lib/signature.rb
Signature.Request.identical?
def identical?(a, b) return true if a.nil? && b.nil? return false if a.nil? || b.nil? return false unless a.bytesize == b.bytesize a.bytes.zip(b.bytes).reduce(0) { |memo, (a, b)| memo += a ^ b } == 0 end
ruby
def identical?(a, b) return true if a.nil? && b.nil? return false if a.nil? || b.nil? return false unless a.bytesize == b.bytesize a.bytes.zip(b.bytes).reduce(0) { |memo, (a, b)| memo += a ^ b } == 0 end
[ "def", "identical?", "(", "a", ",", "b", ")", "return", "true", "if", "a", ".", "nil?", "&&", "b", ".", "nil?", "return", "false", "if", "a", ".", "nil?", "||", "b", ".", "nil?", "return", "false", "unless", "a", ".", "bytesize", "==", "b", ".", "bytesize", "a", ".", "bytes", ".", "zip", "(", "b", ".", "bytes", ")", ".", "reduce", "(", "0", ")", "{", "|", "memo", ",", "(", "a", ",", "b", ")", "|", "memo", "+=", "a", "^", "b", "}", "==", "0", "end" ]
Constant time string comparison
[ "Constant", "time", "string", "comparison" ]
9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20
https://github.com/mloughran/signature/blob/9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20/lib/signature.rb#L225-L230
2,315
RoxasShadow/sottolio
opal/sottolio/script.rb
Sottolio.Script.method_missing
def method_missing(m, *args, &block) if args.any? args = args.first if args.length == 1 @var << { m.to_sym => args } instance_variable_set "@#{m}", args else instance_variable_get "@#{m}" end end
ruby
def method_missing(m, *args, &block) if args.any? args = args.first if args.length == 1 @var << { m.to_sym => args } instance_variable_set "@#{m}", args else instance_variable_get "@#{m}" end end
[ "def", "method_missing", "(", "m", ",", "*", "args", ",", "&", "block", ")", "if", "args", ".", "any?", "args", "=", "args", ".", "first", "if", "args", ".", "length", "==", "1", "@var", "<<", "{", "m", ".", "to_sym", "=>", "args", "}", "instance_variable_set", "\"@#{m}\"", ",", "args", "else", "instance_variable_get", "\"@#{m}\"", "end", "end" ]
Script's commands
[ "Script", "s", "commands" ]
6687db3cd5df3278d03436b848534ae0f90a4bbd
https://github.com/RoxasShadow/sottolio/blob/6687db3cd5df3278d03436b848534ae0f90a4bbd/opal/sottolio/script.rb#L43-L51
2,316
LIFX/lifx-gem
lib/lifx/tag_manager.rb
LIFX.TagManager.purge_unused_tags!
def purge_unused_tags! unused_tags.each do |tag| logger.info("Purging tag '#{tag}'") entries_with(label: tag).each do |entry| payload = Protocol::Device::SetTagLabels.new(tags: id_to_tags_field(entry.tag_id), label: '') context.send_message(target: Target.new(site_id: entry.site_id), payload: payload, acknowledge: true) end end Timeout.timeout(5) do while !unused_tags.empty? sleep 0.1 end end end
ruby
def purge_unused_tags! unused_tags.each do |tag| logger.info("Purging tag '#{tag}'") entries_with(label: tag).each do |entry| payload = Protocol::Device::SetTagLabels.new(tags: id_to_tags_field(entry.tag_id), label: '') context.send_message(target: Target.new(site_id: entry.site_id), payload: payload, acknowledge: true) end end Timeout.timeout(5) do while !unused_tags.empty? sleep 0.1 end end end
[ "def", "purge_unused_tags!", "unused_tags", ".", "each", "do", "|", "tag", "|", "logger", ".", "info", "(", "\"Purging tag '#{tag}'\"", ")", "entries_with", "(", "label", ":", "tag", ")", ".", "each", "do", "|", "entry", "|", "payload", "=", "Protocol", "::", "Device", "::", "SetTagLabels", ".", "new", "(", "tags", ":", "id_to_tags_field", "(", "entry", ".", "tag_id", ")", ",", "label", ":", "''", ")", "context", ".", "send_message", "(", "target", ":", "Target", ".", "new", "(", "site_id", ":", "entry", ".", "site_id", ")", ",", "payload", ":", "payload", ",", "acknowledge", ":", "true", ")", "end", "end", "Timeout", ".", "timeout", "(", "5", ")", "do", "while", "!", "unused_tags", ".", "empty?", "sleep", "0.1", "end", "end", "end" ]
This will clear out tags that currently do not resolve to any devices. If used when devices that are tagged with a tag that is not attached to an active device, it will effectively untag them when they're back on.
[ "This", "will", "clear", "out", "tags", "that", "currently", "do", "not", "resolve", "to", "any", "devices", ".", "If", "used", "when", "devices", "that", "are", "tagged", "with", "a", "tag", "that", "is", "not", "attached", "to", "an", "active", "device", "it", "will", "effectively", "untag", "them", "when", "they", "re", "back", "on", "." ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/tag_manager.rb#L72-L87
2,317
MaximeD/gem_updater
lib/gem_updater.rb
GemUpdater.Updater.format_diff
def format_diff gemfile.changes.map do |gem, details| ERB.new(template, nil, '<>').result(binding) end end
ruby
def format_diff gemfile.changes.map do |gem, details| ERB.new(template, nil, '<>').result(binding) end end
[ "def", "format_diff", "gemfile", ".", "changes", ".", "map", "do", "|", "gem", ",", "details", "|", "ERB", ".", "new", "(", "template", ",", "nil", ",", "'<>'", ")", ".", "result", "(", "binding", ")", "end", "end" ]
Format the diff to get human readable information on the gems that were updated.
[ "Format", "the", "diff", "to", "get", "human", "readable", "information", "on", "the", "gems", "that", "were", "updated", "." ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater.rb#L41-L45
2,318
MaximeD/gem_updater
lib/gem_updater.rb
GemUpdater.Updater.fill_changelogs
def fill_changelogs [].tap do |threads| gemfile.changes.each do |gem_name, details| threads << Thread.new { retrieve_gem_changes(gem_name, details) } end end.each(&:join) end
ruby
def fill_changelogs [].tap do |threads| gemfile.changes.each do |gem_name, details| threads << Thread.new { retrieve_gem_changes(gem_name, details) } end end.each(&:join) end
[ "def", "fill_changelogs", "[", "]", ".", "tap", "do", "|", "threads", "|", "gemfile", ".", "changes", ".", "each", "do", "|", "gem_name", ",", "details", "|", "threads", "<<", "Thread", ".", "new", "{", "retrieve_gem_changes", "(", "gem_name", ",", "details", ")", "}", "end", "end", ".", "each", "(", ":join", ")", "end" ]
For each gem, retrieve its changelog
[ "For", "each", "gem", "retrieve", "its", "changelog" ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater.rb#L50-L56
2,319
MaximeD/gem_updater
lib/gem_updater.rb
GemUpdater.Updater.find_source
def find_source(gem, source) case source when Bundler::Source::Rubygems GemUpdater::RubyGemsFetcher.new(gem, source).source_uri when Bundler::Source::Git source.uri.gsub(/^git/, 'http').chomp('.git') end end
ruby
def find_source(gem, source) case source when Bundler::Source::Rubygems GemUpdater::RubyGemsFetcher.new(gem, source).source_uri when Bundler::Source::Git source.uri.gsub(/^git/, 'http').chomp('.git') end end
[ "def", "find_source", "(", "gem", ",", "source", ")", "case", "source", "when", "Bundler", "::", "Source", "::", "Rubygems", "GemUpdater", "::", "RubyGemsFetcher", ".", "new", "(", "gem", ",", "source", ")", ".", "source_uri", "when", "Bundler", "::", "Source", "::", "Git", "source", ".", "uri", ".", "gsub", "(", "/", "/", ",", "'http'", ")", ".", "chomp", "(", "'.git'", ")", "end", "end" ]
Find where is hosted the source of a gem @param gem [String] the name of the gem @param source [Bundler::Source] gem's source @return [String] url where gem is hosted
[ "Find", "where", "is", "hosted", "the", "source", "of", "a", "gem" ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater.rb#L63-L70
2,320
MaximeD/gem_updater
lib/gem_updater.rb
GemUpdater.Updater.template
def template File.read("#{Dir.home}/.gem_updater_template.erb") rescue Errno::ENOENT File.read(File.expand_path('../lib/gem_updater_template.erb', __dir__)) end
ruby
def template File.read("#{Dir.home}/.gem_updater_template.erb") rescue Errno::ENOENT File.read(File.expand_path('../lib/gem_updater_template.erb', __dir__)) end
[ "def", "template", "File", ".", "read", "(", "\"#{Dir.home}/.gem_updater_template.erb\"", ")", "rescue", "Errno", "::", "ENOENT", "File", ".", "read", "(", "File", ".", "expand_path", "(", "'../lib/gem_updater_template.erb'", ",", "__dir__", ")", ")", "end" ]
Get the template for gem's diff. It can use a custom template. @return [ERB] the template
[ "Get", "the", "template", "for", "gem", "s", "diff", ".", "It", "can", "use", "a", "custom", "template", "." ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater.rb#L87-L91
2,321
mustafaturan/omnicat
lib/omnicat/classifier.rb
OmniCat.Classifier.strategy=
def strategy=(classifier) is_interchangeable?(classifier) if @strategy && classifier.category_count == 0 previous_strategy = @strategy @strategy = classifier convert_categories_with_docs(previous_strategy) else @strategy = classifier end end
ruby
def strategy=(classifier) is_interchangeable?(classifier) if @strategy && classifier.category_count == 0 previous_strategy = @strategy @strategy = classifier convert_categories_with_docs(previous_strategy) else @strategy = classifier end end
[ "def", "strategy", "=", "(", "classifier", ")", "is_interchangeable?", "(", "classifier", ")", "if", "@strategy", "&&", "classifier", ".", "category_count", "==", "0", "previous_strategy", "=", "@strategy", "@strategy", "=", "classifier", "convert_categories_with_docs", "(", "previous_strategy", ")", "else", "@strategy", "=", "classifier", "end", "end" ]
nodoc Changes classifier strategy and train new strategy if needed
[ "nodoc", "Changes", "classifier", "strategy", "and", "train", "new", "strategy", "if", "needed" ]
03511027e8e1b7b8b797251834590f85eae9d879
https://github.com/mustafaturan/omnicat/blob/03511027e8e1b7b8b797251834590f85eae9d879/lib/omnicat/classifier.rb#L31-L40
2,322
mustafaturan/omnicat
lib/omnicat/result.rb
OmniCat.Result.add_score
def add_score(score) @total_score += score.value @scores[score.key] = score if @top_score_key.nil? || @scores[@top_score_key].value < score.value @top_score_key = score.key end end
ruby
def add_score(score) @total_score += score.value @scores[score.key] = score if @top_score_key.nil? || @scores[@top_score_key].value < score.value @top_score_key = score.key end end
[ "def", "add_score", "(", "score", ")", "@total_score", "+=", "score", ".", "value", "@scores", "[", "score", ".", "key", "]", "=", "score", "if", "@top_score_key", ".", "nil?", "||", "@scores", "[", "@top_score_key", "]", ".", "value", "<", "score", ".", "value", "@top_score_key", "=", "score", ".", "key", "end", "end" ]
Method for adding new score to result ==== Parameters * +score+ - OmniCat::Score
[ "Method", "for", "adding", "new", "score", "to", "result" ]
03511027e8e1b7b8b797251834590f85eae9d879
https://github.com/mustafaturan/omnicat/blob/03511027e8e1b7b8b797251834590f85eae9d879/lib/omnicat/result.rb#L19-L25
2,323
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.add_hook
def add_hook(payload_class, hook_arg = nil, &hook_block) hook = block_given? ? hook_block : hook_arg if !hook || !hook.is_a?(Proc) raise "Must pass a proc either as an argument or a block" end @message_hooks[payload_class] << hook end
ruby
def add_hook(payload_class, hook_arg = nil, &hook_block) hook = block_given? ? hook_block : hook_arg if !hook || !hook.is_a?(Proc) raise "Must pass a proc either as an argument or a block" end @message_hooks[payload_class] << hook end
[ "def", "add_hook", "(", "payload_class", ",", "hook_arg", "=", "nil", ",", "&", "hook_block", ")", "hook", "=", "block_given?", "?", "hook_block", ":", "hook_arg", "if", "!", "hook", "||", "!", "hook", ".", "is_a?", "(", "Proc", ")", "raise", "\"Must pass a proc either as an argument or a block\"", "end", "@message_hooks", "[", "payload_class", "]", "<<", "hook", "end" ]
Adds a block to be run when a payload of class `payload_class` is received @param payload_class [Class] Payload type to execute block on @param &hook [Proc] Hook to run @api private @return [void]
[ "Adds", "a", "block", "to", "be", "run", "when", "a", "payload", "of", "class", "payload_class", "is", "received" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L56-L62
2,324
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.color
def color(refresh: false, fetch: true) @color = nil if refresh send_message!(Protocol::Light::Get.new, wait_for: Protocol::Light::State) if fetch && !@color @color end
ruby
def color(refresh: false, fetch: true) @color = nil if refresh send_message!(Protocol::Light::Get.new, wait_for: Protocol::Light::State) if fetch && !@color @color end
[ "def", "color", "(", "refresh", ":", "false", ",", "fetch", ":", "true", ")", "@color", "=", "nil", "if", "refresh", "send_message!", "(", "Protocol", "::", "Light", "::", "Get", ".", "new", ",", "wait_for", ":", "Protocol", "::", "Light", "::", "State", ")", "if", "fetch", "&&", "!", "@color", "@color", "end" ]
Returns the color of the device. @param refresh: [Boolean] If true, will request for current color @param fetch: [Boolean] If false, it will not request current color if it's not cached @return [Color] Color
[ "Returns", "the", "color", "of", "the", "device", "." ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L77-L81
2,325
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.set_label
def set_label(label) if label.bytes.length > MAX_LABEL_LENGTH raise LabelTooLong.new("Label length in bytes must be below or equal to #{MAX_LABEL_LENGTH}") end while self.label != label send_message!(Protocol::Device::SetLabel.new(label: label.encode('utf-8')), wait_for: Protocol::Device::StateLabel) end self end
ruby
def set_label(label) if label.bytes.length > MAX_LABEL_LENGTH raise LabelTooLong.new("Label length in bytes must be below or equal to #{MAX_LABEL_LENGTH}") end while self.label != label send_message!(Protocol::Device::SetLabel.new(label: label.encode('utf-8')), wait_for: Protocol::Device::StateLabel) end self end
[ "def", "set_label", "(", "label", ")", "if", "label", ".", "bytes", ".", "length", ">", "MAX_LABEL_LENGTH", "raise", "LabelTooLong", ".", "new", "(", "\"Label length in bytes must be below or equal to #{MAX_LABEL_LENGTH}\"", ")", "end", "while", "self", ".", "label", "!=", "label", "send_message!", "(", "Protocol", "::", "Device", "::", "SetLabel", ".", "new", "(", "label", ":", "label", ".", "encode", "(", "'utf-8'", ")", ")", ",", "wait_for", ":", "Protocol", "::", "Device", "::", "StateLabel", ")", "end", "self", "end" ]
Sets the label of the light @param label [String] Desired label @raise [LabelTooLong] if label is greater than {MAX_LABEL_LENGTH} @return [Light] self
[ "Sets", "the", "label", "of", "the", "light" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L100-L108
2,326
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.set_power!
def set_power!(state) level = case state when :on 1 when :off 0 else raise ArgumentError.new("Must pass in either :on or :off") end send_message!(Protocol::Device::SetPower.new(level: level), wait_for: Protocol::Device::StatePower) do |payload| if level == 0 payload.level == 0 else payload.level > 0 end end self end
ruby
def set_power!(state) level = case state when :on 1 when :off 0 else raise ArgumentError.new("Must pass in either :on or :off") end send_message!(Protocol::Device::SetPower.new(level: level), wait_for: Protocol::Device::StatePower) do |payload| if level == 0 payload.level == 0 else payload.level > 0 end end self end
[ "def", "set_power!", "(", "state", ")", "level", "=", "case", "state", "when", ":on", "1", "when", ":off", "0", "else", "raise", "ArgumentError", ".", "new", "(", "\"Must pass in either :on or :off\"", ")", "end", "send_message!", "(", "Protocol", "::", "Device", "::", "SetPower", ".", "new", "(", "level", ":", "level", ")", ",", "wait_for", ":", "Protocol", "::", "Device", "::", "StatePower", ")", "do", "|", "payload", "|", "if", "level", "==", "0", "payload", ".", "level", "==", "0", "else", "payload", ".", "level", ">", "0", "end", "end", "self", "end" ]
Set the power state to `state` synchronously. @param state [:on, :off] @return [Light, LightCollection] self for chaining
[ "Set", "the", "power", "state", "to", "state", "synchronously", "." ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L113-L130
2,327
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.time
def time send_message!(Protocol::Device::GetTime.new, wait_for: Protocol::Device::StateTime) do |payload| Time.at(payload.time.to_f / NSEC_IN_SEC) end end
ruby
def time send_message!(Protocol::Device::GetTime.new, wait_for: Protocol::Device::StateTime) do |payload| Time.at(payload.time.to_f / NSEC_IN_SEC) end end
[ "def", "time", "send_message!", "(", "Protocol", "::", "Device", "::", "GetTime", ".", "new", ",", "wait_for", ":", "Protocol", "::", "Device", "::", "StateTime", ")", "do", "|", "payload", "|", "Time", ".", "at", "(", "payload", ".", "time", ".", "to_f", "/", "NSEC_IN_SEC", ")", "end", "end" ]
Returns the local time of the light @return [Time]
[ "Returns", "the", "local", "time", "of", "the", "light" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L174-L178
2,328
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.latency
def latency start = Time.now.to_f send_message!(Protocol::Device::GetTime.new, wait_for: Protocol::Device::StateTime) Time.now.to_f - start end
ruby
def latency start = Time.now.to_f send_message!(Protocol::Device::GetTime.new, wait_for: Protocol::Device::StateTime) Time.now.to_f - start end
[ "def", "latency", "start", "=", "Time", ".", "now", ".", "to_f", "send_message!", "(", "Protocol", "::", "Device", "::", "GetTime", ".", "new", ",", "wait_for", ":", "Protocol", "::", "Device", "::", "StateTime", ")", "Time", ".", "now", ".", "to_f", "-", "start", "end" ]
Pings the device and measures response time. @return [Float] Latency from sending a message to receiving a response.
[ "Pings", "the", "device", "and", "measures", "response", "time", "." ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L190-L194
2,329
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.mesh_firmware
def mesh_firmware(fetch: true) @mesh_firmware ||= begin send_message!(Protocol::Device::GetMeshFirmware.new, wait_for: Protocol::Device::StateMeshFirmware) do |payload| Firmware.new(payload) end if fetch end end
ruby
def mesh_firmware(fetch: true) @mesh_firmware ||= begin send_message!(Protocol::Device::GetMeshFirmware.new, wait_for: Protocol::Device::StateMeshFirmware) do |payload| Firmware.new(payload) end if fetch end end
[ "def", "mesh_firmware", "(", "fetch", ":", "true", ")", "@mesh_firmware", "||=", "begin", "send_message!", "(", "Protocol", "::", "Device", "::", "GetMeshFirmware", ".", "new", ",", "wait_for", ":", "Protocol", "::", "Device", "::", "StateMeshFirmware", ")", "do", "|", "payload", "|", "Firmware", ".", "new", "(", "payload", ")", "end", "if", "fetch", "end", "end" ]
Returns the mesh firmware details @api private @return [Hash] firmware details
[ "Returns", "the", "mesh", "firmware", "details" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L199-L206
2,330
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.wifi_firmware
def wifi_firmware(fetch: true) @wifi_firmware ||= begin send_message!(Protocol::Device::GetWifiFirmware.new, wait_for: Protocol::Device::StateWifiFirmware) do |payload| Firmware.new(payload) end if fetch end end
ruby
def wifi_firmware(fetch: true) @wifi_firmware ||= begin send_message!(Protocol::Device::GetWifiFirmware.new, wait_for: Protocol::Device::StateWifiFirmware) do |payload| Firmware.new(payload) end if fetch end end
[ "def", "wifi_firmware", "(", "fetch", ":", "true", ")", "@wifi_firmware", "||=", "begin", "send_message!", "(", "Protocol", "::", "Device", "::", "GetWifiFirmware", ".", "new", ",", "wait_for", ":", "Protocol", "::", "Device", "::", "StateWifiFirmware", ")", "do", "|", "payload", "|", "Firmware", ".", "new", "(", "payload", ")", "end", "if", "fetch", "end", "end" ]
Returns the wifi firmware details @api private @return [Hash] firmware details
[ "Returns", "the", "wifi", "firmware", "details" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L211-L218
2,331
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.temperature
def temperature send_message!(Protocol::Light::GetTemperature.new, wait_for: Protocol::Light::StateTemperature) do |payload| payload.temperature / 100.0 end end
ruby
def temperature send_message!(Protocol::Light::GetTemperature.new, wait_for: Protocol::Light::StateTemperature) do |payload| payload.temperature / 100.0 end end
[ "def", "temperature", "send_message!", "(", "Protocol", "::", "Light", "::", "GetTemperature", ".", "new", ",", "wait_for", ":", "Protocol", "::", "Light", "::", "StateTemperature", ")", "do", "|", "payload", "|", "payload", ".", "temperature", "/", "100.0", "end", "end" ]
Returns the temperature of the device @return [Float] Temperature in Celcius
[ "Returns", "the", "temperature", "of", "the", "device" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L222-L227
2,332
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.mesh_info
def mesh_info send_message!(Protocol::Device::GetMeshInfo.new, wait_for: Protocol::Device::StateMeshInfo) do |payload| { signal: payload.signal, # This is in Milliwatts tx: payload.tx, rx: payload.rx } end end
ruby
def mesh_info send_message!(Protocol::Device::GetMeshInfo.new, wait_for: Protocol::Device::StateMeshInfo) do |payload| { signal: payload.signal, # This is in Milliwatts tx: payload.tx, rx: payload.rx } end end
[ "def", "mesh_info", "send_message!", "(", "Protocol", "::", "Device", "::", "GetMeshInfo", ".", "new", ",", "wait_for", ":", "Protocol", "::", "Device", "::", "StateMeshInfo", ")", "do", "|", "payload", "|", "{", "signal", ":", "payload", ".", "signal", ",", "# This is in Milliwatts", "tx", ":", "payload", ".", "tx", ",", "rx", ":", "payload", ".", "rx", "}", "end", "end" ]
Returns mesh network info @api private @return [Hash] Mesh network info
[ "Returns", "mesh", "network", "info" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L232-L241
2,333
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.wifi_info
def wifi_info send_message!(Protocol::Device::GetWifiInfo.new, wait_for: Protocol::Device::StateWifiInfo) do |payload| { signal: payload.signal, # This is in Milliwatts tx: payload.tx, rx: payload.rx } end end
ruby
def wifi_info send_message!(Protocol::Device::GetWifiInfo.new, wait_for: Protocol::Device::StateWifiInfo) do |payload| { signal: payload.signal, # This is in Milliwatts tx: payload.tx, rx: payload.rx } end end
[ "def", "wifi_info", "send_message!", "(", "Protocol", "::", "Device", "::", "GetWifiInfo", ".", "new", ",", "wait_for", ":", "Protocol", "::", "Device", "::", "StateWifiInfo", ")", "do", "|", "payload", "|", "{", "signal", ":", "payload", ".", "signal", ",", "# This is in Milliwatts", "tx", ":", "payload", ".", "tx", ",", "rx", ":", "payload", ".", "rx", "}", "end", "end" ]
Returns wifi network info @api private @return [Hash] wifi network info
[ "Returns", "wifi", "network", "info" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L246-L255
2,334
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.version
def version send_message!(Protocol::Device::GetVersion.new, wait_for: Protocol::Device::StateVersion) do |payload| { vendor: payload.vendor, product: payload.product, version: payload.version } end end
ruby
def version send_message!(Protocol::Device::GetVersion.new, wait_for: Protocol::Device::StateVersion) do |payload| { vendor: payload.vendor, product: payload.product, version: payload.version } end end
[ "def", "version", "send_message!", "(", "Protocol", "::", "Device", "::", "GetVersion", ".", "new", ",", "wait_for", ":", "Protocol", "::", "Device", "::", "StateVersion", ")", "do", "|", "payload", "|", "{", "vendor", ":", "payload", ".", "vendor", ",", "product", ":", "payload", ".", "product", ",", "version", ":", "payload", ".", "version", "}", "end", "end" ]
Returns version info @api private @return [Hash] version info
[ "Returns", "version", "info" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L260-L269
2,335
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.uptime
def uptime send_message!(Protocol::Device::GetInfo.new, wait_for: Protocol::Device::StateInfo) do |payload| payload.uptime.to_f / NSEC_IN_SEC end end
ruby
def uptime send_message!(Protocol::Device::GetInfo.new, wait_for: Protocol::Device::StateInfo) do |payload| payload.uptime.to_f / NSEC_IN_SEC end end
[ "def", "uptime", "send_message!", "(", "Protocol", "::", "Device", "::", "GetInfo", ".", "new", ",", "wait_for", ":", "Protocol", "::", "Device", "::", "StateInfo", ")", "do", "|", "payload", "|", "payload", ".", "uptime", ".", "to_f", "/", "NSEC_IN_SEC", "end", "end" ]
Return device uptime @api private @return [Float] Device uptime in seconds
[ "Return", "device", "uptime" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L274-L279
2,336
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.last_downtime
def last_downtime send_message!(Protocol::Device::GetInfo.new, wait_for: Protocol::Device::StateInfo) do |payload| payload.downtime.to_f / NSEC_IN_SEC end end
ruby
def last_downtime send_message!(Protocol::Device::GetInfo.new, wait_for: Protocol::Device::StateInfo) do |payload| payload.downtime.to_f / NSEC_IN_SEC end end
[ "def", "last_downtime", "send_message!", "(", "Protocol", "::", "Device", "::", "GetInfo", ".", "new", ",", "wait_for", ":", "Protocol", "::", "Device", "::", "StateInfo", ")", "do", "|", "payload", "|", "payload", ".", "downtime", ".", "to_f", "/", "NSEC_IN_SEC", "end", "end" ]
Return device last downtime @api private @return [Float] Device's last downtime in secodns
[ "Return", "device", "last", "downtime" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L284-L289
2,337
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.send_message
def send_message(payload, acknowledge: true, at_time: nil) context.send_message(target: Target.new(device_id: id), payload: payload, acknowledge: acknowledge, at_time: at_time) end
ruby
def send_message(payload, acknowledge: true, at_time: nil) context.send_message(target: Target.new(device_id: id), payload: payload, acknowledge: acknowledge, at_time: at_time) end
[ "def", "send_message", "(", "payload", ",", "acknowledge", ":", "true", ",", "at_time", ":", "nil", ")", "context", ".", "send_message", "(", "target", ":", "Target", ".", "new", "(", "device_id", ":", "id", ")", ",", "payload", ":", "payload", ",", "acknowledge", ":", "acknowledge", ",", "at_time", ":", "at_time", ")", "end" ]
Compare current Light to another light @param other [Light] @return [-1, 0, 1] Comparison value Queues a message to be sent the Light @param payload [Protocol::Payload] the payload to send @param acknowledge: [Boolean] whether the device should respond @param at_time: [Integer] Unix epoch in milliseconds to run the payload. Only applicable to certain payload types. @return [Light] returns self for chaining
[ "Compare", "current", "Light", "to", "another", "light" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L361-L363
2,338
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.send_message!
def send_message!(payload, wait_for: wait_for, wait_timeout: Config.message_wait_timeout, retry_interval: Config.message_retry_interval, &block) if Thread.current[:sync_enabled] raise "Cannot use synchronous methods inside a sync block" end result = nil begin block ||= Proc.new { |msg| true } proc = -> (payload) { result = block.call(payload) } add_hook(wait_for, proc) try_until -> { result }, timeout: wait_timeout, timeout_exception: TimeoutError, action_interval: retry_interval, signal: @message_signal do send_message(payload) end result rescue TimeoutError backtrace = caller_locations(2).map { |c| c.to_s } caller_method = caller_locations(2, 1).first.label ex = MessageTimeout.new("#{caller_method}: Timeout exceeded waiting for response from #{self}") ex.device = self ex.set_backtrace(backtrace) raise ex ensure remove_hook(wait_for, proc) end end
ruby
def send_message!(payload, wait_for: wait_for, wait_timeout: Config.message_wait_timeout, retry_interval: Config.message_retry_interval, &block) if Thread.current[:sync_enabled] raise "Cannot use synchronous methods inside a sync block" end result = nil begin block ||= Proc.new { |msg| true } proc = -> (payload) { result = block.call(payload) } add_hook(wait_for, proc) try_until -> { result }, timeout: wait_timeout, timeout_exception: TimeoutError, action_interval: retry_interval, signal: @message_signal do send_message(payload) end result rescue TimeoutError backtrace = caller_locations(2).map { |c| c.to_s } caller_method = caller_locations(2, 1).first.label ex = MessageTimeout.new("#{caller_method}: Timeout exceeded waiting for response from #{self}") ex.device = self ex.set_backtrace(backtrace) raise ex ensure remove_hook(wait_for, proc) end end
[ "def", "send_message!", "(", "payload", ",", "wait_for", ":", "wait_for", ",", "wait_timeout", ":", "Config", ".", "message_wait_timeout", ",", "retry_interval", ":", "Config", ".", "message_retry_interval", ",", "&", "block", ")", "if", "Thread", ".", "current", "[", ":sync_enabled", "]", "raise", "\"Cannot use synchronous methods inside a sync block\"", "end", "result", "=", "nil", "begin", "block", "||=", "Proc", ".", "new", "{", "|", "msg", "|", "true", "}", "proc", "=", "->", "(", "payload", ")", "{", "result", "=", "block", ".", "call", "(", "payload", ")", "}", "add_hook", "(", "wait_for", ",", "proc", ")", "try_until", "->", "{", "result", "}", ",", "timeout", ":", "wait_timeout", ",", "timeout_exception", ":", "TimeoutError", ",", "action_interval", ":", "retry_interval", ",", "signal", ":", "@message_signal", "do", "send_message", "(", "payload", ")", "end", "result", "rescue", "TimeoutError", "backtrace", "=", "caller_locations", "(", "2", ")", ".", "map", "{", "|", "c", "|", "c", ".", "to_s", "}", "caller_method", "=", "caller_locations", "(", "2", ",", "1", ")", ".", "first", ".", "label", "ex", "=", "MessageTimeout", ".", "new", "(", "\"#{caller_method}: Timeout exceeded waiting for response from #{self}\"", ")", "ex", ".", "device", "=", "self", "ex", ".", "set_backtrace", "(", "backtrace", ")", "raise", "ex", "ensure", "remove_hook", "(", "wait_for", ",", "proc", ")", "end", "end" ]
Queues a message to be sent to the Light and waits for a response @param payload [Protocol::Payload] the payload to send @param wait_for: [Class] the payload class to wait for @param wait_timeout: [Numeric] wait timeout @param block: [Proc] the block that is executed when the expected `wait_for` payload comes back. If the return value is false or nil, it will try to send the message again. @return [Object] the truthy result of `block` is returned. @raise [MessageTimeout] if the device doesn't respond in time
[ "Queues", "a", "message", "to", "be", "sent", "to", "the", "Light", "and", "waits", "for", "a", "response" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L377-L403
2,339
logicminds/nexus-client
lib/nexus_client.rb
Nexus.Client.gav_data
def gav_data(gav) res = {} request = Typhoeus::Request.new( "#{host_url}/service/local/artifact/maven/resolve", :params => gav.to_hash,:connecttimeout => 5, :headers => { 'Accept' => 'application/json' } ) request.on_failure do |response| raise("Failed to get gav data for #{gav.to_s}") end request.on_complete do |response| res = JSON.parse(response.response_body) end request.run res['data'] end
ruby
def gav_data(gav) res = {} request = Typhoeus::Request.new( "#{host_url}/service/local/artifact/maven/resolve", :params => gav.to_hash,:connecttimeout => 5, :headers => { 'Accept' => 'application/json' } ) request.on_failure do |response| raise("Failed to get gav data for #{gav.to_s}") end request.on_complete do |response| res = JSON.parse(response.response_body) end request.run res['data'] end
[ "def", "gav_data", "(", "gav", ")", "res", "=", "{", "}", "request", "=", "Typhoeus", "::", "Request", ".", "new", "(", "\"#{host_url}/service/local/artifact/maven/resolve\"", ",", ":params", "=>", "gav", ".", "to_hash", ",", ":connecttimeout", "=>", "5", ",", ":headers", "=>", "{", "'Accept'", "=>", "'application/json'", "}", ")", "request", ".", "on_failure", "do", "|", "response", "|", "raise", "(", "\"Failed to get gav data for #{gav.to_s}\"", ")", "end", "request", ".", "on_complete", "do", "|", "response", "|", "res", "=", "JSON", ".", "parse", "(", "response", ".", "response_body", ")", "end", "request", ".", "run", "res", "[", "'data'", "]", "end" ]
retrieves the attributes of the gav
[ "retrieves", "the", "attributes", "of", "the", "gav" ]
26b07e1478dd129f80bf145bf3db0f8219b12bda
https://github.com/logicminds/nexus-client/blob/26b07e1478dd129f80bf145bf3db0f8219b12bda/lib/nexus_client.rb#L80-L96
2,340
logicminds/nexus-client
lib/nexus_client.rb
Nexus.Client.sha
def sha(file, use_sha_file=false) if use_sha_file and File.exists?("#{file}.sha1") # reading the file is faster than doing a hash, so we keep the hash in the file # then we read back and compare. There is no reason to perform sha1 everytime begin File.open("#{file}.sha1", 'r') { |f| f.read().strip} rescue Digest::SHA1.file(File.expand_path(file)).hexdigest end else Digest::SHA1.file(File.expand_path(file)).hexdigest end end
ruby
def sha(file, use_sha_file=false) if use_sha_file and File.exists?("#{file}.sha1") # reading the file is faster than doing a hash, so we keep the hash in the file # then we read back and compare. There is no reason to perform sha1 everytime begin File.open("#{file}.sha1", 'r') { |f| f.read().strip} rescue Digest::SHA1.file(File.expand_path(file)).hexdigest end else Digest::SHA1.file(File.expand_path(file)).hexdigest end end
[ "def", "sha", "(", "file", ",", "use_sha_file", "=", "false", ")", "if", "use_sha_file", "and", "File", ".", "exists?", "(", "\"#{file}.sha1\"", ")", "# reading the file is faster than doing a hash, so we keep the hash in the file", "# then we read back and compare. There is no reason to perform sha1 everytime", "begin", "File", ".", "open", "(", "\"#{file}.sha1\"", ",", "'r'", ")", "{", "|", "f", "|", "f", ".", "read", "(", ")", ".", "strip", "}", "rescue", "Digest", "::", "SHA1", ".", "file", "(", "File", ".", "expand_path", "(", "file", ")", ")", ".", "hexdigest", "end", "else", "Digest", "::", "SHA1", ".", "file", "(", "File", ".", "expand_path", "(", "file", ")", ")", ".", "hexdigest", "end", "end" ]
returns the sha1 of the file
[ "returns", "the", "sha1", "of", "the", "file" ]
26b07e1478dd129f80bf145bf3db0f8219b12bda
https://github.com/logicminds/nexus-client/blob/26b07e1478dd129f80bf145bf3db0f8219b12bda/lib/nexus_client.rb#L99-L111
2,341
logicminds/nexus-client
lib/nexus_client.rb
Nexus.Client.sha_match?
def sha_match?(file, gav, use_sha_file=false) if File.exists?(file) if gav.sha1.nil? gav.sha1 = gav_data(gav)['sha1'] end sha(file,use_sha_file) == gav.sha1 else false end end
ruby
def sha_match?(file, gav, use_sha_file=false) if File.exists?(file) if gav.sha1.nil? gav.sha1 = gav_data(gav)['sha1'] end sha(file,use_sha_file) == gav.sha1 else false end end
[ "def", "sha_match?", "(", "file", ",", "gav", ",", "use_sha_file", "=", "false", ")", "if", "File", ".", "exists?", "(", "file", ")", "if", "gav", ".", "sha1", ".", "nil?", "gav", ".", "sha1", "=", "gav_data", "(", "gav", ")", "[", "'sha1'", "]", "end", "sha", "(", "file", ",", "use_sha_file", ")", "==", "gav", ".", "sha1", "else", "false", "end", "end" ]
sha_match? returns bool by comparing the sha1 of the nexus gav artifact and the local file
[ "sha_match?", "returns", "bool", "by", "comparing", "the", "sha1", "of", "the", "nexus", "gav", "artifact", "and", "the", "local", "file" ]
26b07e1478dd129f80bf145bf3db0f8219b12bda
https://github.com/logicminds/nexus-client/blob/26b07e1478dd129f80bf145bf3db0f8219b12bda/lib/nexus_client.rb#L114-L123
2,342
logicminds/nexus-client
lib/nexus_client.rb
Nexus.Client.write_sha1
def write_sha1(file,sha1) shafile = "#{file}.sha1" File.open(shafile, 'w') { |f| f.write(sha1) } end
ruby
def write_sha1(file,sha1) shafile = "#{file}.sha1" File.open(shafile, 'w') { |f| f.write(sha1) } end
[ "def", "write_sha1", "(", "file", ",", "sha1", ")", "shafile", "=", "\"#{file}.sha1\"", "File", ".", "open", "(", "shafile", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "sha1", ")", "}", "end" ]
writes the sha1 a file if and only if the contents of the file do not match
[ "writes", "the", "sha1", "a", "file", "if", "and", "only", "if", "the", "contents", "of", "the", "file", "do", "not", "match" ]
26b07e1478dd129f80bf145bf3db0f8219b12bda
https://github.com/logicminds/nexus-client/blob/26b07e1478dd129f80bf145bf3db0f8219b12bda/lib/nexus_client.rb#L128-L131
2,343
MaximeD/gem_updater
lib/gem_updater/source_page_parser.rb
GemUpdater.SourcePageParser.known_https
def known_https(uri) case uri.host when HOSTS[:github] # remove possible subdomain like 'wiki.github.com' URI "https://github.com#{uri.path}" when HOSTS[:bitbucket] URI "https://#{uri.host}#{uri.path}" when HOSTS[:rubygems] URI "https://#{uri.host}#{uri.path}" else uri end end
ruby
def known_https(uri) case uri.host when HOSTS[:github] # remove possible subdomain like 'wiki.github.com' URI "https://github.com#{uri.path}" when HOSTS[:bitbucket] URI "https://#{uri.host}#{uri.path}" when HOSTS[:rubygems] URI "https://#{uri.host}#{uri.path}" else uri end end
[ "def", "known_https", "(", "uri", ")", "case", "uri", ".", "host", "when", "HOSTS", "[", ":github", "]", "# remove possible subdomain like 'wiki.github.com'", "URI", "\"https://github.com#{uri.path}\"", "when", "HOSTS", "[", ":bitbucket", "]", "URI", "\"https://#{uri.host}#{uri.path}\"", "when", "HOSTS", "[", ":rubygems", "]", "URI", "\"https://#{uri.host}#{uri.path}\"", "else", "uri", "end", "end" ]
Some uris are not https, but we know they should be, in which case we have an https redirection which is not properly handled by open-uri @param uri [URI::HTTP] @return [URI::HTTPS|URI::HTTP]
[ "Some", "uris", "are", "not", "https", "but", "we", "know", "they", "should", "be", "in", "which", "case", "we", "have", "an", "https", "redirection", "which", "is", "not", "properly", "handled", "by", "open", "-", "uri" ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater/source_page_parser.rb#L66-L78
2,344
MaximeD/gem_updater
lib/gem_updater/source_page_parser.rb
GemUpdater.SourcePageParser.changelog_names
def changelog_names CHANGELOG_NAMES.flat_map do |name| [name, name.upcase, name.capitalize] end.uniq end
ruby
def changelog_names CHANGELOG_NAMES.flat_map do |name| [name, name.upcase, name.capitalize] end.uniq end
[ "def", "changelog_names", "CHANGELOG_NAMES", ".", "flat_map", "do", "|", "name", "|", "[", "name", ",", "name", ".", "upcase", ",", "name", ".", "capitalize", "]", "end", ".", "uniq", "end" ]
List possible names for a changelog since humans may have many many ways to call it. @return [Array] list of possible names
[ "List", "possible", "names", "for", "a", "changelog", "since", "humans", "may", "have", "many", "many", "ways", "to", "call", "it", "." ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater/source_page_parser.rb#L94-L98
2,345
dewski/kss-rails
app/helpers/kss/application_helper.rb
Kss.ApplicationHelper.styleguide_block
def styleguide_block(section, &block) raise ArgumentError, "Missing block" unless block_given? @section = styleguide.section(section) if [email protected] raise "KSS styleguide section is nil, is section '#{section}' defined in your css?" end content = capture(&block) render 'kss/shared/styleguide_block', :section => @section, :example_html => content end
ruby
def styleguide_block(section, &block) raise ArgumentError, "Missing block" unless block_given? @section = styleguide.section(section) if [email protected] raise "KSS styleguide section is nil, is section '#{section}' defined in your css?" end content = capture(&block) render 'kss/shared/styleguide_block', :section => @section, :example_html => content end
[ "def", "styleguide_block", "(", "section", ",", "&", "block", ")", "raise", "ArgumentError", ",", "\"Missing block\"", "unless", "block_given?", "@section", "=", "styleguide", ".", "section", "(", "section", ")", "if", "!", "@section", ".", "raw", "raise", "\"KSS styleguide section is nil, is section '#{section}' defined in your css?\"", "end", "content", "=", "capture", "(", "block", ")", "render", "'kss/shared/styleguide_block'", ",", ":section", "=>", "@section", ",", ":example_html", "=>", "content", "end" ]
Generates a styleguide block. A little bit evil with @_out_buf, but if you're using something like Rails, you can write a much cleaner helper very easily.
[ "Generates", "a", "styleguide", "block", ".", "A", "little", "bit", "evil", "with" ]
3bec7e1a0e14b771bc2eeed10474f74ba34a03ed
https://github.com/dewski/kss-rails/blob/3bec7e1a0e14b771bc2eeed10474f74ba34a03ed/app/helpers/kss/application_helper.rb#L6-L17
2,346
mikamai/akamai_api
lib/akamai_api/eccu/soap_body.rb
AkamaiApi::ECCU.SoapBody.array
def array name, values array_attrs = { 'soapenc:arrayType' => "xsd:string[#{values.length}]", 'xsi:type' => 'wsdl:ArrayOfString' } builder.tag! name, array_attrs do |tag| values.each { |value| tag.item value } end self end
ruby
def array name, values array_attrs = { 'soapenc:arrayType' => "xsd:string[#{values.length}]", 'xsi:type' => 'wsdl:ArrayOfString' } builder.tag! name, array_attrs do |tag| values.each { |value| tag.item value } end self end
[ "def", "array", "name", ",", "values", "array_attrs", "=", "{", "'soapenc:arrayType'", "=>", "\"xsd:string[#{values.length}]\"", ",", "'xsi:type'", "=>", "'wsdl:ArrayOfString'", "}", "builder", ".", "tag!", "name", ",", "array_attrs", "do", "|", "tag", "|", "values", ".", "each", "{", "|", "value", "|", "tag", ".", "item", "value", "}", "end", "self", "end" ]
Appends an argument of type array @param [String] name argument name @param [Array] values @return [SoapBody]
[ "Appends", "an", "argument", "of", "type", "array" ]
a6bc1369e118bb298c71019c9788e5c9bd1753c8
https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/eccu/soap_body.rb#L82-L91
2,347
mikamai/akamai_api
lib/akamai_api/ccu/purge_status/request.rb
AkamaiApi::CCU::PurgeStatus.Request.execute
def execute purge_id_or_progress_uri purge_id_or_progress_uri = normalize_progress_uri purge_id_or_progress_uri response = self.class.get purge_id_or_progress_uri, basic_auth: AkamaiApi.auth parse_response response end
ruby
def execute purge_id_or_progress_uri purge_id_or_progress_uri = normalize_progress_uri purge_id_or_progress_uri response = self.class.get purge_id_or_progress_uri, basic_auth: AkamaiApi.auth parse_response response end
[ "def", "execute", "purge_id_or_progress_uri", "purge_id_or_progress_uri", "=", "normalize_progress_uri", "purge_id_or_progress_uri", "response", "=", "self", ".", "class", ".", "get", "purge_id_or_progress_uri", ",", "basic_auth", ":", "AkamaiApi", ".", "auth", "parse_response", "response", "end" ]
Checks the status of the requested associated with the given argument @return [Response] an object detailing the response @raise [AkamaiApi::CCU::PurgeStatus::NotFound] when the request cannot be found @raise [AkamaiApi::CCU::Error] when there is an error in the request @raise [AkamaiApi::Unauthorized] when login credentials are invalid
[ "Checks", "the", "status", "of", "the", "requested", "associated", "with", "the", "given", "argument" ]
a6bc1369e118bb298c71019c9788e5c9bd1753c8
https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/ccu/purge_status/request.rb#L37-L41
2,348
mikamai/akamai_api
lib/akamai_api/eccu/find_request.rb
AkamaiApi::ECCU.FindRequest.execute
def execute retrieve_content = false with_soap_error_handling do response = client_call :get_info, message: request_body(retrieve_content).to_s FindResponse.new response[:eccu_info] end end
ruby
def execute retrieve_content = false with_soap_error_handling do response = client_call :get_info, message: request_body(retrieve_content).to_s FindResponse.new response[:eccu_info] end end
[ "def", "execute", "retrieve_content", "=", "false", "with_soap_error_handling", "do", "response", "=", "client_call", ":get_info", ",", "message", ":", "request_body", "(", "retrieve_content", ")", ".", "to_s", "FindResponse", ".", "new", "response", "[", ":eccu_info", "]", "end", "end" ]
Returns the details of an ECCU request @param [true,false] retrieve_content set to true if you want to retrieve request content too @return [FindResponse]
[ "Returns", "the", "details", "of", "an", "ECCU", "request" ]
a6bc1369e118bb298c71019c9788e5c9bd1753c8
https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/eccu/find_request.rb#L28-L33
2,349
mikamai/akamai_api
lib/akamai_api/ccu/purge/request.rb
AkamaiApi::CCU::Purge.Request.execute
def execute *items akamai = Akamai::Edgegrid::HTTP.new(address=baseuri.host, port=baseuri.port) akamai.setup_edgegrid(creds) http = Net::HTTP.new(address=baseuri.host, port=baseuri.port) http.use_ssl = true items = Array.wrap(items.first) if items.length == 1 req = Net::HTTP::Post.new(resource, initheader = @@headers).tap do |pq| if for_ccu_v2? pq.body = request_body items else pq.body = {"objects" => items}.to_json end end timestamp = Akamai::Edgegrid::HTTP.eg_timestamp() nonce = Akamai::Edgegrid::HTTP.new_nonce() req['Authorization'] = akamai.make_auth_header(req, timestamp, nonce) parse_response http.request(req) end
ruby
def execute *items akamai = Akamai::Edgegrid::HTTP.new(address=baseuri.host, port=baseuri.port) akamai.setup_edgegrid(creds) http = Net::HTTP.new(address=baseuri.host, port=baseuri.port) http.use_ssl = true items = Array.wrap(items.first) if items.length == 1 req = Net::HTTP::Post.new(resource, initheader = @@headers).tap do |pq| if for_ccu_v2? pq.body = request_body items else pq.body = {"objects" => items}.to_json end end timestamp = Akamai::Edgegrid::HTTP.eg_timestamp() nonce = Akamai::Edgegrid::HTTP.new_nonce() req['Authorization'] = akamai.make_auth_header(req, timestamp, nonce) parse_response http.request(req) end
[ "def", "execute", "*", "items", "akamai", "=", "Akamai", "::", "Edgegrid", "::", "HTTP", ".", "new", "(", "address", "=", "baseuri", ".", "host", ",", "port", "=", "baseuri", ".", "port", ")", "akamai", ".", "setup_edgegrid", "(", "creds", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "address", "=", "baseuri", ".", "host", ",", "port", "=", "baseuri", ".", "port", ")", "http", ".", "use_ssl", "=", "true", "items", "=", "Array", ".", "wrap", "(", "items", ".", "first", ")", "if", "items", ".", "length", "==", "1", "req", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "resource", ",", "initheader", "=", "@@headers", ")", ".", "tap", "do", "|", "pq", "|", "if", "for_ccu_v2?", "pq", ".", "body", "=", "request_body", "items", "else", "pq", ".", "body", "=", "{", "\"objects\"", "=>", "items", "}", ".", "to_json", "end", "end", "timestamp", "=", "Akamai", "::", "Edgegrid", "::", "HTTP", ".", "eg_timestamp", "(", ")", "nonce", "=", "Akamai", "::", "Edgegrid", "::", "HTTP", ".", "new_nonce", "(", ")", "req", "[", "'Authorization'", "]", "=", "akamai", ".", "make_auth_header", "(", "req", ",", "timestamp", ",", "nonce", ")", "parse_response", "http", ".", "request", "(", "req", ")", "end" ]
Clean the requested resources. @param [Array<String>] items One or more resources to clean @return [Response] an object representing the received response @raise [AkamaiApi::CCU::Error] when there is an error in the request @raise [AkamaiApi::Unauthorized] when login credentials are invalid @example Clean a single resource request.execute 'http://foo.bar/t.txt' @example Clean multiple resources request.execute '12345', '12346'
[ "Clean", "the", "requested", "resources", "." ]
a6bc1369e118bb298c71019c9788e5c9bd1753c8
https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/ccu/purge/request.rb#L74-L94
2,350
mikamai/akamai_api
lib/akamai_api/ccu/purge/request.rb
AkamaiApi::CCU::Purge.Request.request_body
def request_body items { type: type, action: action, domain: domain, objects: items }.to_json end
ruby
def request_body items { type: type, action: action, domain: domain, objects: items }.to_json end
[ "def", "request_body", "items", "{", "type", ":", "type", ",", "action", ":", "action", ",", "domain", ":", "domain", ",", "objects", ":", "items", "}", ".", "to_json", "end" ]
Request body to send to the API. @param [Array<String>] items resources to clean @return [String] request body in JSON format
[ "Request", "body", "to", "send", "to", "the", "API", "." ]
a6bc1369e118bb298c71019c9788e5c9bd1753c8
https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/ccu/purge/request.rb#L99-L101
2,351
mikamai/akamai_api
lib/akamai_api/ccu.rb
AkamaiApi.CCU.purge
def purge action, type, items, opts = {} request = Purge::Request.new action, type, domain: opts[:domain] request.execute items end
ruby
def purge action, type, items, opts = {} request = Purge::Request.new action, type, domain: opts[:domain] request.execute items end
[ "def", "purge", "action", ",", "type", ",", "items", ",", "opts", "=", "{", "}", "request", "=", "Purge", "::", "Request", ".", "new", "action", ",", "type", ",", "domain", ":", "opts", "[", ":domain", "]", "request", ".", "execute", "items", "end" ]
Purges one or more resources @param [String,Symbol] action type of clean action. Allowed values are: - :invalidate - :remove Check {AkamaiApi::CCU::Purge::Request#action} for more details @param [String,Symbol] type type of resource to clean. Allowed values are: - :cpcode - :arl Check {AkamaiApi::CCU::Purge::Request#type} for more details @param [String, Array] items resource(s) to clean @param [Hash] opts additional options @option opts [String] :domain domain type where to act. Allowed values are: - :production - :staging Check {AkamaiApi::CCU::Purge::Request#domain} for more details @return [AkamaiApi::CCU::Purge::Response] an object representing the received response @raise [AkamaiApi::CCU::Error] when there is an error in the request @raise [AkamaiApi::Unauthorized] when login credentials are invalid
[ "Purges", "one", "or", "more", "resources" ]
a6bc1369e118bb298c71019c9788e5c9bd1753c8
https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/ccu.rb#L129-L132
2,352
waiting-for-dev/string-direction
lib/string-direction/strategies/dominant_strategy.rb
StringDirection.DominantStrategy.run
def run(string) string = string.to_s ltr_count = chars_count(string, ltr_regex) rtl_count = chars_count(string, rtl_regex) diff = ltr_count - rtl_count return ltr if diff > 0 return rtl if diff < 0 nil end
ruby
def run(string) string = string.to_s ltr_count = chars_count(string, ltr_regex) rtl_count = chars_count(string, rtl_regex) diff = ltr_count - rtl_count return ltr if diff > 0 return rtl if diff < 0 nil end
[ "def", "run", "(", "string", ")", "string", "=", "string", ".", "to_s", "ltr_count", "=", "chars_count", "(", "string", ",", "ltr_regex", ")", "rtl_count", "=", "chars_count", "(", "string", ",", "rtl_regex", ")", "diff", "=", "ltr_count", "-", "rtl_count", "return", "ltr", "if", "diff", ">", "0", "return", "rtl", "if", "diff", "<", "0", "nil", "end" ]
Get the number of ltr and rtl characters in the supplied string and infer direction from the most common type. For this strategy the direction can be ltr or rtl, but never bidi. In case of draw it returns nil. params [String] The string to inspect @return [String, nil]
[ "Get", "the", "number", "of", "ltr", "and", "rtl", "characters", "in", "the", "supplied", "string", "and", "infer", "direction", "from", "the", "most", "common", "type", ".", "For", "this", "strategy", "the", "direction", "can", "be", "ltr", "or", "rtl", "but", "never", "bidi", ".", "In", "case", "of", "draw", "it", "returns", "nil", "." ]
c976ffe0ba91161d14d6e2d069f6febad5b32d34
https://github.com/waiting-for-dev/string-direction/blob/c976ffe0ba91161d14d6e2d069f6febad5b32d34/lib/string-direction/strategies/dominant_strategy.rb#L10-L18
2,353
mikamai/akamai_api
lib/akamai_api/eccu/find_response.rb
AkamaiApi::ECCU.FindResponse.file
def file content64 = get_if_handleable(raw[:contents]) { :content => content64 ? Base64.decode64(content64) : nil, :size => raw[:file_size].to_i, :name => get_if_handleable(raw[:filename]), :md5 => get_if_handleable(raw[:md5_digest]) }.reject { |k, v| v.nil? } end
ruby
def file content64 = get_if_handleable(raw[:contents]) { :content => content64 ? Base64.decode64(content64) : nil, :size => raw[:file_size].to_i, :name => get_if_handleable(raw[:filename]), :md5 => get_if_handleable(raw[:md5_digest]) }.reject { |k, v| v.nil? } end
[ "def", "file", "content64", "=", "get_if_handleable", "(", "raw", "[", ":contents", "]", ")", "{", ":content", "=>", "content64", "?", "Base64", ".", "decode64", "(", "content64", ")", ":", "nil", ",", ":size", "=>", "raw", "[", ":file_size", "]", ".", "to_i", ",", ":name", "=>", "get_if_handleable", "(", "raw", "[", ":filename", "]", ")", ",", ":md5", "=>", "get_if_handleable", "(", "raw", "[", ":md5_digest", "]", ")", "}", ".", "reject", "{", "|", "k", ",", "v", "|", "v", ".", "nil?", "}", "end" ]
Uploaded file details @return [Hash] file details - :content [String] file content - :size [Fixnum] file size - :name [String] file name - :md5 [String] MD5 digest of the file content
[ "Uploaded", "file", "details" ]
a6bc1369e118bb298c71019c9788e5c9bd1753c8
https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/eccu/find_response.rb#L63-L71
2,354
mikamai/akamai_api
lib/akamai_api/eccu/find_response.rb
AkamaiApi::ECCU.FindResponse.property
def property { :name => get_if_handleable(raw[:property_name]), :exact_match => (raw[:property_name_exact_match] == true), :type => get_if_handleable(raw[:property_type]) }.reject { |k, v| v.nil? } end
ruby
def property { :name => get_if_handleable(raw[:property_name]), :exact_match => (raw[:property_name_exact_match] == true), :type => get_if_handleable(raw[:property_type]) }.reject { |k, v| v.nil? } end
[ "def", "property", "{", ":name", "=>", "get_if_handleable", "(", "raw", "[", ":property_name", "]", ")", ",", ":exact_match", "=>", "(", "raw", "[", ":property_name_exact_match", "]", "==", "true", ")", ",", ":type", "=>", "get_if_handleable", "(", "raw", "[", ":property_type", "]", ")", "}", ".", "reject", "{", "|", "k", ",", "v", "|", "v", ".", "nil?", "}", "end" ]
Digital property details @return [Hash] property details - :name [String] - :exact_match [true,false] - :type [String]
[ "Digital", "property", "details" ]
a6bc1369e118bb298c71019c9788e5c9bd1753c8
https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/eccu/find_response.rb#L93-L99
2,355
mikamai/akamai_api
lib/akamai_api/eccu/find_response.rb
AkamaiApi::ECCU.FindResponse.get_if_handleable
def get_if_handleable value case value when String then value when DateTime then value.to_time.utc.xmlschema(3) else nil end end
ruby
def get_if_handleable value case value when String then value when DateTime then value.to_time.utc.xmlschema(3) else nil end end
[ "def", "get_if_handleable", "value", "case", "value", "when", "String", "then", "value", "when", "DateTime", "then", "value", ".", "to_time", ".", "utc", ".", "xmlschema", "(", "3", ")", "else", "nil", "end", "end" ]
This method is used because, for nil values, savon will respond with an hash containing all other attributes. If we check that the expected type is matched, we can prevent to retrieve wrong values
[ "This", "method", "is", "used", "because", "for", "nil", "values", "savon", "will", "respond", "with", "an", "hash", "containing", "all", "other", "attributes", ".", "If", "we", "check", "that", "the", "expected", "type", "is", "matched", "we", "can", "prevent", "to", "retrieve", "wrong", "values" ]
a6bc1369e118bb298c71019c9788e5c9bd1753c8
https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/eccu/find_response.rb#L106-L112
2,356
waiting-for-dev/string-direction
lib/string-direction/strategies/marks_strategy.rb
StringDirection.MarksStrategy.run
def run(string) string = string.to_s if ltr_mark?(string) && rtl_mark?(string) bidi elsif ltr_mark?(string) ltr elsif rtl_mark?(string) rtl end end
ruby
def run(string) string = string.to_s if ltr_mark?(string) && rtl_mark?(string) bidi elsif ltr_mark?(string) ltr elsif rtl_mark?(string) rtl end end
[ "def", "run", "(", "string", ")", "string", "=", "string", ".", "to_s", "if", "ltr_mark?", "(", "string", ")", "&&", "rtl_mark?", "(", "string", ")", "bidi", "elsif", "ltr_mark?", "(", "string", ")", "ltr", "elsif", "rtl_mark?", "(", "string", ")", "rtl", "end", "end" ]
Look for the presence of unicode marks in given string and infers from them its direction params [String] The string to inspect @return [String, nil]
[ "Look", "for", "the", "presence", "of", "unicode", "marks", "in", "given", "string", "and", "infers", "from", "them", "its", "direction" ]
c976ffe0ba91161d14d6e2d069f6febad5b32d34
https://github.com/waiting-for-dev/string-direction/blob/c976ffe0ba91161d14d6e2d069f6febad5b32d34/lib/string-direction/strategies/marks_strategy.rb#L14-L23
2,357
ahnick/ahocorasick
lib/ahocorasick.rb
AhoC.Trie.add
def add pattern node = @root # If this is a string process each character if String(pattern) == pattern pattern.each_char do |char| if node.goto(char) == nil node = node.add(char) else node = node.goto(char) end end else # Otherwise, pattern should support "each" method. for item in pattern if node.goto(item) == nil node = node.add(item) else node = node.goto(item) end end end if block_given? node.output = yield pattern else node.output = [pattern] end end
ruby
def add pattern node = @root # If this is a string process each character if String(pattern) == pattern pattern.each_char do |char| if node.goto(char) == nil node = node.add(char) else node = node.goto(char) end end else # Otherwise, pattern should support "each" method. for item in pattern if node.goto(item) == nil node = node.add(item) else node = node.goto(item) end end end if block_given? node.output = yield pattern else node.output = [pattern] end end
[ "def", "add", "pattern", "node", "=", "@root", "# If this is a string process each character", "if", "String", "(", "pattern", ")", "==", "pattern", "pattern", ".", "each_char", "do", "|", "char", "|", "if", "node", ".", "goto", "(", "char", ")", "==", "nil", "node", "=", "node", ".", "add", "(", "char", ")", "else", "node", "=", "node", ".", "goto", "(", "char", ")", "end", "end", "else", "# Otherwise, pattern should support \"each\" method.", "for", "item", "in", "pattern", "if", "node", ".", "goto", "(", "item", ")", "==", "nil", "node", "=", "node", ".", "add", "(", "item", ")", "else", "node", "=", "node", ".", "goto", "(", "item", ")", "end", "end", "end", "if", "block_given?", "node", ".", "output", "=", "yield", "pattern", "else", "node", ".", "output", "=", "[", "pattern", "]", "end", "end" ]
Creates an empty AhoC Trie with only a root node Accepts an optional argument (either :DFA or :NFA) indicating the type of automaton to build. If no argument is passed an NFA will be built. Add a pattern to the Trie. Accepts an optional block that can be used to modify the node output.
[ "Creates", "an", "empty", "AhoC", "Trie", "with", "only", "a", "root", "node" ]
bf5f66ab5823aba83fbedb3460d642292bc85a5f
https://github.com/ahnick/ahocorasick/blob/bf5f66ab5823aba83fbedb3460d642292bc85a5f/lib/ahocorasick.rb#L71-L98
2,358
GoodMeasuresLLC/draper-cancancan
lib/draper/cancancan.rb
Draper.CanCanCan.can?
def can?(action, subject, *extra_args) while subject.is_a?(Draper::Decorator) subject = subject.model end super(action, subject, *extra_args) end
ruby
def can?(action, subject, *extra_args) while subject.is_a?(Draper::Decorator) subject = subject.model end super(action, subject, *extra_args) end
[ "def", "can?", "(", "action", ",", "subject", ",", "*", "extra_args", ")", "while", "subject", ".", "is_a?", "(", "Draper", "::", "Decorator", ")", "subject", "=", "subject", ".", "model", "end", "super", "(", "action", ",", "subject", ",", "extra_args", ")", "end" ]
actually don't need any code in my gem's namespace ..
[ "actually", "don", "t", "need", "any", "code", "in", "my", "gem", "s", "namespace", ".." ]
0042efe4028d053e9db2a36c9fbf08f7d7935844
https://github.com/GoodMeasuresLLC/draper-cancancan/blob/0042efe4028d053e9db2a36c9fbf08f7d7935844/lib/draper/cancancan.rb#L6-L12
2,359
jarib/celerity
lib/celerity/element.rb
Celerity.Element.method_missing
def method_missing(meth, *args, &blk) assert_exists meth = selector_to_attribute(meth) if self.class::ATTRIBUTES.include?(meth) || (self.class == Element && @object.hasAttribute(meth.to_s)) return @object.getAttribute(meth.to_s) end Log.warn "Element\#method_missing calling super with #{meth.inspect}" super end
ruby
def method_missing(meth, *args, &blk) assert_exists meth = selector_to_attribute(meth) if self.class::ATTRIBUTES.include?(meth) || (self.class == Element && @object.hasAttribute(meth.to_s)) return @object.getAttribute(meth.to_s) end Log.warn "Element\#method_missing calling super with #{meth.inspect}" super end
[ "def", "method_missing", "(", "meth", ",", "*", "args", ",", "&", "blk", ")", "assert_exists", "meth", "=", "selector_to_attribute", "(", "meth", ")", "if", "self", ".", "class", "::", "ATTRIBUTES", ".", "include?", "(", "meth", ")", "||", "(", "self", ".", "class", "==", "Element", "&&", "@object", ".", "hasAttribute", "(", "meth", ".", "to_s", ")", ")", "return", "@object", ".", "getAttribute", "(", "meth", ".", "to_s", ")", "end", "Log", ".", "warn", "\"Element\\#method_missing calling super with #{meth.inspect}\"", "super", "end" ]
Dynamically get element attributes. @see ATTRIBUTES constant for a list of valid methods for a given element. @return [String] The resulting attribute. @raise [NoMethodError] if the element doesn't support this attribute.
[ "Dynamically", "get", "element", "attributes", "." ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/element.rb#L267-L277
2,360
tario/imageruby
lib/imageruby/bitmap/rbbitmap.rb
ImageRuby.RubyBitmapModl.get_pixel
def get_pixel(x,y) index = (y*@width + x) pointindex = index*3 Color.from_rgba( @array[pointindex+2].ord, @array[pointindex+1].ord, @array[pointindex].ord, @alpha ? @alpha[index].ord : 255 ) end
ruby
def get_pixel(x,y) index = (y*@width + x) pointindex = index*3 Color.from_rgba( @array[pointindex+2].ord, @array[pointindex+1].ord, @array[pointindex].ord, @alpha ? @alpha[index].ord : 255 ) end
[ "def", "get_pixel", "(", "x", ",", "y", ")", "index", "=", "(", "y", "@width", "+", "x", ")", "pointindex", "=", "index", "3", "Color", ".", "from_rgba", "(", "@array", "[", "pointindex", "+", "2", "]", ".", "ord", ",", "@array", "[", "pointindex", "+", "1", "]", ".", "ord", ",", "@array", "[", "pointindex", "]", ".", "ord", ",", "@alpha", "?", "@alpha", "[", "index", "]", ".", "ord", ":", "255", ")", "end" ]
return a Color object of a given x and y coord
[ "return", "a", "Color", "object", "of", "a", "given", "x", "and", "y", "coord" ]
ba38c3e4a5c8c068566501f0e73357fd219535e4
https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/bitmap/rbbitmap.rb#L40-L50
2,361
tario/imageruby
lib/imageruby/bitmap/rbbitmap.rb
ImageRuby.RubyBitmapModl.set_pixel
def set_pixel(x,y,color) index = (y*@width + x) pointindex = index*3 @array[pointindex+2] = color.r.chr @array[pointindex+1] = color.g.chr @array[pointindex] = color.b.chr if color.a != 255 then @alpha = 255.chr*(@height * @width) unless @alpha @alpha[index] = color.a.chr end self end
ruby
def set_pixel(x,y,color) index = (y*@width + x) pointindex = index*3 @array[pointindex+2] = color.r.chr @array[pointindex+1] = color.g.chr @array[pointindex] = color.b.chr if color.a != 255 then @alpha = 255.chr*(@height * @width) unless @alpha @alpha[index] = color.a.chr end self end
[ "def", "set_pixel", "(", "x", ",", "y", ",", "color", ")", "index", "=", "(", "y", "@width", "+", "x", ")", "pointindex", "=", "index", "3", "@array", "[", "pointindex", "+", "2", "]", "=", "color", ".", "r", ".", "chr", "@array", "[", "pointindex", "+", "1", "]", "=", "color", ".", "g", ".", "chr", "@array", "[", "pointindex", "]", "=", "color", ".", "b", ".", "chr", "if", "color", ".", "a", "!=", "255", "then", "@alpha", "=", "255", ".", "chr", "(", "@height", "*", "@width", ")", "unless", "@alpha", "@alpha", "[", "index", "]", "=", "color", ".", "a", ".", "chr", "end", "self", "end" ]
Creates a duplicate of the image set a color value for a image
[ "Creates", "a", "duplicate", "of", "the", "image", "set", "a", "color", "value", "for", "a", "image" ]
ba38c3e4a5c8c068566501f0e73357fd219535e4
https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/bitmap/rbbitmap.rb#L65-L79
2,362
famished-tiger/Rley
lib/rley/parse_tree_visitor.rb
Rley.ParseTreeVisitor.traverse_subnodes
def traverse_subnodes(aParentNode) subnodes = aParentNode.subnodes broadcast(:before_subnodes, aParentNode, subnodes) # Let's proceed with the visit of subnodes subnodes.each { |a_node| a_node.accept(self) } broadcast(:after_subnodes, aParentNode, subnodes) end
ruby
def traverse_subnodes(aParentNode) subnodes = aParentNode.subnodes broadcast(:before_subnodes, aParentNode, subnodes) # Let's proceed with the visit of subnodes subnodes.each { |a_node| a_node.accept(self) } broadcast(:after_subnodes, aParentNode, subnodes) end
[ "def", "traverse_subnodes", "(", "aParentNode", ")", "subnodes", "=", "aParentNode", ".", "subnodes", "broadcast", "(", ":before_subnodes", ",", "aParentNode", ",", "subnodes", ")", "# Let's proceed with the visit of subnodes", "subnodes", ".", "each", "{", "|", "a_node", "|", "a_node", ".", "accept", "(", "self", ")", "}", "broadcast", "(", ":after_subnodes", ",", "aParentNode", ",", "subnodes", ")", "end" ]
Visit event. The visitor is about to visit the subnodes of a non terminal node. @param aParentNode [NonTeminalNode] the (non-terminal) parent node.
[ "Visit", "event", ".", "The", "visitor", "is", "about", "to", "visit", "the", "subnodes", "of", "a", "non", "terminal", "node", "." ]
307a8ed6a328182c3cb83a0c3ed04c04b7135a13
https://github.com/famished-tiger/Rley/blob/307a8ed6a328182c3cb83a0c3ed04c04b7135a13/lib/rley/parse_tree_visitor.rb#L87-L95
2,363
famished-tiger/Rley
lib/rley/parse_tree_visitor.rb
Rley.ParseTreeVisitor.broadcast
def broadcast(msg, *args) subscribers.each do |subscr| next unless subscr.respond_to?(msg) || subscr.respond_to?(:accept_all) subscr.send(msg, *args) end end
ruby
def broadcast(msg, *args) subscribers.each do |subscr| next unless subscr.respond_to?(msg) || subscr.respond_to?(:accept_all) subscr.send(msg, *args) end end
[ "def", "broadcast", "(", "msg", ",", "*", "args", ")", "subscribers", ".", "each", "do", "|", "subscr", "|", "next", "unless", "subscr", ".", "respond_to?", "(", "msg", ")", "||", "subscr", ".", "respond_to?", "(", ":accept_all", ")", "subscr", ".", "send", "(", "msg", ",", "args", ")", "end", "end" ]
Send a notification to all subscribers. @param msg [Symbol] event to notify @param args [Array] arguments of the notification.
[ "Send", "a", "notification", "to", "all", "subscribers", "." ]
307a8ed6a328182c3cb83a0c3ed04c04b7135a13
https://github.com/famished-tiger/Rley/blob/307a8ed6a328182c3cb83a0c3ed04c04b7135a13/lib/rley/parse_tree_visitor.rb#L100-L106
2,364
jarib/celerity
lib/celerity/browser.rb
Celerity.Browser.goto
def goto(uri, headers = nil) uri = "http://#{uri}" unless uri =~ %r{://} request = HtmlUnit::WebRequest.new(::Java::JavaNet::URL.new(uri)) request.setAdditionalHeaders(headers) if headers request.setCharset(@charset) rescue_status_code_exception do self.page = @webclient.getPage(request) end url() end
ruby
def goto(uri, headers = nil) uri = "http://#{uri}" unless uri =~ %r{://} request = HtmlUnit::WebRequest.new(::Java::JavaNet::URL.new(uri)) request.setAdditionalHeaders(headers) if headers request.setCharset(@charset) rescue_status_code_exception do self.page = @webclient.getPage(request) end url() end
[ "def", "goto", "(", "uri", ",", "headers", "=", "nil", ")", "uri", "=", "\"http://#{uri}\"", "unless", "uri", "=~", "%r{", "}", "request", "=", "HtmlUnit", "::", "WebRequest", ".", "new", "(", "::", "Java", "::", "JavaNet", "::", "URL", ".", "new", "(", "uri", ")", ")", "request", ".", "setAdditionalHeaders", "(", "headers", ")", "if", "headers", "request", ".", "setCharset", "(", "@charset", ")", "rescue_status_code_exception", "do", "self", ".", "page", "=", "@webclient", ".", "getPage", "(", "request", ")", "end", "url", "(", ")", "end" ]
Goto the given URL @param [String] uri The url. @param [Hash] (optional) a Hash of HTTP headers to use for the request. @return [String] The url.
[ "Goto", "the", "given", "URL" ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L96-L109
2,365
jarib/celerity
lib/celerity/browser.rb
Celerity.Browser.send_keys
def send_keys(keys) keys = keys.gsub(/\s*/, '').scan(/((?:\{[A-Z]+?\})|.)/u).flatten keys.each do |key| element = @page.getFocusedElement case key when "{TAB}" @page.tabToNextElement when /\w/ element.type(key) else raise NotImplementedError end end end
ruby
def send_keys(keys) keys = keys.gsub(/\s*/, '').scan(/((?:\{[A-Z]+?\})|.)/u).flatten keys.each do |key| element = @page.getFocusedElement case key when "{TAB}" @page.tabToNextElement when /\w/ element.type(key) else raise NotImplementedError end end end
[ "def", "send_keys", "(", "keys", ")", "keys", "=", "keys", ".", "gsub", "(", "/", "\\s", "/", ",", "''", ")", ".", "scan", "(", "/", "\\{", "\\}", "/u", ")", ".", "flatten", "keys", ".", "each", "do", "|", "key", "|", "element", "=", "@page", ".", "getFocusedElement", "case", "key", "when", "\"{TAB}\"", "@page", ".", "tabToNextElement", "when", "/", "\\w", "/", "element", ".", "type", "(", "key", ")", "else", "raise", "NotImplementedError", "end", "end", "end" ]
experimental - should be removed?
[ "experimental", "-", "should", "be", "removed?" ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L400-L413
2,366
jarib/celerity
lib/celerity/browser.rb
Celerity.Browser.resynchronized
def resynchronized(&block) old_controller = @webclient.ajaxController @webclient.setAjaxController(::HtmlUnit::NicelyResynchronizingAjaxController.new) yield self @webclient.setAjaxController(old_controller) end
ruby
def resynchronized(&block) old_controller = @webclient.ajaxController @webclient.setAjaxController(::HtmlUnit::NicelyResynchronizingAjaxController.new) yield self @webclient.setAjaxController(old_controller) end
[ "def", "resynchronized", "(", "&", "block", ")", "old_controller", "=", "@webclient", ".", "ajaxController", "@webclient", ".", "setAjaxController", "(", "::", "HtmlUnit", "::", "NicelyResynchronizingAjaxController", ".", "new", ")", "yield", "self", "@webclient", ".", "setAjaxController", "(", "old_controller", ")", "end" ]
Allows you to temporarily switch to HtmlUnit's NicelyResynchronizingAjaxController to resynchronize ajax calls. @browser.resynchronized do |b| b.link(:id, 'trigger_ajax_call').click end @yieldparam [Celerity::Browser] browser The current browser object. @see Celerity::Browser#new for how to configure the browser to always use this.
[ "Allows", "you", "to", "temporarily", "switch", "to", "HtmlUnit", "s", "NicelyResynchronizingAjaxController", "to", "resynchronize", "ajax", "calls", "." ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L469-L474
2,367
jarib/celerity
lib/celerity/browser.rb
Celerity.Browser.confirm
def confirm(bool, &block) blk = lambda { bool } listener.add_listener(:confirm, &blk) yield listener.remove_listener(:confirm, blk) end
ruby
def confirm(bool, &block) blk = lambda { bool } listener.add_listener(:confirm, &blk) yield listener.remove_listener(:confirm, blk) end
[ "def", "confirm", "(", "bool", ",", "&", "block", ")", "blk", "=", "lambda", "{", "bool", "}", "listener", ".", "add_listener", "(", ":confirm", ",", "blk", ")", "yield", "listener", ".", "remove_listener", "(", ":confirm", ",", "blk", ")", "end" ]
Specify a boolean value to click either 'OK' or 'Cancel' in any confirm dialogs that might show up during the duration of the given block. (Celerity only) @param [Boolean] bool true to click 'OK', false to click 'cancel' @param [Proc] block A block that will trigger the confirm() call(s).
[ "Specify", "a", "boolean", "value", "to", "click", "either", "OK", "or", "Cancel", "in", "any", "confirm", "dialogs", "that", "might", "show", "up", "during", "the", "duration", "of", "the", "given", "block", "." ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L562-L568
2,368
jarib/celerity
lib/celerity/browser.rb
Celerity.Browser.add_checker
def add_checker(checker = nil, &block) if block_given? @error_checkers << block elsif Proc === checker @error_checkers << checker else raise ArgumentError, "argument must be a Proc or block" end end
ruby
def add_checker(checker = nil, &block) if block_given? @error_checkers << block elsif Proc === checker @error_checkers << checker else raise ArgumentError, "argument must be a Proc or block" end end
[ "def", "add_checker", "(", "checker", "=", "nil", ",", "&", "block", ")", "if", "block_given?", "@error_checkers", "<<", "block", "elsif", "Proc", "===", "checker", "@error_checkers", "<<", "checker", "else", "raise", "ArgumentError", ",", "\"argument must be a Proc or block\"", "end", "end" ]
Add a 'checker' proc that will be run on every page load @param [Proc] checker The proc to be run (can also be given as a block) @yieldparam [Celerity::Browser] browser The current browser object. @raise [ArgumentError] if no Proc or block was given.
[ "Add", "a", "checker", "proc", "that", "will", "be", "run", "on", "every", "page", "load" ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L578-L586
2,369
jarib/celerity
lib/celerity/browser.rb
Celerity.Browser.page=
def page=(value) return if @page == value @page = value if @page.respond_to?("getDocumentElement") @object = @page.getDocumentElement || @object elsif @page.is_a? HtmlUnit::UnexpectedPage raise UnexpectedPageException, @page.getWebResponse.getContentType end render unless @viewer == DefaultViewer run_error_checks value end
ruby
def page=(value) return if @page == value @page = value if @page.respond_to?("getDocumentElement") @object = @page.getDocumentElement || @object elsif @page.is_a? HtmlUnit::UnexpectedPage raise UnexpectedPageException, @page.getWebResponse.getContentType end render unless @viewer == DefaultViewer run_error_checks value end
[ "def", "page", "=", "(", "value", ")", "return", "if", "@page", "==", "value", "@page", "=", "value", "if", "@page", ".", "respond_to?", "(", "\"getDocumentElement\"", ")", "@object", "=", "@page", ".", "getDocumentElement", "||", "@object", "elsif", "@page", ".", "is_a?", "HtmlUnit", "::", "UnexpectedPage", "raise", "UnexpectedPageException", ",", "@page", ".", "getWebResponse", ".", "getContentType", "end", "render", "unless", "@viewer", "==", "DefaultViewer", "run_error_checks", "value", "end" ]
Sets the current page object for the browser @param [HtmlUnit::HtmlPage] value The page to set. @api private
[ "Sets", "the", "current", "page", "object", "for", "the", "browser" ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L746-L760
2,370
jarib/celerity
lib/celerity/browser.rb
Celerity.Browser.enable_event_listener
def enable_event_listener @event_listener ||= lambda do |event| self.page = @page ? @page.getEnclosingWindow.getEnclosedPage : event.getNewPage end listener.add_listener(:web_window_event, &@event_listener) end
ruby
def enable_event_listener @event_listener ||= lambda do |event| self.page = @page ? @page.getEnclosingWindow.getEnclosedPage : event.getNewPage end listener.add_listener(:web_window_event, &@event_listener) end
[ "def", "enable_event_listener", "@event_listener", "||=", "lambda", "do", "|", "event", "|", "self", ".", "page", "=", "@page", "?", "@page", ".", "getEnclosingWindow", ".", "getEnclosedPage", ":", "event", ".", "getNewPage", "end", "listener", ".", "add_listener", "(", ":web_window_event", ",", "@event_listener", ")", "end" ]
Enable Celerity's internal WebWindowEventListener @api private
[ "Enable", "Celerity", "s", "internal", "WebWindowEventListener" ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L787-L793
2,371
jarib/celerity
lib/celerity/browser.rb
Celerity.Browser.render
def render @viewer.render_html(self.send(@render_type), url) rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EPIPE @viewer = DefaultViewer end
ruby
def render @viewer.render_html(self.send(@render_type), url) rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EPIPE @viewer = DefaultViewer end
[ "def", "render", "@viewer", ".", "render_html", "(", "self", ".", "send", "(", "@render_type", ")", ",", "url", ")", "rescue", "Errno", "::", "ECONNREFUSED", ",", "Errno", "::", "ECONNRESET", ",", "Errno", "::", "EPIPE", "@viewer", "=", "DefaultViewer", "end" ]
Render the current page on the connected viewer. @api private
[ "Render", "the", "current", "page", "on", "the", "connected", "viewer", "." ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L913-L917
2,372
tario/imageruby
lib/imageruby/pureruby.rb
ImageRuby.PureRubyImageMethods.[]
def [] (x,y) if x.instance_of? Fixnum and y.instance_of? Fixnum get_pixel(fixx(x),fixy(y)) else x = (fixx(x)..fixx(x)) if x.instance_of? Fixnum y = (fixy(y)..fixy(y)) if y.instance_of? Fixnum if x.instance_of? Range x = (fixx(x.first)..fixx(x.last)) end if y.instance_of? Range y = (fixy(y.first)..fixy(y.last)) end newimg = Image.new(x.last + 1 - x.first, y.last + 1 - y.first) width = x.count (0..y.count).each do |y_| destpointer = y_*width*3 origpointer = ((y.first + y_)*self.width + x.first)*3 newimg.pixel_data[destpointer..destpointer+width*3] = self.pixel_data[origpointer..origpointer+width*3] end newimg end end
ruby
def [] (x,y) if x.instance_of? Fixnum and y.instance_of? Fixnum get_pixel(fixx(x),fixy(y)) else x = (fixx(x)..fixx(x)) if x.instance_of? Fixnum y = (fixy(y)..fixy(y)) if y.instance_of? Fixnum if x.instance_of? Range x = (fixx(x.first)..fixx(x.last)) end if y.instance_of? Range y = (fixy(y.first)..fixy(y.last)) end newimg = Image.new(x.last + 1 - x.first, y.last + 1 - y.first) width = x.count (0..y.count).each do |y_| destpointer = y_*width*3 origpointer = ((y.first + y_)*self.width + x.first)*3 newimg.pixel_data[destpointer..destpointer+width*3] = self.pixel_data[origpointer..origpointer+width*3] end newimg end end
[ "def", "[]", "(", "x", ",", "y", ")", "if", "x", ".", "instance_of?", "Fixnum", "and", "y", ".", "instance_of?", "Fixnum", "get_pixel", "(", "fixx", "(", "x", ")", ",", "fixy", "(", "y", ")", ")", "else", "x", "=", "(", "fixx", "(", "x", ")", "..", "fixx", "(", "x", ")", ")", "if", "x", ".", "instance_of?", "Fixnum", "y", "=", "(", "fixy", "(", "y", ")", "..", "fixy", "(", "y", ")", ")", "if", "y", ".", "instance_of?", "Fixnum", "if", "x", ".", "instance_of?", "Range", "x", "=", "(", "fixx", "(", "x", ".", "first", ")", "..", "fixx", "(", "x", ".", "last", ")", ")", "end", "if", "y", ".", "instance_of?", "Range", "y", "=", "(", "fixy", "(", "y", ".", "first", ")", "..", "fixy", "(", "y", ".", "last", ")", ")", "end", "newimg", "=", "Image", ".", "new", "(", "x", ".", "last", "+", "1", "-", "x", ".", "first", ",", "y", ".", "last", "+", "1", "-", "y", ".", "first", ")", "width", "=", "x", ".", "count", "(", "0", "..", "y", ".", "count", ")", ".", "each", "do", "|", "y_", "|", "destpointer", "=", "y_", "width", "3", "origpointer", "=", "(", "(", "y", ".", "first", "+", "y_", ")", "*", "self", ".", "width", "+", "x", ".", "first", ")", "*", "3", "newimg", ".", "pixel_data", "[", "destpointer", "..", "destpointer", "+", "width", "3", "]", "=", "self", ".", "pixel_data", "[", "origpointer", "..", "origpointer", "+", "width", "3", "]", "end", "newimg", "end", "end" ]
Returs the color of a pixel locate in the given x and y coordinates or a rectangle section of the image if a range is specified Example image[0,0] # return a Color object representing the color of the pixel at 0,0 image[0..20,10..30] # return a image object with the cropped rectagle with x between 0 and 20 and y between 10 and 30 image[0..20,20] # return a image object cropped rectagle with x between 0 and 20 and y equals 15
[ "Returs", "the", "color", "of", "a", "pixel", "locate", "in", "the", "given", "x", "and", "y", "coordinates", "or", "a", "rectangle", "section", "of", "the", "image", "if", "a", "range", "is", "specified" ]
ba38c3e4a5c8c068566501f0e73357fd219535e4
https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L55-L84
2,373
tario/imageruby
lib/imageruby/pureruby.rb
ImageRuby.PureRubyImageMethods.[]=
def []= (x,y,obj) if x.instance_of? Fixnum and y.instance_of? Fixnum set_pixel(x,y,obj) else x = (x..x) if x.instance_of? Fixnum y = (y..y) if y.instance_of? Fixnum width = x.count (0..y.count-1).each do |y_| origpointer = y_*obj.width*3 destpointer = ((y.first + y_)*self.width + x.first)*3 self.pixel_data[destpointer..destpointer+obj.width*3-1] = obj.pixel_data[origpointer..origpointer+obj.width*3-1] end end end
ruby
def []= (x,y,obj) if x.instance_of? Fixnum and y.instance_of? Fixnum set_pixel(x,y,obj) else x = (x..x) if x.instance_of? Fixnum y = (y..y) if y.instance_of? Fixnum width = x.count (0..y.count-1).each do |y_| origpointer = y_*obj.width*3 destpointer = ((y.first + y_)*self.width + x.first)*3 self.pixel_data[destpointer..destpointer+obj.width*3-1] = obj.pixel_data[origpointer..origpointer+obj.width*3-1] end end end
[ "def", "[]=", "(", "x", ",", "y", ",", "obj", ")", "if", "x", ".", "instance_of?", "Fixnum", "and", "y", ".", "instance_of?", "Fixnum", "set_pixel", "(", "x", ",", "y", ",", "obj", ")", "else", "x", "=", "(", "x", "..", "x", ")", "if", "x", ".", "instance_of?", "Fixnum", "y", "=", "(", "y", "..", "y", ")", "if", "y", ".", "instance_of?", "Fixnum", "width", "=", "x", ".", "count", "(", "0", "..", "y", ".", "count", "-", "1", ")", ".", "each", "do", "|", "y_", "|", "origpointer", "=", "y_", "obj", ".", "width", "3", "destpointer", "=", "(", "(", "y", ".", "first", "+", "y_", ")", "*", "self", ".", "width", "+", "x", ".", "first", ")", "*", "3", "self", ".", "pixel_data", "[", "destpointer", "..", "destpointer", "+", "obj", ".", "width", "3", "-", "1", "]", "=", "obj", ".", "pixel_data", "[", "origpointer", "..", "origpointer", "+", "obj", ".", "width", "3", "-", "1", "]", "end", "end", "end" ]
Set the color of a pixel locate in the given x and y coordinates or replace a rectangle section of the image with other image of equal dimensions if a range is specified Example image[0,0] = Color.red # set the color of pixel at 0,0 to Color.red image[0..20,10..30] = other_image # replace the rectagle with x between 0 and 20 and y between 10 and 30 with other_image
[ "Set", "the", "color", "of", "a", "pixel", "locate", "in", "the", "given", "x", "and", "y", "coordinates", "or", "replace", "a", "rectangle", "section", "of", "the", "image", "with", "other", "image", "of", "equal", "dimensions", "if", "a", "range", "is", "specified" ]
ba38c3e4a5c8c068566501f0e73357fd219535e4
https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L95-L112
2,374
tario/imageruby
lib/imageruby/pureruby.rb
ImageRuby.PureRubyImageMethods.each_pixel
def each_pixel (0..@width-1).each do |x| (0..@height-1).each do |y| yield(x,y,get_pixel(x,y)) end end end
ruby
def each_pixel (0..@width-1).each do |x| (0..@height-1).each do |y| yield(x,y,get_pixel(x,y)) end end end
[ "def", "each_pixel", "(", "0", "..", "@width", "-", "1", ")", ".", "each", "do", "|", "x", "|", "(", "0", "..", "@height", "-", "1", ")", ".", "each", "do", "|", "y", "|", "yield", "(", "x", ",", "y", ",", "get_pixel", "(", "x", ",", "y", ")", ")", "end", "end", "end" ]
Walks each pixel on the image, block is mandantory to call this function and return as yield block calls x,y and pixel color for each pixel of the image This function does not allow to modify any color information of the image (use map_pixel for that) Examples: image.each_pixel do |x,y,color| print "pixel at (#{x},#{y}): #{color.inspect}\n" end
[ "Walks", "each", "pixel", "on", "the", "image", "block", "is", "mandantory", "to", "call", "this", "function", "and", "return", "as", "yield", "block", "calls", "x", "y", "and", "pixel", "color", "for", "each", "pixel", "of", "the", "image" ]
ba38c3e4a5c8c068566501f0e73357fd219535e4
https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L198-L204
2,375
tario/imageruby
lib/imageruby/pureruby.rb
ImageRuby.PureRubyImageMethods.map_pixel
def map_pixel Image.new(@width, @height) do |x,y| yield(x,y,get_pixel(x,y)) end end
ruby
def map_pixel Image.new(@width, @height) do |x,y| yield(x,y,get_pixel(x,y)) end end
[ "def", "map_pixel", "Image", ".", "new", "(", "@width", ",", "@height", ")", "do", "|", "x", ",", "y", "|", "yield", "(", "x", ",", "y", ",", "get_pixel", "(", "x", ",", "y", ")", ")", "end", "end" ]
Creates a new image of same dimensions in which each pixel is replaced with the value returned by the block passed as parameter, the block receives the coordinates and color of each pixel Example image_without_red = image.map_pixel{|x,y,color| color.r = 0; color } # remove color channel of all pixels
[ "Creates", "a", "new", "image", "of", "same", "dimensions", "in", "which", "each", "pixel", "is", "replaced", "with", "the", "value", "returned", "by", "the", "block", "passed", "as", "parameter", "the", "block", "receives", "the", "coordinates", "and", "color", "of", "each", "pixel" ]
ba38c3e4a5c8c068566501f0e73357fd219535e4
https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L212-L216
2,376
tario/imageruby
lib/imageruby/pureruby.rb
ImageRuby.PureRubyImageMethods.map_pixel!
def map_pixel! each_pixel do |x,y,color| set_pixel(x,y, yield(x,y,get_pixel(x,y))) end self end
ruby
def map_pixel! each_pixel do |x,y,color| set_pixel(x,y, yield(x,y,get_pixel(x,y))) end self end
[ "def", "map_pixel!", "each_pixel", "do", "|", "x", ",", "y", ",", "color", "|", "set_pixel", "(", "x", ",", "y", ",", "yield", "(", "x", ",", "y", ",", "get_pixel", "(", "x", ",", "y", ")", ")", ")", "end", "self", "end" ]
Replace each pixel of the image with the value returned by the block passed as parameter, the block receives the coordinates and color of each pixel Example image.map_pixel!{|x,y,color| color.r = 0; color } # remove color channel of all pixels
[ "Replace", "each", "pixel", "of", "the", "image", "with", "the", "value", "returned", "by", "the", "block", "passed", "as", "parameter", "the", "block", "receives", "the", "coordinates", "and", "color", "of", "each", "pixel" ]
ba38c3e4a5c8c068566501f0e73357fd219535e4
https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L224-L230
2,377
tario/imageruby
lib/imageruby/pureruby.rb
ImageRuby.PureRubyImageMethods.color_replace
def color_replace(color1, color2) newimage = self.dup newimage.color_replace!(color1,color2) newimage end
ruby
def color_replace(color1, color2) newimage = self.dup newimage.color_replace!(color1,color2) newimage end
[ "def", "color_replace", "(", "color1", ",", "color2", ")", "newimage", "=", "self", ".", "dup", "newimage", ".", "color_replace!", "(", "color1", ",", "color2", ")", "newimage", "end" ]
Duplicate the image and then call color_replace! method with the given parameters
[ "Duplicate", "the", "image", "and", "then", "call", "color_replace!", "method", "with", "the", "given", "parameters" ]
ba38c3e4a5c8c068566501f0e73357fd219535e4
https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L233-L238
2,378
tario/imageruby
lib/imageruby/pureruby.rb
ImageRuby.PureRubyImageMethods.color_replace!
def color_replace!( color1, color2) strcolor1 = color1.to_s strcolor2 = color2.to_s a = color2.a.chr (0..width*height).each do |i| if pixel_data[i*3..i*3+2] == strcolor1 then pixel_data[i*3..i*3+2] = strcolor2 alpha_data[i] = a end end end
ruby
def color_replace!( color1, color2) strcolor1 = color1.to_s strcolor2 = color2.to_s a = color2.a.chr (0..width*height).each do |i| if pixel_data[i*3..i*3+2] == strcolor1 then pixel_data[i*3..i*3+2] = strcolor2 alpha_data[i] = a end end end
[ "def", "color_replace!", "(", "color1", ",", "color2", ")", "strcolor1", "=", "color1", ".", "to_s", "strcolor2", "=", "color2", ".", "to_s", "a", "=", "color2", ".", "a", ".", "chr", "(", "0", "..", "width", "height", ")", ".", "each", "do", "|", "i", "|", "if", "pixel_data", "[", "i", "3", "..", "i", "3", "+", "2", "]", "==", "strcolor1", "then", "pixel_data", "[", "i", "3", "..", "i", "3", "+", "2", "]", "=", "strcolor2", "alpha_data", "[", "i", "]", "=", "a", "end", "end", "end" ]
Replace the color given in the first argument by the color given in the second with alpha values Examples image.color_replace!(Color.red, Color.black) # replace red with black image.color_replace!(Color.black, Color.coerce([0,0,0,128]) ) # replace black with %50 transparent black
[ "Replace", "the", "color", "given", "in", "the", "first", "argument", "by", "the", "color", "given", "in", "the", "second", "with", "alpha", "values" ]
ba38c3e4a5c8c068566501f0e73357fd219535e4
https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L246-L258
2,379
tario/imageruby
lib/imageruby/pureruby.rb
ImageRuby.PureRubyImageMethods.mask
def mask(color1 = nil) color1 = color1 || Color.from_rgb(255,255,255) color2 = color1.dup color2.a = 0 color_replace(color1,color2) end
ruby
def mask(color1 = nil) color1 = color1 || Color.from_rgb(255,255,255) color2 = color1.dup color2.a = 0 color_replace(color1,color2) end
[ "def", "mask", "(", "color1", "=", "nil", ")", "color1", "=", "color1", "||", "Color", ".", "from_rgb", "(", "255", ",", "255", ",", "255", ")", "color2", "=", "color1", ".", "dup", "color2", ".", "a", "=", "0", "color_replace", "(", "color1", ",", "color2", ")", "end" ]
Replace a color with %100 transparency, useful for mask drawing Example masked = other_image.mask(Color.black) image.draw(0,0,masked) # draw the image without the black pixels
[ "Replace", "a", "color", "with", "%100", "transparency", "useful", "for", "mask", "drawing" ]
ba38c3e4a5c8c068566501f0e73357fd219535e4
https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L266-L272
2,380
postmodern/tdiff
lib/tdiff/unordered.rb
TDiff.Unordered.tdiff_unordered
def tdiff_unordered(tree,&block) return enum_for(:tdiff_unordered,tree) unless block # check if the nodes differ unless tdiff_equal(tree) yield '-', self yield '+', tree return self end yield ' ', self tdiff_recursive_unordered(tree,&block) return self end
ruby
def tdiff_unordered(tree,&block) return enum_for(:tdiff_unordered,tree) unless block # check if the nodes differ unless tdiff_equal(tree) yield '-', self yield '+', tree return self end yield ' ', self tdiff_recursive_unordered(tree,&block) return self end
[ "def", "tdiff_unordered", "(", "tree", ",", "&", "block", ")", "return", "enum_for", "(", ":tdiff_unordered", ",", "tree", ")", "unless", "block", "# check if the nodes differ", "unless", "tdiff_equal", "(", "tree", ")", "yield", "'-'", ",", "self", "yield", "'+'", ",", "tree", "return", "self", "end", "yield", "' '", ",", "self", "tdiff_recursive_unordered", "(", "tree", ",", "block", ")", "return", "self", "end" ]
Finds the differences between `self` and another tree, not respecting the order of the nodes. @param [#tdiff_each_child] tree The other tree. @yield [change, node] The given block will be passed the added or removed nodes. @yieldparam [' ', '+', '-'] change The state-change of the node. @yieldparam [Object] node A node from one of the two trees. @return [Enumerator] If no block is given, an Enumerator object will be returned. @since 0.2.0
[ "Finds", "the", "differences", "between", "self", "and", "another", "tree", "not", "respecting", "the", "order", "of", "the", "nodes", "." ]
238f13540529f492726a5d152a833475c1a42f32
https://github.com/postmodern/tdiff/blob/238f13540529f492726a5d152a833475c1a42f32/lib/tdiff/unordered.rb#L37-L51
2,381
postmodern/tdiff
lib/tdiff/unordered.rb
TDiff.Unordered.tdiff_recursive_unordered
def tdiff_recursive_unordered(tree,&block) x = enum_for(:tdiff_each_child,self) y = enum_for(:tdiff_each_child,tree) unchanged = {} changes = [] x.each_with_index do |xi,i| y.each_with_index do |yj,j| if (!unchanged.has_value?(yj) && xi.tdiff_equal(yj)) unchanged[xi] = yj changes << [i, ' ', xi] break end end unless unchanged.has_key?(xi) changes << [i, '-', xi] end end y.each_with_index do |yj,j| unless unchanged.has_value?(yj) changes << [j, '+', yj] end end # order the changes by index to match the behavior of `tdiff` changes.sort_by { |change| change[0] }.each do |index,change,node| yield change, node end # explicitly release the changes variable changes = nil # recurse down the unchanged nodes unchanged.each do |xi,yj| xi.tdiff_recursive_unordered(yj,&block) end unchanged = nil end
ruby
def tdiff_recursive_unordered(tree,&block) x = enum_for(:tdiff_each_child,self) y = enum_for(:tdiff_each_child,tree) unchanged = {} changes = [] x.each_with_index do |xi,i| y.each_with_index do |yj,j| if (!unchanged.has_value?(yj) && xi.tdiff_equal(yj)) unchanged[xi] = yj changes << [i, ' ', xi] break end end unless unchanged.has_key?(xi) changes << [i, '-', xi] end end y.each_with_index do |yj,j| unless unchanged.has_value?(yj) changes << [j, '+', yj] end end # order the changes by index to match the behavior of `tdiff` changes.sort_by { |change| change[0] }.each do |index,change,node| yield change, node end # explicitly release the changes variable changes = nil # recurse down the unchanged nodes unchanged.each do |xi,yj| xi.tdiff_recursive_unordered(yj,&block) end unchanged = nil end
[ "def", "tdiff_recursive_unordered", "(", "tree", ",", "&", "block", ")", "x", "=", "enum_for", "(", ":tdiff_each_child", ",", "self", ")", "y", "=", "enum_for", "(", ":tdiff_each_child", ",", "tree", ")", "unchanged", "=", "{", "}", "changes", "=", "[", "]", "x", ".", "each_with_index", "do", "|", "xi", ",", "i", "|", "y", ".", "each_with_index", "do", "|", "yj", ",", "j", "|", "if", "(", "!", "unchanged", ".", "has_value?", "(", "yj", ")", "&&", "xi", ".", "tdiff_equal", "(", "yj", ")", ")", "unchanged", "[", "xi", "]", "=", "yj", "changes", "<<", "[", "i", ",", "' '", ",", "xi", "]", "break", "end", "end", "unless", "unchanged", ".", "has_key?", "(", "xi", ")", "changes", "<<", "[", "i", ",", "'-'", ",", "xi", "]", "end", "end", "y", ".", "each_with_index", "do", "|", "yj", ",", "j", "|", "unless", "unchanged", ".", "has_value?", "(", "yj", ")", "changes", "<<", "[", "j", ",", "'+'", ",", "yj", "]", "end", "end", "# order the changes by index to match the behavior of `tdiff`", "changes", ".", "sort_by", "{", "|", "change", "|", "change", "[", "0", "]", "}", ".", "each", "do", "|", "index", ",", "change", ",", "node", "|", "yield", "change", ",", "node", "end", "# explicitly release the changes variable", "changes", "=", "nil", "# recurse down the unchanged nodes", "unchanged", ".", "each", "do", "|", "xi", ",", "yj", "|", "xi", ".", "tdiff_recursive_unordered", "(", "yj", ",", "block", ")", "end", "unchanged", "=", "nil", "end" ]
Recursively compares the differences between the children nodes, without respecting the order of the nodes. @param [#tdiff_each_child] tree The other tree. @yield [change, node] The given block will be passed the added or removed nodes. @yieldparam [' ', '+', '-'] change The state-change of the node. @yieldparam [Object] node A node from one of the two trees. @since 0.3.2
[ "Recursively", "compares", "the", "differences", "between", "the", "children", "nodes", "without", "respecting", "the", "order", "of", "the", "nodes", "." ]
238f13540529f492726a5d152a833475c1a42f32
https://github.com/postmodern/tdiff/blob/238f13540529f492726a5d152a833475c1a42f32/lib/tdiff/unordered.rb#L73-L114
2,382
DimoMohit/onedrive
lib/one_drive.rb
OneDrive.V1.get_drive
def get_drive drive_id url = base_api_url + "/drives/#{drive_id}" @drives = JSON.parse(HTTParty.get(url,headers: set_headers).body) end
ruby
def get_drive drive_id url = base_api_url + "/drives/#{drive_id}" @drives = JSON.parse(HTTParty.get(url,headers: set_headers).body) end
[ "def", "get_drive", "drive_id", "url", "=", "base_api_url", "+", "\"/drives/#{drive_id}\"", "@drives", "=", "JSON", ".", "parse", "(", "HTTParty", ".", "get", "(", "url", ",", "headers", ":", "set_headers", ")", ".", "body", ")", "end" ]
Get a drive by ID
[ "Get", "a", "drive", "by", "ID" ]
e61b5caa8be5be4038d59846e3b6aab606b12a7c
https://github.com/DimoMohit/onedrive/blob/e61b5caa8be5be4038d59846e3b6aab606b12a7c/lib/one_drive.rb#L44-L47
2,383
DimoMohit/onedrive
lib/one_drive.rb
OneDrive.V1.get_users_drive
def get_users_drive id_or_user_principal_name url = base_api_url + "/users/#{id_or_user_principal_name}/drive" @drives = JSON.parse(HTTParty.get(url,headers: set_headers).body) end
ruby
def get_users_drive id_or_user_principal_name url = base_api_url + "/users/#{id_or_user_principal_name}/drive" @drives = JSON.parse(HTTParty.get(url,headers: set_headers).body) end
[ "def", "get_users_drive", "id_or_user_principal_name", "url", "=", "base_api_url", "+", "\"/users/#{id_or_user_principal_name}/drive\"", "@drives", "=", "JSON", ".", "parse", "(", "HTTParty", ".", "get", "(", "url", ",", "headers", ":", "set_headers", ")", ".", "body", ")", "end" ]
Get a user's OneDrive
[ "Get", "a", "user", "s", "OneDrive" ]
e61b5caa8be5be4038d59846e3b6aab606b12a7c
https://github.com/DimoMohit/onedrive/blob/e61b5caa8be5be4038d59846e3b6aab606b12a7c/lib/one_drive.rb#L49-L52
2,384
DimoMohit/onedrive
lib/one_drive.rb
OneDrive.V1.get_my_drive
def get_my_drive url = base_api_url + "/me/drive" @my_drive = JSON.parse(HTTParty.get(url,headers: set_headers).body) end
ruby
def get_my_drive url = base_api_url + "/me/drive" @my_drive = JSON.parse(HTTParty.get(url,headers: set_headers).body) end
[ "def", "get_my_drive", "url", "=", "base_api_url", "+", "\"/me/drive\"", "@my_drive", "=", "JSON", ".", "parse", "(", "HTTParty", ".", "get", "(", "url", ",", "headers", ":", "set_headers", ")", ".", "body", ")", "end" ]
Get a current user's OneDrive
[ "Get", "a", "current", "user", "s", "OneDrive" ]
e61b5caa8be5be4038d59846e3b6aab606b12a7c
https://github.com/DimoMohit/onedrive/blob/e61b5caa8be5be4038d59846e3b6aab606b12a7c/lib/one_drive.rb#L54-L57
2,385
DimoMohit/onedrive
lib/one_drive.rb
OneDrive.V1.get_library_for_site
def get_library_for_site site_id url = base_api_url + "/sites/#{site_id}/drive" @drives = JSON.parse(HTTParty.get(url,headers: set_headers).body) end
ruby
def get_library_for_site site_id url = base_api_url + "/sites/#{site_id}/drive" @drives = JSON.parse(HTTParty.get(url,headers: set_headers).body) end
[ "def", "get_library_for_site", "site_id", "url", "=", "base_api_url", "+", "\"/sites/#{site_id}/drive\"", "@drives", "=", "JSON", ".", "parse", "(", "HTTParty", ".", "get", "(", "url", ",", "headers", ":", "set_headers", ")", ".", "body", ")", "end" ]
Get the document library for a site
[ "Get", "the", "document", "library", "for", "a", "site" ]
e61b5caa8be5be4038d59846e3b6aab606b12a7c
https://github.com/DimoMohit/onedrive/blob/e61b5caa8be5be4038d59846e3b6aab606b12a7c/lib/one_drive.rb#L59-L62
2,386
DimoMohit/onedrive
lib/one_drive.rb
OneDrive.V1.get_special_folder_by_name
def get_special_folder_by_name name url = base_api_url + "/me/drive/special/#{name}" @special_drive = JSON.parse(HTTParty.get(url,headers: set_headers).body) end
ruby
def get_special_folder_by_name name url = base_api_url + "/me/drive/special/#{name}" @special_drive = JSON.parse(HTTParty.get(url,headers: set_headers).body) end
[ "def", "get_special_folder_by_name", "name", "url", "=", "base_api_url", "+", "\"/me/drive/special/#{name}\"", "@special_drive", "=", "JSON", ".", "parse", "(", "HTTParty", ".", "get", "(", "url", ",", "headers", ":", "set_headers", ")", ".", "body", ")", "end" ]
Get a special folder by name
[ "Get", "a", "special", "folder", "by", "name" ]
e61b5caa8be5be4038d59846e3b6aab606b12a7c
https://github.com/DimoMohit/onedrive/blob/e61b5caa8be5be4038d59846e3b6aab606b12a7c/lib/one_drive.rb#L64-L67
2,387
jarib/celerity
lib/celerity/elements/table_row.rb
Celerity.TableRow.child_cell
def child_cell(index) assert_exists if (index - Celerity.index_offset) >= @cells.length raise UnknownCellException, "Unable to locate a cell at index #{index}" end TableCell.new(self, :object, @cells[index - Celerity.index_offset]) end
ruby
def child_cell(index) assert_exists if (index - Celerity.index_offset) >= @cells.length raise UnknownCellException, "Unable to locate a cell at index #{index}" end TableCell.new(self, :object, @cells[index - Celerity.index_offset]) end
[ "def", "child_cell", "(", "index", ")", "assert_exists", "if", "(", "index", "-", "Celerity", ".", "index_offset", ")", ">=", "@cells", ".", "length", "raise", "UnknownCellException", ",", "\"Unable to locate a cell at index #{index}\"", "end", "TableCell", ".", "new", "(", "self", ",", ":object", ",", "@cells", "[", "index", "-", "Celerity", ".", "index_offset", "]", ")", "end" ]
Get the child cell at the given index
[ "Get", "the", "child", "cell", "at", "the", "given", "index" ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/elements/table_row.rb#L33-L41
2,388
jarib/celerity
lib/celerity/elements/table.rb
Celerity.Table.to_a
def to_a assert_exists # @object.getRows.map do |table_row| # table_row.getCells.map { |td| td.asText.strip } # end rows.map do |table_row| table_row.map { |td| td.text } end end
ruby
def to_a assert_exists # @object.getRows.map do |table_row| # table_row.getCells.map { |td| td.asText.strip } # end rows.map do |table_row| table_row.map { |td| td.text } end end
[ "def", "to_a", "assert_exists", "# @object.getRows.map do |table_row|", "# table_row.getCells.map { |td| td.asText.strip }", "# end", "rows", ".", "map", "do", "|", "table_row", "|", "table_row", ".", "map", "{", "|", "td", "|", "td", ".", "text", "}", "end", "end" ]
Returns the text of each cell in the the table as a two-dimensional array. @return [Array<Array<String>>]
[ "Returns", "the", "text", "of", "each", "cell", "in", "the", "the", "table", "as", "a", "two", "-", "dimensional", "array", "." ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/elements/table.rb#L135-L143
2,389
sj26/skinny
lib/skinny.rb
Skinny.Websocket.start!
def start! # Steal any remaining data from rack.input @buffer = @env[Thin::Request::RACK_INPUT].read + @buffer # Remove references to Thin connection objects, freeing memory @env.delete Thin::Request::RACK_INPUT @env.delete Thin::Request::ASYNC_CALLBACK @env.delete Thin::Request::ASYNC_CLOSE # Figure out which version we're using @version = @env['HTTP_SEC_WEBSOCKET_VERSION'] @version ||= "hixie-76" if @env.has_key?('HTTP_SEC_WEBSOCKET_KEY1') and @env.has_key?('HTTP_SEC_WEBSOCKET_KEY2') @version ||= "hixie-75" # Pull out the details we care about @origin ||= @env['HTTP_SEC_WEBSOCKET_ORIGIN'] || @env['HTTP_ORIGIN'] @location ||= "ws#{secure? ? 's' : ''}://#{@env['HTTP_HOST']}#{@env['REQUEST_PATH']}" @protocol ||= @env['HTTP_SEC_WEBSOCKET_PROTOCOL'] || @env['HTTP_WEBSOCKET_PROTOCOL'] EM.next_tick { callback :on_start, self rescue error! "Error in start callback" } # Queue up the actual handshake EM.next_tick method :handshake! @state = :started # Return self so we can be used as a response self rescue error! "Error starting connection" end
ruby
def start! # Steal any remaining data from rack.input @buffer = @env[Thin::Request::RACK_INPUT].read + @buffer # Remove references to Thin connection objects, freeing memory @env.delete Thin::Request::RACK_INPUT @env.delete Thin::Request::ASYNC_CALLBACK @env.delete Thin::Request::ASYNC_CLOSE # Figure out which version we're using @version = @env['HTTP_SEC_WEBSOCKET_VERSION'] @version ||= "hixie-76" if @env.has_key?('HTTP_SEC_WEBSOCKET_KEY1') and @env.has_key?('HTTP_SEC_WEBSOCKET_KEY2') @version ||= "hixie-75" # Pull out the details we care about @origin ||= @env['HTTP_SEC_WEBSOCKET_ORIGIN'] || @env['HTTP_ORIGIN'] @location ||= "ws#{secure? ? 's' : ''}://#{@env['HTTP_HOST']}#{@env['REQUEST_PATH']}" @protocol ||= @env['HTTP_SEC_WEBSOCKET_PROTOCOL'] || @env['HTTP_WEBSOCKET_PROTOCOL'] EM.next_tick { callback :on_start, self rescue error! "Error in start callback" } # Queue up the actual handshake EM.next_tick method :handshake! @state = :started # Return self so we can be used as a response self rescue error! "Error starting connection" end
[ "def", "start!", "# Steal any remaining data from rack.input", "@buffer", "=", "@env", "[", "Thin", "::", "Request", "::", "RACK_INPUT", "]", ".", "read", "+", "@buffer", "# Remove references to Thin connection objects, freeing memory", "@env", ".", "delete", "Thin", "::", "Request", "::", "RACK_INPUT", "@env", ".", "delete", "Thin", "::", "Request", "::", "ASYNC_CALLBACK", "@env", ".", "delete", "Thin", "::", "Request", "::", "ASYNC_CLOSE", "# Figure out which version we're using", "@version", "=", "@env", "[", "'HTTP_SEC_WEBSOCKET_VERSION'", "]", "@version", "||=", "\"hixie-76\"", "if", "@env", ".", "has_key?", "(", "'HTTP_SEC_WEBSOCKET_KEY1'", ")", "and", "@env", ".", "has_key?", "(", "'HTTP_SEC_WEBSOCKET_KEY2'", ")", "@version", "||=", "\"hixie-75\"", "# Pull out the details we care about", "@origin", "||=", "@env", "[", "'HTTP_SEC_WEBSOCKET_ORIGIN'", "]", "||", "@env", "[", "'HTTP_ORIGIN'", "]", "@location", "||=", "\"ws#{secure? ? 's' : ''}://#{@env['HTTP_HOST']}#{@env['REQUEST_PATH']}\"", "@protocol", "||=", "@env", "[", "'HTTP_SEC_WEBSOCKET_PROTOCOL'", "]", "||", "@env", "[", "'HTTP_WEBSOCKET_PROTOCOL'", "]", "EM", ".", "next_tick", "{", "callback", ":on_start", ",", "self", "rescue", "error!", "\"Error in start callback\"", "}", "# Queue up the actual handshake", "EM", ".", "next_tick", "method", ":handshake!", "@state", "=", ":started", "# Return self so we can be used as a response", "self", "rescue", "error!", "\"Error starting connection\"", "end" ]
Start the websocket connection
[ "Start", "the", "websocket", "connection" ]
5b3e222376dd18f6432825a8b05dc691f1f5d5f5
https://github.com/sj26/skinny/blob/5b3e222376dd18f6432825a8b05dc691f1f5d5f5/lib/skinny.rb#L102-L132
2,390
sj26/skinny
lib/skinny.rb
Skinny.Websocket.send_frame
def send_frame opcode, payload="", masked=false payload = payload.dup.force_encoding("ASCII-8BIT") if payload.respond_to? :force_encoding payload_length = payload.bytesize # We don't support continuations (yet), so always send fin fin_byte = 0x80 send_data [fin_byte | opcode].pack("C") # We shouldn't be sending mask, we're a server only masked_byte = masked ? 0x80 : 0x00 if payload_length <= 125 send_data [masked_byte | payload_length].pack("C") elsif payload_length < 2 ** 16 send_data [masked_byte | 126].pack("C") send_data [payload_length].pack("n") else send_data [masked_byte | 127].pack("C") send_data [payload_length / (2 ** 32), payload_length % (2 ** 32)].pack("NN") end if payload_length if masked mask_key = Array.new(4) { rand(256) }.pack("C*") send_data mask_key payload = mask payload, mask_key end send_data payload end end
ruby
def send_frame opcode, payload="", masked=false payload = payload.dup.force_encoding("ASCII-8BIT") if payload.respond_to? :force_encoding payload_length = payload.bytesize # We don't support continuations (yet), so always send fin fin_byte = 0x80 send_data [fin_byte | opcode].pack("C") # We shouldn't be sending mask, we're a server only masked_byte = masked ? 0x80 : 0x00 if payload_length <= 125 send_data [masked_byte | payload_length].pack("C") elsif payload_length < 2 ** 16 send_data [masked_byte | 126].pack("C") send_data [payload_length].pack("n") else send_data [masked_byte | 127].pack("C") send_data [payload_length / (2 ** 32), payload_length % (2 ** 32)].pack("NN") end if payload_length if masked mask_key = Array.new(4) { rand(256) }.pack("C*") send_data mask_key payload = mask payload, mask_key end send_data payload end end
[ "def", "send_frame", "opcode", ",", "payload", "=", "\"\"", ",", "masked", "=", "false", "payload", "=", "payload", ".", "dup", ".", "force_encoding", "(", "\"ASCII-8BIT\"", ")", "if", "payload", ".", "respond_to?", ":force_encoding", "payload_length", "=", "payload", ".", "bytesize", "# We don't support continuations (yet), so always send fin", "fin_byte", "=", "0x80", "send_data", "[", "fin_byte", "|", "opcode", "]", ".", "pack", "(", "\"C\"", ")", "# We shouldn't be sending mask, we're a server only", "masked_byte", "=", "masked", "?", "0x80", ":", "0x00", "if", "payload_length", "<=", "125", "send_data", "[", "masked_byte", "|", "payload_length", "]", ".", "pack", "(", "\"C\"", ")", "elsif", "payload_length", "<", "2", "**", "16", "send_data", "[", "masked_byte", "|", "126", "]", ".", "pack", "(", "\"C\"", ")", "send_data", "[", "payload_length", "]", ".", "pack", "(", "\"n\"", ")", "else", "send_data", "[", "masked_byte", "|", "127", "]", ".", "pack", "(", "\"C\"", ")", "send_data", "[", "payload_length", "/", "(", "2", "**", "32", ")", ",", "payload_length", "%", "(", "2", "**", "32", ")", "]", ".", "pack", "(", "\"NN\"", ")", "end", "if", "payload_length", "if", "masked", "mask_key", "=", "Array", ".", "new", "(", "4", ")", "{", "rand", "(", "256", ")", "}", ".", "pack", "(", "\"C*\"", ")", "send_data", "mask_key", "payload", "=", "mask", "payload", ",", "mask_key", "end", "send_data", "payload", "end", "end" ]
This is for post-hixie-76 versions only
[ "This", "is", "for", "post", "-", "hixie", "-", "76", "versions", "only" ]
5b3e222376dd18f6432825a8b05dc691f1f5d5f5
https://github.com/sj26/skinny/blob/5b3e222376dd18f6432825a8b05dc691f1f5d5f5/lib/skinny.rb#L341-L373
2,391
sj26/skinny
lib/skinny.rb
Skinny.Websocket.finish!
def finish! if hixie_75? or hixie_76? send_data "\xff\x00" else send_frame OPCODE_CLOSE end EM.next_tick { callback(:on_finish, self) rescue error! "Error in finish callback" } EM.next_tick { close_connection_after_writing } @state = :finished rescue error! "Error finishing WebSocket connection" end
ruby
def finish! if hixie_75? or hixie_76? send_data "\xff\x00" else send_frame OPCODE_CLOSE end EM.next_tick { callback(:on_finish, self) rescue error! "Error in finish callback" } EM.next_tick { close_connection_after_writing } @state = :finished rescue error! "Error finishing WebSocket connection" end
[ "def", "finish!", "if", "hixie_75?", "or", "hixie_76?", "send_data", "\"\\xff\\x00\"", "else", "send_frame", "OPCODE_CLOSE", "end", "EM", ".", "next_tick", "{", "callback", "(", ":on_finish", ",", "self", ")", "rescue", "error!", "\"Error in finish callback\"", "}", "EM", ".", "next_tick", "{", "close_connection_after_writing", "}", "@state", "=", ":finished", "rescue", "error!", "\"Error finishing WebSocket connection\"", "end" ]
Finish the connection read for closing
[ "Finish", "the", "connection", "read", "for", "closing" ]
5b3e222376dd18f6432825a8b05dc691f1f5d5f5
https://github.com/sj26/skinny/blob/5b3e222376dd18f6432825a8b05dc691f1f5d5f5/lib/skinny.rb#L384-L397
2,392
jarib/celerity
lib/celerity/xpath_support.rb
Celerity.XpathSupport.elements_by_xpath
def elements_by_xpath(xpath) assert_exists objects = @page.getByXPath(xpath) # should use an ElementCollection here? objects.map { |o| element_from_dom_node(o) } end
ruby
def elements_by_xpath(xpath) assert_exists objects = @page.getByXPath(xpath) # should use an ElementCollection here? objects.map { |o| element_from_dom_node(o) } end
[ "def", "elements_by_xpath", "(", "xpath", ")", "assert_exists", "objects", "=", "@page", ".", "getByXPath", "(", "xpath", ")", "# should use an ElementCollection here?", "objects", ".", "map", "{", "|", "o", "|", "element_from_dom_node", "(", "o", ")", "}", "end" ]
Get all the elements matching the given XPath. @param [String] xpath @return [Array<Celerity::Element>] array of elements
[ "Get", "all", "the", "elements", "matching", "the", "given", "XPath", "." ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/xpath_support.rb#L29-L34
2,393
jarib/celerity
lib/celerity/xpath_support.rb
Celerity.XpathSupport.element_from_dom_node
def element_from_dom_node(obj, identifier_string = nil) element_class = Util.htmlunit2celerity(obj.class) || Element element = element_class.new(self, :object, obj) element.identifier_string = identifier_string element.extend(ClickableElement) unless element.is_a?(ClickableElement) element end
ruby
def element_from_dom_node(obj, identifier_string = nil) element_class = Util.htmlunit2celerity(obj.class) || Element element = element_class.new(self, :object, obj) element.identifier_string = identifier_string element.extend(ClickableElement) unless element.is_a?(ClickableElement) element end
[ "def", "element_from_dom_node", "(", "obj", ",", "identifier_string", "=", "nil", ")", "element_class", "=", "Util", ".", "htmlunit2celerity", "(", "obj", ".", "class", ")", "||", "Element", "element", "=", "element_class", ".", "new", "(", "self", ",", ":object", ",", "obj", ")", "element", ".", "identifier_string", "=", "identifier_string", "element", ".", "extend", "(", "ClickableElement", ")", "unless", "element", ".", "is_a?", "(", "ClickableElement", ")", "element", "end" ]
Convert the given HtmlUnit DomNode to a Celerity object
[ "Convert", "the", "given", "HtmlUnit", "DomNode", "to", "a", "Celerity", "object" ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/xpath_support.rb#L40-L48
2,394
jarib/celerity
lib/celerity/elements/text_field.rb
Celerity.TextField.contains_text
def contains_text(expected_text) assert_exists case expected_text when Regexp value() =~ expected_text when String value().index(expected_text) else raise TypeError, "expected String or Regexp, got #{expected_text.inspect}:#{expected_text.class}" end end
ruby
def contains_text(expected_text) assert_exists case expected_text when Regexp value() =~ expected_text when String value().index(expected_text) else raise TypeError, "expected String or Regexp, got #{expected_text.inspect}:#{expected_text.class}" end end
[ "def", "contains_text", "(", "expected_text", ")", "assert_exists", "case", "expected_text", "when", "Regexp", "value", "(", ")", "=~", "expected_text", "when", "String", "value", "(", ")", ".", "index", "(", "expected_text", ")", "else", "raise", "TypeError", ",", "\"expected String or Regexp, got #{expected_text.inspect}:#{expected_text.class}\"", "end", "end" ]
Check if the given text fields contains the given String or Regexp.
[ "Check", "if", "the", "given", "text", "fields", "contains", "the", "given", "String", "or", "Regexp", "." ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/elements/text_field.rb#L107-L118
2,395
rdunlop/codeclimate_circle_ci_coverage
lib/codeclimate_circle_ci_coverage/patch_simplecov.rb
SimpleCov.ArrayMergeHelper.merge_resultset
def merge_resultset(array) new_array = dup array.each_with_index do |element, i| pair = [element, new_array[i]] new_array[i] = if pair.any?(&:nil?) && pair.map(&:to_i).all?(&:zero?) nil else element.to_i + new_array[i].to_i end end new_array end
ruby
def merge_resultset(array) new_array = dup array.each_with_index do |element, i| pair = [element, new_array[i]] new_array[i] = if pair.any?(&:nil?) && pair.map(&:to_i).all?(&:zero?) nil else element.to_i + new_array[i].to_i end end new_array end
[ "def", "merge_resultset", "(", "array", ")", "new_array", "=", "dup", "array", ".", "each_with_index", "do", "|", "element", ",", "i", "|", "pair", "=", "[", "element", ",", "new_array", "[", "i", "]", "]", "new_array", "[", "i", "]", "=", "if", "pair", ".", "any?", "(", ":nil?", ")", "&&", "pair", ".", "map", "(", ":to_i", ")", ".", "all?", "(", ":zero?", ")", "nil", "else", "element", ".", "to_i", "+", "new_array", "[", "i", "]", ".", "to_i", "end", "end", "new_array", "end" ]
Merges an array of coverage results with self
[ "Merges", "an", "array", "of", "coverage", "results", "with", "self" ]
f881fcae0a0b8809c0fac59c39c375e06dd95e04
https://github.com/rdunlop/codeclimate_circle_ci_coverage/blob/f881fcae0a0b8809c0fac59c39c375e06dd95e04/lib/codeclimate_circle_ci_coverage/patch_simplecov.rb#L10-L21
2,396
jarib/celerity
lib/celerity/elements/image.rb
Celerity.Image.file_created_date
def file_created_date assert_exists web_response = @object.getWebResponse(true) Time.parse(web_response.getResponseHeaderValue("Last-Modified").to_s) end
ruby
def file_created_date assert_exists web_response = @object.getWebResponse(true) Time.parse(web_response.getResponseHeaderValue("Last-Modified").to_s) end
[ "def", "file_created_date", "assert_exists", "web_response", "=", "@object", ".", "getWebResponse", "(", "true", ")", "Time", ".", "parse", "(", "web_response", ".", "getResponseHeaderValue", "(", "\"Last-Modified\"", ")", ".", "to_s", ")", "end" ]
returns the file created date of the image
[ "returns", "the", "file", "created", "date", "of", "the", "image" ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/elements/image.rb#L28-L32
2,397
jarib/celerity
lib/celerity/elements/image.rb
Celerity.Image.save
def save(filename) assert_exists image_reader = @object.getImageReader file = java.io.File.new(filename) buffered_image = image_reader.read(0); javax.imageio.ImageIO.write(buffered_image, image_reader.getFormatName(), file); end
ruby
def save(filename) assert_exists image_reader = @object.getImageReader file = java.io.File.new(filename) buffered_image = image_reader.read(0); javax.imageio.ImageIO.write(buffered_image, image_reader.getFormatName(), file); end
[ "def", "save", "(", "filename", ")", "assert_exists", "image_reader", "=", "@object", ".", "getImageReader", "file", "=", "java", ".", "io", ".", "File", ".", "new", "(", "filename", ")", "buffered_image", "=", "image_reader", ".", "read", "(", "0", ")", ";", "javax", ".", "imageio", ".", "ImageIO", ".", "write", "(", "buffered_image", ",", "image_reader", ".", "getFormatName", "(", ")", ",", "file", ")", ";", "end" ]
Saves the image to the given file
[ "Saves", "the", "image", "to", "the", "given", "file" ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/elements/image.rb#L80-L86
2,398
jarib/celerity
lib/celerity/util.rb
Celerity.Util.matches?
def matches?(string, what) Regexp === what ? string.strip =~ what : string == what.to_s end
ruby
def matches?(string, what) Regexp === what ? string.strip =~ what : string == what.to_s end
[ "def", "matches?", "(", "string", ",", "what", ")", "Regexp", "===", "what", "?", "string", ".", "strip", "=~", "what", ":", "string", "==", "what", ".", "to_s", "end" ]
Used internally. @param [String] string The string to match against. @param [Regexp, String, #to_s] what The match we're looking for. @return [Fixnum, true, false, nil] @api private
[ "Used", "internally", "." ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/util.rb#L124-L126
2,399
jarib/celerity
lib/celerity/listener.rb
Celerity.Listener.add_listener
def add_listener(type, &block) case type when :status @webclient.setStatusHandler(self) when :alert @webclient.setAlertHandler(self) when :attachment @webclient.setAttachmentHandler(self) when :web_window_event @webclient.addWebWindowListener(self) when :html_parser @webclient.setHTMLParserListener(self) when :incorrectness @webclient.setIncorrectnessListener(self) when :confirm @webclient.setConfirmHandler(self) when :prompt @webclient.setPromptHandler(self) else raise ArgumentError, "unknown listener type #{type.inspect}" end @procs[type] << block end
ruby
def add_listener(type, &block) case type when :status @webclient.setStatusHandler(self) when :alert @webclient.setAlertHandler(self) when :attachment @webclient.setAttachmentHandler(self) when :web_window_event @webclient.addWebWindowListener(self) when :html_parser @webclient.setHTMLParserListener(self) when :incorrectness @webclient.setIncorrectnessListener(self) when :confirm @webclient.setConfirmHandler(self) when :prompt @webclient.setPromptHandler(self) else raise ArgumentError, "unknown listener type #{type.inspect}" end @procs[type] << block end
[ "def", "add_listener", "(", "type", ",", "&", "block", ")", "case", "type", "when", ":status", "@webclient", ".", "setStatusHandler", "(", "self", ")", "when", ":alert", "@webclient", ".", "setAlertHandler", "(", "self", ")", "when", ":attachment", "@webclient", ".", "setAttachmentHandler", "(", "self", ")", "when", ":web_window_event", "@webclient", ".", "addWebWindowListener", "(", "self", ")", "when", ":html_parser", "@webclient", ".", "setHTMLParserListener", "(", "self", ")", "when", ":incorrectness", "@webclient", ".", "setIncorrectnessListener", "(", "self", ")", "when", ":confirm", "@webclient", ".", "setConfirmHandler", "(", "self", ")", "when", ":prompt", "@webclient", ".", "setPromptHandler", "(", "self", ")", "else", "raise", "ArgumentError", ",", "\"unknown listener type #{type.inspect}\"", "end", "@procs", "[", "type", "]", "<<", "block", "end" ]
Add a listener block for one of the available types. @see Celerity::Browser#add_listener
[ "Add", "a", "listener", "block", "for", "one", "of", "the", "available", "types", "." ]
90c6eeb3db868be1d9c0195b53f040b5b53d0e91
https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/listener.rb#L27-L50