id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
7,400
rightscale/right_amqp
lib/right_amqp/ha_client/broker_client.rb
RightAMQP.BrokerClient.unserialize
def unserialize(queue, message, options = {}) begin received_at = Time.now.to_f packet = @serializer.method(:load).arity.abs > 1 ? @serializer.load(message, queue) : @serializer.load(message) if options.key?(packet.class) unless options[:no_log] && logger.level != :debug re = "RE-" if packet.respond_to?(:tries) && !packet.tries.empty? packet.received_at = received_at if packet.respond_to?(:received_at) log_filter = options[packet.class] unless logger.level == :debug logger.info("#{re}RECV #{@alias} #{packet.to_s(log_filter, :recv_version)} #{options[:log_data]}") end packet else category = options[:category] + " " if options[:category] logger.error("Received invalid #{category}packet type from queue #{queue} on broker #{@alias}: #{packet.class}\n" + caller.join("\n")) nil end rescue StandardError => e # TODO Taking advantage of Serializer knowledge here even though out of scope trace, track = case e.class.name.sub(/^.*::/, "") when "SerializationError" then [:caller, e.to_s !~ /MissingCertificate|MissingPrivateKey|InvalidSignature/] when "ConnectivityFailure" then [:caller, false] else [:trace, true] end logger.exception("Failed unserializing message from queue #{queue.inspect} on broker #{@alias}", e, trace) @exception_stats.track("receive", e) if track @options[:exception_on_receive_callback].call(message, e) if @options[:exception_on_receive_callback] update_non_delivery_stats("receive failure", e) nil end end
ruby
def unserialize(queue, message, options = {}) begin received_at = Time.now.to_f packet = @serializer.method(:load).arity.abs > 1 ? @serializer.load(message, queue) : @serializer.load(message) if options.key?(packet.class) unless options[:no_log] && logger.level != :debug re = "RE-" if packet.respond_to?(:tries) && !packet.tries.empty? packet.received_at = received_at if packet.respond_to?(:received_at) log_filter = options[packet.class] unless logger.level == :debug logger.info("#{re}RECV #{@alias} #{packet.to_s(log_filter, :recv_version)} #{options[:log_data]}") end packet else category = options[:category] + " " if options[:category] logger.error("Received invalid #{category}packet type from queue #{queue} on broker #{@alias}: #{packet.class}\n" + caller.join("\n")) nil end rescue StandardError => e # TODO Taking advantage of Serializer knowledge here even though out of scope trace, track = case e.class.name.sub(/^.*::/, "") when "SerializationError" then [:caller, e.to_s !~ /MissingCertificate|MissingPrivateKey|InvalidSignature/] when "ConnectivityFailure" then [:caller, false] else [:trace, true] end logger.exception("Failed unserializing message from queue #{queue.inspect} on broker #{@alias}", e, trace) @exception_stats.track("receive", e) if track @options[:exception_on_receive_callback].call(message, e) if @options[:exception_on_receive_callback] update_non_delivery_stats("receive failure", e) nil end end
[ "def", "unserialize", "(", "queue", ",", "message", ",", "options", "=", "{", "}", ")", "begin", "received_at", "=", "Time", ".", "now", ".", "to_f", "packet", "=", "@serializer", ".", "method", "(", ":load", ")", ".", "arity", ".", "abs", ">", "1", "?", "@serializer", ".", "load", "(", "message", ",", "queue", ")", ":", "@serializer", ".", "load", "(", "message", ")", "if", "options", ".", "key?", "(", "packet", ".", "class", ")", "unless", "options", "[", ":no_log", "]", "&&", "logger", ".", "level", "!=", ":debug", "re", "=", "\"RE-\"", "if", "packet", ".", "respond_to?", "(", ":tries", ")", "&&", "!", "packet", ".", "tries", ".", "empty?", "packet", ".", "received_at", "=", "received_at", "if", "packet", ".", "respond_to?", "(", ":received_at", ")", "log_filter", "=", "options", "[", "packet", ".", "class", "]", "unless", "logger", ".", "level", "==", ":debug", "logger", ".", "info", "(", "\"#{re}RECV #{@alias} #{packet.to_s(log_filter, :recv_version)} #{options[:log_data]}\"", ")", "end", "packet", "else", "category", "=", "options", "[", ":category", "]", "+", "\" \"", "if", "options", "[", ":category", "]", "logger", ".", "error", "(", "\"Received invalid #{category}packet type from queue #{queue} on broker #{@alias}: #{packet.class}\\n\"", "+", "caller", ".", "join", "(", "\"\\n\"", ")", ")", "nil", "end", "rescue", "StandardError", "=>", "e", "# TODO Taking advantage of Serializer knowledge here even though out of scope", "trace", ",", "track", "=", "case", "e", ".", "class", ".", "name", ".", "sub", "(", "/", "/", ",", "\"\"", ")", "when", "\"SerializationError\"", "then", "[", ":caller", ",", "e", ".", "to_s", "!~", "/", "/", "]", "when", "\"ConnectivityFailure\"", "then", "[", ":caller", ",", "false", "]", "else", "[", ":trace", ",", "true", "]", "end", "logger", ".", "exception", "(", "\"Failed unserializing message from queue #{queue.inspect} on broker #{@alias}\"", ",", "e", ",", "trace", ")", "@exception_stats", ".", "track", "(", "\"receive\"", ",", "e", ")", "if", "track", "@options", "[", ":exception_on_receive_callback", "]", ".", "call", "(", "message", ",", "e", ")", "if", "@options", "[", ":exception_on_receive_callback", "]", "update_non_delivery_stats", "(", "\"receive failure\"", ",", "e", ")", "nil", "end", "end" ]
Unserialize message, check that it is an acceptable type, and log it === Parameters queue(String):: Name of queue message(String):: Serialized packet options(Hash):: Subscribe options (packet class)(Array(Symbol)):: Filters to be applied in to_s when logging packet to :info, only packet classes specified are accepted, others are not processed but are logged with error :category(String):: Packet category description to be used in error messages :log_data(String):: Additional data to display at end of log entry :no_log(Boolean):: Disable receive logging unless debug level === Return (Packet|nil):: Unserialized packet or nil if not of right type or if there is an exception
[ "Unserialize", "message", "check", "that", "it", "is", "an", "acceptable", "type", "and", "log", "it" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L681-L711
7,401
rightscale/right_amqp
lib/right_amqp/ha_client/broker_client.rb
RightAMQP.BrokerClient.handle_return
def handle_return(header, message) begin to = if header.exchange && !header.exchange.empty? then header.exchange else header.routing_key end reason = header.reply_text callback = @options[:return_message_callback] logger.__send__(callback ? :debug : :info, "RETURN #{@alias} for #{to} because #{reason}") callback.call(@identity, to, reason, message) if callback rescue Exception => e logger.exception("Failed return #{header.inspect} of message from broker #{@alias}", e, :trace) @exception_stats.track("return", e) end true end
ruby
def handle_return(header, message) begin to = if header.exchange && !header.exchange.empty? then header.exchange else header.routing_key end reason = header.reply_text callback = @options[:return_message_callback] logger.__send__(callback ? :debug : :info, "RETURN #{@alias} for #{to} because #{reason}") callback.call(@identity, to, reason, message) if callback rescue Exception => e logger.exception("Failed return #{header.inspect} of message from broker #{@alias}", e, :trace) @exception_stats.track("return", e) end true end
[ "def", "handle_return", "(", "header", ",", "message", ")", "begin", "to", "=", "if", "header", ".", "exchange", "&&", "!", "header", ".", "exchange", ".", "empty?", "then", "header", ".", "exchange", "else", "header", ".", "routing_key", "end", "reason", "=", "header", ".", "reply_text", "callback", "=", "@options", "[", ":return_message_callback", "]", "logger", ".", "__send__", "(", "callback", "?", ":debug", ":", ":info", ",", "\"RETURN #{@alias} for #{to} because #{reason}\"", ")", "callback", ".", "call", "(", "@identity", ",", "to", ",", "reason", ",", "message", ")", "if", "callback", "rescue", "Exception", "=>", "e", "logger", ".", "exception", "(", "\"Failed return #{header.inspect} of message from broker #{@alias}\"", ",", "e", ",", ":trace", ")", "@exception_stats", ".", "track", "(", "\"return\"", ",", "e", ")", "end", "true", "end" ]
Handle message returned by broker because it could not deliver it === Parameters header(AMQP::Protocol::Header):: Message header message(String):: Serialized packet === Return true:: Always return true
[ "Handle", "message", "returned", "by", "broker", "because", "it", "could", "not", "deliver", "it" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L760-L772
7,402
rightscale/right_amqp
lib/right_amqp/ha_client/broker_client.rb
RightAMQP.BrokerClient.execute_callback
def execute_callback(callback, *args) (callback.arity == 2 ? callback.call(*args[0, 2]) : callback.call(*args)) if callback end
ruby
def execute_callback(callback, *args) (callback.arity == 2 ? callback.call(*args[0, 2]) : callback.call(*args)) if callback end
[ "def", "execute_callback", "(", "callback", ",", "*", "args", ")", "(", "callback", ".", "arity", "==", "2", "?", "callback", ".", "call", "(", "args", "[", "0", ",", "2", "]", ")", ":", "callback", ".", "call", "(", "args", ")", ")", "if", "callback", "end" ]
Execute packet receive callback, make it a separate method to ease instrumentation === Parameters callback(Proc):: Proc to run args(Array):: Array of pass-through arguments === Return (Object):: Callback return value
[ "Execute", "packet", "receive", "callback", "make", "it", "a", "separate", "method", "to", "ease", "instrumentation" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L782-L784
7,403
nestor-custodio/crapi
lib/crapi/client.rb
Crapi.Client.ensure_success!
def ensure_success!(response) return if response.is_a? Net::HTTPSuccess message = "#{response.code} - #{response.message}" message += "\n#{response.body}" if response.body.present? raise Crapi::BadHttpResponseError, message end
ruby
def ensure_success!(response) return if response.is_a? Net::HTTPSuccess message = "#{response.code} - #{response.message}" message += "\n#{response.body}" if response.body.present? raise Crapi::BadHttpResponseError, message end
[ "def", "ensure_success!", "(", "response", ")", "return", "if", "response", ".", "is_a?", "Net", "::", "HTTPSuccess", "message", "=", "\"#{response.code} - #{response.message}\"", "message", "+=", "\"\\n#{response.body}\"", "if", "response", ".", "body", ".", "present?", "raise", "Crapi", "::", "BadHttpResponseError", ",", "message", "end" ]
Verifies the given value is that of a successful HTTP response. @param response [Net::HTTPResponse] The response to evaluate as "successful" or not. @raise [Crapi::BadHttpResponseError] @return [nil]
[ "Verifies", "the", "given", "value", "is", "that", "of", "a", "successful", "HTTP", "response", "." ]
cd4741a7106135c0c9c2d99630487c43729ca801
https://github.com/nestor-custodio/crapi/blob/cd4741a7106135c0c9c2d99630487c43729ca801/lib/crapi/client.rb#L282-L289
7,404
nestor-custodio/crapi
lib/crapi/client.rb
Crapi.Client.format_payload
def format_payload(payload, as: JSON_CONTENT_TYPE) ## Non-Hash payloads are passed through as-is. return payload unless payload.is_a? Hash ## Massage Hash-like payloads into a suitable format. case as when JSON_CONTENT_TYPE JSON.generate(payload.as_json) when FORM_CONTENT_TYPE payload.to_query else payload.to_s end end
ruby
def format_payload(payload, as: JSON_CONTENT_TYPE) ## Non-Hash payloads are passed through as-is. return payload unless payload.is_a? Hash ## Massage Hash-like payloads into a suitable format. case as when JSON_CONTENT_TYPE JSON.generate(payload.as_json) when FORM_CONTENT_TYPE payload.to_query else payload.to_s end end
[ "def", "format_payload", "(", "payload", ",", "as", ":", "JSON_CONTENT_TYPE", ")", "## Non-Hash payloads are passed through as-is.", "return", "payload", "unless", "payload", ".", "is_a?", "Hash", "## Massage Hash-like payloads into a suitable format.", "case", "as", "when", "JSON_CONTENT_TYPE", "JSON", ".", "generate", "(", "payload", ".", "as_json", ")", "when", "FORM_CONTENT_TYPE", "payload", ".", "to_query", "else", "payload", ".", "to_s", "end", "end" ]
Serializes the given payload per the requested content-type. @param payload [Hash, String] The payload to format. Strings are returned as-is; Hashes are serialized per the given *as* content-type. @param as [String] The target content-type. @return [String]
[ "Serializes", "the", "given", "payload", "per", "the", "requested", "content", "-", "type", "." ]
cd4741a7106135c0c9c2d99630487c43729ca801
https://github.com/nestor-custodio/crapi/blob/cd4741a7106135c0c9c2d99630487c43729ca801/lib/crapi/client.rb#L304-L317
7,405
nestor-custodio/crapi
lib/crapi/client.rb
Crapi.Client.parse_response
def parse_response(response) case response.content_type when JSON_CONTENT_TYPE JSON.parse(response.body, quirks_mode: true, symbolize_names: true) else response.body end end
ruby
def parse_response(response) case response.content_type when JSON_CONTENT_TYPE JSON.parse(response.body, quirks_mode: true, symbolize_names: true) else response.body end end
[ "def", "parse_response", "(", "response", ")", "case", "response", ".", "content_type", "when", "JSON_CONTENT_TYPE", "JSON", ".", "parse", "(", "response", ".", "body", ",", "quirks_mode", ":", "true", ",", "symbolize_names", ":", "true", ")", "else", "response", ".", "body", "end", "end" ]
Parses the given response as its claimed content-type. @param response [Net::HTTPResponse] The response whose body is to be parsed. @return [Object]
[ "Parses", "the", "given", "response", "as", "its", "claimed", "content", "-", "type", "." ]
cd4741a7106135c0c9c2d99630487c43729ca801
https://github.com/nestor-custodio/crapi/blob/cd4741a7106135c0c9c2d99630487c43729ca801/lib/crapi/client.rb#L328-L335
7,406
jinx/core
lib/jinx/metadata.rb
Jinx.Metadata.pretty_print
def pretty_print(q) map = pretty_print_attribute_hash.delete_if { |k, v| v.nil_or_empty? } # one indented line per entry, all but the last line ending in a comma content = map.map { |label, value| " #{label}=>#{format_print_value(value)}" }.join(",\n") # print the content to the log q.text("#{qp} structure:\n#{content}") end
ruby
def pretty_print(q) map = pretty_print_attribute_hash.delete_if { |k, v| v.nil_or_empty? } # one indented line per entry, all but the last line ending in a comma content = map.map { |label, value| " #{label}=>#{format_print_value(value)}" }.join(",\n") # print the content to the log q.text("#{qp} structure:\n#{content}") end
[ "def", "pretty_print", "(", "q", ")", "map", "=", "pretty_print_attribute_hash", ".", "delete_if", "{", "|", "k", ",", "v", "|", "v", ".", "nil_or_empty?", "}", "# one indented line per entry, all but the last line ending in a comma", "content", "=", "map", ".", "map", "{", "|", "label", ",", "value", "|", "\" #{label}=>#{format_print_value(value)}\"", "}", ".", "join", "(", "\",\\n\"", ")", "# print the content to the log", "q", ".", "text", "(", "\"#{qp} structure:\\n#{content}\"", ")", "end" ]
Prints this classifier's content to the log.
[ "Prints", "this", "classifier", "s", "content", "to", "the", "log", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata.rb#L74-L80
7,407
gemeraldbeanstalk/stalk_climber
lib/stalk_climber/climber_enumerable.rb
StalkClimber.ClimberEnumerable.each_threaded
def each_threaded(&block) # :yields: Object threads = [] climber.connection_pool.connections.each do |connection| threads << Thread.new { connection.send(self.class.enumerator_method, &block) } end threads.each(&:join) return end
ruby
def each_threaded(&block) # :yields: Object threads = [] climber.connection_pool.connections.each do |connection| threads << Thread.new { connection.send(self.class.enumerator_method, &block) } end threads.each(&:join) return end
[ "def", "each_threaded", "(", "&", "block", ")", "# :yields: Object", "threads", "=", "[", "]", "climber", ".", "connection_pool", ".", "connections", ".", "each", "do", "|", "connection", "|", "threads", "<<", "Thread", ".", "new", "{", "connection", ".", "send", "(", "self", ".", "class", ".", "enumerator_method", ",", "block", ")", "}", "end", "threads", ".", "each", "(", ":join", ")", "return", "end" ]
Perform a threaded iteration across all connections in the climber's connection pool. This method cannot be used for enumerable enumeration because a break called within one of the threads will cause a LocalJumpError. This could be fixed, but expected behavior on break varies as to whether or not to wait for all threads before returning a result. However, still useful for operations that always visit all elements. An instance of the element is yielded with each iteration. jobs = ClimberEnumerable.new(:each_job) instance = jobs.new(climber) instance.each_threaded do |job| ... end
[ "Perform", "a", "threaded", "iteration", "across", "all", "connections", "in", "the", "climber", "s", "connection", "pool", ".", "This", "method", "cannot", "be", "used", "for", "enumerable", "enumeration", "because", "a", "break", "called", "within", "one", "of", "the", "threads", "will", "cause", "a", "LocalJumpError", ".", "This", "could", "be", "fixed", "but", "expected", "behavior", "on", "break", "varies", "as", "to", "whether", "or", "not", "to", "wait", "for", "all", "threads", "before", "returning", "a", "result", ".", "However", "still", "useful", "for", "operations", "that", "always", "visit", "all", "elements", ".", "An", "instance", "of", "the", "element", "is", "yielded", "with", "each", "iteration", "." ]
d22f74bbae864ca2771d15621ccbf29d8e86521a
https://github.com/gemeraldbeanstalk/stalk_climber/blob/d22f74bbae864ca2771d15621ccbf29d8e86521a/lib/stalk_climber/climber_enumerable.rb#L65-L72
7,408
grandcloud/sndacs-ruby
lib/sndacs/object.rb
Sndacs.Object.temporary_url
def temporary_url(expires_at = Time.now + 3600) url = URI.escape("#{protocol}#{host(true)}/#{path_prefix}#{key}") signature = Signature.generate_temporary_url_signature(:bucket => name, :resource => key, :expires_at => expires_at, :secret_access_key => secret_access_key) "#{url}?SNDAAccessKeyId=#{access_key_id}&Expires=#{expires_at.to_i.to_s}&Signature=#{signature}" end
ruby
def temporary_url(expires_at = Time.now + 3600) url = URI.escape("#{protocol}#{host(true)}/#{path_prefix}#{key}") signature = Signature.generate_temporary_url_signature(:bucket => name, :resource => key, :expires_at => expires_at, :secret_access_key => secret_access_key) "#{url}?SNDAAccessKeyId=#{access_key_id}&Expires=#{expires_at.to_i.to_s}&Signature=#{signature}" end
[ "def", "temporary_url", "(", "expires_at", "=", "Time", ".", "now", "+", "3600", ")", "url", "=", "URI", ".", "escape", "(", "\"#{protocol}#{host(true)}/#{path_prefix}#{key}\"", ")", "signature", "=", "Signature", ".", "generate_temporary_url_signature", "(", ":bucket", "=>", "name", ",", ":resource", "=>", "key", ",", ":expires_at", "=>", "expires_at", ",", ":secret_access_key", "=>", "secret_access_key", ")", "\"#{url}?SNDAAccessKeyId=#{access_key_id}&Expires=#{expires_at.to_i.to_s}&Signature=#{signature}\"", "end" ]
Returns a temporary url to the object that expires on the timestamp given. Defaults to 5min expire time.
[ "Returns", "a", "temporary", "url", "to", "the", "object", "that", "expires", "on", "the", "timestamp", "given", ".", "Defaults", "to", "5min", "expire", "time", "." ]
4565e926473e3af9df2ae17f728c423662ca750a
https://github.com/grandcloud/sndacs-ruby/blob/4565e926473e3af9df2ae17f728c423662ca750a/lib/sndacs/object.rb#L122-L130
7,409
hetznerZA/log4r_auditor
lib/log4r_auditor/auditor.rb
Log4rAuditor.Log4rAuditor.configuration_is_valid?
def configuration_is_valid?(configuration) required_parameters = ['file_name', 'standard_stream'] required_parameters.each { |parameter| return false unless configuration.include?(parameter) } return false if configuration['file_name'].empty? return false unless ['stdout', 'stderr', 'none'].include?(configuration['standard_stream']) return true end
ruby
def configuration_is_valid?(configuration) required_parameters = ['file_name', 'standard_stream'] required_parameters.each { |parameter| return false unless configuration.include?(parameter) } return false if configuration['file_name'].empty? return false unless ['stdout', 'stderr', 'none'].include?(configuration['standard_stream']) return true end
[ "def", "configuration_is_valid?", "(", "configuration", ")", "required_parameters", "=", "[", "'file_name'", ",", "'standard_stream'", "]", "required_parameters", ".", "each", "{", "|", "parameter", "|", "return", "false", "unless", "configuration", ".", "include?", "(", "parameter", ")", "}", "return", "false", "if", "configuration", "[", "'file_name'", "]", ".", "empty?", "return", "false", "unless", "[", "'stdout'", ",", "'stderr'", ",", "'none'", "]", ".", "include?", "(", "configuration", "[", "'standard_stream'", "]", ")", "return", "true", "end" ]
inversion of control method required by the AuditorAPI to validate the configuration
[ "inversion", "of", "control", "method", "required", "by", "the", "AuditorAPI", "to", "validate", "the", "configuration" ]
a44218ecde0a3aca963c0b0ae69a9ccb03e8435e
https://github.com/hetznerZA/log4r_auditor/blob/a44218ecde0a3aca963c0b0ae69a9ccb03e8435e/lib/log4r_auditor/auditor.rb#L13-L19
7,410
barkerest/incline
app/models/incline/access_group.rb
Incline.AccessGroup.belongs_to?
def belongs_to?(group) group = AccessGroup.get(group) unless group.is_a?(::Incline::AccessGroup) return false unless group safe_belongs_to?(group) end
ruby
def belongs_to?(group) group = AccessGroup.get(group) unless group.is_a?(::Incline::AccessGroup) return false unless group safe_belongs_to?(group) end
[ "def", "belongs_to?", "(", "group", ")", "group", "=", "AccessGroup", ".", "get", "(", "group", ")", "unless", "group", ".", "is_a?", "(", "::", "Incline", "::", "AccessGroup", ")", "return", "false", "unless", "group", "safe_belongs_to?", "(", "group", ")", "end" ]
Determines if this group belongs to the specified group.
[ "Determines", "if", "this", "group", "belongs", "to", "the", "specified", "group", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/access_group.rb#L44-L48
7,411
barkerest/incline
app/models/incline/access_group.rb
Incline.AccessGroup.effective_groups
def effective_groups ret = [ self ] memberships.each do |m| unless ret.include?(m) # prevent infinite recursion tmp = m.effective_groups tmp.each do |g| ret << g unless ret.include?(g) end end end ret.sort{|a,b| a.name <=> b.name} end
ruby
def effective_groups ret = [ self ] memberships.each do |m| unless ret.include?(m) # prevent infinite recursion tmp = m.effective_groups tmp.each do |g| ret << g unless ret.include?(g) end end end ret.sort{|a,b| a.name <=> b.name} end
[ "def", "effective_groups", "ret", "=", "[", "self", "]", "memberships", ".", "each", "do", "|", "m", "|", "unless", "ret", ".", "include?", "(", "m", ")", "# prevent infinite recursion", "tmp", "=", "m", ".", "effective_groups", "tmp", ".", "each", "do", "|", "g", "|", "ret", "<<", "g", "unless", "ret", ".", "include?", "(", "g", ")", "end", "end", "end", "ret", ".", "sort", "{", "|", "a", ",", "b", "|", "a", ".", "name", "<=>", "b", ".", "name", "}", "end" ]
Gets a list of all the groups this group provides effective membership to.
[ "Gets", "a", "list", "of", "all", "the", "groups", "this", "group", "provides", "effective", "membership", "to", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/access_group.rb#L52-L63
7,412
barkerest/incline
app/models/incline/access_group.rb
Incline.AccessGroup.user_ids=
def user_ids=(values) values ||= [] values = [ values ] unless values.is_a?(::Array) values = values.reject{|v| v.blank?}.map{|v| v.to_i} self.users = Incline::User.where(id: values).to_a end
ruby
def user_ids=(values) values ||= [] values = [ values ] unless values.is_a?(::Array) values = values.reject{|v| v.blank?}.map{|v| v.to_i} self.users = Incline::User.where(id: values).to_a end
[ "def", "user_ids", "=", "(", "values", ")", "values", "||=", "[", "]", "values", "=", "[", "values", "]", "unless", "values", ".", "is_a?", "(", "::", "Array", ")", "values", "=", "values", ".", "reject", "{", "|", "v", "|", "v", ".", "blank?", "}", ".", "map", "{", "|", "v", "|", "v", ".", "to_i", "}", "self", ".", "users", "=", "Incline", "::", "User", ".", "where", "(", "id", ":", "values", ")", ".", "to_a", "end" ]
Sets the user IDs for the members of this group.
[ "Sets", "the", "user", "IDs", "for", "the", "members", "of", "this", "group", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/access_group.rb#L79-L84
7,413
starrhorne/konfig
lib/konfig/rails/railtie.rb
Konfig.InitializeKonfig.load_settings
def load_settings(path) # Load the data files Konfig.load_directory(path) # Load all adapters built_in_adapters = File.join(File.dirname(__FILE__), 'adapters', '*.rb') require_all built_in_adapters user_adapters = File.join(path, 'adapters', '*_adapter.rb') require_all user_adapters # Apply the adapters to the data Adapter.create_child_instances(Konfig.default_store.data) Adapter.send_to_child_instances :adapt end
ruby
def load_settings(path) # Load the data files Konfig.load_directory(path) # Load all adapters built_in_adapters = File.join(File.dirname(__FILE__), 'adapters', '*.rb') require_all built_in_adapters user_adapters = File.join(path, 'adapters', '*_adapter.rb') require_all user_adapters # Apply the adapters to the data Adapter.create_child_instances(Konfig.default_store.data) Adapter.send_to_child_instances :adapt end
[ "def", "load_settings", "(", "path", ")", "# Load the data files", "Konfig", ".", "load_directory", "(", "path", ")", "# Load all adapters", "built_in_adapters", "=", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'adapters'", ",", "'*.rb'", ")", "require_all", "built_in_adapters", "user_adapters", "=", "File", ".", "join", "(", "path", ",", "'adapters'", ",", "'*_adapter.rb'", ")", "require_all", "user_adapters", "# Apply the adapters to the data", "Adapter", ".", "create_child_instances", "(", "Konfig", ".", "default_store", ".", "data", ")", "Adapter", ".", "send_to_child_instances", ":adapt", "end" ]
Set up the Konfig system @param [String] path the path to the directory containing config files
[ "Set", "up", "the", "Konfig", "system" ]
5d655945586a489868bb868243d9c0da18c90228
https://github.com/starrhorne/konfig/blob/5d655945586a489868bb868243d9c0da18c90228/lib/konfig/rails/railtie.rb#L28-L43
7,414
riddopic/hoodie
lib/hoodie/utils/crypto.rb
Hoodie.Crypto.encrypt
def encrypt(plain_text, password = nil, salt = nil) password = password.nil? ? Hoodie.crypto.password : password salt = salt.nil? ? Hoodie.crypto.salt : salt cipher = new_cipher(:encrypt, password, salt) cipher.iv = iv = cipher.random_iv ciphertext = cipher.update(plain_text) ciphertext << cipher.final Base64.encode64(combine_iv_ciphertext(iv, ciphertext)) end
ruby
def encrypt(plain_text, password = nil, salt = nil) password = password.nil? ? Hoodie.crypto.password : password salt = salt.nil? ? Hoodie.crypto.salt : salt cipher = new_cipher(:encrypt, password, salt) cipher.iv = iv = cipher.random_iv ciphertext = cipher.update(plain_text) ciphertext << cipher.final Base64.encode64(combine_iv_ciphertext(iv, ciphertext)) end
[ "def", "encrypt", "(", "plain_text", ",", "password", "=", "nil", ",", "salt", "=", "nil", ")", "password", "=", "password", ".", "nil?", "?", "Hoodie", ".", "crypto", ".", "password", ":", "password", "salt", "=", "salt", ".", "nil?", "?", "Hoodie", ".", "crypto", ".", "salt", ":", "salt", "cipher", "=", "new_cipher", "(", ":encrypt", ",", "password", ",", "salt", ")", "cipher", ".", "iv", "=", "iv", "=", "cipher", ".", "random_iv", "ciphertext", "=", "cipher", ".", "update", "(", "plain_text", ")", "ciphertext", "<<", "cipher", ".", "final", "Base64", ".", "encode64", "(", "combine_iv_ciphertext", "(", "iv", ",", "ciphertext", ")", ")", "end" ]
Encrypt the given string using the AES-256-CBC algorithm. @param [String] plain_text The text to encrypt. @param [String] password Secret passphrase to encrypt with. @param [String] salt A cryptographically secure pseudo-random string (SecureRandom.base64) to add a little spice to your encryption. @return [String] Encrypted text, can be deciphered with #decrypt. @api public
[ "Encrypt", "the", "given", "string", "using", "the", "AES", "-", "256", "-", "CBC", "algorithm", "." ]
921601dd4849845d3f5d3765dafcf00178b2aa66
https://github.com/riddopic/hoodie/blob/921601dd4849845d3f5d3765dafcf00178b2aa66/lib/hoodie/utils/crypto.rb#L145-L154
7,415
codescrum/bebox
lib/bebox/environment.rb
Bebox.Environment.generate_hiera_template
def generate_hiera_template ssh_key = Bebox::Project.public_ssh_key_from_file(self.project_root, self.name) project_name = Bebox::Project.shortname_from_file(self.project_root) Bebox::PROVISION_STEPS.each do |step| step_dir = Bebox::Provision.step_name(step) generate_file_from_template("#{templates_path}/puppet/#{step}/hiera/data/environment.yaml.erb", "#{self.project_root}/puppet/steps/#{step_dir}/hiera/data/#{self.name}.yaml", {step_dir: step_dir, ssh_key: ssh_key, project_name: project_name}) end end
ruby
def generate_hiera_template ssh_key = Bebox::Project.public_ssh_key_from_file(self.project_root, self.name) project_name = Bebox::Project.shortname_from_file(self.project_root) Bebox::PROVISION_STEPS.each do |step| step_dir = Bebox::Provision.step_name(step) generate_file_from_template("#{templates_path}/puppet/#{step}/hiera/data/environment.yaml.erb", "#{self.project_root}/puppet/steps/#{step_dir}/hiera/data/#{self.name}.yaml", {step_dir: step_dir, ssh_key: ssh_key, project_name: project_name}) end end
[ "def", "generate_hiera_template", "ssh_key", "=", "Bebox", "::", "Project", ".", "public_ssh_key_from_file", "(", "self", ".", "project_root", ",", "self", ".", "name", ")", "project_name", "=", "Bebox", "::", "Project", ".", "shortname_from_file", "(", "self", ".", "project_root", ")", "Bebox", "::", "PROVISION_STEPS", ".", "each", "do", "|", "step", "|", "step_dir", "=", "Bebox", "::", "Provision", ".", "step_name", "(", "step", ")", "generate_file_from_template", "(", "\"#{templates_path}/puppet/#{step}/hiera/data/environment.yaml.erb\"", ",", "\"#{self.project_root}/puppet/steps/#{step_dir}/hiera/data/#{self.name}.yaml\"", ",", "{", "step_dir", ":", "step_dir", ",", "ssh_key", ":", "ssh_key", ",", "project_name", ":", "project_name", "}", ")", "end", "end" ]
Generate the hiera data template for the environment
[ "Generate", "the", "hiera", "data", "template", "for", "the", "environment" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/environment.rb#L72-L79
7,416
mrackwitz/CLIntegracon
lib/CLIntegracon/subject.rb
CLIntegracon.Subject.replace_path
def replace_path(path, name=nil) name ||= File.basename path self.replace_pattern path, name end
ruby
def replace_path(path, name=nil) name ||= File.basename path self.replace_pattern path, name end
[ "def", "replace_path", "(", "path", ",", "name", "=", "nil", ")", "name", "||=", "File", ".", "basename", "path", "self", ".", "replace_pattern", "path", ",", "name", "end" ]
Define a path, whose occurrences in the output should be replaced by either its basename or a given placeholder. @param [String] path The path @param [String] name The name of the path, or the basename of the given path
[ "Define", "a", "path", "whose", "occurrences", "in", "the", "output", "should", "be", "replaced", "by", "either", "its", "basename", "or", "a", "given", "placeholder", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/subject.rb#L94-L97
7,417
mrackwitz/CLIntegracon
lib/CLIntegracon/subject.rb
CLIntegracon.Subject.run
def run(command_line) require 'open3' env = Hash[environment_vars.map { |k, v| [k.to_s, v.to_s] }] Open3.capture2e(env, command_line.to_s) end
ruby
def run(command_line) require 'open3' env = Hash[environment_vars.map { |k, v| [k.to_s, v.to_s] }] Open3.capture2e(env, command_line.to_s) end
[ "def", "run", "(", "command_line", ")", "require", "'open3'", "env", "=", "Hash", "[", "environment_vars", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ".", "to_s", ",", "v", ".", "to_s", "]", "}", "]", "Open3", ".", "capture2e", "(", "env", ",", "command_line", ".", "to_s", ")", "end" ]
Run the command. @param [String] command_line THe command line to execute @return [[String, Process::Status]] The output, which is emitted during execution, and the exit status.
[ "Run", "the", "command", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/subject.rb#L161-L165
7,418
mrackwitz/CLIntegracon
lib/CLIntegracon/subject.rb
CLIntegracon.Subject.command_line
def command_line(head_arguments='', tail_arguments='') args = [head_arguments, default_args, tail_arguments].flatten.compact.select { |s| s.length > 0 }.join ' ' "#{executable} #{args}" end
ruby
def command_line(head_arguments='', tail_arguments='') args = [head_arguments, default_args, tail_arguments].flatten.compact.select { |s| s.length > 0 }.join ' ' "#{executable} #{args}" end
[ "def", "command_line", "(", "head_arguments", "=", "''", ",", "tail_arguments", "=", "''", ")", "args", "=", "[", "head_arguments", ",", "default_args", ",", "tail_arguments", "]", ".", "flatten", ".", "compact", ".", "select", "{", "|", "s", "|", "s", ".", "length", ">", "0", "}", ".", "join", "' '", "\"#{executable} #{args}\"", "end" ]
Merges the given with the configured arguments and returns the command line to execute. @param [String] head_arguments The arguments to pass to the executable before the default arguments. @param [String] tail_arguments The arguments to pass to the executable after the default arguments. @return [String] The command line to execute.
[ "Merges", "the", "given", "with", "the", "configured", "arguments", "and", "returns", "the", "command", "line", "to", "execute", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/subject.rb#L179-L182
7,419
mrackwitz/CLIntegracon
lib/CLIntegracon/subject.rb
CLIntegracon.Subject.apply_replacements
def apply_replacements(output) replace_patterns.reduce(output) do |output, replacement_pattern| replacement_pattern.replace(output) end end
ruby
def apply_replacements(output) replace_patterns.reduce(output) do |output, replacement_pattern| replacement_pattern.replace(output) end end
[ "def", "apply_replacements", "(", "output", ")", "replace_patterns", ".", "reduce", "(", "output", ")", "do", "|", "output", ",", "replacement_pattern", "|", "replacement_pattern", ".", "replace", "(", "output", ")", "end", "end" ]
Apply the configured replacements to the output. @param [String] output The output, which was emitted while execution. @return [String] The redacted output.
[ "Apply", "the", "configured", "replacements", "to", "the", "output", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/subject.rb#L192-L196
7,420
mova-rb/mova
lib/mova/translator.rb
Mova.Translator.get
def get(key, locale, opts = {}) keys = resolve_scopes(key) locales = resolve_locales(locale) read_first(locales, keys) || opts[:default] || default(locales, keys, opts) end
ruby
def get(key, locale, opts = {}) keys = resolve_scopes(key) locales = resolve_locales(locale) read_first(locales, keys) || opts[:default] || default(locales, keys, opts) end
[ "def", "get", "(", "key", ",", "locale", ",", "opts", "=", "{", "}", ")", "keys", "=", "resolve_scopes", "(", "key", ")", "locales", "=", "resolve_locales", "(", "locale", ")", "read_first", "(", "locales", ",", "keys", ")", "||", "opts", "[", ":default", "]", "||", "default", "(", "locales", ",", "keys", ",", "opts", ")", "end" ]
Retrieves translation from the storage or return default value. @return [String] translation or default value if nothing found @example translator.put(en: {hello: "world"}) translator.get("hello", :en) #=> "world" translator.get("bye", :en) #=> "" @example Providing the default if nothing found translator.get("hello", :de, default: "nothing") #=> "nothing" @overload get(key, locale, opts = {}) @param key [String, Symbol] @param locale [String, Symbol] @overload get(keys, locale, opts = {}) @param keys [Array<String, Symbol>] use this to redefine an array returned by {#keys_to_try}. @param locale [String, Symbol] @example translator.put(en: {fail: "Fail"}) translator.get(["big.fail", "mine.fail"], :en) #=> ""; tried "en.big.fail", then "en.mine.fail" @overload get(key, locales, opts = {}) @param key [String, Symbol] @param locales [Array<String, Symbol>] use this to redefine an array returned by {#locales_to_try}. @example translator.put(en: {hello: "world"}) translator.get(:hello, :de) #=> ""; tried only "de.hello" translator.get(:hello, [:de, :en]) #=> "world"; tried "de.hello", then "en.hello" @example Disable locale fallbacks locally translator.put(en: {hello: "world"}) # suppose this instance has fallback to :en locale translator.get(:hello, :de) #=> "world"; tried "de.hello", then "en.hello" translator.get(:hello, [:de]) #=> ""; tried only "de.hello" @overload get(keys, locales, opts = {}) @param keys [Array<String, Symbol>] @param locales [Array<String, Symbol>] @note Keys fallback has a higher priority than locales one, that is, Mova tries to find a translation for any given key and only then it fallbacks to another locale. @param opts [Hash] @option opts [String] :default use this to redefine default value returned by {#default}. @see #locales_to_try @see #keys_to_try @see #default
[ "Retrieves", "translation", "from", "the", "storage", "or", "return", "default", "value", "." ]
27f981c1f29dc20e5d11068d9342088f0e6bb318
https://github.com/mova-rb/mova/blob/27f981c1f29dc20e5d11068d9342088f0e6bb318/lib/mova/translator.rb#L136-L140
7,421
mova-rb/mova
lib/mova/translator.rb
Mova.Translator.put
def put(translations) Scope.flatten(translations).each do |key, value| storage.write(key, value) unless storage.exist?(key) end end
ruby
def put(translations) Scope.flatten(translations).each do |key, value| storage.write(key, value) unless storage.exist?(key) end end
[ "def", "put", "(", "translations", ")", "Scope", ".", "flatten", "(", "translations", ")", ".", "each", "do", "|", "key", ",", "value", "|", "storage", ".", "write", "(", "key", ",", "value", ")", "unless", "storage", ".", "exist?", "(", "key", ")", "end", "end" ]
Writes translations to the storage. @return [void] @param translations [Hash{String, Symbol => String, Hash}] where root key/keys must be a locale @example translator.put(en: {world: "world"}, uk: {world: "світ"}) translator.get("world", :uk) #=> "світ"
[ "Writes", "translations", "to", "the", "storage", "." ]
27f981c1f29dc20e5d11068d9342088f0e6bb318
https://github.com/mova-rb/mova/blob/27f981c1f29dc20e5d11068d9342088f0e6bb318/lib/mova/translator.rb#L151-L155
7,422
wynst/email_direct
lib/email_direct/service_proxy_patch.rb
EmailDirect.ServiceProxyPatch.build_request
def build_request(method, options) builder = underscore("build_#{method}") self.respond_to?(builder) ? self.send(builder, options) : soap_envelope(options).target! end
ruby
def build_request(method, options) builder = underscore("build_#{method}") self.respond_to?(builder) ? self.send(builder, options) : soap_envelope(options).target! end
[ "def", "build_request", "(", "method", ",", "options", ")", "builder", "=", "underscore", "(", "\"build_#{method}\"", ")", "self", ".", "respond_to?", "(", "builder", ")", "?", "self", ".", "send", "(", "builder", ",", "options", ")", ":", "soap_envelope", "(", "options", ")", ".", "target!", "end" ]
same as original, but don't call .target! on custom builder
[ "same", "as", "original", "but", "don", "t", "call", ".", "target!", "on", "custom", "builder" ]
a6ab948c362c695cfbf12cc4f9c7c0ca8e805c54
https://github.com/wynst/email_direct/blob/a6ab948c362c695cfbf12cc4f9c7c0ca8e805c54/lib/email_direct/service_proxy_patch.rb#L4-L8
7,423
wedesoft/multiarray
lib/multiarray/complex.rb
Hornetseye.InternalComplex.*
def *(other) if other.is_a?(InternalComplex) or other.is_a?(Complex) InternalComplex.new @real * other.real - @imag * other.imag, @real * other.imag + @imag * other.real elsif InternalComplex.generic? other InternalComplex.new @real * other, @imag * other else x, y = other.coerce self x * y end end
ruby
def *(other) if other.is_a?(InternalComplex) or other.is_a?(Complex) InternalComplex.new @real * other.real - @imag * other.imag, @real * other.imag + @imag * other.real elsif InternalComplex.generic? other InternalComplex.new @real * other, @imag * other else x, y = other.coerce self x * y end end
[ "def", "*", "(", "other", ")", "if", "other", ".", "is_a?", "(", "InternalComplex", ")", "or", "other", ".", "is_a?", "(", "Complex", ")", "InternalComplex", ".", "new", "@real", "*", "other", ".", "real", "-", "@imag", "*", "other", ".", "imag", ",", "@real", "*", "other", ".", "imag", "+", "@imag", "*", "other", ".", "real", "elsif", "InternalComplex", ".", "generic?", "other", "InternalComplex", ".", "new", "@real", "*", "other", ",", "@imag", "*", "other", "else", "x", ",", "y", "=", "other", ".", "coerce", "self", "x", "*", "y", "end", "end" ]
Multiply complex values @param [Object] Second operand for binary operation. @return [InternalComplex] The result @private
[ "Multiply", "complex", "values" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/complex.rb#L227-L237
7,424
wedesoft/multiarray
lib/multiarray/complex.rb
Hornetseye.InternalComplex./
def /(other) if other.is_a?(InternalComplex) or other.is_a?(Complex) self * other.conj / other.abs2 elsif InternalComplex.generic? other InternalComplex.new @real / other, @imag / other else x, y = other.coerce self x / y end end
ruby
def /(other) if other.is_a?(InternalComplex) or other.is_a?(Complex) self * other.conj / other.abs2 elsif InternalComplex.generic? other InternalComplex.new @real / other, @imag / other else x, y = other.coerce self x / y end end
[ "def", "/", "(", "other", ")", "if", "other", ".", "is_a?", "(", "InternalComplex", ")", "or", "other", ".", "is_a?", "(", "Complex", ")", "self", "*", "other", ".", "conj", "/", "other", ".", "abs2", "elsif", "InternalComplex", ".", "generic?", "other", "InternalComplex", ".", "new", "@real", "/", "other", ",", "@imag", "/", "other", "else", "x", ",", "y", "=", "other", ".", "coerce", "self", "x", "/", "y", "end", "end" ]
Divide complex values @param [Object] Second operand for binary operation. @return [InternalComplex] The result @private
[ "Divide", "complex", "values" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/complex.rb#L246-L255
7,425
wedesoft/multiarray
lib/multiarray/complex.rb
Hornetseye.COMPLEX_.assign
def assign(value) value = value.simplify if @value.real.respond_to? :assign @value.real.assign value.get.real else @value.real = value.get.real end if @value.imag.respond_to? :assign @value.imag.assign value.get.imag else @value.imag = value.get.imag end value end
ruby
def assign(value) value = value.simplify if @value.real.respond_to? :assign @value.real.assign value.get.real else @value.real = value.get.real end if @value.imag.respond_to? :assign @value.imag.assign value.get.imag else @value.imag = value.get.imag end value end
[ "def", "assign", "(", "value", ")", "value", "=", "value", ".", "simplify", "if", "@value", ".", "real", ".", "respond_to?", ":assign", "@value", ".", "real", ".", "assign", "value", ".", "get", ".", "real", "else", "@value", ".", "real", "=", "value", ".", "get", ".", "real", "end", "if", "@value", ".", "imag", ".", "respond_to?", ":assign", "@value", ".", "imag", ".", "assign", "value", ".", "get", ".", "imag", "else", "@value", ".", "imag", "=", "value", ".", "get", ".", "imag", "end", "value", "end" ]
Constructor for native complex number @param [Complex,InternalComplex] value Complex number. Duplicate object @return [COMPLEX_] Duplicate of +self+. Store new value in this object @param [Object] value New value for this object. @return [Object] Returns +value+. @private
[ "Constructor", "for", "native", "complex", "number" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/complex.rb#L890-L903
7,426
wedesoft/multiarray
lib/multiarray/complex.rb
Hornetseye.Node.real_with_decompose
def real_with_decompose if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy] real_without_decompose elsif typecode < COMPLEX_ decompose 0 else self end end
ruby
def real_with_decompose if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy] real_without_decompose elsif typecode < COMPLEX_ decompose 0 else self end end
[ "def", "real_with_decompose", "if", "typecode", "==", "OBJECT", "or", "is_a?", "(", "Variable", ")", "or", "Thread", ".", "current", "[", ":lazy", "]", "real_without_decompose", "elsif", "typecode", "<", "COMPLEX_", "decompose", "0", "else", "self", "end", "end" ]
Fast extraction for real values of complex array @return [Node] Array with real values.
[ "Fast", "extraction", "for", "real", "values", "of", "complex", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/complex.rb#L990-L998
7,427
wedesoft/multiarray
lib/multiarray/complex.rb
Hornetseye.Node.real=
def real=(value) if typecode < COMPLEX_ decompose( 0 )[] = value elsif typecode == OBJECT self[] = Hornetseye::lazy do value + imag * Complex::I end else self[] = value end end
ruby
def real=(value) if typecode < COMPLEX_ decompose( 0 )[] = value elsif typecode == OBJECT self[] = Hornetseye::lazy do value + imag * Complex::I end else self[] = value end end
[ "def", "real", "=", "(", "value", ")", "if", "typecode", "<", "COMPLEX_", "decompose", "(", "0", ")", "[", "]", "=", "value", "elsif", "typecode", "==", "OBJECT", "self", "[", "]", "=", "Hornetseye", "::", "lazy", "do", "value", "+", "imag", "*", "Complex", "::", "I", "end", "else", "self", "[", "]", "=", "value", "end", "end" ]
Assignment for real values of complex array @param [Object] Value or array of values to assign to real components. @return [Object] Returns +value+.
[ "Assignment", "for", "real", "values", "of", "complex", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/complex.rb#L1007-L1017
7,428
wedesoft/multiarray
lib/multiarray/complex.rb
Hornetseye.Node.imag_with_decompose
def imag_with_decompose if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy] imag_without_decompose elsif typecode < COMPLEX_ decompose 1 else Hornetseye::lazy( *shape ) { typecode.new( 0 ) } end end
ruby
def imag_with_decompose if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy] imag_without_decompose elsif typecode < COMPLEX_ decompose 1 else Hornetseye::lazy( *shape ) { typecode.new( 0 ) } end end
[ "def", "imag_with_decompose", "if", "typecode", "==", "OBJECT", "or", "is_a?", "(", "Variable", ")", "or", "Thread", ".", "current", "[", ":lazy", "]", "imag_without_decompose", "elsif", "typecode", "<", "COMPLEX_", "decompose", "1", "else", "Hornetseye", "::", "lazy", "(", "shape", ")", "{", "typecode", ".", "new", "(", "0", ")", "}", "end", "end" ]
Fast extraction of imaginary values of complex array @return [Node] Array with imaginary values.
[ "Fast", "extraction", "of", "imaginary", "values", "of", "complex", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/complex.rb#L1022-L1030
7,429
tongueroo/balancer
lib/balancer/core.rb
Balancer.Core.set_profile
def set_profile(value) path = "#{root}/.balancer/profiles/#{value}.yml" unless File.exist?(path) puts "The profile file #{path} does not exist. Exiting.".colorize(:red) exit 1 end ENV['BALANCER_PROFILE'] = value end
ruby
def set_profile(value) path = "#{root}/.balancer/profiles/#{value}.yml" unless File.exist?(path) puts "The profile file #{path} does not exist. Exiting.".colorize(:red) exit 1 end ENV['BALANCER_PROFILE'] = value end
[ "def", "set_profile", "(", "value", ")", "path", "=", "\"#{root}/.balancer/profiles/#{value}.yml\"", "unless", "File", ".", "exist?", "(", "path", ")", "puts", "\"The profile file #{path} does not exist. Exiting.\"", ".", "colorize", "(", ":red", ")", "exit", "1", "end", "ENV", "[", "'BALANCER_PROFILE'", "]", "=", "value", "end" ]
Only set the BALANCER_PROFILE if not set already at the CLI. CLI takes highest precedence.
[ "Only", "set", "the", "BALANCER_PROFILE", "if", "not", "set", "already", "at", "the", "CLI", ".", "CLI", "takes", "highest", "precedence", "." ]
c149498e78f73b1dc0a433cc693ec4327c409bab
https://github.com/tongueroo/balancer/blob/c149498e78f73b1dc0a433cc693ec4327c409bab/lib/balancer/core.rb#L24-L31
7,430
Rafaherrero/lpp_11
lib/doublylinkedlist/doublylinkedlist.rb
Doublylinkedlist.Doublylinkedlist.to_s
def to_s actual = @inicio cadena = "|" while !actual.nil? cadena << actual[:valor].to_s if !actual[:sig].nil? cadena << ", " end actual = actual[:sig] end cadena << "|" return cadena end
ruby
def to_s actual = @inicio cadena = "|" while !actual.nil? cadena << actual[:valor].to_s if !actual[:sig].nil? cadena << ", " end actual = actual[:sig] end cadena << "|" return cadena end
[ "def", "to_s", "actual", "=", "@inicio", "cadena", "=", "\"|\"", "while", "!", "actual", ".", "nil?", "cadena", "<<", "actual", "[", ":valor", "]", ".", "to_s", "if", "!", "actual", "[", ":sig", "]", ".", "nil?", "cadena", "<<", "\", \"", "end", "actual", "=", "actual", "[", ":sig", "]", "end", "cadena", "<<", "\"|\"", "return", "cadena", "end" ]
Iniciar los punteros de la lista, inicio y final Metodo para imprimir la lista con formato @return la lista formateada en un string
[ "Iniciar", "los", "punteros", "de", "la", "lista", "inicio", "y", "final", "Metodo", "para", "imprimir", "la", "lista", "con", "formato" ]
7b9a89138db96d603f1f1b1b93735feee5e4c2a2
https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/doublylinkedlist/doublylinkedlist.rb#L14-L28
7,431
Rafaherrero/lpp_11
lib/doublylinkedlist/doublylinkedlist.rb
Doublylinkedlist.Doublylinkedlist.insertar_inicio
def insertar_inicio(val) if @inicio.nil? @inicio = Struct::Nodo.new(nil, val, nil) @final = @inicio else copia = @inicio @inicio = Struct::Nodo.new(nil, val, copia) copia[:ant] = @inicio end end
ruby
def insertar_inicio(val) if @inicio.nil? @inicio = Struct::Nodo.new(nil, val, nil) @final = @inicio else copia = @inicio @inicio = Struct::Nodo.new(nil, val, copia) copia[:ant] = @inicio end end
[ "def", "insertar_inicio", "(", "val", ")", "if", "@inicio", ".", "nil?", "@inicio", "=", "Struct", "::", "Nodo", ".", "new", "(", "nil", ",", "val", ",", "nil", ")", "@final", "=", "@inicio", "else", "copia", "=", "@inicio", "@inicio", "=", "Struct", "::", "Nodo", ".", "new", "(", "nil", ",", "val", ",", "copia", ")", "copia", "[", ":ant", "]", "=", "@inicio", "end", "end" ]
Metodo que nos permite insertar algo al inicio de la lista @param [val] val recibe el valor a insertar en la lista
[ "Metodo", "que", "nos", "permite", "insertar", "algo", "al", "inicio", "de", "la", "lista" ]
7b9a89138db96d603f1f1b1b93735feee5e4c2a2
https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/doublylinkedlist/doublylinkedlist.rb#L32-L41
7,432
Rafaherrero/lpp_11
lib/doublylinkedlist/doublylinkedlist.rb
Doublylinkedlist.Doublylinkedlist.insertar_final
def insertar_final(val) if @final.nil? @inicio = Struct::Nodo.new(nil, val, nil) @final = @inicio else copia = @final @final[:sig] = Struct::Nodo.new(copia, val, nil) copia2 = @final[:sig] @final = copia2 end end
ruby
def insertar_final(val) if @final.nil? @inicio = Struct::Nodo.new(nil, val, nil) @final = @inicio else copia = @final @final[:sig] = Struct::Nodo.new(copia, val, nil) copia2 = @final[:sig] @final = copia2 end end
[ "def", "insertar_final", "(", "val", ")", "if", "@final", ".", "nil?", "@inicio", "=", "Struct", "::", "Nodo", ".", "new", "(", "nil", ",", "val", ",", "nil", ")", "@final", "=", "@inicio", "else", "copia", "=", "@final", "@final", "[", ":sig", "]", "=", "Struct", "::", "Nodo", ".", "new", "(", "copia", ",", "val", ",", "nil", ")", "copia2", "=", "@final", "[", ":sig", "]", "@final", "=", "copia2", "end", "end" ]
Metodo que nos permite insertar algo al final de la lista @param [val] val recibe el valor a insertar en la lista
[ "Metodo", "que", "nos", "permite", "insertar", "algo", "al", "final", "de", "la", "lista" ]
7b9a89138db96d603f1f1b1b93735feee5e4c2a2
https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/doublylinkedlist/doublylinkedlist.rb#L45-L55
7,433
Rafaherrero/lpp_11
lib/doublylinkedlist/doublylinkedlist.rb
Doublylinkedlist.Doublylinkedlist.tamano
def tamano() if [email protected]? contador = 1 copia = @inicio while !copia[:sig].nil? contador += 1 copia2 = copia[:sig] copia = copia2 end end return contador end
ruby
def tamano() if [email protected]? contador = 1 copia = @inicio while !copia[:sig].nil? contador += 1 copia2 = copia[:sig] copia = copia2 end end return contador end
[ "def", "tamano", "(", ")", "if", "!", "@inicio", ".", "nil?", "contador", "=", "1", "copia", "=", "@inicio", "while", "!", "copia", "[", ":sig", "]", ".", "nil?", "contador", "+=", "1", "copia2", "=", "copia", "[", ":sig", "]", "copia", "=", "copia2", "end", "end", "return", "contador", "end" ]
Metodo que nos devuelve la cantidad de elementos en la lista @return cantidad de elementos en la lista
[ "Metodo", "que", "nos", "devuelve", "la", "cantidad", "de", "elementos", "en", "la", "lista" ]
7b9a89138db96d603f1f1b1b93735feee5e4c2a2
https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/doublylinkedlist/doublylinkedlist.rb#L97-L110
7,434
Rafaherrero/lpp_11
lib/doublylinkedlist/doublylinkedlist.rb
Doublylinkedlist.Doublylinkedlist.posicion
def posicion (pos) if @inicio.nil? raise RuntimeError, "La lista esta vacia" end if pos<0 || pos>tamano-1 raise RuntimeError, "La posicion no es correcta" end contador=0 copia=@inicio while contador<pos && !copia.nil? copia2 = copia[:sig] copia = copia2 contador += 1 end return copia[:valor] end
ruby
def posicion (pos) if @inicio.nil? raise RuntimeError, "La lista esta vacia" end if pos<0 || pos>tamano-1 raise RuntimeError, "La posicion no es correcta" end contador=0 copia=@inicio while contador<pos && !copia.nil? copia2 = copia[:sig] copia = copia2 contador += 1 end return copia[:valor] end
[ "def", "posicion", "(", "pos", ")", "if", "@inicio", ".", "nil?", "raise", "RuntimeError", ",", "\"La lista esta vacia\"", "end", "if", "pos", "<", "0", "||", "pos", ">", "tamano", "-", "1", "raise", "RuntimeError", ",", "\"La posicion no es correcta\"", "end", "contador", "=", "0", "copia", "=", "@inicio", "while", "contador", "<", "pos", "&&", "!", "copia", ".", "nil?", "copia2", "=", "copia", "[", ":sig", "]", "copia", "=", "copia2", "contador", "+=", "1", "end", "return", "copia", "[", ":valor", "]", "end" ]
Metodo que devuelve lo contenido en una posicion de la lista @param [pos] pos del elemento deseado @return nodo de la posicion de la lista
[ "Metodo", "que", "devuelve", "lo", "contenido", "en", "una", "posicion", "de", "la", "lista" ]
7b9a89138db96d603f1f1b1b93735feee5e4c2a2
https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/doublylinkedlist/doublylinkedlist.rb#L114-L132
7,435
Rafaherrero/lpp_11
lib/doublylinkedlist/doublylinkedlist.rb
Doublylinkedlist.Doublylinkedlist.ordenar!
def ordenar! cambio = true while cambio cambio = false i = @inicio i_1 = @inicio[:sig] while i_1 != nil if(i[:valor] > i_1[:valor]) i[:valor], i_1[:valor] = i_1[:valor], i[:valor] cambio = true end i = i_1 i_1 = i_1[:sig] end end end
ruby
def ordenar! cambio = true while cambio cambio = false i = @inicio i_1 = @inicio[:sig] while i_1 != nil if(i[:valor] > i_1[:valor]) i[:valor], i_1[:valor] = i_1[:valor], i[:valor] cambio = true end i = i_1 i_1 = i_1[:sig] end end end
[ "def", "ordenar!", "cambio", "=", "true", "while", "cambio", "cambio", "=", "false", "i", "=", "@inicio", "i_1", "=", "@inicio", "[", ":sig", "]", "while", "i_1", "!=", "nil", "if", "(", "i", "[", ":valor", "]", ">", "i_1", "[", ":valor", "]", ")", "i", "[", ":valor", "]", ",", "i_1", "[", ":valor", "]", "=", "i_1", "[", ":valor", "]", ",", "i", "[", ":valor", "]", "cambio", "=", "true", "end", "i", "=", "i_1", "i_1", "=", "i_1", "[", ":sig", "]", "end", "end", "end" ]
Metodo que nos ordenada la lista segun los criterios de la APA
[ "Metodo", "que", "nos", "ordenada", "la", "lista", "segun", "los", "criterios", "de", "la", "APA" ]
7b9a89138db96d603f1f1b1b93735feee5e4c2a2
https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/doublylinkedlist/doublylinkedlist.rb#L144-L159
7,436
djellemah/philtre-rails
lib/philtre-rails/philtre_view_helpers.rb
PhiltreRails.PhiltreViewHelpers.order_by
def order_by( filter, *fields, label: fields.first.to_s.titleize, order_link_class: default_order_link_class ) return label if filter.nil? # current ordering from the filter # each expr is a Sequel::SQL::Expression exprs = Hash[ filter.order_expressions ] # Invert each ordering for the generated link. Current sort order will be displayed. order_links = fields.map do |field| if exprs[field] order_link_class.new exprs[field].invert, active: true else order_link_class.new Sequel.asc(field) end end # filter params must have order in the right format filter_params = filter.filter_parameters.dup filter_params[:order] = unify_array( order_links.map( &:name ) ) params_hash = {filter.class::Model.model_name.param_key.to_sym => filter_params} link_text = raw( [label, order_links.first.andand.icon].compact.join(' ') ) link_to link_text, params_hash, {class: order_links.first.andand.css_class} end
ruby
def order_by( filter, *fields, label: fields.first.to_s.titleize, order_link_class: default_order_link_class ) return label if filter.nil? # current ordering from the filter # each expr is a Sequel::SQL::Expression exprs = Hash[ filter.order_expressions ] # Invert each ordering for the generated link. Current sort order will be displayed. order_links = fields.map do |field| if exprs[field] order_link_class.new exprs[field].invert, active: true else order_link_class.new Sequel.asc(field) end end # filter params must have order in the right format filter_params = filter.filter_parameters.dup filter_params[:order] = unify_array( order_links.map( &:name ) ) params_hash = {filter.class::Model.model_name.param_key.to_sym => filter_params} link_text = raw( [label, order_links.first.andand.icon].compact.join(' ') ) link_to link_text, params_hash, {class: order_links.first.andand.css_class} end
[ "def", "order_by", "(", "filter", ",", "*", "fields", ",", "label", ":", "fields", ".", "first", ".", "to_s", ".", "titleize", ",", "order_link_class", ":", "default_order_link_class", ")", "return", "label", "if", "filter", ".", "nil?", "# current ordering from the filter", "# each expr is a Sequel::SQL::Expression", "exprs", "=", "Hash", "[", "filter", ".", "order_expressions", "]", "# Invert each ordering for the generated link. Current sort order will be displayed.", "order_links", "=", "fields", ".", "map", "do", "|", "field", "|", "if", "exprs", "[", "field", "]", "order_link_class", ".", "new", "exprs", "[", "field", "]", ".", "invert", ",", "active", ":", "true", "else", "order_link_class", ".", "new", "Sequel", ".", "asc", "(", "field", ")", "end", "end", "# filter params must have order in the right format", "filter_params", "=", "filter", ".", "filter_parameters", ".", "dup", "filter_params", "[", ":order", "]", "=", "unify_array", "(", "order_links", ".", "map", "(", ":name", ")", ")", "params_hash", "=", "{", "filter", ".", "class", "::", "Model", ".", "model_name", ".", "param_key", ".", "to_sym", "=>", "filter_params", "}", "link_text", "=", "raw", "(", "[", "label", ",", "order_links", ".", "first", ".", "andand", ".", "icon", "]", ".", "compact", ".", "join", "(", "' '", ")", ")", "link_to", "link_text", ",", "params_hash", ",", "{", "class", ":", "order_links", ".", "first", ".", "andand", ".", "css_class", "}", "end" ]
Heavily modified from SearchLogic.
[ "Heavily", "modified", "from", "SearchLogic", "." ]
d37c7c564d7556081b89b434e34633320dbb28d8
https://github.com/djellemah/philtre-rails/blob/d37c7c564d7556081b89b434e34633320dbb28d8/lib/philtre-rails/philtre_view_helpers.rb#L20-L43
7,437
openSUSE/dm-bugzilla-adapter
lib/dm-bugzilla-adapter/delete.rb
DataMapper::Adapters.BugzillaAdapter.delete
def delete(collection) each_resource_with_edit_url(collection) do |resource, edit_url| connection.delete(edit_url, 'If-Match' => "*") end # return count collection.size end
ruby
def delete(collection) each_resource_with_edit_url(collection) do |resource, edit_url| connection.delete(edit_url, 'If-Match' => "*") end # return count collection.size end
[ "def", "delete", "(", "collection", ")", "each_resource_with_edit_url", "(", "collection", ")", "do", "|", "resource", ",", "edit_url", "|", "connection", ".", "delete", "(", "edit_url", ",", "'If-Match'", "=>", "\"*\"", ")", "end", "# return count", "collection", ".", "size", "end" ]
Constructs and executes DELETE statement for given query @param [Collection] collection collection of records to be deleted @return [Integer] the number of records deleted @api semipublic
[ "Constructs", "and", "executes", "DELETE", "statement", "for", "given", "query" ]
d56a64918f315d5038145b3f0d94852fc38bcca2
https://github.com/openSUSE/dm-bugzilla-adapter/blob/d56a64918f315d5038145b3f0d94852fc38bcca2/lib/dm-bugzilla-adapter/delete.rb#L14-L20
7,438
varyonic/pocus
lib/pocus/session.rb
Pocus.Session.send_request
def send_request(method, path, fields = {}) response = send_logged_request(URI(BASE_URL + path), method, request_data(fields)) fail UnexpectedHttpResponse, response unless response.is_a? Net::HTTPSuccess JSON.parse(response.body) end
ruby
def send_request(method, path, fields = {}) response = send_logged_request(URI(BASE_URL + path), method, request_data(fields)) fail UnexpectedHttpResponse, response unless response.is_a? Net::HTTPSuccess JSON.parse(response.body) end
[ "def", "send_request", "(", "method", ",", "path", ",", "fields", "=", "{", "}", ")", "response", "=", "send_logged_request", "(", "URI", "(", "BASE_URL", "+", "path", ")", ",", "method", ",", "request_data", "(", "fields", ")", ")", "fail", "UnexpectedHttpResponse", ",", "response", "unless", "response", ".", "is_a?", "Net", "::", "HTTPSuccess", "JSON", ".", "parse", "(", "response", ".", "body", ")", "end" ]
Accepts hash of fields to send. Returns parsed response body, always a hash.
[ "Accepts", "hash", "of", "fields", "to", "send", ".", "Returns", "parsed", "response", "body", "always", "a", "hash", "." ]
84cbbda509456fc8afaffd6916dccfc585d23b41
https://github.com/varyonic/pocus/blob/84cbbda509456fc8afaffd6916dccfc585d23b41/lib/pocus/session.rb#L42-L46
7,439
lulibrary/aspire
lib/aspire/user_lookup.rb
Aspire.UserLookup.[]
def [](uri, factory = nil) data = store[uri] data.nil? ? nil : Aspire::Object::User.new(uri, factory, json: data) end
ruby
def [](uri, factory = nil) data = store[uri] data.nil? ? nil : Aspire::Object::User.new(uri, factory, json: data) end
[ "def", "[]", "(", "uri", ",", "factory", "=", "nil", ")", "data", "=", "store", "[", "uri", "]", "data", ".", "nil?", "?", "nil", ":", "Aspire", "::", "Object", "::", "User", ".", "new", "(", "uri", ",", "factory", ",", "json", ":", "data", ")", "end" ]
Initialises a new UserLookup instance @see (Hash#initialize) @param filename [String] the filename of the CSV file to populate the hash @return [void] Returns an Aspire::Object::User instance for a URI @param uri [String] the URI of the user @param factory [Aspire::Object::Factory] the data object factory @return [Aspire::Object::User] the user
[ "Initialises", "a", "new", "UserLookup", "instance" ]
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/user_lookup.rb#L27-L30
7,440
lulibrary/aspire
lib/aspire/user_lookup.rb
Aspire.UserLookup.load
def load(filename = nil) delim = /\s*;\s*/ # The delimiter for email and role lists enum = Aspire::Enumerator::ReportEnumerator.new(filename).enumerator enum.each do |row| # Construct a JSON data structure for the user uri = row[3] data = csv_to_json_api(row, email_delim: delim, role_delim: delim) csv_to_json_other(row, data) # Store the JSON data in the lookup table store[uri] = data end end
ruby
def load(filename = nil) delim = /\s*;\s*/ # The delimiter for email and role lists enum = Aspire::Enumerator::ReportEnumerator.new(filename).enumerator enum.each do |row| # Construct a JSON data structure for the user uri = row[3] data = csv_to_json_api(row, email_delim: delim, role_delim: delim) csv_to_json_other(row, data) # Store the JSON data in the lookup table store[uri] = data end end
[ "def", "load", "(", "filename", "=", "nil", ")", "delim", "=", "/", "\\s", "\\s", "/", "# The delimiter for email and role lists", "enum", "=", "Aspire", "::", "Enumerator", "::", "ReportEnumerator", ".", "new", "(", "filename", ")", ".", "enumerator", "enum", ".", "each", "do", "|", "row", "|", "# Construct a JSON data structure for the user", "uri", "=", "row", "[", "3", "]", "data", "=", "csv_to_json_api", "(", "row", ",", "email_delim", ":", "delim", ",", "role_delim", ":", "delim", ")", "csv_to_json_other", "(", "row", ",", "data", ")", "# Store the JSON data in the lookup table", "store", "[", "uri", "]", "=", "data", "end", "end" ]
Populates the store from an All User Profiles report CSV file @param filename [String] the filename of the CSV file @return [void]
[ "Populates", "the", "store", "from", "an", "All", "User", "Profiles", "report", "CSV", "file" ]
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/user_lookup.rb#L35-L46
7,441
lulibrary/aspire
lib/aspire/user_lookup.rb
Aspire.UserLookup.method_missing
def method_missing(method, *args, &block) super unless store.respond_to?(method) store.public_send(method, *args, &block) end
ruby
def method_missing(method, *args, &block) super unless store.respond_to?(method) store.public_send(method, *args, &block) end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "super", "unless", "store", ".", "respond_to?", "(", "method", ")", "store", ".", "public_send", "(", "method", ",", "args", ",", "block", ")", "end" ]
Proxies missing methods to the store @param method [Symbol] the method name @param args [Array] the method arguments @param block [Proc] the code block @return [Object] the store method result
[ "Proxies", "missing", "methods", "to", "the", "store" ]
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/user_lookup.rb#L53-L56
7,442
lulibrary/aspire
lib/aspire/user_lookup.rb
Aspire.UserLookup.csv_to_json_api
def csv_to_json_api(row, data = {}, email_delim: nil, role_delim: nil) data['email'] = (row[4] || '').split(email_delim) data['firstName'] = row[0] data['role'] = (row[7] || '').split(role_delim) data['surname'] = row[1] data['uri'] = row[3] data end
ruby
def csv_to_json_api(row, data = {}, email_delim: nil, role_delim: nil) data['email'] = (row[4] || '').split(email_delim) data['firstName'] = row[0] data['role'] = (row[7] || '').split(role_delim) data['surname'] = row[1] data['uri'] = row[3] data end
[ "def", "csv_to_json_api", "(", "row", ",", "data", "=", "{", "}", ",", "email_delim", ":", "nil", ",", "role_delim", ":", "nil", ")", "data", "[", "'email'", "]", "=", "(", "row", "[", "4", "]", "||", "''", ")", ".", "split", "(", "email_delim", ")", "data", "[", "'firstName'", "]", "=", "row", "[", "0", "]", "data", "[", "'role'", "]", "=", "(", "row", "[", "7", "]", "||", "''", ")", ".", "split", "(", "role_delim", ")", "data", "[", "'surname'", "]", "=", "row", "[", "1", "]", "data", "[", "'uri'", "]", "=", "row", "[", "3", "]", "data", "end" ]
Adds CSV fields which mirror the Aspire user profile JSON API fields @param row [Array] the fields from the All User Profiles report CSV @param data [Hash] the JSON representation of the user profile @return [Hash] the JSON data hash
[ "Adds", "CSV", "fields", "which", "mirror", "the", "Aspire", "user", "profile", "JSON", "API", "fields" ]
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/user_lookup.rb#L80-L87
7,443
lulibrary/aspire
lib/aspire/user_lookup.rb
Aspire.UserLookup.csv_to_json_other
def csv_to_json_other(row, data = {}) # The following fields are not present in the JSON API response but are in # the All User Profiles report - they are included for completeness. data['jobRole'] = row[5] || '' data['lastLogin'] = row[8] data['name'] = row[2] || '' data['visibility'] = row[6] || '' data end
ruby
def csv_to_json_other(row, data = {}) # The following fields are not present in the JSON API response but are in # the All User Profiles report - they are included for completeness. data['jobRole'] = row[5] || '' data['lastLogin'] = row[8] data['name'] = row[2] || '' data['visibility'] = row[6] || '' data end
[ "def", "csv_to_json_other", "(", "row", ",", "data", "=", "{", "}", ")", "# The following fields are not present in the JSON API response but are in", "# the All User Profiles report - they are included for completeness.", "data", "[", "'jobRole'", "]", "=", "row", "[", "5", "]", "||", "''", "data", "[", "'lastLogin'", "]", "=", "row", "[", "8", "]", "data", "[", "'name'", "]", "=", "row", "[", "2", "]", "||", "''", "data", "[", "'visibility'", "]", "=", "row", "[", "6", "]", "||", "''", "data", "end" ]
Adds CSV fields which aren't part of the Aspire user profile JSON API @param row [Array] the fields from the All User Profiles report CSV @param data [Hash] the JSON representation of the user profile @return [Hash] the JSON data hash
[ "Adds", "CSV", "fields", "which", "aren", "t", "part", "of", "the", "Aspire", "user", "profile", "JSON", "API" ]
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/user_lookup.rb#L93-L101
7,444
cotag/couchbase-id
lib/couchbase-id/generator.rb
CouchbaseId.Generator.generate_id
def generate_id if self.id.nil? # # Generate the id (incrementing values as required) # overflow = self.class.__overflow__ ||= self.class.bucket.get("#{self.class.design_document}:#{CLUSTER_ID}:overflow", :quiet => true) # Don't error if not there count = self.class.bucket.incr("#{self.class.design_document}:#{CLUSTER_ID}:count", :create => true) # This models current id count if count == 0 || overflow.nil? overflow ||= 0 overflow += 1 # We shouldn't need to worry about concurrency here due to the size of count # Would require ~18446744073709551615 concurrent writes self.class.bucket.set("#{self.class.design_document}:#{CLUSTER_ID}:overflow", overflow) self.class.__overflow__ = overflow end self.id = self.class.__class_id_generator__.call(overflow, count) # # So an existing id would only be present if: # => something crashed before incrementing the overflow # => this is another request was occurring before the overflow is incremented # # Basically only the overflow should be able to cause issues, we'll increment the count just to be sure # One would hope this code only ever runs under high load during an overflow event # while self.class.bucket.get(self.id, :quiet => true).present? # Set in-case we are here due to a crash (concurrency is not an issue) # Note we are not incrementing the @__overflow__ variable self.class.bucket.set("#{self.class.design_document}:#{CLUSTER_ID}:overflow", overflow + 1) count = self.class.bucket.incr("#{self.class.design_document}:#{CLUSTER_ID}:count") # Increment just in case (attempt to avoid infinite loops) # Reset the overflow if self.class.__overflow__ == overflow self.class.__overflow__ = nil end # Generate the new id self.id = self.class.__class_id_generator__.call(overflow + 1, count) end end end
ruby
def generate_id if self.id.nil? # # Generate the id (incrementing values as required) # overflow = self.class.__overflow__ ||= self.class.bucket.get("#{self.class.design_document}:#{CLUSTER_ID}:overflow", :quiet => true) # Don't error if not there count = self.class.bucket.incr("#{self.class.design_document}:#{CLUSTER_ID}:count", :create => true) # This models current id count if count == 0 || overflow.nil? overflow ||= 0 overflow += 1 # We shouldn't need to worry about concurrency here due to the size of count # Would require ~18446744073709551615 concurrent writes self.class.bucket.set("#{self.class.design_document}:#{CLUSTER_ID}:overflow", overflow) self.class.__overflow__ = overflow end self.id = self.class.__class_id_generator__.call(overflow, count) # # So an existing id would only be present if: # => something crashed before incrementing the overflow # => this is another request was occurring before the overflow is incremented # # Basically only the overflow should be able to cause issues, we'll increment the count just to be sure # One would hope this code only ever runs under high load during an overflow event # while self.class.bucket.get(self.id, :quiet => true).present? # Set in-case we are here due to a crash (concurrency is not an issue) # Note we are not incrementing the @__overflow__ variable self.class.bucket.set("#{self.class.design_document}:#{CLUSTER_ID}:overflow", overflow + 1) count = self.class.bucket.incr("#{self.class.design_document}:#{CLUSTER_ID}:count") # Increment just in case (attempt to avoid infinite loops) # Reset the overflow if self.class.__overflow__ == overflow self.class.__overflow__ = nil end # Generate the new id self.id = self.class.__class_id_generator__.call(overflow + 1, count) end end end
[ "def", "generate_id", "if", "self", ".", "id", ".", "nil?", "#", "# Generate the id (incrementing values as required)", "#", "overflow", "=", "self", ".", "class", ".", "__overflow__", "||=", "self", ".", "class", ".", "bucket", ".", "get", "(", "\"#{self.class.design_document}:#{CLUSTER_ID}:overflow\"", ",", ":quiet", "=>", "true", ")", "# Don't error if not there", "count", "=", "self", ".", "class", ".", "bucket", ".", "incr", "(", "\"#{self.class.design_document}:#{CLUSTER_ID}:count\"", ",", ":create", "=>", "true", ")", "# This models current id count", "if", "count", "==", "0", "||", "overflow", ".", "nil?", "overflow", "||=", "0", "overflow", "+=", "1", "# We shouldn't need to worry about concurrency here due to the size of count", "# Would require ~18446744073709551615 concurrent writes", "self", ".", "class", ".", "bucket", ".", "set", "(", "\"#{self.class.design_document}:#{CLUSTER_ID}:overflow\"", ",", "overflow", ")", "self", ".", "class", ".", "__overflow__", "=", "overflow", "end", "self", ".", "id", "=", "self", ".", "class", ".", "__class_id_generator__", ".", "call", "(", "overflow", ",", "count", ")", "#", "# So an existing id would only be present if:", "# => something crashed before incrementing the overflow", "# => this is another request was occurring before the overflow is incremented", "#", "# Basically only the overflow should be able to cause issues, we'll increment the count just to be sure", "# One would hope this code only ever runs under high load during an overflow event", "#", "while", "self", ".", "class", ".", "bucket", ".", "get", "(", "self", ".", "id", ",", ":quiet", "=>", "true", ")", ".", "present?", "# Set in-case we are here due to a crash (concurrency is not an issue)", "# Note we are not incrementing the @__overflow__ variable", "self", ".", "class", ".", "bucket", ".", "set", "(", "\"#{self.class.design_document}:#{CLUSTER_ID}:overflow\"", ",", "overflow", "+", "1", ")", "count", "=", "self", ".", "class", ".", "bucket", ".", "incr", "(", "\"#{self.class.design_document}:#{CLUSTER_ID}:count\"", ")", "# Increment just in case (attempt to avoid infinite loops)", "# Reset the overflow", "if", "self", ".", "class", ".", "__overflow__", "==", "overflow", "self", ".", "class", ".", "__overflow__", "=", "nil", "end", "# Generate the new id", "self", ".", "id", "=", "self", ".", "class", ".", "__class_id_generator__", ".", "call", "(", "overflow", "+", "1", ",", "count", ")", "end", "end", "end" ]
Cluster ID number instance method
[ "Cluster", "ID", "number", "instance", "method" ]
d62bf8d72aa4cda4603104f2e2f1b81e8f4e88e4
https://github.com/cotag/couchbase-id/blob/d62bf8d72aa4cda4603104f2e2f1b81e8f4e88e4/lib/couchbase-id/generator.rb#L36-L78
7,445
PragTob/wingtips
lib/wingtips/dsl.rb
Wingtips.DSL.merge_template_options
def merge_template_options(default_options, template_key, custom_options = {}) template_options = configuration.template_options.fetch template_key, {} options = Wingtips::HashUtils.deep_merge(default_options, template_options) Wingtips::HashUtils.deep_merge(options, custom_options) end
ruby
def merge_template_options(default_options, template_key, custom_options = {}) template_options = configuration.template_options.fetch template_key, {} options = Wingtips::HashUtils.deep_merge(default_options, template_options) Wingtips::HashUtils.deep_merge(options, custom_options) end
[ "def", "merge_template_options", "(", "default_options", ",", "template_key", ",", "custom_options", "=", "{", "}", ")", "template_options", "=", "configuration", ".", "template_options", ".", "fetch", "template_key", ",", "{", "}", "options", "=", "Wingtips", "::", "HashUtils", ".", "deep_merge", "(", "default_options", ",", "template_options", ")", "Wingtips", "::", "HashUtils", ".", "deep_merge", "(", "options", ",", "custom_options", ")", "end" ]
merge order is = defaults, template, custom
[ "merge", "order", "is", "=", "defaults", "template", "custom" ]
df47ecdf19fdd9e7091e96232a24c2d7fb43a3ab
https://github.com/PragTob/wingtips/blob/df47ecdf19fdd9e7091e96232a24c2d7fb43a3ab/lib/wingtips/dsl.rb#L40-L44
7,446
feduxorg/the_array_comparator
lib/the_array_comparator/cache.rb
TheArrayComparator.Cache.add
def add(cache, strategy) c = cache.to_sym s = strategy.to_sym fail Exceptions::UnknownCachingStrategy, "Unknown caching strategy \":#{strategy}\" given. Did you register it in advance?" unless caching_strategies.key?(strategy) caches[c] = caching_strategies[s].new caches[c] end
ruby
def add(cache, strategy) c = cache.to_sym s = strategy.to_sym fail Exceptions::UnknownCachingStrategy, "Unknown caching strategy \":#{strategy}\" given. Did you register it in advance?" unless caching_strategies.key?(strategy) caches[c] = caching_strategies[s].new caches[c] end
[ "def", "add", "(", "cache", ",", "strategy", ")", "c", "=", "cache", ".", "to_sym", "s", "=", "strategy", ".", "to_sym", "fail", "Exceptions", "::", "UnknownCachingStrategy", ",", "\"Unknown caching strategy \\\":#{strategy}\\\" given. Did you register it in advance?\"", "unless", "caching_strategies", ".", "key?", "(", "strategy", ")", "caches", "[", "c", "]", "=", "caching_strategies", "[", "s", "]", ".", "new", "caches", "[", "c", "]", "end" ]
Add a new cache @param [Symbol] cache the cache to be created @param [Symbol] strategy the cache strategy to be used
[ "Add", "a", "new", "cache" ]
66cdaf953909a34366cbee2b519dfcf306bc03c7
https://github.com/feduxorg/the_array_comparator/blob/66cdaf953909a34366cbee2b519dfcf306bc03c7/lib/the_array_comparator/cache.rb#L54-L62
7,447
wooandoo/motion-pool
motion/common/term.rb
Term.ANSIColor.uncolored
def uncolored(string = nil) # :yields: if block_given? yield.gsub(COLORED_REGEXP, '') elsif string string.gsub(COLORED_REGEXP, '') elsif respond_to?(:to_str) gsub(COLORED_REGEXP, '') else '' end end
ruby
def uncolored(string = nil) # :yields: if block_given? yield.gsub(COLORED_REGEXP, '') elsif string string.gsub(COLORED_REGEXP, '') elsif respond_to?(:to_str) gsub(COLORED_REGEXP, '') else '' end end
[ "def", "uncolored", "(", "string", "=", "nil", ")", "# :yields:", "if", "block_given?", "yield", ".", "gsub", "(", "COLORED_REGEXP", ",", "''", ")", "elsif", "string", "string", ".", "gsub", "(", "COLORED_REGEXP", ",", "''", ")", "elsif", "respond_to?", "(", ":to_str", ")", "gsub", "(", "COLORED_REGEXP", ",", "''", ")", "else", "''", "end", "end" ]
Returns an uncolored version of the string, that is all ANSI-sequences are stripped from the string.
[ "Returns", "an", "uncolored", "version", "of", "the", "string", "that", "is", "all", "ANSI", "-", "sequences", "are", "stripped", "from", "the", "string", "." ]
e0a8b56a096e7bcf90a60d3ae0f62018e92dcf2b
https://github.com/wooandoo/motion-pool/blob/e0a8b56a096e7bcf90a60d3ae0f62018e92dcf2b/motion/common/term.rb#L536-L546
7,448
riddopic/garcun
lib/garcon/task/atomic.rb
Garcon.AtomicDirectUpdate.try_update
def try_update old_value = get new_value = yield old_value unless compare_and_set(old_value, new_value) raise ConcurrentUpdateError, "Update failed" end new_value end
ruby
def try_update old_value = get new_value = yield old_value unless compare_and_set(old_value, new_value) raise ConcurrentUpdateError, "Update failed" end new_value end
[ "def", "try_update", "old_value", "=", "get", "new_value", "=", "yield", "old_value", "unless", "compare_and_set", "(", "old_value", ",", "new_value", ")", "raise", "ConcurrentUpdateError", ",", "\"Update failed\"", "end", "new_value", "end" ]
Pass the current value to the given block, replacing it with the block's result. Raise an exception if the update fails. @yield [Object] Calculate a new value for the atomic reference using given (old) value. @yieldparam [Object] old_value The starting value of the atomic reference. @raise [Garcon::ConcurrentUpdateError] If the update fails @return [Object] the new value
[ "Pass", "the", "current", "value", "to", "the", "given", "block", "replacing", "it", "with", "the", "block", "s", "result", ".", "Raise", "an", "exception", "if", "the", "update", "fails", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/atomic.rb#L51-L58
7,449
riddopic/garcun
lib/garcon/task/atomic.rb
Garcon.AtomicMutex._compare_and_set
def _compare_and_set(old_value, new_value) return false unless @mutex.try_lock begin return false unless @value.equal? old_value @value = new_value ensure @mutex.unlock end true end
ruby
def _compare_and_set(old_value, new_value) return false unless @mutex.try_lock begin return false unless @value.equal? old_value @value = new_value ensure @mutex.unlock end true end
[ "def", "_compare_and_set", "(", "old_value", ",", "new_value", ")", "return", "false", "unless", "@mutex", ".", "try_lock", "begin", "return", "false", "unless", "@value", ".", "equal?", "old_value", "@value", "=", "new_value", "ensure", "@mutex", ".", "unlock", "end", "true", "end" ]
Atomically sets the value to the given updated value if the current value is equal the expected value. @param [Object] old_value The expected value. @param [Object] new_value The new value. @return [Boolean] `true` if successful, `false` indicates that the actual value was not equal to the expected value.
[ "Atomically", "sets", "the", "value", "to", "the", "given", "updated", "value", "if", "the", "current", "value", "is", "equal", "the", "expected", "value", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/atomic.rb#L140-L149
7,450
avdgaag/whenner
lib/whenner/deferred.rb
Whenner.Deferred.fulfill
def fulfill(value = nil) raise CannotTransitionError if rejected? return if fulfilled? unless resolved? self.value = value resolve_to(:fulfilled) end self end
ruby
def fulfill(value = nil) raise CannotTransitionError if rejected? return if fulfilled? unless resolved? self.value = value resolve_to(:fulfilled) end self end
[ "def", "fulfill", "(", "value", "=", "nil", ")", "raise", "CannotTransitionError", "if", "rejected?", "return", "if", "fulfilled?", "unless", "resolved?", "self", ".", "value", "=", "value", "resolve_to", "(", ":fulfilled", ")", "end", "self", "end" ]
Fulfill this promise with an optional value. The value will be stored in the deferred and passed along to any registered `done` callbacks. When fulfilling a deferred twice, nothing happens. @raise [CannotTransitionError] when it was already fulfilled. @return [Deferred] self
[ "Fulfill", "this", "promise", "with", "an", "optional", "value", ".", "The", "value", "will", "be", "stored", "in", "the", "deferred", "and", "passed", "along", "to", "any", "registered", "done", "callbacks", "." ]
f27331435402648d02377bef9fce9ff8ae84845a
https://github.com/avdgaag/whenner/blob/f27331435402648d02377bef9fce9ff8ae84845a/lib/whenner/deferred.rb#L76-L84
7,451
avdgaag/whenner
lib/whenner/deferred.rb
Whenner.Deferred.reject
def reject(reason = nil) raise CannotTransitionError if fulfilled? return if rejected? unless resolved? self.reason = reason resolve_to(:rejected) end self end
ruby
def reject(reason = nil) raise CannotTransitionError if fulfilled? return if rejected? unless resolved? self.reason = reason resolve_to(:rejected) end self end
[ "def", "reject", "(", "reason", "=", "nil", ")", "raise", "CannotTransitionError", "if", "fulfilled?", "return", "if", "rejected?", "unless", "resolved?", "self", ".", "reason", "=", "reason", "resolve_to", "(", ":rejected", ")", "end", "self", "end" ]
Reject this promise with an optional reason. The reason will be stored in the deferred and passed along to any registered `fail` callbacks. When rejecting a deferred twice, nothing happens. @raise [CannotTransitionError] when it was already fulfilled. @return [Deferred] self
[ "Reject", "this", "promise", "with", "an", "optional", "reason", ".", "The", "reason", "will", "be", "stored", "in", "the", "deferred", "and", "passed", "along", "to", "any", "registered", "fail", "callbacks", "." ]
f27331435402648d02377bef9fce9ff8ae84845a
https://github.com/avdgaag/whenner/blob/f27331435402648d02377bef9fce9ff8ae84845a/lib/whenner/deferred.rb#L93-L101
7,452
avdgaag/whenner
lib/whenner/deferred.rb
Whenner.Deferred.fail
def fail(&block) cb = Callback.new(block) rejected_callbacks << cb cb.call(*callback_response) if rejected? cb.promise end
ruby
def fail(&block) cb = Callback.new(block) rejected_callbacks << cb cb.call(*callback_response) if rejected? cb.promise end
[ "def", "fail", "(", "&", "block", ")", "cb", "=", "Callback", ".", "new", "(", "block", ")", "rejected_callbacks", "<<", "cb", "cb", ".", "call", "(", "callback_response", ")", "if", "rejected?", "cb", ".", "promise", "end" ]
Register a callback to be run when the deferred is rejected. @yieldparam [Object] reason @return [Promise] a new promise representing the return value of the callback, or -- when that return value is a promise itself -- a promise mimicking that promise.
[ "Register", "a", "callback", "to", "be", "run", "when", "the", "deferred", "is", "rejected", "." ]
f27331435402648d02377bef9fce9ff8ae84845a
https://github.com/avdgaag/whenner/blob/f27331435402648d02377bef9fce9ff8ae84845a/lib/whenner/deferred.rb#L147-L152
7,453
avdgaag/whenner
lib/whenner/deferred.rb
Whenner.Deferred.always
def always(&block) cb = Callback.new(block) always_callbacks << cb cb.call(*callback_response) if resolved? cb.promise end
ruby
def always(&block) cb = Callback.new(block) always_callbacks << cb cb.call(*callback_response) if resolved? cb.promise end
[ "def", "always", "(", "&", "block", ")", "cb", "=", "Callback", ".", "new", "(", "block", ")", "always_callbacks", "<<", "cb", "cb", ".", "call", "(", "callback_response", ")", "if", "resolved?", "cb", ".", "promise", "end" ]
Register a callback to be run when the deferred is resolved. @yieldparam [Object] value @yieldparam [Object] reason @return [Promise] a new promise representing the return value of the callback, or -- when that return value is a promise itself -- a promise mimicking that promise.
[ "Register", "a", "callback", "to", "be", "run", "when", "the", "deferred", "is", "resolved", "." ]
f27331435402648d02377bef9fce9ff8ae84845a
https://github.com/avdgaag/whenner/blob/f27331435402648d02377bef9fce9ff8ae84845a/lib/whenner/deferred.rb#L161-L166
7,454
garytaylor/capybara_objects
lib/capybara_objects/scoped_finders.rb
CapybaraObjects.ScopedFinders.get_component
def get_component(ctype, *args) registry.lookup_ctype(ctype).new(*args).tap do |comp| comp.scope = full_scope comp.validate! end end
ruby
def get_component(ctype, *args) registry.lookup_ctype(ctype).new(*args).tap do |comp| comp.scope = full_scope comp.validate! end end
[ "def", "get_component", "(", "ctype", ",", "*", "args", ")", "registry", ".", "lookup_ctype", "(", "ctype", ")", ".", "new", "(", "args", ")", ".", "tap", "do", "|", "comp", "|", "comp", ".", "scope", "=", "full_scope", "comp", ".", "validate!", "end", "end" ]
Fetch a component from within this component @TODO Make this operate within the scope @TODO Pass the scope on to any found instances @param [String|Symbol] ctype The component alias to find @param [Any] args Any further arguments are passed on to the instance of the component @return [CapybaraObjects::ComponentObject] An instance inheriting from the component object
[ "Fetch", "a", "component", "from", "within", "this", "component" ]
7cc2998400a35ceb6f9354cdf949fc59eddcdb12
https://github.com/garytaylor/capybara_objects/blob/7cc2998400a35ceb6f9354cdf949fc59eddcdb12/lib/capybara_objects/scoped_finders.rb#L12-L17
7,455
AvnerCohen/service-jynx
lib/service_jynx.rb
ServiceJynx.Jynx.clean_aged
def clean_aged(time_now) near_past = time_now - @time_window_in_seconds @errors = @errors.reverse.select{|time_stamp| time_stamp > near_past }.reverse.to_a end
ruby
def clean_aged(time_now) near_past = time_now - @time_window_in_seconds @errors = @errors.reverse.select{|time_stamp| time_stamp > near_past }.reverse.to_a end
[ "def", "clean_aged", "(", "time_now", ")", "near_past", "=", "time_now", "-", "@time_window_in_seconds", "@errors", "=", "@errors", ".", "reverse", ".", "select", "{", "|", "time_stamp", "|", "time_stamp", ">", "near_past", "}", ".", "reverse", ".", "to_a", "end" ]
clean up errors that are older than time_window_in_secons
[ "clean", "up", "errors", "that", "are", "older", "than", "time_window_in_secons" ]
01f21aee273d12021d20e5d7b97e13ec6b9bc291
https://github.com/AvnerCohen/service-jynx/blob/01f21aee273d12021d20e5d7b97e13ec6b9bc291/lib/service_jynx.rb#L63-L66
7,456
ErikSchlyter/rspec-illustrate
lib/rspec/illustrate.rb
RSpec.Illustrate.illustrate
def illustrate(content, *args) illustration = { :text => content.to_s, :show_when_passed => true, :show_when_failed => true, :show_when_pending => true } args.each{|arg| illustration[arg] = true if arg.is_a?(Symbol) illustration.merge!(arg) if arg.kind_of?(Hash) } RSpec.current_example.metadata[:illustrations] << illustration content end
ruby
def illustrate(content, *args) illustration = { :text => content.to_s, :show_when_passed => true, :show_when_failed => true, :show_when_pending => true } args.each{|arg| illustration[arg] = true if arg.is_a?(Symbol) illustration.merge!(arg) if arg.kind_of?(Hash) } RSpec.current_example.metadata[:illustrations] << illustration content end
[ "def", "illustrate", "(", "content", ",", "*", "args", ")", "illustration", "=", "{", ":text", "=>", "content", ".", "to_s", ",", ":show_when_passed", "=>", "true", ",", ":show_when_failed", "=>", "true", ",", ":show_when_pending", "=>", "true", "}", "args", ".", "each", "{", "|", "arg", "|", "illustration", "[", "arg", "]", "=", "true", "if", "arg", ".", "is_a?", "(", "Symbol", ")", "illustration", ".", "merge!", "(", "arg", ")", "if", "arg", ".", "kind_of?", "(", "Hash", ")", "}", "RSpec", ".", "current_example", ".", "metadata", "[", ":illustrations", "]", "<<", "illustration", "content", "end" ]
Stores an object in the surrounding example's metadata, which can be used by the output formatter as an illustration for the example. @param content The object that will act as an illustration. @param args [Array<Hash, Symbol>] Additional options. @return The given illustration object.
[ "Stores", "an", "object", "in", "the", "surrounding", "example", "s", "metadata", "which", "can", "be", "used", "by", "the", "output", "formatter", "as", "an", "illustration", "for", "the", "example", "." ]
f9275bdb5cc86642bee187acf327ee3c3d311577
https://github.com/ErikSchlyter/rspec-illustrate/blob/f9275bdb5cc86642bee187acf327ee3c3d311577/lib/rspec/illustrate.rb#L14-L27
7,457
avdgaag/observatory
lib/observatory/dispatcher.rb
Observatory.Dispatcher.connect
def connect(signal, *args, &block) # ugly argument parsing. # Make sure that there is either a block given, or that the second argument is # something callable. If there is a block given, the second argument, if given, # must be a Hash which defaults to an empty Hash. If there is no block given, # the third optional argument must be Hash. if block_given? observer = block if args.size == 1 && args.first.is_a?(Hash) options = args.first elsif args.size == 0 options = {} else raise ArgumentError, 'When given a block, #connect only expects a signal and options hash as arguments' end else observer = args.shift raise ArgumentError, 'Use a block, method or proc to specify an observer' unless observer.respond_to?(:call) if args.any? options = args.shift raise ArgumentError, '#connect only expects a signal, method and options hash as arguments' unless options.is_a?(Hash) || args.any? else options = {} end end # Initialize the list of observers for this signal and add this observer observers[signal] ||= Stack.new observers[signal].push(observer, options[:priority]) end
ruby
def connect(signal, *args, &block) # ugly argument parsing. # Make sure that there is either a block given, or that the second argument is # something callable. If there is a block given, the second argument, if given, # must be a Hash which defaults to an empty Hash. If there is no block given, # the third optional argument must be Hash. if block_given? observer = block if args.size == 1 && args.first.is_a?(Hash) options = args.first elsif args.size == 0 options = {} else raise ArgumentError, 'When given a block, #connect only expects a signal and options hash as arguments' end else observer = args.shift raise ArgumentError, 'Use a block, method or proc to specify an observer' unless observer.respond_to?(:call) if args.any? options = args.shift raise ArgumentError, '#connect only expects a signal, method and options hash as arguments' unless options.is_a?(Hash) || args.any? else options = {} end end # Initialize the list of observers for this signal and add this observer observers[signal] ||= Stack.new observers[signal].push(observer, options[:priority]) end
[ "def", "connect", "(", "signal", ",", "*", "args", ",", "&", "block", ")", "# ugly argument parsing.", "# Make sure that there is either a block given, or that the second argument is", "# something callable. If there is a block given, the second argument, if given,", "# must be a Hash which defaults to an empty Hash. If there is no block given,", "# the third optional argument must be Hash.", "if", "block_given?", "observer", "=", "block", "if", "args", ".", "size", "==", "1", "&&", "args", ".", "first", ".", "is_a?", "(", "Hash", ")", "options", "=", "args", ".", "first", "elsif", "args", ".", "size", "==", "0", "options", "=", "{", "}", "else", "raise", "ArgumentError", ",", "'When given a block, #connect only expects a signal and options hash as arguments'", "end", "else", "observer", "=", "args", ".", "shift", "raise", "ArgumentError", ",", "'Use a block, method or proc to specify an observer'", "unless", "observer", ".", "respond_to?", "(", ":call", ")", "if", "args", ".", "any?", "options", "=", "args", ".", "shift", "raise", "ArgumentError", ",", "'#connect only expects a signal, method and options hash as arguments'", "unless", "options", ".", "is_a?", "(", "Hash", ")", "||", "args", ".", "any?", "else", "options", "=", "{", "}", "end", "end", "# Initialize the list of observers for this signal and add this observer", "observers", "[", "signal", "]", "||=", "Stack", ".", "new", "observers", "[", "signal", "]", ".", "push", "(", "observer", ",", "options", "[", ":priority", "]", ")", "end" ]
Register a observer for a given signal. Instead of adding a method or Proc object to the stack, you could also use a block. Either the observer argument or the block is required. Optionally, you could pass in an options hash as the last argument, that can specify an explicit priority. When omitted, an internal counter starting from 1 will be used. To make sure your observer is called last, specify a high, **positive** number. To make sure your observer is called first, specify a high, **negative** number. @example Using a block as an observer dispatcher.connect('post.publish') do |event| puts "Post was published" end @example Using a method as an observer class Reporter def log(event) puts "Post published" end end dispatcher.connect('post.publish', Reporter.new.method(:log)) @example Determining observer call order using priority dispatcher.connect('pulp', :priority => 10) do puts "I dare you!" end dispatcher.connect('pulp', :priority => -10) do puts "I double-dare you!" end # output when "pulp" is triggered: "I double-dare you!" "I dare you!" @overload connect(signal, observer, options = {}) @param [String] signal is the name used by the observable to trigger observers @param [#call] observer is the Proc or method that will react to an event issued by an observable. @param [Hash] options is an optional Hash of additional options. @option options [Fixnum] :priority is the priority of this observer in the stack of all observers for this signal. A higher number means lower priority. Negative numbers are allowed. @overload connect(signal, options = {}, &block) @param [String] signal is the name used by the observable to trigger observers @param [Hash] options is an optional Hash of additional options. @option options [Fixnum] :priority is the priority of this observer in the stack of all observers for this signal. A higher number means lower priority. Negative numbers are allowed. @return [#call] the added observer
[ "Register", "a", "observer", "for", "a", "given", "signal", "." ]
af8fdb445c42f425067ac97c39fcdbef5ebac73e
https://github.com/avdgaag/observatory/blob/af8fdb445c42f425067ac97c39fcdbef5ebac73e/lib/observatory/dispatcher.rb#L132-L161
7,458
avdgaag/observatory
lib/observatory/dispatcher.rb
Observatory.Dispatcher.disconnect
def disconnect(signal, observer) return nil unless observers.key?(signal) observers[signal].delete(observer) end
ruby
def disconnect(signal, observer) return nil unless observers.key?(signal) observers[signal].delete(observer) end
[ "def", "disconnect", "(", "signal", ",", "observer", ")", "return", "nil", "unless", "observers", ".", "key?", "(", "signal", ")", "observers", "[", "signal", "]", ".", "delete", "(", "observer", ")", "end" ]
Removes an observer from a signal stack, so it no longer gets triggered. @param [String] signal is the name of the stack to remove the observer from. @param [#call] observer is the original observer to remove. @return [#call, nil] the removed observer or nil if it could not be found
[ "Removes", "an", "observer", "from", "a", "signal", "stack", "so", "it", "no", "longer", "gets", "triggered", "." ]
af8fdb445c42f425067ac97c39fcdbef5ebac73e
https://github.com/avdgaag/observatory/blob/af8fdb445c42f425067ac97c39fcdbef5ebac73e/lib/observatory/dispatcher.rb#L169-L172
7,459
wedesoft/multiarray
lib/multiarray/gcctype.rb
Hornetseye.GCCType.identifier
def identifier case @typecode when nil 'void' when BOOL 'char' when BYTE 'char' when UBYTE 'unsigned char' when SINT 'short int' when USINT 'unsigned short int' when INT 'int' when UINT 'unsigned int' when SFLOAT 'float' when DFLOAT 'double' else if @typecode < Pointer_ 'unsigned char *' elsif @typecode < INDEX_ 'int' else raise "No identifier available for #{@typecode.inspect}" end end end
ruby
def identifier case @typecode when nil 'void' when BOOL 'char' when BYTE 'char' when UBYTE 'unsigned char' when SINT 'short int' when USINT 'unsigned short int' when INT 'int' when UINT 'unsigned int' when SFLOAT 'float' when DFLOAT 'double' else if @typecode < Pointer_ 'unsigned char *' elsif @typecode < INDEX_ 'int' else raise "No identifier available for #{@typecode.inspect}" end end end
[ "def", "identifier", "case", "@typecode", "when", "nil", "'void'", "when", "BOOL", "'char'", "when", "BYTE", "'char'", "when", "UBYTE", "'unsigned char'", "when", "SINT", "'short int'", "when", "USINT", "'unsigned short int'", "when", "INT", "'int'", "when", "UINT", "'unsigned int'", "when", "SFLOAT", "'float'", "when", "DFLOAT", "'double'", "else", "if", "@typecode", "<", "Pointer_", "'unsigned char *'", "elsif", "@typecode", "<", "INDEX_", "'int'", "else", "raise", "\"No identifier available for #{@typecode.inspect}\"", "end", "end", "end" ]
Construct GCC type @param [Class] typecode Native type (e.g. +UBYTE+). @private Get C identifier for native type @return [String] String with valid C syntax to declare type. @private
[ "Construct", "GCC", "type" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gcctype.rb#L39-L70
7,460
wedesoft/multiarray
lib/multiarray/gcctype.rb
Hornetseye.GCCType.identifiers
def identifiers if @typecode < Composite GCCType.new( @typecode.element_type ).identifiers * @typecode.num_elements else [ GCCType.new( @typecode ).identifier ] end end
ruby
def identifiers if @typecode < Composite GCCType.new( @typecode.element_type ).identifiers * @typecode.num_elements else [ GCCType.new( @typecode ).identifier ] end end
[ "def", "identifiers", "if", "@typecode", "<", "Composite", "GCCType", ".", "new", "(", "@typecode", ".", "element_type", ")", ".", "identifiers", "*", "@typecode", ".", "num_elements", "else", "[", "GCCType", ".", "new", "(", "@typecode", ")", ".", "identifier", "]", "end", "end" ]
Get array of C identifiers for native type @return [Array<String>] Array of C declarations for the elements of the type. @private
[ "Get", "array", "of", "C", "identifiers", "for", "native", "type" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gcctype.rb#L77-L83
7,461
wedesoft/multiarray
lib/multiarray/gcctype.rb
Hornetseye.GCCType.r2c
def r2c case @typecode when BOOL [ proc { |expr| "( #{expr} ) != Qfalse" } ] when BYTE, UBYTE, SINT, USINT, INT, UINT [ proc { |expr| "NUM2INT( #{expr} )" } ] when SFLOAT, DFLOAT [ proc { |expr| "NUM2DBL( #{expr} )" } ] else if @typecode < Pointer_ [ proc { |expr| "(#{identifier})mallocToPtr( #{expr} )" } ] elsif @typecode < Composite GCCType.new( @typecode.element_type ).r2c * @typecode.num_elements else raise "No conversion available for #{@typecode.inspect}" end end end
ruby
def r2c case @typecode when BOOL [ proc { |expr| "( #{expr} ) != Qfalse" } ] when BYTE, UBYTE, SINT, USINT, INT, UINT [ proc { |expr| "NUM2INT( #{expr} )" } ] when SFLOAT, DFLOAT [ proc { |expr| "NUM2DBL( #{expr} )" } ] else if @typecode < Pointer_ [ proc { |expr| "(#{identifier})mallocToPtr( #{expr} )" } ] elsif @typecode < Composite GCCType.new( @typecode.element_type ).r2c * @typecode.num_elements else raise "No conversion available for #{@typecode.inspect}" end end end
[ "def", "r2c", "case", "@typecode", "when", "BOOL", "[", "proc", "{", "|", "expr", "|", "\"( #{expr} ) != Qfalse\"", "}", "]", "when", "BYTE", ",", "UBYTE", ",", "SINT", ",", "USINT", ",", "INT", ",", "UINT", "[", "proc", "{", "|", "expr", "|", "\"NUM2INT( #{expr} )\"", "}", "]", "when", "SFLOAT", ",", "DFLOAT", "[", "proc", "{", "|", "expr", "|", "\"NUM2DBL( #{expr} )\"", "}", "]", "else", "if", "@typecode", "<", "Pointer_", "[", "proc", "{", "|", "expr", "|", "\"(#{identifier})mallocToPtr( #{expr} )\"", "}", "]", "elsif", "@typecode", "<", "Composite", "GCCType", ".", "new", "(", "@typecode", ".", "element_type", ")", ".", "r2c", "*", "@typecode", ".", "num_elements", "else", "raise", "\"No conversion available for #{@typecode.inspect}\"", "end", "end", "end" ]
Get code for converting Ruby VALUE to C value This method returns a nameless function. The nameless function is used for getting the code to convert a given parameter to a C value of this type. @return [Proc] Nameless function accepting a C expression to be converted. @private
[ "Get", "code", "for", "converting", "Ruby", "VALUE", "to", "C", "value" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gcctype.rb#L93-L110
7,462
ozgg/weighted-select
lib/weighted-select.rb
WeightedSelect.Selector.add
def add(item, weight) delta = Integer(weight) if delta > 0 new_weight = @total_weight + delta weights[@total_weight...new_weight] = item @total_weight = new_weight end end
ruby
def add(item, weight) delta = Integer(weight) if delta > 0 new_weight = @total_weight + delta weights[@total_weight...new_weight] = item @total_weight = new_weight end end
[ "def", "add", "(", "item", ",", "weight", ")", "delta", "=", "Integer", "(", "weight", ")", "if", "delta", ">", "0", "new_weight", "=", "@total_weight", "+", "delta", "weights", "[", "@total_weight", "...", "new_weight", "]", "=", "item", "@total_weight", "=", "new_weight", "end", "end" ]
Sets initial weights Accepts Hash as an argument, where keys are items and corresponding values are their weights (positive integers). @param [Hash] weights Add item with weight @param [Object] item @param [Integer] weight
[ "Sets", "initial", "weights" ]
5cf3a8a1f2ba74f2885dcc8111396e5ca10ccad4
https://github.com/ozgg/weighted-select/blob/5cf3a8a1f2ba74f2885dcc8111396e5ca10ccad4/lib/weighted-select.rb#L23-L30
7,463
ozgg/weighted-select
lib/weighted-select.rb
WeightedSelect.Selector.extract_item
def extract_item weight = Random.rand(@total_weight) @weights.each do |range, item| return item if range === weight end end
ruby
def extract_item weight = Random.rand(@total_weight) @weights.each do |range, item| return item if range === weight end end
[ "def", "extract_item", "weight", "=", "Random", ".", "rand", "(", "@total_weight", ")", "@weights", ".", "each", "do", "|", "range", ",", "item", "|", "return", "item", "if", "range", "===", "weight", "end", "end" ]
Extract item based on weights distribution @return [Object]
[ "Extract", "item", "based", "on", "weights", "distribution" ]
5cf3a8a1f2ba74f2885dcc8111396e5ca10ccad4
https://github.com/ozgg/weighted-select/blob/5cf3a8a1f2ba74f2885dcc8111396e5ca10ccad4/lib/weighted-select.rb#L44-L49
7,464
knuedge/off_the_grid
lib/off_the_grid/host_group.rb
OffTheGrid.HostGroup.entries
def entries extract_detail(:hostlist).map do |host| host =~ /^@/ ? HostGroup.new(host) : ExecuteHost.new(host) end end
ruby
def entries extract_detail(:hostlist).map do |host| host =~ /^@/ ? HostGroup.new(host) : ExecuteHost.new(host) end end
[ "def", "entries", "extract_detail", "(", ":hostlist", ")", ".", "map", "do", "|", "host", "|", "host", "=~", "/", "/", "?", "HostGroup", ".", "new", "(", "host", ")", ":", "ExecuteHost", ".", "new", "(", "host", ")", "end", "end" ]
Direct entries in this HostGroup's hostlist attribute
[ "Direct", "entries", "in", "this", "HostGroup", "s", "hostlist", "attribute" ]
cf367b6d22de5c73da2e2550e1f45e103a219a51
https://github.com/knuedge/off_the_grid/blob/cf367b6d22de5c73da2e2550e1f45e103a219a51/lib/off_the_grid/host_group.rb#L20-L24
7,465
knuedge/off_the_grid
lib/off_the_grid/host_group.rb
OffTheGrid.HostGroup.hosts
def hosts entries.map do |entry| entry.is_a?(HostGroup) ? entry.hosts : entry end.flatten.uniq end
ruby
def hosts entries.map do |entry| entry.is_a?(HostGroup) ? entry.hosts : entry end.flatten.uniq end
[ "def", "hosts", "entries", ".", "map", "do", "|", "entry", "|", "entry", ".", "is_a?", "(", "HostGroup", ")", "?", "entry", ".", "hosts", ":", "entry", "end", ".", "flatten", ".", "uniq", "end" ]
A recursive listing of all hosts associated with this HostGroup
[ "A", "recursive", "listing", "of", "all", "hosts", "associated", "with", "this", "HostGroup" ]
cf367b6d22de5c73da2e2550e1f45e103a219a51
https://github.com/knuedge/off_the_grid/blob/cf367b6d22de5c73da2e2550e1f45e103a219a51/lib/off_the_grid/host_group.rb#L27-L31
7,466
syborg/mme_tools
lib/mme_tools/webparse.rb
MMETools.Webparse.datify
def datify(str) pttrn = /(\d+)[\/-](\d+)[\/-](\d+)(\W+(\d+)\:(\d+))?/ day, month, year, dummy, hour, min = str.match(pttrn).captures.map {|d| d ? d.to_i : 0 } case year when 0..69 year += 2000 when 70..99 year += 1900 end DateTime.civil year, month, day, hour, min end
ruby
def datify(str) pttrn = /(\d+)[\/-](\d+)[\/-](\d+)(\W+(\d+)\:(\d+))?/ day, month, year, dummy, hour, min = str.match(pttrn).captures.map {|d| d ? d.to_i : 0 } case year when 0..69 year += 2000 when 70..99 year += 1900 end DateTime.civil year, month, day, hour, min end
[ "def", "datify", "(", "str", ")", "pttrn", "=", "/", "\\d", "\\/", "\\d", "\\/", "\\d", "\\W", "\\d", "\\:", "\\d", "/", "day", ",", "month", ",", "year", ",", "dummy", ",", "hour", ",", "min", "=", "str", ".", "match", "(", "pttrn", ")", ".", "captures", ".", "map", "{", "|", "d", "|", "d", "?", "d", ".", "to_i", ":", "0", "}", "case", "year", "when", "0", "..", "69", "year", "+=", "2000", "when", "70", "..", "99", "year", "+=", "1900", "end", "DateTime", ".", "civil", "year", ",", "month", ",", "day", ",", "hour", ",", "min", "end" ]
Extracts and returns the first provable DateTime from a string
[ "Extracts", "and", "returns", "the", "first", "provable", "DateTime", "from", "a", "string" ]
e93919f7fcfb408b941d6144290991a7feabaa7d
https://github.com/syborg/mme_tools/blob/e93919f7fcfb408b941d6144290991a7feabaa7d/lib/mme_tools/webparse.rb#L78-L88
7,467
nulogy/spreadsheet
lib/spreadsheet/workbook.rb
Spreadsheet.Workbook.format
def format idx case idx when Integer @formats[idx] || @default_format when String @formats.find do |fmt| fmt.name == idx end end end
ruby
def format idx case idx when Integer @formats[idx] || @default_format when String @formats.find do |fmt| fmt.name == idx end end end
[ "def", "format", "idx", "case", "idx", "when", "Integer", "@formats", "[", "idx", "]", "||", "@default_format", "when", "String", "@formats", ".", "find", "do", "|", "fmt", "|", "fmt", ".", "name", "==", "idx", "end", "end", "end" ]
The Format at _idx_, or - if _idx_ is a String - the Format with name == _idx_
[ "The", "Format", "at", "_idx_", "or", "-", "if", "_idx_", "is", "a", "String", "-", "the", "Format", "with", "name", "==", "_idx_" ]
c89825047f02ab26deddaab779f3b4ca349b6a0c
https://github.com/nulogy/spreadsheet/blob/c89825047f02ab26deddaab779f3b4ca349b6a0c/lib/spreadsheet/workbook.rb#L72-L79
7,468
robfors/ruby-sumac
lib/sumac/directive_queue.rb
Sumac.DirectiveQueue.execute_next
def execute_next(&block) @mutex.synchronize do if @active_thread condition_variable = ConditionVariable.new @waiting_threads.unshift(condition_variable) condition_variable.wait(@mutex) end @active_thread = true end return_value = yield ensure @mutex.synchronize do @active_thread = false next_waiting_thread = @waiting_threads.shift next_waiting_thread&.signal end end
ruby
def execute_next(&block) @mutex.synchronize do if @active_thread condition_variable = ConditionVariable.new @waiting_threads.unshift(condition_variable) condition_variable.wait(@mutex) end @active_thread = true end return_value = yield ensure @mutex.synchronize do @active_thread = false next_waiting_thread = @waiting_threads.shift next_waiting_thread&.signal end end
[ "def", "execute_next", "(", "&", "block", ")", "@mutex", ".", "synchronize", "do", "if", "@active_thread", "condition_variable", "=", "ConditionVariable", ".", "new", "@waiting_threads", ".", "unshift", "(", "condition_variable", ")", "condition_variable", ".", "wait", "(", "@mutex", ")", "end", "@active_thread", "=", "true", "end", "return_value", "=", "yield", "ensure", "@mutex", ".", "synchronize", "do", "@active_thread", "=", "false", "next_waiting_thread", "=", "@waiting_threads", ".", "shift", "next_waiting_thread", "&.", "signal", "end", "end" ]
Execute a block next. If no other thread is executing a block, the block will be executed immediately. If another thread is executing a block, add the thread to the front of the queue and executes the block when the current thread has finished its block. @note if multiple threads are queued via this method their order is undefined @yield [] executed when permitted @raise [Exception] anything raised in block @return [Object] return value from block
[ "Execute", "a", "block", "next", ".", "If", "no", "other", "thread", "is", "executing", "a", "block", "the", "block", "will", "be", "executed", "immediately", ".", "If", "another", "thread", "is", "executing", "a", "block", "add", "the", "thread", "to", "the", "front", "of", "the", "queue", "and", "executes", "the", "block", "when", "the", "current", "thread", "has", "finished", "its", "block", "." ]
524fa68b7d1bb10a74baa69cd594ab2b8cae20a3
https://github.com/robfors/ruby-sumac/blob/524fa68b7d1bb10a74baa69cd594ab2b8cae20a3/lib/sumac/directive_queue.rb#L49-L65
7,469
Sammidysam/file_templater
lib/file_templater/template.rb
FileTemplater.Template.transform_file_name
def transform_file_name(file) if @bind variables = file.scan(/{{([^}]*)}}/).flatten variables.each do |v| file.sub!("{{#{v}}}", @bind.get_binding.eval(v)) end end (!@nomodify && file.end_with?(".erb") && !File.directory?(file)) ? File.basename(file, ".*") : file end
ruby
def transform_file_name(file) if @bind variables = file.scan(/{{([^}]*)}}/).flatten variables.each do |v| file.sub!("{{#{v}}}", @bind.get_binding.eval(v)) end end (!@nomodify && file.end_with?(".erb") && !File.directory?(file)) ? File.basename(file, ".*") : file end
[ "def", "transform_file_name", "(", "file", ")", "if", "@bind", "variables", "=", "file", ".", "scan", "(", "/", "/", ")", ".", "flatten", "variables", ".", "each", "do", "|", "v", "|", "file", ".", "sub!", "(", "\"{{#{v}}}\"", ",", "@bind", ".", "get_binding", ".", "eval", "(", "v", ")", ")", "end", "end", "(", "!", "@nomodify", "&&", "file", ".", "end_with?", "(", "\".erb\"", ")", "&&", "!", "File", ".", "directory?", "(", "file", ")", ")", "?", "File", ".", "basename", "(", "file", ",", "\".*\"", ")", ":", "file", "end" ]
Expands the variable-in-file-name notation.
[ "Expands", "the", "variable", "-", "in", "-", "file", "-", "name", "notation", "." ]
081b3d4b82aaa955551a790a2ee8a90870dc1b45
https://github.com/Sammidysam/file_templater/blob/081b3d4b82aaa955551a790a2ee8a90870dc1b45/lib/file_templater/template.rb#L57-L67
7,470
riddopic/garcun
lib/garcon/utility/file_helper.rb
Garcon.FileHelper.which
def which(prog, path = ENV['PATH']) path.split(File::PATH_SEPARATOR).each do |dir| file = File.join(dir, prog) return file if File.executable?(file) && !File.directory?(file) end nil end
ruby
def which(prog, path = ENV['PATH']) path.split(File::PATH_SEPARATOR).each do |dir| file = File.join(dir, prog) return file if File.executable?(file) && !File.directory?(file) end nil end
[ "def", "which", "(", "prog", ",", "path", "=", "ENV", "[", "'PATH'", "]", ")", "path", ".", "split", "(", "File", "::", "PATH_SEPARATOR", ")", ".", "each", "do", "|", "dir", "|", "file", "=", "File", ".", "join", "(", "dir", ",", "prog", ")", "return", "file", "if", "File", ".", "executable?", "(", "file", ")", "&&", "!", "File", ".", "directory?", "(", "file", ")", "end", "nil", "end" ]
Looks for the first occurrence of program within path. @param [String] cmd The name of the command to find. @param [String] path The path to search for the command. @return [String, NilClass] @api public
[ "Looks", "for", "the", "first", "occurrence", "of", "program", "within", "path", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/file_helper.rb#L53-L60
7,471
riddopic/garcun
lib/garcon/utility/file_helper.rb
Garcon.FileHelper.whereis
def whereis(prog, path = ENV['PATH']) dirs = [] path.split(File::PATH_SEPARATOR).each do |dir| f = File.join(dir,prog) if File.executable?(f) && !File.directory?(f) if block_given? yield f else dirs << f end end end dirs.empty? ? nil : dirs end
ruby
def whereis(prog, path = ENV['PATH']) dirs = [] path.split(File::PATH_SEPARATOR).each do |dir| f = File.join(dir,prog) if File.executable?(f) && !File.directory?(f) if block_given? yield f else dirs << f end end end dirs.empty? ? nil : dirs end
[ "def", "whereis", "(", "prog", ",", "path", "=", "ENV", "[", "'PATH'", "]", ")", "dirs", "=", "[", "]", "path", ".", "split", "(", "File", "::", "PATH_SEPARATOR", ")", ".", "each", "do", "|", "dir", "|", "f", "=", "File", ".", "join", "(", "dir", ",", "prog", ")", "if", "File", ".", "executable?", "(", "f", ")", "&&", "!", "File", ".", "directory?", "(", "f", ")", "if", "block_given?", "yield", "f", "else", "dirs", "<<", "f", "end", "end", "end", "dirs", ".", "empty?", "?", "nil", ":", "dirs", "end" ]
In block form, yields each program within path. In non-block form, returns an array of each program within path. Returns nil if not found found. @example whereis('ruby') # => [ [0] "/opt/chefdk/embedded/bin/ruby", [1] "/usr/bin/ruby", [2] "/Users/sharding/.rvm/rubies/ruby-2.2.0/bin/ruby", [3] "/usr/bin/ruby" ] @param [String] cmd The name of the command to find. @param [String] path The path to search for the command. @return [String, Array, NilClass] @api public
[ "In", "block", "form", "yields", "each", "program", "within", "path", ".", "In", "non", "-", "block", "form", "returns", "an", "array", "of", "each", "program", "within", "path", ".", "Returns", "nil", "if", "not", "found", "found", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/file_helper.rb#L84-L98
7,472
tpendragon/marmotta
lib/marmotta/connection.rb
Marmotta.Connection.get
def get(resource_uri) result = connection.get("resource") do |request| request.query[:uri] = resource_uri.to_s request.query.delete(:graph) end MaybeGraphResult.new(result).value end
ruby
def get(resource_uri) result = connection.get("resource") do |request| request.query[:uri] = resource_uri.to_s request.query.delete(:graph) end MaybeGraphResult.new(result).value end
[ "def", "get", "(", "resource_uri", ")", "result", "=", "connection", ".", "get", "(", "\"resource\"", ")", "do", "|", "request", "|", "request", ".", "query", "[", ":uri", "]", "=", "resource_uri", ".", "to_s", "request", ".", "query", ".", "delete", "(", ":graph", ")", "end", "MaybeGraphResult", ".", "new", "(", "result", ")", ".", "value", "end" ]
Returns an RDFSource represented by the resource URI. @param [String, #to_s] resource_uri URI to request @return [RDF::Graph] The resulting graph
[ "Returns", "an", "RDFSource", "represented", "by", "the", "resource", "URI", "." ]
01b28f656a441f4e23690c7eaf3b3b3ef76a888b
https://github.com/tpendragon/marmotta/blob/01b28f656a441f4e23690c7eaf3b3b3ef76a888b/lib/marmotta/connection.rb#L18-L24
7,473
tpendragon/marmotta
lib/marmotta/connection.rb
Marmotta.Connection.delete
def delete(resource_uri) connection.delete("resource") do |request| request.query[:uri] = resource_uri.to_s request.query.delete(:graph) end end
ruby
def delete(resource_uri) connection.delete("resource") do |request| request.query[:uri] = resource_uri.to_s request.query.delete(:graph) end end
[ "def", "delete", "(", "resource_uri", ")", "connection", ".", "delete", "(", "\"resource\"", ")", "do", "|", "request", "|", "request", ".", "query", "[", ":uri", "]", "=", "resource_uri", ".", "to_s", "request", ".", "query", ".", "delete", "(", ":graph", ")", "end", "end" ]
Deletes a subject from the context. @param [String, #to_s] resource_uri URI of resource to delete. @return [True, False] Result of deleting. @todo Should this only delete triples from the given context?
[ "Deletes", "a", "subject", "from", "the", "context", "." ]
01b28f656a441f4e23690c7eaf3b3b3ef76a888b
https://github.com/tpendragon/marmotta/blob/01b28f656a441f4e23690c7eaf3b3b3ef76a888b/lib/marmotta/connection.rb#L38-L43
7,474
barkerest/incline
app/models/incline/user.rb
Incline.User.partial_email
def partial_email @partial_email ||= begin uid,_,domain = email.partition('@') if uid.length < 4 uid = '*' * uid.length elsif uid.length < 8 uid = uid[0..2] + ('*' * (uid.length - 3)) else uid = uid[0..2] + ('*' * (uid.length - 6)) + uid[-3..-1] end "#{uid}@#{domain}" end end
ruby
def partial_email @partial_email ||= begin uid,_,domain = email.partition('@') if uid.length < 4 uid = '*' * uid.length elsif uid.length < 8 uid = uid[0..2] + ('*' * (uid.length - 3)) else uid = uid[0..2] + ('*' * (uid.length - 6)) + uid[-3..-1] end "#{uid}@#{domain}" end end
[ "def", "partial_email", "@partial_email", "||=", "begin", "uid", ",", "_", ",", "domain", "=", "email", ".", "partition", "(", "'@'", ")", "if", "uid", ".", "length", "<", "4", "uid", "=", "'*'", "*", "uid", ".", "length", "elsif", "uid", ".", "length", "<", "8", "uid", "=", "uid", "[", "0", "..", "2", "]", "+", "(", "'*'", "*", "(", "uid", ".", "length", "-", "3", ")", ")", "else", "uid", "=", "uid", "[", "0", "..", "2", "]", "+", "(", "'*'", "*", "(", "uid", ".", "length", "-", "6", ")", ")", "+", "uid", "[", "-", "3", "..", "-", "1", "]", "end", "\"#{uid}@#{domain}\"", "end", "end" ]
Gets the email address in a partially obfuscated fashion.
[ "Gets", "the", "email", "address", "in", "a", "partially", "obfuscated", "fashion", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/user.rb#L86-L99
7,475
barkerest/incline
app/models/incline/user.rb
Incline.User.effective_groups
def effective_groups(refresh = false) @effective_groups = nil if refresh @effective_groups ||= if system_admin? AccessGroup.all.map{ |g| g.to_s.upcase } else groups .collect{ |g| g.effective_groups } .flatten end .map{ |g| g.to_s.upcase } .uniq .sort end
ruby
def effective_groups(refresh = false) @effective_groups = nil if refresh @effective_groups ||= if system_admin? AccessGroup.all.map{ |g| g.to_s.upcase } else groups .collect{ |g| g.effective_groups } .flatten end .map{ |g| g.to_s.upcase } .uniq .sort end
[ "def", "effective_groups", "(", "refresh", "=", "false", ")", "@effective_groups", "=", "nil", "if", "refresh", "@effective_groups", "||=", "if", "system_admin?", "AccessGroup", ".", "all", ".", "map", "{", "|", "g", "|", "g", ".", "to_s", ".", "upcase", "}", "else", "groups", ".", "collect", "{", "|", "g", "|", "g", ".", "effective_groups", "}", ".", "flatten", "end", ".", "map", "{", "|", "g", "|", "g", ".", "to_s", ".", "upcase", "}", ".", "uniq", ".", "sort", "end" ]
Gets the effective group membership of this user.
[ "Gets", "the", "effective", "group", "membership", "of", "this", "user", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/user.rb#L124-L136
7,476
barkerest/incline
app/models/incline/user.rb
Incline.User.has_any_group?
def has_any_group?(*group_list) return :system_admin if system_admin? return false if anonymous? r = group_list.select{|g| effective_groups.include?(g.upcase)} r.blank? ? false : r end
ruby
def has_any_group?(*group_list) return :system_admin if system_admin? return false if anonymous? r = group_list.select{|g| effective_groups.include?(g.upcase)} r.blank? ? false : r end
[ "def", "has_any_group?", "(", "*", "group_list", ")", "return", ":system_admin", "if", "system_admin?", "return", "false", "if", "anonymous?", "r", "=", "group_list", ".", "select", "{", "|", "g", "|", "effective_groups", ".", "include?", "(", "g", ".", "upcase", ")", "}", "r", ".", "blank?", "?", "false", ":", "r", "end" ]
Does this user have the equivalent of one or more of these groups?
[ "Does", "this", "user", "have", "the", "equivalent", "of", "one", "or", "more", "of", "these", "groups?" ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/user.rb#L140-L147
7,477
barkerest/incline
app/models/incline/user.rb
Incline.User.remember
def remember self.remember_token = Incline::User::new_token update_attribute(:remember_digest, Incline::User::digest(self.remember_token)) end
ruby
def remember self.remember_token = Incline::User::new_token update_attribute(:remember_digest, Incline::User::digest(self.remember_token)) end
[ "def", "remember", "self", ".", "remember_token", "=", "Incline", "::", "User", "::", "new_token", "update_attribute", "(", ":remember_digest", ",", "Incline", "::", "User", "::", "digest", "(", "self", ".", "remember_token", ")", ")", "end" ]
Generates a remember token and saves the digest to the user model.
[ "Generates", "a", "remember", "token", "and", "saves", "the", "digest", "to", "the", "user", "model", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/user.rb#L151-L154
7,478
barkerest/incline
app/models/incline/user.rb
Incline.User.authenticated?
def authenticated?(attribute, token) return false unless respond_to?("#{attribute}_digest") digest = send("#{attribute}_digest") return false if digest.blank? BCrypt::Password.new(digest).is_password?(token) end
ruby
def authenticated?(attribute, token) return false unless respond_to?("#{attribute}_digest") digest = send("#{attribute}_digest") return false if digest.blank? BCrypt::Password.new(digest).is_password?(token) end
[ "def", "authenticated?", "(", "attribute", ",", "token", ")", "return", "false", "unless", "respond_to?", "(", "\"#{attribute}_digest\"", ")", "digest", "=", "send", "(", "\"#{attribute}_digest\"", ")", "return", "false", "if", "digest", ".", "blank?", "BCrypt", "::", "Password", ".", "new", "(", "digest", ")", ".", "is_password?", "(", "token", ")", "end" ]
Determines if the supplied token digests to the stored digest in the user model.
[ "Determines", "if", "the", "supplied", "token", "digests", "to", "the", "stored", "digest", "in", "the", "user", "model", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/user.rb#L164-L169
7,479
barkerest/incline
app/models/incline/user.rb
Incline.User.disable
def disable(other_user, reason) return false unless other_user&.system_admin? return false if other_user == self update_columns( disabled_by: other_user.email, disabled_at: Time.now, disabled_reason: reason, enabled: false ) && refresh_comments end
ruby
def disable(other_user, reason) return false unless other_user&.system_admin? return false if other_user == self update_columns( disabled_by: other_user.email, disabled_at: Time.now, disabled_reason: reason, enabled: false ) && refresh_comments end
[ "def", "disable", "(", "other_user", ",", "reason", ")", "return", "false", "unless", "other_user", "&.", "system_admin?", "return", "false", "if", "other_user", "==", "self", "update_columns", "(", "disabled_by", ":", "other_user", ".", "email", ",", "disabled_at", ":", "Time", ".", "now", ",", "disabled_reason", ":", "reason", ",", "enabled", ":", "false", ")", "&&", "refresh_comments", "end" ]
Disables the user. The +other_user+ is required, cannot be the current user, and must be a system administrator. The +reason+ is technically optional, but should be provided.
[ "Disables", "the", "user", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/user.rb#L176-L186
7,480
barkerest/incline
app/models/incline/user.rb
Incline.User.create_reset_digest
def create_reset_digest self.reset_token = Incline::User::new_token update_columns( reset_digest: Incline::User::digest(reset_token), reset_sent_at: Time.now ) end
ruby
def create_reset_digest self.reset_token = Incline::User::new_token update_columns( reset_digest: Incline::User::digest(reset_token), reset_sent_at: Time.now ) end
[ "def", "create_reset_digest", "self", ".", "reset_token", "=", "Incline", "::", "User", "::", "new_token", "update_columns", "(", "reset_digest", ":", "Incline", "::", "User", "::", "digest", "(", "reset_token", ")", ",", "reset_sent_at", ":", "Time", ".", "now", ")", "end" ]
Creates a reset token and stores the digest to the user model.
[ "Creates", "a", "reset", "token", "and", "stores", "the", "digest", "to", "the", "user", "model", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/user.rb#L217-L223
7,481
barkerest/incline
app/models/incline/user.rb
Incline.User.failed_login_streak
def failed_login_streak @failed_login_streak ||= begin results = login_histories.where.not(successful: true) if last_successful_login results = results.where('created_at > ?', last_successful_login.created_at) end results.order(created_at: :desc) end end
ruby
def failed_login_streak @failed_login_streak ||= begin results = login_histories.where.not(successful: true) if last_successful_login results = results.where('created_at > ?', last_successful_login.created_at) end results.order(created_at: :desc) end end
[ "def", "failed_login_streak", "@failed_login_streak", "||=", "begin", "results", "=", "login_histories", ".", "where", ".", "not", "(", "successful", ":", "true", ")", "if", "last_successful_login", "results", "=", "results", ".", "where", "(", "'created_at > ?'", ",", "last_successful_login", ".", "created_at", ")", "end", "results", ".", "order", "(", "created_at", ":", ":desc", ")", "end", "end" ]
Gets the failed logins for a user since the last successful login.
[ "Gets", "the", "failed", "logins", "for", "a", "user", "since", "the", "last", "successful", "login", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/user.rb#L251-L260
7,482
leoniv/ass_maintainer-info_base
lib/ass_maintainer/info_base.rb
AssMaintainer.InfoBase.add_hook
def add_hook(hook, &block) fail ArgumentError, "Invalid hook `#{hook}'" unless\ HOOKS.keys.include? hook fail ArgumentError, 'Block require' unless block_given? options[hook] = block end
ruby
def add_hook(hook, &block) fail ArgumentError, "Invalid hook `#{hook}'" unless\ HOOKS.keys.include? hook fail ArgumentError, 'Block require' unless block_given? options[hook] = block end
[ "def", "add_hook", "(", "hook", ",", "&", "block", ")", "fail", "ArgumentError", ",", "\"Invalid hook `#{hook}'\"", "unless", "HOOKS", ".", "keys", ".", "include?", "hook", "fail", "ArgumentError", ",", "'Block require'", "unless", "block_given?", "options", "[", "hook", "]", "=", "block", "end" ]
Add hook. In all hook whill be passed +self+ @raise [ArgumentError] if invalid hook name or not block given @param hook [Symbol] hook name
[ "Add", "hook", ".", "In", "all", "hook", "whill", "be", "passed", "+", "self", "+" ]
1cc9212fc240dafb058faae1e122eb9c8ece1cf7
https://github.com/leoniv/ass_maintainer-info_base/blob/1cc9212fc240dafb058faae1e122eb9c8ece1cf7/lib/ass_maintainer/info_base.rb#L137-L142
7,483
leoniv/ass_maintainer-info_base
lib/ass_maintainer/info_base.rb
AssMaintainer.InfoBase.make_infobase!
def make_infobase! fail MethodDenied, :make_infobase! if read_only? before_make.call(self) maker.execute(self) after_make.call(self) self end
ruby
def make_infobase! fail MethodDenied, :make_infobase! if read_only? before_make.call(self) maker.execute(self) after_make.call(self) self end
[ "def", "make_infobase!", "fail", "MethodDenied", ",", ":make_infobase!", "if", "read_only?", "before_make", ".", "call", "(", "self", ")", "maker", ".", "execute", "(", "self", ")", "after_make", ".", "call", "(", "self", ")", "self", "end" ]
Make new empty infobase wrpped in +before_make+ and +after_make+ hooks @raise [MethodDenied] if infobase {#read_only?}
[ "Make", "new", "empty", "infobase", "wrpped", "in", "+", "before_make", "+", "and", "+", "after_make", "+", "hooks" ]
1cc9212fc240dafb058faae1e122eb9c8ece1cf7
https://github.com/leoniv/ass_maintainer-info_base/blob/1cc9212fc240dafb058faae1e122eb9c8ece1cf7/lib/ass_maintainer/info_base.rb#L166-L172
7,484
leoniv/ass_maintainer-info_base
lib/ass_maintainer/info_base.rb
AssMaintainer.InfoBase.rm_infobase!
def rm_infobase! fail MethodDenied, :rm_infobase! if read_only? before_rm.call(self) destroyer.execute(self) after_rm.call(self) end
ruby
def rm_infobase! fail MethodDenied, :rm_infobase! if read_only? before_rm.call(self) destroyer.execute(self) after_rm.call(self) end
[ "def", "rm_infobase!", "fail", "MethodDenied", ",", ":rm_infobase!", "if", "read_only?", "before_rm", ".", "call", "(", "self", ")", "destroyer", ".", "execute", "(", "self", ")", "after_rm", ".", "call", "(", "self", ")", "end" ]
Remove infobase wrpped in +before_rm+ and +after_rm+ hooks @raise [MethodDenied] if infobase {#read_only?}
[ "Remove", "infobase", "wrpped", "in", "+", "before_rm", "+", "and", "+", "after_rm", "+", "hooks" ]
1cc9212fc240dafb058faae1e122eb9c8ece1cf7
https://github.com/leoniv/ass_maintainer-info_base/blob/1cc9212fc240dafb058faae1e122eb9c8ece1cf7/lib/ass_maintainer/info_base.rb#L186-L191
7,485
leoniv/ass_maintainer-info_base
lib/ass_maintainer/info_base.rb
AssMaintainer.InfoBase.dump
def dump(path) designer do dumpIB path end.run.wait.result.verify! path end
ruby
def dump(path) designer do dumpIB path end.run.wait.result.verify! path end
[ "def", "dump", "(", "path", ")", "designer", "do", "dumpIB", "path", "end", ".", "run", ".", "wait", ".", "result", ".", "verify!", "path", "end" ]
Dump infobase to +.dt+ file
[ "Dump", "infobase", "to", "+", ".", "dt", "+", "file" ]
1cc9212fc240dafb058faae1e122eb9c8ece1cf7
https://github.com/leoniv/ass_maintainer-info_base/blob/1cc9212fc240dafb058faae1e122eb9c8ece1cf7/lib/ass_maintainer/info_base.rb#L260-L265
7,486
leoniv/ass_maintainer-info_base
lib/ass_maintainer/info_base.rb
AssMaintainer.InfoBase.restore!
def restore!(path) fail MethodDenied, :restore! if read_only? designer do restoreIB path end.run.wait.result.verify! path end
ruby
def restore!(path) fail MethodDenied, :restore! if read_only? designer do restoreIB path end.run.wait.result.verify! path end
[ "def", "restore!", "(", "path", ")", "fail", "MethodDenied", ",", ":restore!", "if", "read_only?", "designer", "do", "restoreIB", "path", "end", ".", "run", ".", "wait", ".", "result", ".", "verify!", "path", "end" ]
Restore infobase from +.dt+ file @raise [MethodDenied] if {#read_only?}
[ "Restore", "infobase", "from", "+", ".", "dt", "+", "file" ]
1cc9212fc240dafb058faae1e122eb9c8ece1cf7
https://github.com/leoniv/ass_maintainer-info_base/blob/1cc9212fc240dafb058faae1e122eb9c8ece1cf7/lib/ass_maintainer/info_base.rb#L269-L275
7,487
riddopic/hoodie
lib/hoodie/memoizable.rb
Hoodie.Memoizable.memoize
def memoize(methods, cache = nil) cache ||= Hoodie::Stash.new methods.each do |name| uncached_name = "#{name}_uncached".to_sym singleton_class.class_eval do alias_method uncached_name, name define_method(name) do |*a, &b| cache.cache(name) { send uncached_name, *a, &b } end end end end
ruby
def memoize(methods, cache = nil) cache ||= Hoodie::Stash.new methods.each do |name| uncached_name = "#{name}_uncached".to_sym singleton_class.class_eval do alias_method uncached_name, name define_method(name) do |*a, &b| cache.cache(name) { send uncached_name, *a, &b } end end end end
[ "def", "memoize", "(", "methods", ",", "cache", "=", "nil", ")", "cache", "||=", "Hoodie", "::", "Stash", ".", "new", "methods", ".", "each", "do", "|", "name", "|", "uncached_name", "=", "\"#{name}_uncached\"", ".", "to_sym", "singleton_class", ".", "class_eval", "do", "alias_method", "uncached_name", ",", "name", "define_method", "(", "name", ")", "do", "|", "*", "a", ",", "&", "b", "|", "cache", ".", "cache", "(", "name", ")", "{", "send", "uncached_name", ",", "a", ",", "b", "}", "end", "end", "end", "end" ]
Create a new memoized method. To use, extend class with Memoizable, then, in initialize, call memoize @return [undefined]
[ "Create", "a", "new", "memoized", "method", ".", "To", "use", "extend", "class", "with", "Memoizable", "then", "in", "initialize", "call", "memoize" ]
921601dd4849845d3f5d3765dafcf00178b2aa66
https://github.com/riddopic/hoodie/blob/921601dd4849845d3f5d3765dafcf00178b2aa66/lib/hoodie/memoizable.rb#L33-L44
7,488
coralnexus/nucleon
lib/core/manager.rb
Nucleon.Manager.parallel_finalize
def parallel_finalize active_plugins.each do |namespace, namespace_plugins| namespace_plugins.each do |plugin_type, type_plugins| type_plugins.each do |instance_name, plugin| remove(plugin) end end end end
ruby
def parallel_finalize active_plugins.each do |namespace, namespace_plugins| namespace_plugins.each do |plugin_type, type_plugins| type_plugins.each do |instance_name, plugin| remove(plugin) end end end end
[ "def", "parallel_finalize", "active_plugins", ".", "each", "do", "|", "namespace", ",", "namespace_plugins", "|", "namespace_plugins", ".", "each", "do", "|", "plugin_type", ",", "type_plugins", "|", "type_plugins", ".", "each", "do", "|", "instance_name", ",", "plugin", "|", "remove", "(", "plugin", ")", "end", "end", "end", "end" ]
Initialize a new Nucleon environment IMORTANT: The environment constructor should accept no parameters! * *Parameters* - [String, Symbol] *actor_id* Name of the plugin manager - [Boolean] *reset* Whether or not to reinitialize the manager * *Returns* - [Void] This method does not return a value * *Errors* See also: - Nucleon::Facade#logger - Nucleon::Environment Perform any cleanup operations during manager shutdown This only runs when in parallel mode. * *Parameters* * *Returns* - [Void] This method does not return a value * *Errors* See also: - #active_plugins - #remove
[ "Initialize", "a", "new", "Nucleon", "environment" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/manager.rb#L125-L133
7,489
coralnexus/nucleon
lib/core/manager.rb
Nucleon.Manager.define_plugin
def define_plugin(namespace, plugin_type, base_path, file, &code) # :yields: data @@environments[@actor_id].define_plugin(namespace, plugin_type, base_path, file, &code) myself end
ruby
def define_plugin(namespace, plugin_type, base_path, file, &code) # :yields: data @@environments[@actor_id].define_plugin(namespace, plugin_type, base_path, file, &code) myself end
[ "def", "define_plugin", "(", "namespace", ",", "plugin_type", ",", "base_path", ",", "file", ",", "&", "code", ")", "# :yields: data", "@@environments", "[", "@actor_id", "]", ".", "define_plugin", "(", "namespace", ",", "plugin_type", ",", "base_path", ",", "file", ",", "code", ")", "myself", "end" ]
Define a new plugin provider of a specified plugin type. * *Parameters* - [String, Symbol] *namespace* Namespace that contains plugin types - [String, Symbol] *plugin_type* Plugin type name to fetch default provider - [String] *base_path* Base load path of the plugin provider - [String] *file* File that contains the provider definition * *Returns* - [Nucleon::Manager, Celluloid::Actor] Returns reference to self for compound operations * *Errors* * *Yields* - [Hash<Symbol|ANY>] *data* Plugin load information See: - Nucleon::Environment#define_plugin
[ "Define", "a", "new", "plugin", "provider", "of", "a", "specified", "plugin", "type", "." ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/manager.rb#L357-L360
7,490
UzxMx/api_warden
lib/api_warden/authentication.rb
ApiWarden.Authentication.authenticate!
def authenticate! return unless @authenticated.nil? id, access_token = @params.retrieve_id, @params.retrieve_access_token @key_for_access_token = @scope.key_for_access_token(id, access_token) if access_token && !access_token.empty? ApiWarden.redis { |conn| @value_for_access_token = conn.get(@key_for_access_token) } end unless @value_for_access_token @authenticated = false raise AuthenticationError end @authenticated = true @id = id @access_token = access_token self end
ruby
def authenticate! return unless @authenticated.nil? id, access_token = @params.retrieve_id, @params.retrieve_access_token @key_for_access_token = @scope.key_for_access_token(id, access_token) if access_token && !access_token.empty? ApiWarden.redis { |conn| @value_for_access_token = conn.get(@key_for_access_token) } end unless @value_for_access_token @authenticated = false raise AuthenticationError end @authenticated = true @id = id @access_token = access_token self end
[ "def", "authenticate!", "return", "unless", "@authenticated", ".", "nil?", "id", ",", "access_token", "=", "@params", ".", "retrieve_id", ",", "@params", ".", "retrieve_access_token", "@key_for_access_token", "=", "@scope", ".", "key_for_access_token", "(", "id", ",", "access_token", ")", "if", "access_token", "&&", "!", "access_token", ".", "empty?", "ApiWarden", ".", "redis", "{", "|", "conn", "|", "@value_for_access_token", "=", "conn", ".", "get", "(", "@key_for_access_token", ")", "}", "end", "unless", "@value_for_access_token", "@authenticated", "=", "false", "raise", "AuthenticationError", "end", "@authenticated", "=", "true", "@id", "=", "id", "@access_token", "=", "access_token", "self", "end" ]
This method will only authenticate once, and cache the result. @return self
[ "This", "method", "will", "only", "authenticate", "once", "and", "cache", "the", "result", "." ]
78e4fa421abc5333da2df6903d736d8e4871483a
https://github.com/UzxMx/api_warden/blob/78e4fa421abc5333da2df6903d736d8e4871483a/lib/api_warden/authentication.rb#L51-L70
7,491
UzxMx/api_warden
lib/api_warden/authentication.rb
ApiWarden.Authentication.ttl_for_access_token=
def ttl_for_access_token=(seconds) raise_if_authentication_failed! key = @key_for_access_token value = @value_for_access_token ApiWarden.redis { |conn| conn.set(key, value, ex: seconds) } end
ruby
def ttl_for_access_token=(seconds) raise_if_authentication_failed! key = @key_for_access_token value = @value_for_access_token ApiWarden.redis { |conn| conn.set(key, value, ex: seconds) } end
[ "def", "ttl_for_access_token", "=", "(", "seconds", ")", "raise_if_authentication_failed!", "key", "=", "@key_for_access_token", "value", "=", "@value_for_access_token", "ApiWarden", ".", "redis", "{", "|", "conn", "|", "conn", ".", "set", "(", "key", ",", "value", ",", "ex", ":", "seconds", ")", "}", "end" ]
Set the ttl for access token.
[ "Set", "the", "ttl", "for", "access", "token", "." ]
78e4fa421abc5333da2df6903d736d8e4871483a
https://github.com/UzxMx/api_warden/blob/78e4fa421abc5333da2df6903d736d8e4871483a/lib/api_warden/authentication.rb#L115-L121
7,492
kddeisz/helpful_comments
lib/helpful_comments/controller_routes.rb
HelpfulComments.ControllerRoutes.build
def build controller_name = @klass.name.gsub(/Controller$/, '').underscore Rails.application.routes.routes.each_with_object({}) do |route, comments| if route.defaults[:controller] == controller_name verb_match = route.verb.to_s.match(/\^(.*)\$/) verbs = verb_match.nil? ? '*' : verb_match[1] (comments[route.defaults[:action]] ||= []) << "#{verbs} #{route.ast}" end end end
ruby
def build controller_name = @klass.name.gsub(/Controller$/, '').underscore Rails.application.routes.routes.each_with_object({}) do |route, comments| if route.defaults[:controller] == controller_name verb_match = route.verb.to_s.match(/\^(.*)\$/) verbs = verb_match.nil? ? '*' : verb_match[1] (comments[route.defaults[:action]] ||= []) << "#{verbs} #{route.ast}" end end end
[ "def", "build", "controller_name", "=", "@klass", ".", "name", ".", "gsub", "(", "/", "/", ",", "''", ")", ".", "underscore", "Rails", ".", "application", ".", "routes", ".", "routes", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "route", ",", "comments", "|", "if", "route", ".", "defaults", "[", ":controller", "]", "==", "controller_name", "verb_match", "=", "route", ".", "verb", ".", "to_s", ".", "match", "(", "/", "\\^", "\\$", "/", ")", "verbs", "=", "verb_match", ".", "nil?", "?", "'*'", ":", "verb_match", "[", "1", "]", "(", "comments", "[", "route", ".", "defaults", "[", ":action", "]", "]", "||=", "[", "]", ")", "<<", "\"#{verbs} #{route.ast}\"", "end", "end", "end" ]
takes a controller builds the lines to be put into the file
[ "takes", "a", "controller", "builds", "the", "lines", "to", "be", "put", "into", "the", "file" ]
45dce953a4f248ad847ca0032872a059eace58a4
https://github.com/kddeisz/helpful_comments/blob/45dce953a4f248ad847ca0032872a059eace58a4/lib/helpful_comments/controller_routes.rb#L10-L19
7,493
Lupeipei/i18n-processes
lib/i18n/processes/data/tree/siblings.rb
I18n::Processes::Data::Tree.Siblings.set
def set(full_key, node) fail 'value should be a I18n::Processes::Data::Tree::Node' unless node.is_a?(Node) key_part, rest = split_key(full_key, 2) child = key_to_node[key_part] if rest unless child child = Node.new( key: key_part, parent: parent, children: [], warn_about_add_children_to_leaf: @warn_add_children_to_leaf ) append! child end unless child.children warn_add_children_to_leaf child if @warn_about_add_children_to_leaf child.children = [] end child.children.set rest, node else remove! child if child append! node end dirty! node end
ruby
def set(full_key, node) fail 'value should be a I18n::Processes::Data::Tree::Node' unless node.is_a?(Node) key_part, rest = split_key(full_key, 2) child = key_to_node[key_part] if rest unless child child = Node.new( key: key_part, parent: parent, children: [], warn_about_add_children_to_leaf: @warn_add_children_to_leaf ) append! child end unless child.children warn_add_children_to_leaf child if @warn_about_add_children_to_leaf child.children = [] end child.children.set rest, node else remove! child if child append! node end dirty! node end
[ "def", "set", "(", "full_key", ",", "node", ")", "fail", "'value should be a I18n::Processes::Data::Tree::Node'", "unless", "node", ".", "is_a?", "(", "Node", ")", "key_part", ",", "rest", "=", "split_key", "(", "full_key", ",", "2", ")", "child", "=", "key_to_node", "[", "key_part", "]", "if", "rest", "unless", "child", "child", "=", "Node", ".", "new", "(", "key", ":", "key_part", ",", "parent", ":", "parent", ",", "children", ":", "[", "]", ",", "warn_about_add_children_to_leaf", ":", "@warn_add_children_to_leaf", ")", "append!", "child", "end", "unless", "child", ".", "children", "warn_add_children_to_leaf", "child", "if", "@warn_about_add_children_to_leaf", "child", ".", "children", "=", "[", "]", "end", "child", ".", "children", ".", "set", "rest", ",", "node", "else", "remove!", "child", "if", "child", "append!", "node", "end", "dirty!", "node", "end" ]
add or replace node by full key
[ "add", "or", "replace", "node", "by", "full", "key" ]
83c91517f80b82371ab19e197665e6e131024df3
https://github.com/Lupeipei/i18n-processes/blob/83c91517f80b82371ab19e197665e6e131024df3/lib/i18n/processes/data/tree/siblings.rb#L106-L132
7,494
hinrik/ircsupport
lib/ircsupport/encoding.rb
IRCSupport.Encoding.decode_irc!
def decode_irc!(string, encoding = :irc) if encoding == :irc # If incoming text is valid UTF-8, it will be interpreted as # such. If it fails validation, a CP1252 -> UTF-8 conversion # is performed. This allows you to see non-ASCII from mIRC # users (non-UTF-8) and other users sending you UTF-8. # # (from http://xchat.org/encoding/#hybrid) string.force_encoding("UTF-8") if !string.valid_encoding? string.force_encoding("CP1252").encode!("UTF-8", {:invalid => :replace, :undef => :replace}) end else string.force_encoding(encoding).encode!({:invalid => :replace, :undef => :replace}) string = string.chars.select { |c| c.valid_encoding? }.join end return string end
ruby
def decode_irc!(string, encoding = :irc) if encoding == :irc # If incoming text is valid UTF-8, it will be interpreted as # such. If it fails validation, a CP1252 -> UTF-8 conversion # is performed. This allows you to see non-ASCII from mIRC # users (non-UTF-8) and other users sending you UTF-8. # # (from http://xchat.org/encoding/#hybrid) string.force_encoding("UTF-8") if !string.valid_encoding? string.force_encoding("CP1252").encode!("UTF-8", {:invalid => :replace, :undef => :replace}) end else string.force_encoding(encoding).encode!({:invalid => :replace, :undef => :replace}) string = string.chars.select { |c| c.valid_encoding? }.join end return string end
[ "def", "decode_irc!", "(", "string", ",", "encoding", "=", ":irc", ")", "if", "encoding", "==", ":irc", "# If incoming text is valid UTF-8, it will be interpreted as", "# such. If it fails validation, a CP1252 -> UTF-8 conversion", "# is performed. This allows you to see non-ASCII from mIRC", "# users (non-UTF-8) and other users sending you UTF-8.", "#", "# (from http://xchat.org/encoding/#hybrid)", "string", ".", "force_encoding", "(", "\"UTF-8\"", ")", "if", "!", "string", ".", "valid_encoding?", "string", ".", "force_encoding", "(", "\"CP1252\"", ")", ".", "encode!", "(", "\"UTF-8\"", ",", "{", ":invalid", "=>", ":replace", ",", ":undef", "=>", ":replace", "}", ")", "end", "else", "string", ".", "force_encoding", "(", "encoding", ")", ".", "encode!", "(", "{", ":invalid", "=>", ":replace", ",", ":undef", "=>", ":replace", "}", ")", "string", "=", "string", ".", "chars", ".", "select", "{", "|", "c", "|", "c", ".", "valid_encoding?", "}", ".", "join", "end", "return", "string", "end" ]
Decode a message from an IRC connection, modifying it in place. @param [String] string The IRC string you want to decode. @param [Symbol] encoding The source encoding. @return [String] A UTF-8 Ruby string.
[ "Decode", "a", "message", "from", "an", "IRC", "connection", "modifying", "it", "in", "place", "." ]
d028b7d5ccc604a6af175ee2264c18d25b1f7dff
https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/encoding.rb#L27-L45
7,495
hinrik/ircsupport
lib/ircsupport/encoding.rb
IRCSupport.Encoding.encode_irc!
def encode_irc!(string, encoding = :irc) if encoding == :irc # If your text contains only characters that fit inside the CP1252 # code page (aka Windows Latin-1), the entire line will be sent # that way. mIRC users should see it correctly. XChat users who # are using UTF-8 will also see it correctly, because it will fail # UTF-8 validation and will be assumed to be CP1252, even by older # XChat versions. # # If the text doesn't fit inside the CP1252 code page, (for example if you # type Eastern European characters, or Russian) it will be sent as UTF-8. Only # UTF-8 capable clients will be able to see these characters correctly # # (from http://xchat.org/encoding/#hybrid) begin string.encode!("CP1252") rescue ::Encoding::UndefinedConversionError end else string.encode!(encoding, {:invalid => :replace, :undef => :replace}).force_encoding("ASCII-8BIT") end return string end
ruby
def encode_irc!(string, encoding = :irc) if encoding == :irc # If your text contains only characters that fit inside the CP1252 # code page (aka Windows Latin-1), the entire line will be sent # that way. mIRC users should see it correctly. XChat users who # are using UTF-8 will also see it correctly, because it will fail # UTF-8 validation and will be assumed to be CP1252, even by older # XChat versions. # # If the text doesn't fit inside the CP1252 code page, (for example if you # type Eastern European characters, or Russian) it will be sent as UTF-8. Only # UTF-8 capable clients will be able to see these characters correctly # # (from http://xchat.org/encoding/#hybrid) begin string.encode!("CP1252") rescue ::Encoding::UndefinedConversionError end else string.encode!(encoding, {:invalid => :replace, :undef => :replace}).force_encoding("ASCII-8BIT") end return string end
[ "def", "encode_irc!", "(", "string", ",", "encoding", "=", ":irc", ")", "if", "encoding", "==", ":irc", "# If your text contains only characters that fit inside the CP1252", "# code page (aka Windows Latin-1), the entire line will be sent", "# that way. mIRC users should see it correctly. XChat users who", "# are using UTF-8 will also see it correctly, because it will fail", "# UTF-8 validation and will be assumed to be CP1252, even by older", "# XChat versions.", "#", "# If the text doesn't fit inside the CP1252 code page, (for example if you", "# type Eastern European characters, or Russian) it will be sent as UTF-8. Only", "# UTF-8 capable clients will be able to see these characters correctly", "#", "# (from http://xchat.org/encoding/#hybrid)", "begin", "string", ".", "encode!", "(", "\"CP1252\"", ")", "rescue", "::", "Encoding", "::", "UndefinedConversionError", "end", "else", "string", ".", "encode!", "(", "encoding", ",", "{", ":invalid", "=>", ":replace", ",", ":undef", "=>", ":replace", "}", ")", ".", "force_encoding", "(", "\"ASCII-8BIT\"", ")", "end", "return", "string", "end" ]
Encode a message to be sent over an IRC connection, modifying it in place. @param [String] string The string you want to encode. @param [Symbol] encoding The target encoding. @return [String] A string encoded in the encoding you specified.
[ "Encode", "a", "message", "to", "be", "sent", "over", "an", "IRC", "connection", "modifying", "it", "in", "place", "." ]
d028b7d5ccc604a6af175ee2264c18d25b1f7dff
https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/encoding.rb#L51-L74
7,496
otherinbox/luggage
lib/luggage/message.rb
Luggage.Message.reload
def reload fields = fetch_fields @mail = Mail.new(fields["BODY[]"]) @flags = fields["FLAGS"] @date = Time.parse(fields["INTERNALDATE"]) self end
ruby
def reload fields = fetch_fields @mail = Mail.new(fields["BODY[]"]) @flags = fields["FLAGS"] @date = Time.parse(fields["INTERNALDATE"]) self end
[ "def", "reload", "fields", "=", "fetch_fields", "@mail", "=", "Mail", ".", "new", "(", "fields", "[", "\"BODY[]\"", "]", ")", "@flags", "=", "fields", "[", "\"FLAGS\"", "]", "@date", "=", "Time", ".", "parse", "(", "fields", "[", "\"INTERNALDATE\"", "]", ")", "self", "end" ]
Fetch this message from the server and update all its attributes
[ "Fetch", "this", "message", "from", "the", "server", "and", "update", "all", "its", "attributes" ]
032095e09e34cf93186dd9eea4d617d6cdfdd3ec
https://github.com/otherinbox/luggage/blob/032095e09e34cf93186dd9eea4d617d6cdfdd3ec/lib/luggage/message.rb#L68-L74
7,497
otherinbox/luggage
lib/luggage/message.rb
Luggage.Message.save!
def save! mailbox.select! connection.append(mailbox.name, raw_message, flags, date) end
ruby
def save! mailbox.select! connection.append(mailbox.name, raw_message, flags, date) end
[ "def", "save!", "mailbox", ".", "select!", "connection", ".", "append", "(", "mailbox", ".", "name", ",", "raw_message", ",", "flags", ",", "date", ")", "end" ]
Append this message to the remote mailbox
[ "Append", "this", "message", "to", "the", "remote", "mailbox" ]
032095e09e34cf93186dd9eea4d617d6cdfdd3ec
https://github.com/otherinbox/luggage/blob/032095e09e34cf93186dd9eea4d617d6cdfdd3ec/lib/luggage/message.rb#L78-L81
7,498
otherinbox/luggage
lib/luggage/message.rb
Luggage.Message.copy_to!
def copy_to!(mailbox_name) mailbox.select! connection.uid_copy([uid], Luggage::Mailbox.convert_mailbox_name(mailbox_name)) end
ruby
def copy_to!(mailbox_name) mailbox.select! connection.uid_copy([uid], Luggage::Mailbox.convert_mailbox_name(mailbox_name)) end
[ "def", "copy_to!", "(", "mailbox_name", ")", "mailbox", ".", "select!", "connection", ".", "uid_copy", "(", "[", "uid", "]", ",", "Luggage", "::", "Mailbox", ".", "convert_mailbox_name", "(", "mailbox_name", ")", ")", "end" ]
Uses IMAP's COPY command to copy the message into the named mailbox
[ "Uses", "IMAP", "s", "COPY", "command", "to", "copy", "the", "message", "into", "the", "named", "mailbox" ]
032095e09e34cf93186dd9eea4d617d6cdfdd3ec
https://github.com/otherinbox/luggage/blob/032095e09e34cf93186dd9eea4d617d6cdfdd3ec/lib/luggage/message.rb#L85-L88
7,499
detroit/detroit-locat
lib/detroit-locat.rb
Detroit.LOCat.generate
def generate options = {} options[:title] = title if title options[:format] = format if format options[:output] = output if output options[:config] = config if config options[:files] = collect_files locat = ::LOCat::Command.new(options) locat.run end
ruby
def generate options = {} options[:title] = title if title options[:format] = format if format options[:output] = output if output options[:config] = config if config options[:files] = collect_files locat = ::LOCat::Command.new(options) locat.run end
[ "def", "generate", "options", "=", "{", "}", "options", "[", ":title", "]", "=", "title", "if", "title", "options", "[", ":format", "]", "=", "format", "if", "format", "options", "[", ":output", "]", "=", "output", "if", "output", "options", "[", ":config", "]", "=", "config", "if", "config", "options", "[", ":files", "]", "=", "collect_files", "locat", "=", "::", "LOCat", "::", "Command", ".", "new", "(", "options", ")", "locat", ".", "run", "end" ]
S E R V I C E M E T H O D S Render templates.
[ "S", "E", "R", "V", "I", "C", "E", "M", "E", "T", "H", "O", "D", "S", "Render", "templates", "." ]
dff72e2880a2c83a4b763e590326e5af56073981
https://github.com/detroit/detroit-locat/blob/dff72e2880a2c83a4b763e590326e5af56073981/lib/detroit-locat.rb#L61-L73