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,100
jinx/core
lib/jinx/metadata/inverse.rb
Jinx.Inverse.detect_inverse_attribute
def detect_inverse_attribute(klass) # The candidate attributes return the referencing type and don't already have an inverse. candidates = domain_attributes.compose { |prop| klass <= prop.type and prop.inverse.nil? } pa = detect_inverse_attribute_from_candidates(klass, candidates) if pa then logger.debug { "#{qp} #{klass.qp} inverse attribute is #{pa}." } else logger.debug { "#{qp} #{klass.qp} inverse attribute was not detected." } end pa end
ruby
def detect_inverse_attribute(klass) # The candidate attributes return the referencing type and don't already have an inverse. candidates = domain_attributes.compose { |prop| klass <= prop.type and prop.inverse.nil? } pa = detect_inverse_attribute_from_candidates(klass, candidates) if pa then logger.debug { "#{qp} #{klass.qp} inverse attribute is #{pa}." } else logger.debug { "#{qp} #{klass.qp} inverse attribute was not detected." } end pa end
[ "def", "detect_inverse_attribute", "(", "klass", ")", "# The candidate attributes return the referencing type and don't already have an inverse.", "candidates", "=", "domain_attributes", ".", "compose", "{", "|", "prop", "|", "klass", "<=", "prop", ".", "type", "and", "prop", ".", "inverse", ".", "nil?", "}", "pa", "=", "detect_inverse_attribute_from_candidates", "(", "klass", ",", "candidates", ")", "if", "pa", "then", "logger", ".", "debug", "{", "\"#{qp} #{klass.qp} inverse attribute is #{pa}.\"", "}", "else", "logger", ".", "debug", "{", "\"#{qp} #{klass.qp} inverse attribute was not detected.\"", "}", "end", "pa", "end" ]
Detects an unambiguous attribute which refers to the given referencing class. If there is exactly one attribute with the given return type, then that attribute is chosen. Otherwise, the attribute whose name matches the underscored referencing class name is chosen, if any. @param [Class] klass the referencing class @return [Symbol, nil] the inverse attribute for the given referencing class and inverse, or nil if no owner attribute was detected
[ "Detects", "an", "unambiguous", "attribute", "which", "refers", "to", "the", "given", "referencing", "class", ".", "If", "there", "is", "exactly", "one", "attribute", "with", "the", "given", "return", "type", "then", "that", "attribute", "is", "chosen", ".", "Otherwise", "the", "attribute", "whose", "name", "matches", "the", "underscored", "referencing", "class", "name", "is", "chosen", "if", "any", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/inverse.rb#L101-L111
7,101
jinx/core
lib/jinx/metadata/inverse.rb
Jinx.Inverse.delegate_writer_to_inverse
def delegate_writer_to_inverse(attribute, inverse) prop = property(attribute) # nothing to do if no inverse inv_prop = prop.inverse_property || return logger.debug { "Delegating #{qp}.#{attribute} update to the inverse #{prop.type.qp}.#{inv_prop}..." } # redefine the write to set the dependent inverse redefine_method(prop.writer) do |old_writer| # delegate to the Jinx::Resource set_inverse method lambda { |dep| set_inverse(dep, old_writer, inv_prop.writer) } end end
ruby
def delegate_writer_to_inverse(attribute, inverse) prop = property(attribute) # nothing to do if no inverse inv_prop = prop.inverse_property || return logger.debug { "Delegating #{qp}.#{attribute} update to the inverse #{prop.type.qp}.#{inv_prop}..." } # redefine the write to set the dependent inverse redefine_method(prop.writer) do |old_writer| # delegate to the Jinx::Resource set_inverse method lambda { |dep| set_inverse(dep, old_writer, inv_prop.writer) } end end
[ "def", "delegate_writer_to_inverse", "(", "attribute", ",", "inverse", ")", "prop", "=", "property", "(", "attribute", ")", "# nothing to do if no inverse", "inv_prop", "=", "prop", ".", "inverse_property", "||", "return", "logger", ".", "debug", "{", "\"Delegating #{qp}.#{attribute} update to the inverse #{prop.type.qp}.#{inv_prop}...\"", "}", "# redefine the write to set the dependent inverse", "redefine_method", "(", "prop", ".", "writer", ")", "do", "|", "old_writer", "|", "# delegate to the Jinx::Resource set_inverse method", "lambda", "{", "|", "dep", "|", "set_inverse", "(", "dep", ",", "old_writer", ",", "inv_prop", ".", "writer", ")", "}", "end", "end" ]
Redefines the attribute writer method to delegate to its inverse writer. This is done to enforce inverse integrity. For a +Person+ attribute +account+ with inverse +holder+, this is equivalent to the following: class Person alias :set_account :account= def account=(acct) acct.holder = self if acct set_account(acct) end end
[ "Redefines", "the", "attribute", "writer", "method", "to", "delegate", "to", "its", "inverse", "writer", ".", "This", "is", "done", "to", "enforce", "inverse", "integrity", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/inverse.rb#L124-L134
7,102
jinx/core
lib/jinx/metadata/inverse.rb
Jinx.Inverse.restrict_attribute_inverse
def restrict_attribute_inverse(prop, inverse) logger.debug { "Restricting #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}..." } rst_prop = prop.restrict(self, :inverse => inverse) logger.debug { "Restricted #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}." } rst_prop end
ruby
def restrict_attribute_inverse(prop, inverse) logger.debug { "Restricting #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}..." } rst_prop = prop.restrict(self, :inverse => inverse) logger.debug { "Restricted #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}." } rst_prop end
[ "def", "restrict_attribute_inverse", "(", "prop", ",", "inverse", ")", "logger", ".", "debug", "{", "\"Restricting #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}...\"", "}", "rst_prop", "=", "prop", ".", "restrict", "(", "self", ",", ":inverse", "=>", "inverse", ")", "logger", ".", "debug", "{", "\"Restricted #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}.\"", "}", "rst_prop", "end" ]
Copies the given attribute metadata from its declarer to this class. The new attribute metadata has the same attribute access methods, but the declarer is this class and the inverse is the given inverse attribute. @param [Property] prop the attribute to copy @param [Symbol] the attribute inverse @return [Property] the copied attribute metadata
[ "Copies", "the", "given", "attribute", "metadata", "from", "its", "declarer", "to", "this", "class", ".", "The", "new", "attribute", "metadata", "has", "the", "same", "attribute", "access", "methods", "but", "the", "declarer", "is", "this", "class", "and", "the", "inverse", "is", "the", "given", "inverse", "attribute", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/inverse.rb#L145-L150
7,103
jinx/core
lib/jinx/metadata/inverse.rb
Jinx.Inverse.add_inverse_updater
def add_inverse_updater(attribute) prop = property(attribute) # the reader and writer methods rdr, wtr = prop.accessors # the inverse attribute metadata inv_prop = prop.inverse_property # the inverse attribute reader and writer inv_rdr, inv_wtr = inv_accessors = inv_prop.accessors # Redefine the writer method to update the inverse by delegating to the inverse. redefine_method(wtr) do |old_wtr| # the attribute reader and (superseded) writer accessors = [rdr, old_wtr] if inv_prop.collection? then lambda { |other| add_to_inverse_collection(other, accessors, inv_rdr) } else lambda { |other| set_inversible_noncollection_attribute(other, accessors, inv_wtr) } end end logger.debug { "Injected inverse #{inv_prop} updater into #{qp}.#{attribute} writer method #{wtr}." } end
ruby
def add_inverse_updater(attribute) prop = property(attribute) # the reader and writer methods rdr, wtr = prop.accessors # the inverse attribute metadata inv_prop = prop.inverse_property # the inverse attribute reader and writer inv_rdr, inv_wtr = inv_accessors = inv_prop.accessors # Redefine the writer method to update the inverse by delegating to the inverse. redefine_method(wtr) do |old_wtr| # the attribute reader and (superseded) writer accessors = [rdr, old_wtr] if inv_prop.collection? then lambda { |other| add_to_inverse_collection(other, accessors, inv_rdr) } else lambda { |other| set_inversible_noncollection_attribute(other, accessors, inv_wtr) } end end logger.debug { "Injected inverse #{inv_prop} updater into #{qp}.#{attribute} writer method #{wtr}." } end
[ "def", "add_inverse_updater", "(", "attribute", ")", "prop", "=", "property", "(", "attribute", ")", "# the reader and writer methods", "rdr", ",", "wtr", "=", "prop", ".", "accessors", "# the inverse attribute metadata", "inv_prop", "=", "prop", ".", "inverse_property", "# the inverse attribute reader and writer", "inv_rdr", ",", "inv_wtr", "=", "inv_accessors", "=", "inv_prop", ".", "accessors", "# Redefine the writer method to update the inverse by delegating to the inverse.", "redefine_method", "(", "wtr", ")", "do", "|", "old_wtr", "|", "# the attribute reader and (superseded) writer", "accessors", "=", "[", "rdr", ",", "old_wtr", "]", "if", "inv_prop", ".", "collection?", "then", "lambda", "{", "|", "other", "|", "add_to_inverse_collection", "(", "other", ",", "accessors", ",", "inv_rdr", ")", "}", "else", "lambda", "{", "|", "other", "|", "set_inversible_noncollection_attribute", "(", "other", ",", "accessors", ",", "inv_wtr", ")", "}", "end", "end", "logger", ".", "debug", "{", "\"Injected inverse #{inv_prop} updater into #{qp}.#{attribute} writer method #{wtr}.\"", "}", "end" ]
Modifies the given attribute writer method to update the given inverse. @param (see #set_attribute_inverse)
[ "Modifies", "the", "given", "attribute", "writer", "method", "to", "update", "the", "given", "inverse", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/inverse.rb#L168-L187
7,104
jpsilvashy/epicmix
lib/epicmix.rb
Epicmix.Client.login
def login url = 'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/authenticate.ashx' options = { :query => { :loginID => username, :password => password }} response = HTTParty.post(url, options) token_from(response) # if response.instance_of? Net::HTTPOK end
ruby
def login url = 'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/authenticate.ashx' options = { :query => { :loginID => username, :password => password }} response = HTTParty.post(url, options) token_from(response) # if response.instance_of? Net::HTTPOK end
[ "def", "login", "url", "=", "'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/authenticate.ashx'", "options", "=", "{", ":query", "=>", "{", ":loginID", "=>", "username", ",", ":password", "=>", "password", "}", "}", "response", "=", "HTTParty", ".", "post", "(", "url", ",", "options", ")", "token_from", "(", "response", ")", "# if response.instance_of? Net::HTTPOK", "end" ]
Initializes and logs in to Epicmix Login to epic mix
[ "Initializes", "and", "logs", "in", "to", "Epicmix", "Login", "to", "epic", "mix" ]
c2d930c78e845f10115171ddd16b58f1db3af009
https://github.com/jpsilvashy/epicmix/blob/c2d930c78e845f10115171ddd16b58f1db3af009/lib/epicmix.rb#L17-L24
7,105
jpsilvashy/epicmix
lib/epicmix.rb
Epicmix.Client.season_stats
def season_stats url = 'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/userstats.ashx' options = { :timetype => 'season', :token => token } response = HTTParty.get(url, :query => options, :headers => headers) JSON.parse(response.body)['seasonStats'] end
ruby
def season_stats url = 'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/userstats.ashx' options = { :timetype => 'season', :token => token } response = HTTParty.get(url, :query => options, :headers => headers) JSON.parse(response.body)['seasonStats'] end
[ "def", "season_stats", "url", "=", "'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/userstats.ashx'", "options", "=", "{", ":timetype", "=>", "'season'", ",", ":token", "=>", "token", "}", "response", "=", "HTTParty", ".", "get", "(", "url", ",", ":query", "=>", "options", ",", ":headers", "=>", "headers", ")", "JSON", ".", "parse", "(", "response", ".", "body", ")", "[", "'seasonStats'", "]", "end" ]
Gets all your season stats
[ "Gets", "all", "your", "season", "stats" ]
c2d930c78e845f10115171ddd16b58f1db3af009
https://github.com/jpsilvashy/epicmix/blob/c2d930c78e845f10115171ddd16b58f1db3af009/lib/epicmix.rb#L27-L34
7,106
BideoWego/mousevc
lib/mousevc/validation.rb
Mousevc.Validation.min_length?
def min_length?(value, length) has_min_length = coerce_bool (value.length >= length) unless has_min_length @error = "Error, expected value to have at least #{length} characters, got: #{value.length}" end has_min_length end
ruby
def min_length?(value, length) has_min_length = coerce_bool (value.length >= length) unless has_min_length @error = "Error, expected value to have at least #{length} characters, got: #{value.length}" end has_min_length end
[ "def", "min_length?", "(", "value", ",", "length", ")", "has_min_length", "=", "coerce_bool", "(", "value", ".", "length", ">=", "length", ")", "unless", "has_min_length", "@error", "=", "\"Error, expected value to have at least #{length} characters, got: #{value.length}\"", "end", "has_min_length", "end" ]
Returns +true+ if the value has at least the specified length @param value [String] the value @param length [Integer] the length @return [Boolean]
[ "Returns", "+", "true", "+", "if", "the", "value", "has", "at", "least", "the", "specified", "length" ]
71bc2240afa3353250e39e50b3cb6a762a452836
https://github.com/BideoWego/mousevc/blob/71bc2240afa3353250e39e50b3cb6a762a452836/lib/mousevc/validation.rb#L71-L77
7,107
BideoWego/mousevc
lib/mousevc/validation.rb
Mousevc.Validation.max_length?
def max_length?(value, length) has_max_length = coerce_bool (value.length <= length) unless has_max_length @error = "Error, expected value to have at most #{length} characters, got: #{value.length}" end has_max_length end
ruby
def max_length?(value, length) has_max_length = coerce_bool (value.length <= length) unless has_max_length @error = "Error, expected value to have at most #{length} characters, got: #{value.length}" end has_max_length end
[ "def", "max_length?", "(", "value", ",", "length", ")", "has_max_length", "=", "coerce_bool", "(", "value", ".", "length", "<=", "length", ")", "unless", "has_max_length", "@error", "=", "\"Error, expected value to have at most #{length} characters, got: #{value.length}\"", "end", "has_max_length", "end" ]
Returns +true+ if the value has at most the specified length @param value [String] the value @param length [Integer] the length @return [Boolean]
[ "Returns", "+", "true", "+", "if", "the", "value", "has", "at", "most", "the", "specified", "length" ]
71bc2240afa3353250e39e50b3cb6a762a452836
https://github.com/BideoWego/mousevc/blob/71bc2240afa3353250e39e50b3cb6a762a452836/lib/mousevc/validation.rb#L86-L92
7,108
BideoWego/mousevc
lib/mousevc/validation.rb
Mousevc.Validation.exact_length?
def exact_length?(value, length) has_exact_length = coerce_bool (value.length == length) unless has_exact_length @error = "Error, expected value to have exactly #{length} characters, got: #{value.length}" end has_exact_length end
ruby
def exact_length?(value, length) has_exact_length = coerce_bool (value.length == length) unless has_exact_length @error = "Error, expected value to have exactly #{length} characters, got: #{value.length}" end has_exact_length end
[ "def", "exact_length?", "(", "value", ",", "length", ")", "has_exact_length", "=", "coerce_bool", "(", "value", ".", "length", "==", "length", ")", "unless", "has_exact_length", "@error", "=", "\"Error, expected value to have exactly #{length} characters, got: #{value.length}\"", "end", "has_exact_length", "end" ]
Returns +true+ if the value has exactly the specified length @param value [String] the value @param length [Integer] the length @return [Boolean]
[ "Returns", "+", "true", "+", "if", "the", "value", "has", "exactly", "the", "specified", "length" ]
71bc2240afa3353250e39e50b3cb6a762a452836
https://github.com/BideoWego/mousevc/blob/71bc2240afa3353250e39e50b3cb6a762a452836/lib/mousevc/validation.rb#L101-L107
7,109
ktkaushik/beta_invite
app/controllers/beta_invite/beta_invites_controller.rb
BetaInvite.BetaInvitesController.create
def create email = params[:beta_invite][:email] beta_invite = BetaInvite.new( email: email, token: SecureRandom.hex(10) ) if beta_invite.save flash[:success] = "#{email} has been registered for beta invite" # send an email if configured if BetaInviteSetup.send_email_to_admins BetaInvite::BetaInviteNotificationMailer.notify_admins( BetaInviteSetup.from_email, BetaInviteSetup.admin_emails, email, BetaInvite.count ).deliver end if BetaInviteSetup.send_thank_you_email BetaInvite::BetaInviteNotificationMailer.thank_user( BetaInviteSetup.from_email, email ).deliver end redirect_to beta_invites_path else flash[:alert] = beta_invite.errors.full_messages redirect_to new_beta_invite_path end end
ruby
def create email = params[:beta_invite][:email] beta_invite = BetaInvite.new( email: email, token: SecureRandom.hex(10) ) if beta_invite.save flash[:success] = "#{email} has been registered for beta invite" # send an email if configured if BetaInviteSetup.send_email_to_admins BetaInvite::BetaInviteNotificationMailer.notify_admins( BetaInviteSetup.from_email, BetaInviteSetup.admin_emails, email, BetaInvite.count ).deliver end if BetaInviteSetup.send_thank_you_email BetaInvite::BetaInviteNotificationMailer.thank_user( BetaInviteSetup.from_email, email ).deliver end redirect_to beta_invites_path else flash[:alert] = beta_invite.errors.full_messages redirect_to new_beta_invite_path end end
[ "def", "create", "email", "=", "params", "[", ":beta_invite", "]", "[", ":email", "]", "beta_invite", "=", "BetaInvite", ".", "new", "(", "email", ":", "email", ",", "token", ":", "SecureRandom", ".", "hex", "(", "10", ")", ")", "if", "beta_invite", ".", "save", "flash", "[", ":success", "]", "=", "\"#{email} has been registered for beta invite\"", "# send an email if configured", "if", "BetaInviteSetup", ".", "send_email_to_admins", "BetaInvite", "::", "BetaInviteNotificationMailer", ".", "notify_admins", "(", "BetaInviteSetup", ".", "from_email", ",", "BetaInviteSetup", ".", "admin_emails", ",", "email", ",", "BetaInvite", ".", "count", ")", ".", "deliver", "end", "if", "BetaInviteSetup", ".", "send_thank_you_email", "BetaInvite", "::", "BetaInviteNotificationMailer", ".", "thank_user", "(", "BetaInviteSetup", ".", "from_email", ",", "email", ")", ".", "deliver", "end", "redirect_to", "beta_invites_path", "else", "flash", "[", ":alert", "]", "=", "beta_invite", ".", "errors", ".", "full_messages", "redirect_to", "new_beta_invite_path", "end", "end" ]
Save the email and a randomly generated token
[ "Save", "the", "email", "and", "a", "randomly", "generated", "token" ]
9819622812516ac78e54f76cc516d616e993599a
https://github.com/ktkaushik/beta_invite/blob/9819622812516ac78e54f76cc516d616e993599a/app/controllers/beta_invite/beta_invites_controller.rb#L11-L31
7,110
spox/spockets
lib/spockets/watcher.rb
Spockets.Watcher.stop
def stop if(@runner.nil? && @stop) raise NotRunning.new elsif(@runner.nil? || [email protected]?) @stop = true @runner = nil else @stop = true if(@runner) @runner.raise Resync.new if @runner.alive? && @runner.stop? @runner.join(0.05) if @runner @runner.kill if @runner && @runner.alive? end @runner = nil end nil end
ruby
def stop if(@runner.nil? && @stop) raise NotRunning.new elsif(@runner.nil? || [email protected]?) @stop = true @runner = nil else @stop = true if(@runner) @runner.raise Resync.new if @runner.alive? && @runner.stop? @runner.join(0.05) if @runner @runner.kill if @runner && @runner.alive? end @runner = nil end nil end
[ "def", "stop", "if", "(", "@runner", ".", "nil?", "&&", "@stop", ")", "raise", "NotRunning", ".", "new", "elsif", "(", "@runner", ".", "nil?", "||", "!", "@runner", ".", "alive?", ")", "@stop", "=", "true", "@runner", "=", "nil", "else", "@stop", "=", "true", "if", "(", "@runner", ")", "@runner", ".", "raise", "Resync", ".", "new", "if", "@runner", ".", "alive?", "&&", "@runner", ".", "stop?", "@runner", ".", "join", "(", "0.05", ")", "if", "@runner", "@runner", ".", "kill", "if", "@runner", "&&", "@runner", ".", "alive?", "end", "@runner", "=", "nil", "end", "nil", "end" ]
stop the watcher
[ "stop", "the", "watcher" ]
48a314b0ca34a698489055f7a986d294906b74c1
https://github.com/spox/spockets/blob/48a314b0ca34a698489055f7a986d294906b74c1/lib/spockets/watcher.rb#L39-L55
7,111
spox/spockets
lib/spockets/watcher.rb
Spockets.Watcher.watch
def watch until(@stop) begin resultset = Kernel.select(@sockets.keys, nil, nil, nil) for sock in resultset[0] string = sock.gets if(sock.closed? || string.nil?) if(@sockets[sock][:closed]) @sockets[sock][:closed].each do |pr| pr[1].call(*([sock]+pr[0])) end end @sockets.delete(sock) else string = clean? ? do_clean(string) : string process(string.dup, sock) end end rescue Resync # break select and relisten # end end @runner = nil end
ruby
def watch until(@stop) begin resultset = Kernel.select(@sockets.keys, nil, nil, nil) for sock in resultset[0] string = sock.gets if(sock.closed? || string.nil?) if(@sockets[sock][:closed]) @sockets[sock][:closed].each do |pr| pr[1].call(*([sock]+pr[0])) end end @sockets.delete(sock) else string = clean? ? do_clean(string) : string process(string.dup, sock) end end rescue Resync # break select and relisten # end end @runner = nil end
[ "def", "watch", "until", "(", "@stop", ")", "begin", "resultset", "=", "Kernel", ".", "select", "(", "@sockets", ".", "keys", ",", "nil", ",", "nil", ",", "nil", ")", "for", "sock", "in", "resultset", "[", "0", "]", "string", "=", "sock", ".", "gets", "if", "(", "sock", ".", "closed?", "||", "string", ".", "nil?", ")", "if", "(", "@sockets", "[", "sock", "]", "[", ":closed", "]", ")", "@sockets", "[", "sock", "]", "[", ":closed", "]", ".", "each", "do", "|", "pr", "|", "pr", "[", "1", "]", ".", "call", "(", "(", "[", "sock", "]", "+", "pr", "[", "0", "]", ")", ")", "end", "end", "@sockets", ".", "delete", "(", "sock", ")", "else", "string", "=", "clean?", "?", "do_clean", "(", "string", ")", ":", "string", "process", "(", "string", ".", "dup", ",", "sock", ")", "end", "end", "rescue", "Resync", "# break select and relisten #", "end", "end", "@runner", "=", "nil", "end" ]
Watch the sockets and send strings for processing
[ "Watch", "the", "sockets", "and", "send", "strings", "for", "processing" ]
48a314b0ca34a698489055f7a986d294906b74c1
https://github.com/spox/spockets/blob/48a314b0ca34a698489055f7a986d294906b74c1/lib/spockets/watcher.rb#L76-L99
7,112
riddopic/hoodie
lib/hoodie/utils/file_helper.rb
Hoodie.FileHelper.command_in_path?
def command_in_path?(command) found = ENV['PATH'].split(File::PATH_SEPARATOR).map do |p| File.exist?(File.join(p, command)) end found.include?(true) end
ruby
def command_in_path?(command) found = ENV['PATH'].split(File::PATH_SEPARATOR).map do |p| File.exist?(File.join(p, command)) end found.include?(true) end
[ "def", "command_in_path?", "(", "command", ")", "found", "=", "ENV", "[", "'PATH'", "]", ".", "split", "(", "File", "::", "PATH_SEPARATOR", ")", ".", "map", "do", "|", "p", "|", "File", ".", "exist?", "(", "File", ".", "join", "(", "p", ",", "command", ")", ")", "end", "found", ".", "include?", "(", "true", ")", "end" ]
Checks in PATH returns true if the command is found. @param [String] command The name of the command to look for. @return [Boolean] True if the command is found in the path.
[ "Checks", "in", "PATH", "returns", "true", "if", "the", "command", "is", "found", "." ]
921601dd4849845d3f5d3765dafcf00178b2aa66
https://github.com/riddopic/hoodie/blob/921601dd4849845d3f5d3765dafcf00178b2aa66/lib/hoodie/utils/file_helper.rb#L35-L40
7,113
mbj/ducktrap
lib/ducktrap/pretty_dump.rb
Ducktrap.PrettyDump.pretty_inspect
def pretty_inspect io = StringIO.new formatter = Formatter.new(io) pretty_dump(formatter) io.rewind io.read end
ruby
def pretty_inspect io = StringIO.new formatter = Formatter.new(io) pretty_dump(formatter) io.rewind io.read end
[ "def", "pretty_inspect", "io", "=", "StringIO", ".", "new", "formatter", "=", "Formatter", ".", "new", "(", "io", ")", "pretty_dump", "(", "formatter", ")", "io", ".", "rewind", "io", ".", "read", "end" ]
Return pretty inspection @return [String] @api private
[ "Return", "pretty", "inspection" ]
482d874d3eb43b2dbb518b8537851d742d785903
https://github.com/mbj/ducktrap/blob/482d874d3eb43b2dbb518b8537851d742d785903/lib/ducktrap/pretty_dump.rb#L22-L28
7,114
PRX/fixer_client
lib/fixer/response.rb
Fixer.Response.method_missing
def method_missing(method_name, *args, &block) if self.has_key?(method_name.to_s) self.[](method_name, &block) elsif self.body.respond_to?(method_name) self.body.send(method_name, *args, &block) elsif self.request[:api].respond_to?(method_name) self.request[:api].send(method_name, *args, &block) else super end end
ruby
def method_missing(method_name, *args, &block) if self.has_key?(method_name.to_s) self.[](method_name, &block) elsif self.body.respond_to?(method_name) self.body.send(method_name, *args, &block) elsif self.request[:api].respond_to?(method_name) self.request[:api].send(method_name, *args, &block) else super end end
[ "def", "method_missing", "(", "method_name", ",", "*", "args", ",", "&", "block", ")", "if", "self", ".", "has_key?", "(", "method_name", ".", "to_s", ")", "self", ".", "[]", "(", "method_name", ",", "block", ")", "elsif", "self", ".", "body", ".", "respond_to?", "(", "method_name", ")", "self", ".", "body", ".", "send", "(", "method_name", ",", "args", ",", "block", ")", "elsif", "self", ".", "request", "[", ":api", "]", ".", "respond_to?", "(", "method_name", ")", "self", ".", "request", "[", ":api", "]", ".", "send", "(", "method_name", ",", "args", ",", "block", ")", "else", "super", "end", "end" ]
Coerce any method calls for body attributes
[ "Coerce", "any", "method", "calls", "for", "body", "attributes" ]
56dab7912496d3bcefe519eb326c99dcdb754ccf
https://github.com/PRX/fixer_client/blob/56dab7912496d3bcefe519eb326c99dcdb754ccf/lib/fixer/response.rb#L48-L58
7,115
salesking/sk_sdk
lib/sk_sdk/sync.rb
SK::SDK.Sync.update
def update(side, flds=nil) raise ArgumentError, 'The side to update must be :l or :r' unless [:l, :r].include?(side) target, source = (side==:l) ? [:l, :r] : [:r, :l] # use set field/s or update all flds ||= fields target_obj = self.send("#{target}_obj") source_obj = self.send("#{source}_obj") flds.each do |fld| target_name = fld.send("#{target}_name") source_name = fld.send("#{source}_name") # remember for log old_val = target_obj.send(target_name) rescue 'empty' # get new value through transfer method or direct new_val = if fld.transition? cur_trans = fld.send("#{target}_trans") eval "#{cur_trans} source_obj.send( source_name )" else source_obj.send( source_name ) end target_obj.send( "#{target_name}=" , new_val ) log << "#{target_name} was: #{old_val} updated from: #{source_name} with value: #{new_val}" end end
ruby
def update(side, flds=nil) raise ArgumentError, 'The side to update must be :l or :r' unless [:l, :r].include?(side) target, source = (side==:l) ? [:l, :r] : [:r, :l] # use set field/s or update all flds ||= fields target_obj = self.send("#{target}_obj") source_obj = self.send("#{source}_obj") flds.each do |fld| target_name = fld.send("#{target}_name") source_name = fld.send("#{source}_name") # remember for log old_val = target_obj.send(target_name) rescue 'empty' # get new value through transfer method or direct new_val = if fld.transition? cur_trans = fld.send("#{target}_trans") eval "#{cur_trans} source_obj.send( source_name )" else source_obj.send( source_name ) end target_obj.send( "#{target_name}=" , new_val ) log << "#{target_name} was: #{old_val} updated from: #{source_name} with value: #{new_val}" end end
[ "def", "update", "(", "side", ",", "flds", "=", "nil", ")", "raise", "ArgumentError", ",", "'The side to update must be :l or :r'", "unless", "[", ":l", ",", ":r", "]", ".", "include?", "(", "side", ")", "target", ",", "source", "=", "(", "side", "==", ":l", ")", "?", "[", ":l", ",", ":r", "]", ":", "[", ":r", ",", ":l", "]", "# use set field/s or update all", "flds", "||=", "fields", "target_obj", "=", "self", ".", "send", "(", "\"#{target}_obj\"", ")", "source_obj", "=", "self", ".", "send", "(", "\"#{source}_obj\"", ")", "flds", ".", "each", "do", "|", "fld", "|", "target_name", "=", "fld", ".", "send", "(", "\"#{target}_name\"", ")", "source_name", "=", "fld", ".", "send", "(", "\"#{source}_name\"", ")", "# remember for log", "old_val", "=", "target_obj", ".", "send", "(", "target_name", ")", "rescue", "'empty'", "# get new value through transfer method or direct", "new_val", "=", "if", "fld", ".", "transition?", "cur_trans", "=", "fld", ".", "send", "(", "\"#{target}_trans\"", ")", "eval", "\"#{cur_trans} source_obj.send( source_name )\"", "else", "source_obj", ".", "send", "(", "source_name", ")", "end", "target_obj", ".", "send", "(", "\"#{target_name}=\"", ",", "new_val", ")", "log", "<<", "\"#{target_name} was: #{old_val} updated from: #{source_name} with value: #{new_val}\"", "end", "end" ]
Update a side with the values from the other side. Populates the log with updated fields and values. @param [String|Symbol] side to update l OR r @param [Array<Field>, nil] flds fields to update, default nil update all fields
[ "Update", "a", "side", "with", "the", "values", "from", "the", "other", "side", ".", "Populates", "the", "log", "with", "updated", "fields", "and", "values", "." ]
03170b2807cc4e1f1ba44c704c308370c6563dbc
https://github.com/salesking/sk_sdk/blob/03170b2807cc4e1f1ba44c704c308370c6563dbc/lib/sk_sdk/sync.rb#L111-L134
7,116
mdub/pith
lib/pith/input.rb
Pith.Input.ignorable?
def ignorable? @ignorable ||= path.each_filename do |path_component| project.config.ignore_patterns.each do |pattern| return true if File.fnmatch(pattern, path_component) end end end
ruby
def ignorable? @ignorable ||= path.each_filename do |path_component| project.config.ignore_patterns.each do |pattern| return true if File.fnmatch(pattern, path_component) end end end
[ "def", "ignorable?", "@ignorable", "||=", "path", ".", "each_filename", "do", "|", "path_component", "|", "project", ".", "config", ".", "ignore_patterns", ".", "each", "do", "|", "pattern", "|", "return", "true", "if", "File", ".", "fnmatch", "(", "pattern", ",", "path_component", ")", "end", "end", "end" ]
Consider whether this input can be ignored. Returns true if it can.
[ "Consider", "whether", "this", "input", "can", "be", "ignored", "." ]
a78047cf65653172817b0527672bf6df960d510f
https://github.com/mdub/pith/blob/a78047cf65653172817b0527672bf6df960d510f/lib/pith/input.rb#L33-L39
7,117
mdub/pith
lib/pith/input.rb
Pith.Input.render
def render(context, locals = {}, &block) return file.read if !template? ensure_loaded pipeline.inject(@template_text) do |text, processor| template = processor.new(file.to_s, @template_start_line) { text } template.render(context, locals, &block) end end
ruby
def render(context, locals = {}, &block) return file.read if !template? ensure_loaded pipeline.inject(@template_text) do |text, processor| template = processor.new(file.to_s, @template_start_line) { text } template.render(context, locals, &block) end end
[ "def", "render", "(", "context", ",", "locals", "=", "{", "}", ",", "&", "block", ")", "return", "file", ".", "read", "if", "!", "template?", "ensure_loaded", "pipeline", ".", "inject", "(", "@template_text", ")", "do", "|", "text", ",", "processor", "|", "template", "=", "processor", ".", "new", "(", "file", ".", "to_s", ",", "@template_start_line", ")", "{", "text", "}", "template", ".", "render", "(", "context", ",", "locals", ",", "block", ")", "end", "end" ]
Render this input using Tilt
[ "Render", "this", "input", "using", "Tilt" ]
a78047cf65653172817b0527672bf6df960d510f
https://github.com/mdub/pith/blob/a78047cf65653172817b0527672bf6df960d510f/lib/pith/input.rb#L71-L78
7,118
mdub/pith
lib/pith/input.rb
Pith.Input.load
def load @load_time = Time.now @meta = {} if template? logger.debug "loading #{path}" file.open do |io| read_meta(io) @template_start_line = io.lineno + 1 @template_text = io.read end end end
ruby
def load @load_time = Time.now @meta = {} if template? logger.debug "loading #{path}" file.open do |io| read_meta(io) @template_start_line = io.lineno + 1 @template_text = io.read end end end
[ "def", "load", "@load_time", "=", "Time", ".", "now", "@meta", "=", "{", "}", "if", "template?", "logger", ".", "debug", "\"loading #{path}\"", "file", ".", "open", "do", "|", "io", "|", "read_meta", "(", "io", ")", "@template_start_line", "=", "io", ".", "lineno", "+", "1", "@template_text", "=", "io", ".", "read", "end", "end", "end" ]
Read input file, extracting YAML meta-data header, and template content.
[ "Read", "input", "file", "extracting", "YAML", "meta", "-", "data", "header", "and", "template", "content", "." ]
a78047cf65653172817b0527672bf6df960d510f
https://github.com/mdub/pith/blob/a78047cf65653172817b0527672bf6df960d510f/lib/pith/input.rb#L188-L199
7,119
4rlm/utf8_sanitizer
lib/utf8_sanitizer/utf.rb
Utf8Sanitizer.UTF.process_hash_row
def process_hash_row(hsh) if @headers.any? keys_or_values = hsh.values @row_id = hsh[:row_id] else keys_or_values = hsh.keys.map(&:to_s) end file_line = keys_or_values.join(',') validated_line = utf_filter(check_utf(file_line)) res = line_parse(validated_line) res end
ruby
def process_hash_row(hsh) if @headers.any? keys_or_values = hsh.values @row_id = hsh[:row_id] else keys_or_values = hsh.keys.map(&:to_s) end file_line = keys_or_values.join(',') validated_line = utf_filter(check_utf(file_line)) res = line_parse(validated_line) res end
[ "def", "process_hash_row", "(", "hsh", ")", "if", "@headers", ".", "any?", "keys_or_values", "=", "hsh", ".", "values", "@row_id", "=", "hsh", "[", ":row_id", "]", "else", "keys_or_values", "=", "hsh", ".", "keys", ".", "map", "(", ":to_s", ")", "end", "file_line", "=", "keys_or_values", ".", "join", "(", "','", ")", "validated_line", "=", "utf_filter", "(", "check_utf", "(", "file_line", ")", ")", "res", "=", "line_parse", "(", "validated_line", ")", "res", "end" ]
process_hash_row - helper VALIDATE HASHES Converts hash keys and vals into parsed line.
[ "process_hash_row", "-", "helper", "VALIDATE", "HASHES", "Converts", "hash", "keys", "and", "vals", "into", "parsed", "line", "." ]
4e7cb63cda21e5e4f5c4e954e468fbb4f854bb05
https://github.com/4rlm/utf8_sanitizer/blob/4e7cb63cda21e5e4f5c4e954e468fbb4f854bb05/lib/utf8_sanitizer/utf.rb#L63-L75
7,120
4rlm/utf8_sanitizer
lib/utf8_sanitizer/utf.rb
Utf8Sanitizer.UTF.line_parse
def line_parse(validated_line) return unless validated_line row = validated_line.split(',') return unless row.any? if @headers.empty? @headers = row else @data_hash.merge!(row_to_hsh(row)) @valid_rows << @data_hash end end
ruby
def line_parse(validated_line) return unless validated_line row = validated_line.split(',') return unless row.any? if @headers.empty? @headers = row else @data_hash.merge!(row_to_hsh(row)) @valid_rows << @data_hash end end
[ "def", "line_parse", "(", "validated_line", ")", "return", "unless", "validated_line", "row", "=", "validated_line", ".", "split", "(", "','", ")", "return", "unless", "row", ".", "any?", "if", "@headers", ".", "empty?", "@headers", "=", "row", "else", "@data_hash", ".", "merge!", "(", "row_to_hsh", "(", "row", ")", ")", "@valid_rows", "<<", "@data_hash", "end", "end" ]
line_parse - helper VALIDATE HASHES Parses line to row, then updates final results.
[ "line_parse", "-", "helper", "VALIDATE", "HASHES", "Parses", "line", "to", "row", "then", "updates", "final", "results", "." ]
4e7cb63cda21e5e4f5c4e954e468fbb4f854bb05
https://github.com/4rlm/utf8_sanitizer/blob/4e7cb63cda21e5e4f5c4e954e468fbb4f854bb05/lib/utf8_sanitizer/utf.rb#L79-L89
7,121
barkerest/shells
lib/shells/shell_base/prompt.rb
Shells.ShellBase.wait_for_prompt
def wait_for_prompt(silence_timeout = nil, command_timeout = nil, timeout_error = true) #:doc: raise Shells::NotRunning unless running? silence_timeout ||= options[:silence_timeout] command_timeout ||= options[:command_timeout] # when did we send a NL and how many have we sent while waiting for output? nudged_at = nil nudge_count = 0 silence_timeout = silence_timeout.to_s.to_f unless silence_timeout.is_a?(Numeric) nudge_seconds = if silence_timeout > 0 (silence_timeout / 3.0) # we want to nudge twice before officially timing out. else 0 end # if there is a limit for the command timeout, then set the absolute timeout for the loop. command_timeout = command_timeout.to_s.to_f unless command_timeout.is_a?(Numeric) timeout = if command_timeout > 0 Time.now + command_timeout else nil end # loop until the output matches the prompt regex. # if something gets output async server side, the silence timeout will be handy in getting the shell to reappear. # a match while waiting for output is invalid, so by requiring that flag to be false this should work with # unbuffered input as well. until output =~ prompt_match && !wait_for_output # hint that we need to let another thread run. Thread.pass last_response = last_output # Do we need to nudge the shell? if nudge_seconds > 0 && (Time.now - last_response) > nudge_seconds nudge_count = (nudged_at.nil? || nudged_at < last_response) ? 1 : (nudge_count + 1) # Have we previously nudged the shell? if nudge_count > 2 # we timeout on the third nudge. raise Shells::SilenceTimeout if timeout_error debug ' > silence timeout' return false else nudged_at = Time.now queue_input line_ending # wait a bit longer... self.last_output = nudged_at end end # honor the absolute timeout. if timeout && Time.now > timeout raise Shells::CommandTimeout if timeout_error debug ' > command timeout' return false end end # make sure there is a newline before the prompt, just to keep everything clean. pos = (output =~ prompt_match) if output[pos - 1] != "\n" # no newline before prompt, fix that. self.output = output[0...pos] + "\n" + output[pos..-1] end # make sure there is a newline at the end of STDOUT content buffer. if stdout[-1] != "\n" # no newline at end, fix that. self.stdout += "\n" end true end
ruby
def wait_for_prompt(silence_timeout = nil, command_timeout = nil, timeout_error = true) #:doc: raise Shells::NotRunning unless running? silence_timeout ||= options[:silence_timeout] command_timeout ||= options[:command_timeout] # when did we send a NL and how many have we sent while waiting for output? nudged_at = nil nudge_count = 0 silence_timeout = silence_timeout.to_s.to_f unless silence_timeout.is_a?(Numeric) nudge_seconds = if silence_timeout > 0 (silence_timeout / 3.0) # we want to nudge twice before officially timing out. else 0 end # if there is a limit for the command timeout, then set the absolute timeout for the loop. command_timeout = command_timeout.to_s.to_f unless command_timeout.is_a?(Numeric) timeout = if command_timeout > 0 Time.now + command_timeout else nil end # loop until the output matches the prompt regex. # if something gets output async server side, the silence timeout will be handy in getting the shell to reappear. # a match while waiting for output is invalid, so by requiring that flag to be false this should work with # unbuffered input as well. until output =~ prompt_match && !wait_for_output # hint that we need to let another thread run. Thread.pass last_response = last_output # Do we need to nudge the shell? if nudge_seconds > 0 && (Time.now - last_response) > nudge_seconds nudge_count = (nudged_at.nil? || nudged_at < last_response) ? 1 : (nudge_count + 1) # Have we previously nudged the shell? if nudge_count > 2 # we timeout on the third nudge. raise Shells::SilenceTimeout if timeout_error debug ' > silence timeout' return false else nudged_at = Time.now queue_input line_ending # wait a bit longer... self.last_output = nudged_at end end # honor the absolute timeout. if timeout && Time.now > timeout raise Shells::CommandTimeout if timeout_error debug ' > command timeout' return false end end # make sure there is a newline before the prompt, just to keep everything clean. pos = (output =~ prompt_match) if output[pos - 1] != "\n" # no newline before prompt, fix that. self.output = output[0...pos] + "\n" + output[pos..-1] end # make sure there is a newline at the end of STDOUT content buffer. if stdout[-1] != "\n" # no newline at end, fix that. self.stdout += "\n" end true end
[ "def", "wait_for_prompt", "(", "silence_timeout", "=", "nil", ",", "command_timeout", "=", "nil", ",", "timeout_error", "=", "true", ")", "#:doc:\r", "raise", "Shells", "::", "NotRunning", "unless", "running?", "silence_timeout", "||=", "options", "[", ":silence_timeout", "]", "command_timeout", "||=", "options", "[", ":command_timeout", "]", "# when did we send a NL and how many have we sent while waiting for output?\r", "nudged_at", "=", "nil", "nudge_count", "=", "0", "silence_timeout", "=", "silence_timeout", ".", "to_s", ".", "to_f", "unless", "silence_timeout", ".", "is_a?", "(", "Numeric", ")", "nudge_seconds", "=", "if", "silence_timeout", ">", "0", "(", "silence_timeout", "/", "3.0", ")", "# we want to nudge twice before officially timing out.\r", "else", "0", "end", "# if there is a limit for the command timeout, then set the absolute timeout for the loop.\r", "command_timeout", "=", "command_timeout", ".", "to_s", ".", "to_f", "unless", "command_timeout", ".", "is_a?", "(", "Numeric", ")", "timeout", "=", "if", "command_timeout", ">", "0", "Time", ".", "now", "+", "command_timeout", "else", "nil", "end", "# loop until the output matches the prompt regex.\r", "# if something gets output async server side, the silence timeout will be handy in getting the shell to reappear.\r", "# a match while waiting for output is invalid, so by requiring that flag to be false this should work with\r", "# unbuffered input as well.\r", "until", "output", "=~", "prompt_match", "&&", "!", "wait_for_output", "# hint that we need to let another thread run.\r", "Thread", ".", "pass", "last_response", "=", "last_output", "# Do we need to nudge the shell?\r", "if", "nudge_seconds", ">", "0", "&&", "(", "Time", ".", "now", "-", "last_response", ")", ">", "nudge_seconds", "nudge_count", "=", "(", "nudged_at", ".", "nil?", "||", "nudged_at", "<", "last_response", ")", "?", "1", ":", "(", "nudge_count", "+", "1", ")", "# Have we previously nudged the shell?\r", "if", "nudge_count", ">", "2", "# we timeout on the third nudge.\r", "raise", "Shells", "::", "SilenceTimeout", "if", "timeout_error", "debug", "' > silence timeout'", "return", "false", "else", "nudged_at", "=", "Time", ".", "now", "queue_input", "line_ending", "# wait a bit longer...\r", "self", ".", "last_output", "=", "nudged_at", "end", "end", "# honor the absolute timeout.\r", "if", "timeout", "&&", "Time", ".", "now", ">", "timeout", "raise", "Shells", "::", "CommandTimeout", "if", "timeout_error", "debug", "' > command timeout'", "return", "false", "end", "end", "# make sure there is a newline before the prompt, just to keep everything clean.\r", "pos", "=", "(", "output", "=~", "prompt_match", ")", "if", "output", "[", "pos", "-", "1", "]", "!=", "\"\\n\"", "# no newline before prompt, fix that.\r", "self", ".", "output", "=", "output", "[", "0", "...", "pos", "]", "+", "\"\\n\"", "+", "output", "[", "pos", "..", "-", "1", "]", "end", "# make sure there is a newline at the end of STDOUT content buffer.\r", "if", "stdout", "[", "-", "1", "]", "!=", "\"\\n\"", "# no newline at end, fix that.\r", "self", ".", "stdout", "+=", "\"\\n\"", "end", "true", "end" ]
Waits for the prompt to appear at the end of the output. Once the prompt appears, new input can be sent to the shell. This is automatically called in +exec+ so you would only need to call it directly if you were sending data manually to the shell. This method is used internally in the +exec+ method, but there may be legitimate use cases outside of that method as well.
[ "Waits", "for", "the", "prompt", "to", "appear", "at", "the", "end", "of", "the", "output", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/prompt.rb#L46-L124
7,122
barkerest/shells
lib/shells/shell_base/prompt.rb
Shells.ShellBase.temporary_prompt
def temporary_prompt(prompt) #:doc: raise Shells::NotRunning unless running? old_prompt = prompt_match begin self.prompt_match = prompt yield if block_given? ensure self.prompt_match = old_prompt end end
ruby
def temporary_prompt(prompt) #:doc: raise Shells::NotRunning unless running? old_prompt = prompt_match begin self.prompt_match = prompt yield if block_given? ensure self.prompt_match = old_prompt end end
[ "def", "temporary_prompt", "(", "prompt", ")", "#:doc:\r", "raise", "Shells", "::", "NotRunning", "unless", "running?", "old_prompt", "=", "prompt_match", "begin", "self", ".", "prompt_match", "=", "prompt", "yield", "if", "block_given?", "ensure", "self", ".", "prompt_match", "=", "old_prompt", "end", "end" ]
Sets the prompt to the value temporarily for execution of the code block.
[ "Sets", "the", "prompt", "to", "the", "value", "temporarily", "for", "execution", "of", "the", "code", "block", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/prompt.rb#L128-L137
7,123
jakewendt/simply_authorized
generators/simply_authorized/simply_authorized_generator.rb
Rails::Generator::Commands.Base.next_migration_string
def next_migration_string(padding = 3) @s = ([email protected]?)? @s.to_i + 1 : if ActiveRecord::Base.timestamped_migrations Time.now.utc.strftime("%Y%m%d%H%M%S") else "%.#{padding}d" % next_migration_number end end
ruby
def next_migration_string(padding = 3) @s = ([email protected]?)? @s.to_i + 1 : if ActiveRecord::Base.timestamped_migrations Time.now.utc.strftime("%Y%m%d%H%M%S") else "%.#{padding}d" % next_migration_number end end
[ "def", "next_migration_string", "(", "padding", "=", "3", ")", "@s", "=", "(", "!", "@s", ".", "nil?", ")", "?", "@s", ".", "to_i", "+", "1", ":", "if", "ActiveRecord", "::", "Base", ".", "timestamped_migrations", "Time", ".", "now", ".", "utc", ".", "strftime", "(", "\"%Y%m%d%H%M%S\"", ")", "else", "\"%.#{padding}d\"", "%", "next_migration_number", "end", "end" ]
the loop through migrations happens so fast that they all have the same timestamp which won't work when you actually try to migrate. All the timestamps MUST be unique.
[ "the", "loop", "through", "migrations", "happens", "so", "fast", "that", "they", "all", "have", "the", "same", "timestamp", "which", "won", "t", "work", "when", "you", "actually", "try", "to", "migrate", ".", "All", "the", "timestamps", "MUST", "be", "unique", "." ]
11a1c8bfdf1561bf14243a516cdbe901aac55e53
https://github.com/jakewendt/simply_authorized/blob/11a1c8bfdf1561bf14243a516cdbe901aac55e53/generators/simply_authorized/simply_authorized_generator.rb#L76-L82
7,124
Hubro/rozi
lib/rozi/shared.rb
Rozi.Shared.interpret_color
def interpret_color(color) if color.is_a? String # Turns RRGGBB into BBGGRR for hex conversion. color = color[-2..-1] << color[2..3] << color[0..1] color = color.to_i(16) end color end
ruby
def interpret_color(color) if color.is_a? String # Turns RRGGBB into BBGGRR for hex conversion. color = color[-2..-1] << color[2..3] << color[0..1] color = color.to_i(16) end color end
[ "def", "interpret_color", "(", "color", ")", "if", "color", ".", "is_a?", "String", "# Turns RRGGBB into BBGGRR for hex conversion.", "color", "=", "color", "[", "-", "2", "..", "-", "1", "]", "<<", "color", "[", "2", "..", "3", "]", "<<", "color", "[", "0", "..", "1", "]", "color", "=", "color", ".", "to_i", "(", "16", ")", "end", "color", "end" ]
Converts the input to an RGB color represented by an integer @param [String, Integer] color Can be a RRGGBB hex string or an integer @return [Integer] @example interpret_color(255) # => 255 interpret_color("ABCDEF") # => 15715755
[ "Converts", "the", "input", "to", "an", "RGB", "color", "represented", "by", "an", "integer" ]
05a52dcc947be2e9bd0c7e881b9770239b28290a
https://github.com/Hubro/rozi/blob/05a52dcc947be2e9bd0c7e881b9770239b28290a/lib/rozi/shared.rb#L34-L42
7,125
BideoWego/mousevc
lib/mousevc/app.rb
Mousevc.App.listen
def listen begin clear_view @router.route unless Input.quit? reset if Input.reset? end until Input.quit? end
ruby
def listen begin clear_view @router.route unless Input.quit? reset if Input.reset? end until Input.quit? end
[ "def", "listen", "begin", "clear_view", "@router", ".", "route", "unless", "Input", ".", "quit?", "reset", "if", "Input", ".", "reset?", "end", "until", "Input", ".", "quit?", "end" ]
Runs the application loop. Clears the system view each iteration. Calls route on the router instance. If the user is trying to reset or quit the application responds accordingly. Clears Input class variables before exit.
[ "Runs", "the", "application", "loop", ".", "Clears", "the", "system", "view", "each", "iteration", ".", "Calls", "route", "on", "the", "router", "instance", "." ]
71bc2240afa3353250e39e50b3cb6a762a452836
https://github.com/BideoWego/mousevc/blob/71bc2240afa3353250e39e50b3cb6a762a452836/lib/mousevc/app.rb#L124-L130
7,126
jinx/core
lib/jinx/helpers/log.rb
Jinx.MultilineLogger.format_message
def format_message(severity, datetime, progname, msg) if String === msg then msg.inject('') { |s, line| s << super(severity, datetime, progname, line.chomp) } else super end end
ruby
def format_message(severity, datetime, progname, msg) if String === msg then msg.inject('') { |s, line| s << super(severity, datetime, progname, line.chomp) } else super end end
[ "def", "format_message", "(", "severity", ",", "datetime", ",", "progname", ",", "msg", ")", "if", "String", "===", "msg", "then", "msg", ".", "inject", "(", "''", ")", "{", "|", "s", ",", "line", "|", "s", "<<", "super", "(", "severity", ",", "datetime", ",", "progname", ",", "line", ".", "chomp", ")", "}", "else", "super", "end", "end" ]
Writes msg to the log device. Each line in msg is formatted separately. @param (see Logger#format_message) @return (see Logger#format_message)
[ "Writes", "msg", "to", "the", "log", "device", ".", "Each", "line", "in", "msg", "is", "formatted", "separately", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/helpers/log.rb#L39-L45
7,127
stormbrew/user_input
lib/user_input/type_safe_hash.rb
UserInput.TypeSafeHash.each_pair
def each_pair(type, default = nil) real_hash.each_key() { |key| value = fetch(key, type, default) if (!value.nil?) yield(key, value) end } end
ruby
def each_pair(type, default = nil) real_hash.each_key() { |key| value = fetch(key, type, default) if (!value.nil?) yield(key, value) end } end
[ "def", "each_pair", "(", "type", ",", "default", "=", "nil", ")", "real_hash", ".", "each_key", "(", ")", "{", "|", "key", "|", "value", "=", "fetch", "(", "key", ",", "type", ",", "default", ")", "if", "(", "!", "value", ".", "nil?", ")", "yield", "(", "key", ",", "value", ")", "end", "}", "end" ]
Enumerates the key, value pairs in the has.
[ "Enumerates", "the", "key", "value", "pairs", "in", "the", "has", "." ]
593a1deb08f0634089d25542971ad0ac57542259
https://github.com/stormbrew/user_input/blob/593a1deb08f0634089d25542971ad0ac57542259/lib/user_input/type_safe_hash.rb#L60-L67
7,128
stormbrew/user_input
lib/user_input/type_safe_hash.rb
UserInput.TypeSafeHash.each_match
def each_match(regex, type, default = nil) real_hash.each_key() { |key| if (matchinfo = regex.match(key)) value = fetch(key, type, default) if (!value.nil?) yield(matchinfo, value) end end } end
ruby
def each_match(regex, type, default = nil) real_hash.each_key() { |key| if (matchinfo = regex.match(key)) value = fetch(key, type, default) if (!value.nil?) yield(matchinfo, value) end end } end
[ "def", "each_match", "(", "regex", ",", "type", ",", "default", "=", "nil", ")", "real_hash", ".", "each_key", "(", ")", "{", "|", "key", "|", "if", "(", "matchinfo", "=", "regex", ".", "match", "(", "key", ")", ")", "value", "=", "fetch", "(", "key", ",", "type", ",", "default", ")", "if", "(", "!", "value", ".", "nil?", ")", "yield", "(", "matchinfo", ",", "value", ")", "end", "end", "}", "end" ]
Enumerates keys that match a regex, passing the match object and the value.
[ "Enumerates", "keys", "that", "match", "a", "regex", "passing", "the", "match", "object", "and", "the", "value", "." ]
593a1deb08f0634089d25542971ad0ac57542259
https://github.com/stormbrew/user_input/blob/593a1deb08f0634089d25542971ad0ac57542259/lib/user_input/type_safe_hash.rb#L71-L80
7,129
booqable/scoped_serializer
lib/scoped_serializer/serializer.rb
ScopedSerializer.Serializer.attributes_hash
def attributes_hash attributes = @scope.attributes.collect do |attr| value = fetch_property(attr) if value.kind_of?(BigDecimal) value = value.to_f end [attr, value] end Hash[attributes] end
ruby
def attributes_hash attributes = @scope.attributes.collect do |attr| value = fetch_property(attr) if value.kind_of?(BigDecimal) value = value.to_f end [attr, value] end Hash[attributes] end
[ "def", "attributes_hash", "attributes", "=", "@scope", ".", "attributes", ".", "collect", "do", "|", "attr", "|", "value", "=", "fetch_property", "(", "attr", ")", "if", "value", ".", "kind_of?", "(", "BigDecimal", ")", "value", "=", "value", ".", "to_f", "end", "[", "attr", ",", "value", "]", "end", "Hash", "[", "attributes", "]", "end" ]
Collects attributes for serialization. Attributes can be overwritten in the serializer. @return [Hash]
[ "Collects", "attributes", "for", "serialization", ".", "Attributes", "can", "be", "overwritten", "in", "the", "serializer", "." ]
fb163bbf61f54a5e8684e4aba3908592bdd986ac
https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/serializer.rb#L96-L108
7,130
booqable/scoped_serializer
lib/scoped_serializer/serializer.rb
ScopedSerializer.Serializer.associations_hash
def associations_hash hash = {} @scope.associations.each do |association, options| hash.merge!(render_association(association, options)) end hash end
ruby
def associations_hash hash = {} @scope.associations.each do |association, options| hash.merge!(render_association(association, options)) end hash end
[ "def", "associations_hash", "hash", "=", "{", "}", "@scope", ".", "associations", ".", "each", "do", "|", "association", ",", "options", "|", "hash", ".", "merge!", "(", "render_association", "(", "association", ",", "options", ")", ")", "end", "hash", "end" ]
Collects associations for serialization. Associations can be overwritten in the serializer. @return [Hash]
[ "Collects", "associations", "for", "serialization", ".", "Associations", "can", "be", "overwritten", "in", "the", "serializer", "." ]
fb163bbf61f54a5e8684e4aba3908592bdd986ac
https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/serializer.rb#L116-L122
7,131
booqable/scoped_serializer
lib/scoped_serializer/serializer.rb
ScopedSerializer.Serializer.render_association
def render_association(association_data, options={}) hash = {} if association_data.is_a?(Hash) association_data.each do |association, association_options| data = render_association(association, options.merge(:include => association_options)) hash.merge!(data) if data end elsif association_data.is_a?(Array) association_data.each do |option| data = render_association(option) hash.merge!(data) if data end else if options[:preload] includes = options[:preload] == true ? options[:include] : options[:preload] end if (object = fetch_association(association_data, includes)) data = ScopedSerializer.for(object, options.merge(:associations => options[:include])).as_json hash.merge!(data) if data end end hash end
ruby
def render_association(association_data, options={}) hash = {} if association_data.is_a?(Hash) association_data.each do |association, association_options| data = render_association(association, options.merge(:include => association_options)) hash.merge!(data) if data end elsif association_data.is_a?(Array) association_data.each do |option| data = render_association(option) hash.merge!(data) if data end else if options[:preload] includes = options[:preload] == true ? options[:include] : options[:preload] end if (object = fetch_association(association_data, includes)) data = ScopedSerializer.for(object, options.merge(:associations => options[:include])).as_json hash.merge!(data) if data end end hash end
[ "def", "render_association", "(", "association_data", ",", "options", "=", "{", "}", ")", "hash", "=", "{", "}", "if", "association_data", ".", "is_a?", "(", "Hash", ")", "association_data", ".", "each", "do", "|", "association", ",", "association_options", "|", "data", "=", "render_association", "(", "association", ",", "options", ".", "merge", "(", ":include", "=>", "association_options", ")", ")", "hash", ".", "merge!", "(", "data", ")", "if", "data", "end", "elsif", "association_data", ".", "is_a?", "(", "Array", ")", "association_data", ".", "each", "do", "|", "option", "|", "data", "=", "render_association", "(", "option", ")", "hash", ".", "merge!", "(", "data", ")", "if", "data", "end", "else", "if", "options", "[", ":preload", "]", "includes", "=", "options", "[", ":preload", "]", "==", "true", "?", "options", "[", ":include", "]", ":", "options", "[", ":preload", "]", "end", "if", "(", "object", "=", "fetch_association", "(", "association_data", ",", "includes", ")", ")", "data", "=", "ScopedSerializer", ".", "for", "(", "object", ",", "options", ".", "merge", "(", ":associations", "=>", "options", "[", ":include", "]", ")", ")", ".", "as_json", "hash", ".", "merge!", "(", "data", ")", "if", "data", "end", "end", "hash", "end" ]
Renders a specific association. @return [Hash] @example render_association(:employee) render_association([:employee, :company]) render_association({ :employee => :address })
[ "Renders", "a", "specific", "association", "." ]
fb163bbf61f54a5e8684e4aba3908592bdd986ac
https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/serializer.rb#L134-L159
7,132
booqable/scoped_serializer
lib/scoped_serializer/serializer.rb
ScopedSerializer.Serializer.fetch_property
def fetch_property(property) return nil unless property unless respond_to?(property) object = @resource.send(property) else object = send(property) end end
ruby
def fetch_property(property) return nil unless property unless respond_to?(property) object = @resource.send(property) else object = send(property) end end
[ "def", "fetch_property", "(", "property", ")", "return", "nil", "unless", "property", "unless", "respond_to?", "(", "property", ")", "object", "=", "@resource", ".", "send", "(", "property", ")", "else", "object", "=", "send", "(", "property", ")", "end", "end" ]
Fetches property from the serializer or resource. This method makes it possible to overwrite defined attributes or associations.
[ "Fetches", "property", "from", "the", "serializer", "or", "resource", ".", "This", "method", "makes", "it", "possible", "to", "overwrite", "defined", "attributes", "or", "associations", "." ]
fb163bbf61f54a5e8684e4aba3908592bdd986ac
https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/serializer.rb#L165-L173
7,133
booqable/scoped_serializer
lib/scoped_serializer/serializer.rb
ScopedSerializer.Serializer.fetch_association
def fetch_association(name, includes=nil) association = fetch_property(name) if includes.present? && ! @resource.association(name).loaded? association.includes(includes) else association end end
ruby
def fetch_association(name, includes=nil) association = fetch_property(name) if includes.present? && ! @resource.association(name).loaded? association.includes(includes) else association end end
[ "def", "fetch_association", "(", "name", ",", "includes", "=", "nil", ")", "association", "=", "fetch_property", "(", "name", ")", "if", "includes", ".", "present?", "&&", "!", "@resource", ".", "association", "(", "name", ")", ".", "loaded?", "association", ".", "includes", "(", "includes", ")", "else", "association", "end", "end" ]
Fetches association and eager loads data. Doesn't eager load when includes is empty or when the association has already been loaded. @example fetch_association(:comments, :user)
[ "Fetches", "association", "and", "eager", "loads", "data", ".", "Doesn", "t", "eager", "load", "when", "includes", "is", "empty", "or", "when", "the", "association", "has", "already", "been", "loaded", "." ]
fb163bbf61f54a5e8684e4aba3908592bdd986ac
https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/serializer.rb#L182-L190
7,134
inside-track/remi
lib/remi/job.rb
Remi.Job.execute
def execute(*components) execute_transforms if components.empty? || components.include?(:transforms) execute_sub_jobs if components.empty? || components.include?(:sub_jobs) execute_load_targets if components.empty? || components.include?(:load_targets) self end
ruby
def execute(*components) execute_transforms if components.empty? || components.include?(:transforms) execute_sub_jobs if components.empty? || components.include?(:sub_jobs) execute_load_targets if components.empty? || components.include?(:load_targets) self end
[ "def", "execute", "(", "*", "components", ")", "execute_transforms", "if", "components", ".", "empty?", "||", "components", ".", "include?", "(", ":transforms", ")", "execute_sub_jobs", "if", "components", ".", "empty?", "||", "components", ".", "include?", "(", ":sub_jobs", ")", "execute_load_targets", "if", "components", ".", "empty?", "||", "components", ".", "include?", "(", ":load_targets", ")", "self", "end" ]
Execute the specified components of the job. @param components [Array<symbol>] list of components to execute (e.g., `:transforms`, `:load_targets`) @return [self]
[ "Execute", "the", "specified", "components", "of", "the", "job", "." ]
f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7
https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/job.rb#L284-L289
7,135
tclaus/keytechkit.gem
lib/keytechKit/user.rb
KeytechKit.User.load
def load(username) options = {} options[:basic_auth] = @auth response = self.class.get("/user/#{username}", options) if response.success? self.response = response parse_response self else raise response.response end end
ruby
def load(username) options = {} options[:basic_auth] = @auth response = self.class.get("/user/#{username}", options) if response.success? self.response = response parse_response self else raise response.response end end
[ "def", "load", "(", "username", ")", "options", "=", "{", "}", "options", "[", ":basic_auth", "]", "=", "@auth", "response", "=", "self", ".", "class", ".", "get", "(", "\"/user/#{username}\"", ",", "options", ")", "if", "response", ".", "success?", "self", ".", "response", "=", "response", "parse_response", "self", "else", "raise", "response", ".", "response", "end", "end" ]
Returns a updated user object username = key of user
[ "Returns", "a", "updated", "user", "object", "username", "=", "key", "of", "user" ]
caa7a6bee32b75ec18a4004179ae10cb69d148c2
https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/user.rb#L27-L38
7,136
jinx/core
lib/jinx/metadata/dependency.rb
Jinx.Dependency.add_dependent_property
def add_dependent_property(property, *flags) logger.debug { "Marking #{qp}.#{property} as a dependent attribute of type #{property.type.qp}..." } flags << :dependent unless flags.include?(:dependent) property.qualify(*flags) inv = property.inverse inv_type = property.type # example: Parent.add_dependent_property(child_prop) with inverse :parent calls the following: # Child.add_owner(Parent, :children, :parent) inv_type.add_owner(self, property.attribute, inv) if inv then logger.debug "Marked #{qp}.#{property} as a dependent attribute with inverse #{inv_type.qp}.#{inv}." else logger.debug "Marked #{qp}.#{property} as a uni-directional dependent attribute." end end
ruby
def add_dependent_property(property, *flags) logger.debug { "Marking #{qp}.#{property} as a dependent attribute of type #{property.type.qp}..." } flags << :dependent unless flags.include?(:dependent) property.qualify(*flags) inv = property.inverse inv_type = property.type # example: Parent.add_dependent_property(child_prop) with inverse :parent calls the following: # Child.add_owner(Parent, :children, :parent) inv_type.add_owner(self, property.attribute, inv) if inv then logger.debug "Marked #{qp}.#{property} as a dependent attribute with inverse #{inv_type.qp}.#{inv}." else logger.debug "Marked #{qp}.#{property} as a uni-directional dependent attribute." end end
[ "def", "add_dependent_property", "(", "property", ",", "*", "flags", ")", "logger", ".", "debug", "{", "\"Marking #{qp}.#{property} as a dependent attribute of type #{property.type.qp}...\"", "}", "flags", "<<", ":dependent", "unless", "flags", ".", "include?", "(", ":dependent", ")", "property", ".", "qualify", "(", "flags", ")", "inv", "=", "property", ".", "inverse", "inv_type", "=", "property", ".", "type", "# example: Parent.add_dependent_property(child_prop) with inverse :parent calls the following:", "# Child.add_owner(Parent, :children, :parent)", "inv_type", ".", "add_owner", "(", "self", ",", "property", ".", "attribute", ",", "inv", ")", "if", "inv", "then", "logger", ".", "debug", "\"Marked #{qp}.#{property} as a dependent attribute with inverse #{inv_type.qp}.#{inv}.\"", "else", "logger", ".", "debug", "\"Marked #{qp}.#{property} as a uni-directional dependent attribute.\"", "end", "end" ]
Adds the given property as a dependent. If the property inverse is not a collection, then the property writer is modified to delegate to the dependent owner writer. This enforces referential integrity by ensuring that the following post-condition holds: * _owner_._attribute_._inverse_ == _owner_ where: * _owner_ is an instance this property's declaring class * _inverse_ is the owner inverse attribute defined in the dependent class @param [Property] property the dependent to add @param [<Symbol>] flags the attribute qualifier flags
[ "Adds", "the", "given", "property", "as", "a", "dependent", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/dependency.rb#L21-L35
7,137
jinx/core
lib/jinx/metadata/dependency.rb
Jinx.Dependency.add_owner
def add_owner(klass, inverse, attribute=nil) if inverse.nil? then raise ValidationError.new("Owner #{klass.qp} missing dependent attribute for dependent #{qp}") end logger.debug { "Adding #{qp} owner #{klass.qp}#{' attribute ' + attribute.to_s if attribute} with inverse #{inverse}..." } if @owner_prop_hash then raise MetadataError.new("Can't add #{qp} owner #{klass.qp} after dependencies have been accessed") end # Detect the owner attribute, if necessary. attribute ||= detect_owner_attribute(klass, inverse) hash = local_owner_property_hash # Guard against a conflicting owner reference attribute. if hash[klass] then raise MetadataError.new("Cannot set #{qp} owner attribute to #{attribute or 'nil'} since it is already set to #{hash[klass]}") end # Add the owner class => attribute entry. # The attribute is nil if the dependency is unidirectional, i.e. there is an owner class which # references this class via a dependency attribute but there is no inverse owner attribute. prop = property(attribute) if attribute hash[klass] = prop # If the dependency is unidirectional, then our job is done. if attribute.nil? then logger.debug { "#{qp} owner #{klass.qp} has unidirectional dependent attribute #{inverse}." } return end # Bi-directional: add the owner property. local_owner_properties << prop # Set the inverse if necessary. unless prop.inverse then set_attribute_inverse(attribute, inverse) end # Set the owner flag if necessary. prop.qualify(:owner) unless prop.owner? # Redefine the writer method to issue a warning if the owner is changed. rdr, wtr = prop.accessors redefine_method(wtr) do |old_wtr| lambda do |ref| prev = send(rdr) send(old_wtr, ref) if prev and prev != ref then if ref.nil? then logger.warn("Unset the #{self} owner #{attribute} #{prev}.") elsif ref.key != prev.key then logger.warn("Reset the #{self} owner #{attribute} from #{prev} to #{ref}.") end end ref end end logger.debug { "Injected owner change warning into #{qp}.#{attribute} writer method #{wtr}." } logger.debug { "#{qp} owner #{klass.qp} attribute is #{attribute} with inverse #{inverse}." } end
ruby
def add_owner(klass, inverse, attribute=nil) if inverse.nil? then raise ValidationError.new("Owner #{klass.qp} missing dependent attribute for dependent #{qp}") end logger.debug { "Adding #{qp} owner #{klass.qp}#{' attribute ' + attribute.to_s if attribute} with inverse #{inverse}..." } if @owner_prop_hash then raise MetadataError.new("Can't add #{qp} owner #{klass.qp} after dependencies have been accessed") end # Detect the owner attribute, if necessary. attribute ||= detect_owner_attribute(klass, inverse) hash = local_owner_property_hash # Guard against a conflicting owner reference attribute. if hash[klass] then raise MetadataError.new("Cannot set #{qp} owner attribute to #{attribute or 'nil'} since it is already set to #{hash[klass]}") end # Add the owner class => attribute entry. # The attribute is nil if the dependency is unidirectional, i.e. there is an owner class which # references this class via a dependency attribute but there is no inverse owner attribute. prop = property(attribute) if attribute hash[klass] = prop # If the dependency is unidirectional, then our job is done. if attribute.nil? then logger.debug { "#{qp} owner #{klass.qp} has unidirectional dependent attribute #{inverse}." } return end # Bi-directional: add the owner property. local_owner_properties << prop # Set the inverse if necessary. unless prop.inverse then set_attribute_inverse(attribute, inverse) end # Set the owner flag if necessary. prop.qualify(:owner) unless prop.owner? # Redefine the writer method to issue a warning if the owner is changed. rdr, wtr = prop.accessors redefine_method(wtr) do |old_wtr| lambda do |ref| prev = send(rdr) send(old_wtr, ref) if prev and prev != ref then if ref.nil? then logger.warn("Unset the #{self} owner #{attribute} #{prev}.") elsif ref.key != prev.key then logger.warn("Reset the #{self} owner #{attribute} from #{prev} to #{ref}.") end end ref end end logger.debug { "Injected owner change warning into #{qp}.#{attribute} writer method #{wtr}." } logger.debug { "#{qp} owner #{klass.qp} attribute is #{attribute} with inverse #{inverse}." } end
[ "def", "add_owner", "(", "klass", ",", "inverse", ",", "attribute", "=", "nil", ")", "if", "inverse", ".", "nil?", "then", "raise", "ValidationError", ".", "new", "(", "\"Owner #{klass.qp} missing dependent attribute for dependent #{qp}\"", ")", "end", "logger", ".", "debug", "{", "\"Adding #{qp} owner #{klass.qp}#{' attribute ' + attribute.to_s if attribute} with inverse #{inverse}...\"", "}", "if", "@owner_prop_hash", "then", "raise", "MetadataError", ".", "new", "(", "\"Can't add #{qp} owner #{klass.qp} after dependencies have been accessed\"", ")", "end", "# Detect the owner attribute, if necessary.", "attribute", "||=", "detect_owner_attribute", "(", "klass", ",", "inverse", ")", "hash", "=", "local_owner_property_hash", "# Guard against a conflicting owner reference attribute.", "if", "hash", "[", "klass", "]", "then", "raise", "MetadataError", ".", "new", "(", "\"Cannot set #{qp} owner attribute to #{attribute or 'nil'} since it is already set to #{hash[klass]}\"", ")", "end", "# Add the owner class => attribute entry.", "# The attribute is nil if the dependency is unidirectional, i.e. there is an owner class which", "# references this class via a dependency attribute but there is no inverse owner attribute.", "prop", "=", "property", "(", "attribute", ")", "if", "attribute", "hash", "[", "klass", "]", "=", "prop", "# If the dependency is unidirectional, then our job is done.", "if", "attribute", ".", "nil?", "then", "logger", ".", "debug", "{", "\"#{qp} owner #{klass.qp} has unidirectional dependent attribute #{inverse}.\"", "}", "return", "end", "# Bi-directional: add the owner property.", "local_owner_properties", "<<", "prop", "# Set the inverse if necessary.", "unless", "prop", ".", "inverse", "then", "set_attribute_inverse", "(", "attribute", ",", "inverse", ")", "end", "# Set the owner flag if necessary.", "prop", ".", "qualify", "(", ":owner", ")", "unless", "prop", ".", "owner?", "# Redefine the writer method to issue a warning if the owner is changed.", "rdr", ",", "wtr", "=", "prop", ".", "accessors", "redefine_method", "(", "wtr", ")", "do", "|", "old_wtr", "|", "lambda", "do", "|", "ref", "|", "prev", "=", "send", "(", "rdr", ")", "send", "(", "old_wtr", ",", "ref", ")", "if", "prev", "and", "prev", "!=", "ref", "then", "if", "ref", ".", "nil?", "then", "logger", ".", "warn", "(", "\"Unset the #{self} owner #{attribute} #{prev}.\"", ")", "elsif", "ref", ".", "key", "!=", "prev", ".", "key", "then", "logger", ".", "warn", "(", "\"Reset the #{self} owner #{attribute} from #{prev} to #{ref}.\"", ")", "end", "end", "ref", "end", "end", "logger", ".", "debug", "{", "\"Injected owner change warning into #{qp}.#{attribute} writer method #{wtr}.\"", "}", "logger", ".", "debug", "{", "\"#{qp} owner #{klass.qp} attribute is #{attribute} with inverse #{inverse}.\"", "}", "end" ]
Adds the given owner class to this dependent class. This method must be called before any dependent attribute is accessed. If the attribute is given, then the attribute inverse is set. Otherwise, if there is not already an owner attribute, then a new owner attribute is created. The name of the new attribute is the lower-case demodulized owner class name. @param [Class] the owner class @param [Symbol] inverse the owner -> dependent attribute @param [Symbol, nil] attribute the dependent -> owner attribute, if known @raise [ValidationError] if the inverse is nil
[ "Adds", "the", "given", "owner", "class", "to", "this", "dependent", "class", ".", "This", "method", "must", "be", "called", "before", "any", "dependent", "attribute", "is", "accessed", ".", "If", "the", "attribute", "is", "given", "then", "the", "attribute", "inverse", "is", "set", ".", "Otherwise", "if", "there", "is", "not", "already", "an", "owner", "attribute", "then", "a", "new", "owner", "attribute", "is", "created", ".", "The", "name", "of", "the", "new", "attribute", "is", "the", "lower", "-", "case", "demodulized", "owner", "class", "name", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/dependency.rb#L146-L200
7,138
jinx/core
lib/jinx/metadata/dependency.rb
Jinx.Dependency.add_owner_attribute
def add_owner_attribute(attribute) prop = property(attribute) otype = prop.type hash = local_owner_property_hash if hash.include?(otype) then oa = hash[otype] unless oa.nil? then raise MetadataError.new("Cannot set #{qp} owner attribute to #{attribute} since it is already set to #{oa}") end hash[otype] = prop else add_owner(otype, prop.inverse, attribute) end end
ruby
def add_owner_attribute(attribute) prop = property(attribute) otype = prop.type hash = local_owner_property_hash if hash.include?(otype) then oa = hash[otype] unless oa.nil? then raise MetadataError.new("Cannot set #{qp} owner attribute to #{attribute} since it is already set to #{oa}") end hash[otype] = prop else add_owner(otype, prop.inverse, attribute) end end
[ "def", "add_owner_attribute", "(", "attribute", ")", "prop", "=", "property", "(", "attribute", ")", "otype", "=", "prop", ".", "type", "hash", "=", "local_owner_property_hash", "if", "hash", ".", "include?", "(", "otype", ")", "then", "oa", "=", "hash", "[", "otype", "]", "unless", "oa", ".", "nil?", "then", "raise", "MetadataError", ".", "new", "(", "\"Cannot set #{qp} owner attribute to #{attribute} since it is already set to #{oa}\"", ")", "end", "hash", "[", "otype", "]", "=", "prop", "else", "add_owner", "(", "otype", ",", "prop", ".", "inverse", ",", "attribute", ")", "end", "end" ]
Adds the given attribute as an owner. This method is called when a new attribute is added that references an existing owner. @param [Symbol] attribute the owner attribute
[ "Adds", "the", "given", "attribute", "as", "an", "owner", ".", "This", "method", "is", "called", "when", "a", "new", "attribute", "is", "added", "that", "references", "an", "existing", "owner", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/dependency.rb#L206-L219
7,139
nrser/nrser.rb
lib/nrser/errors/abstract_method_error.rb
NRSER.AbstractMethodError.method_instance
def method_instance lazy_var :@method_instance do # Just drop a warning if we can't get the method object logger.catch.warn( "Failed to get method", instance: instance, method_name: method_name, ) do instance.method method_name end end end
ruby
def method_instance lazy_var :@method_instance do # Just drop a warning if we can't get the method object logger.catch.warn( "Failed to get method", instance: instance, method_name: method_name, ) do instance.method method_name end end end
[ "def", "method_instance", "lazy_var", ":@method_instance", "do", "# Just drop a warning if we can't get the method object", "logger", ".", "catch", ".", "warn", "(", "\"Failed to get method\"", ",", "instance", ":", "instance", ",", "method_name", ":", "method_name", ",", ")", "do", "instance", ".", "method", "method_name", "end", "end", "end" ]
Construct a new `AbstractMethodError`. @param [Object] instance Instance that invoked the abstract method. @param [Symbol | String] method_name Name of abstract method. #initialize
[ "Construct", "a", "new", "AbstractMethodError", "." ]
7db9a729ec65894dfac13fd50851beae8b809738
https://github.com/nrser/nrser.rb/blob/7db9a729ec65894dfac13fd50851beae8b809738/lib/nrser/errors/abstract_method_error.rb#L88-L99
7,140
ghuls-apps/ghuls-lib
lib/ghuls/lib.rb
GHULS.Lib.get_user_and_check
def get_user_and_check(user) user_full = @octokit.user(user) { username: user_full[:login], avatar: user_full[:avatar_url] } rescue Octokit::NotFound return false end
ruby
def get_user_and_check(user) user_full = @octokit.user(user) { username: user_full[:login], avatar: user_full[:avatar_url] } rescue Octokit::NotFound return false end
[ "def", "get_user_and_check", "(", "user", ")", "user_full", "=", "@octokit", ".", "user", "(", "user", ")", "{", "username", ":", "user_full", "[", ":login", "]", ",", "avatar", ":", "user_full", "[", ":avatar_url", "]", "}", "rescue", "Octokit", "::", "NotFound", "return", "false", "end" ]
Gets the Octokit and colors for the program. @param opts [Hash] The options to use. The ones that are used by this method are: :token, :pass, and :user. @return [Hash] A hash containing objects formatted as { git: Octokit::Client, colors: JSON } Gets the user and checks if it exists in the process. @param user [Any] The user ID or name. @return [Hash] Their username and avatar URL. @return [Boolean] False if it does not exist.
[ "Gets", "the", "Octokit", "and", "colors", "for", "the", "program", "." ]
2f8324d8508610ee1fe0007bf4a89b39e95b85f6
https://github.com/ghuls-apps/ghuls-lib/blob/2f8324d8508610ee1fe0007bf4a89b39e95b85f6/lib/ghuls/lib.rb#L43-L51
7,141
ghuls-apps/ghuls-lib
lib/ghuls/lib.rb
GHULS.Lib.get_forks_stars_watchers
def get_forks_stars_watchers(repository) { forks: @octokit.forks(repository).length, stars: @octokit.stargazers(repository).length, watchers: @octokit.subscribers(repository).length } end
ruby
def get_forks_stars_watchers(repository) { forks: @octokit.forks(repository).length, stars: @octokit.stargazers(repository).length, watchers: @octokit.subscribers(repository).length } end
[ "def", "get_forks_stars_watchers", "(", "repository", ")", "{", "forks", ":", "@octokit", ".", "forks", "(", "repository", ")", ".", "length", ",", "stars", ":", "@octokit", ".", "stargazers", "(", "repository", ")", ".", "length", ",", "watchers", ":", "@octokit", ".", "subscribers", "(", "repository", ")", ".", "length", "}", "end" ]
Gets the number of forkers, stargazers, and watchers. @param repository [String] The full repository name. @return [Hash] The forks, stars, and watcher count.
[ "Gets", "the", "number", "of", "forkers", "stargazers", "and", "watchers", "." ]
2f8324d8508610ee1fe0007bf4a89b39e95b85f6
https://github.com/ghuls-apps/ghuls-lib/blob/2f8324d8508610ee1fe0007bf4a89b39e95b85f6/lib/ghuls/lib.rb#L92-L98
7,142
ghuls-apps/ghuls-lib
lib/ghuls/lib.rb
GHULS.Lib.get_followers_following
def get_followers_following(username) { following: @octokit.following(username).length, followers: @octokit.followers(username).length } end
ruby
def get_followers_following(username) { following: @octokit.following(username).length, followers: @octokit.followers(username).length } end
[ "def", "get_followers_following", "(", "username", ")", "{", "following", ":", "@octokit", ".", "following", "(", "username", ")", ".", "length", ",", "followers", ":", "@octokit", ".", "followers", "(", "username", ")", ".", "length", "}", "end" ]
Gets the number of followers and users followed by the user. @param username [String] See #get_user_and_check @return [Hash] The number of following and followed users.
[ "Gets", "the", "number", "of", "followers", "and", "users", "followed", "by", "the", "user", "." ]
2f8324d8508610ee1fe0007bf4a89b39e95b85f6
https://github.com/ghuls-apps/ghuls-lib/blob/2f8324d8508610ee1fe0007bf4a89b39e95b85f6/lib/ghuls/lib.rb#L103-L108
7,143
ghuls-apps/ghuls-lib
lib/ghuls/lib.rb
GHULS.Lib.get_user_langs
def get_user_langs(username) repos = get_user_repos(username) langs = {} repos[:public].each do |r| next if repos[:forks].include? r repo_langs = @octokit.languages(r) repo_langs.each do |l, b| if langs[l].nil? langs[l] = b else langs[l] += b end end end langs end
ruby
def get_user_langs(username) repos = get_user_repos(username) langs = {} repos[:public].each do |r| next if repos[:forks].include? r repo_langs = @octokit.languages(r) repo_langs.each do |l, b| if langs[l].nil? langs[l] = b else langs[l] += b end end end langs end
[ "def", "get_user_langs", "(", "username", ")", "repos", "=", "get_user_repos", "(", "username", ")", "langs", "=", "{", "}", "repos", "[", ":public", "]", ".", "each", "do", "|", "r", "|", "next", "if", "repos", "[", ":forks", "]", ".", "include?", "r", "repo_langs", "=", "@octokit", ".", "languages", "(", "r", ")", "repo_langs", ".", "each", "do", "|", "l", ",", "b", "|", "if", "langs", "[", "l", "]", ".", "nil?", "langs", "[", "l", "]", "=", "b", "else", "langs", "[", "l", "]", "+=", "b", "end", "end", "end", "langs", "end" ]
Gets the langauges and their bytes for the user. @param username [String] See #get_user_and_check @return [Hash] The languages and their bytes, as formatted as { :Ruby => 129890, :CoffeeScript => 5970 }
[ "Gets", "the", "langauges", "and", "their", "bytes", "for", "the", "user", "." ]
2f8324d8508610ee1fe0007bf4a89b39e95b85f6
https://github.com/ghuls-apps/ghuls-lib/blob/2f8324d8508610ee1fe0007bf4a89b39e95b85f6/lib/ghuls/lib.rb#L151-L166
7,144
ghuls-apps/ghuls-lib
lib/ghuls/lib.rb
GHULS.Lib.get_org_langs
def get_org_langs(username) org_repos = get_org_repos(username) langs = {} org_repos[:public].each do |r| next if org_repos[:forks].include? r repo_langs = @octokit.languages(r) repo_langs.each do |l, b| if langs[l].nil? langs[l] = b else langs[l] += b end end end langs end
ruby
def get_org_langs(username) org_repos = get_org_repos(username) langs = {} org_repos[:public].each do |r| next if org_repos[:forks].include? r repo_langs = @octokit.languages(r) repo_langs.each do |l, b| if langs[l].nil? langs[l] = b else langs[l] += b end end end langs end
[ "def", "get_org_langs", "(", "username", ")", "org_repos", "=", "get_org_repos", "(", "username", ")", "langs", "=", "{", "}", "org_repos", "[", ":public", "]", ".", "each", "do", "|", "r", "|", "next", "if", "org_repos", "[", ":forks", "]", ".", "include?", "r", "repo_langs", "=", "@octokit", ".", "languages", "(", "r", ")", "repo_langs", ".", "each", "do", "|", "l", ",", "b", "|", "if", "langs", "[", "l", "]", ".", "nil?", "langs", "[", "l", "]", "=", "b", "else", "langs", "[", "l", "]", "+=", "b", "end", "end", "end", "langs", "end" ]
Gets the languages and their bytes for the user's organizations. @param username [String] See #get_user_and_check @return [Hash] See #get_user_langs
[ "Gets", "the", "languages", "and", "their", "bytes", "for", "the", "user", "s", "organizations", "." ]
2f8324d8508610ee1fe0007bf4a89b39e95b85f6
https://github.com/ghuls-apps/ghuls-lib/blob/2f8324d8508610ee1fe0007bf4a89b39e95b85f6/lib/ghuls/lib.rb#L171-L186
7,145
ghuls-apps/ghuls-lib
lib/ghuls/lib.rb
GHULS.Lib.get_color_for_language
def get_color_for_language(lang) color_lang = @colors[lang] color = color_lang['color'] if color_lang.nil? || color.nil? return StringUtility.random_color_six else return color end end
ruby
def get_color_for_language(lang) color_lang = @colors[lang] color = color_lang['color'] if color_lang.nil? || color.nil? return StringUtility.random_color_six else return color end end
[ "def", "get_color_for_language", "(", "lang", ")", "color_lang", "=", "@colors", "[", "lang", "]", "color", "=", "color_lang", "[", "'color'", "]", "if", "color_lang", ".", "nil?", "||", "color", ".", "nil?", "return", "StringUtility", ".", "random_color_six", "else", "return", "color", "end", "end" ]
Gets the defined color for the language. @param lang [String] The language name. @return [String] The 6 digit hexidecimal color. @return [Nil] If there is no defined color for the language.
[ "Gets", "the", "defined", "color", "for", "the", "language", "." ]
2f8324d8508610ee1fe0007bf4a89b39e95b85f6
https://github.com/ghuls-apps/ghuls-lib/blob/2f8324d8508610ee1fe0007bf4a89b39e95b85f6/lib/ghuls/lib.rb#L192-L200
7,146
ghuls-apps/ghuls-lib
lib/ghuls/lib.rb
GHULS.Lib.get_language_percentages
def get_language_percentages(langs) total = 0 langs.each { |_, b| total += b } lang_percents = {} langs.each do |l, b| percent = self.class.calculate_percent(b, total.to_f) lang_percents[l] = percent.round(2) end lang_percents end
ruby
def get_language_percentages(langs) total = 0 langs.each { |_, b| total += b } lang_percents = {} langs.each do |l, b| percent = self.class.calculate_percent(b, total.to_f) lang_percents[l] = percent.round(2) end lang_percents end
[ "def", "get_language_percentages", "(", "langs", ")", "total", "=", "0", "langs", ".", "each", "{", "|", "_", ",", "b", "|", "total", "+=", "b", "}", "lang_percents", "=", "{", "}", "langs", ".", "each", "do", "|", "l", ",", "b", "|", "percent", "=", "self", ".", "class", ".", "calculate_percent", "(", "b", ",", "total", ".", "to_f", ")", "lang_percents", "[", "l", "]", "=", "percent", ".", "round", "(", "2", ")", "end", "lang_percents", "end" ]
Gets the percentages for each language in a hash. @param langs [Hash] The language hash obtained by the get_langs methods. @return [Hash] The language percentages formatted as { Ruby: 50%, CoffeeScript: 50% }
[ "Gets", "the", "percentages", "for", "each", "language", "in", "a", "hash", "." ]
2f8324d8508610ee1fe0007bf4a89b39e95b85f6
https://github.com/ghuls-apps/ghuls-lib/blob/2f8324d8508610ee1fe0007bf4a89b39e95b85f6/lib/ghuls/lib.rb#L206-L215
7,147
rubiojr/yumrepo
lib/yumrepo.rb
YumRepo.Repomd.filelists
def filelists fl = [] @repomd.xpath("/xmlns:repomd/xmlns:data[@type=\"filelists\"]/xmlns:location").each do |f| fl << File.join(@url, f['href']) end fl end
ruby
def filelists fl = [] @repomd.xpath("/xmlns:repomd/xmlns:data[@type=\"filelists\"]/xmlns:location").each do |f| fl << File.join(@url, f['href']) end fl end
[ "def", "filelists", "fl", "=", "[", "]", "@repomd", ".", "xpath", "(", "\"/xmlns:repomd/xmlns:data[@type=\\\"filelists\\\"]/xmlns:location\"", ")", ".", "each", "do", "|", "f", "|", "fl", "<<", "File", ".", "join", "(", "@url", ",", "f", "[", "'href'", "]", ")", "end", "fl", "end" ]
Rasises exception if can't retrieve repomd.xml
[ "Rasises", "exception", "if", "can", "t", "retrieve", "repomd", ".", "xml" ]
9fd44835a6160ef0959823a3e3d91963ce61456e
https://github.com/rubiojr/yumrepo/blob/9fd44835a6160ef0959823a3e3d91963ce61456e/lib/yumrepo.rb#L107-L113
7,148
vpacher/xpay
lib/xpay/payment.rb
Xpay.Payment.rewrite_request_block
def rewrite_request_block(auth_type="ST3DAUTH") # set the required AUTH type REXML::XPath.first(@request_xml, "//Request").attributes["Type"] = auth_type # delete term url and merchant name ops = REXML::XPath.first(@request_xml, "//Operation") ["TermUrl", "MerchantName"].each { |e| ops.delete_element e } # delete accept and user agent in customer info customer_info = REXML::XPath.first(@request_xml, "//CustomerInfo") ["Accept", "UserAgent"].each { |e| customer_info.delete_element e } # delete credit card details and add TransactionVerifier and TransactionReference from response xml # CC details are not needed anymore as verifier and reference are sufficient cc_details = REXML::XPath.first(@request_xml, "//CreditCard") ["Number", "Type", "SecurityCode", "StartDate", "ExpiryDate", "Issue"].each { |e| cc_details.delete_element e } cc_details.add_element("TransactionVerifier").text = REXML::XPath.first(@response_xml, "//TransactionVerifier").text cc_details.add_element("ParentTransactionReference").text = REXML::XPath.first(@response_xml, "//TransactionReference").text # unless it is an AUTH request, add additional required info for a 3DAUTH request unless auth_type == "AUTH" pm_method = REXML::XPath.first(@request_xml, "//PaymentMethod") threedsecure = pm_method.add_element("ThreeDSecure") threedsecure.add_element("Enrolled").text = REXML::XPath.first(@response_xml, "//Enrolled").text threedsecure.add_element("MD").text = REXML::XPath.first(@response_xml, "//MD").text rescue "" end true end
ruby
def rewrite_request_block(auth_type="ST3DAUTH") # set the required AUTH type REXML::XPath.first(@request_xml, "//Request").attributes["Type"] = auth_type # delete term url and merchant name ops = REXML::XPath.first(@request_xml, "//Operation") ["TermUrl", "MerchantName"].each { |e| ops.delete_element e } # delete accept and user agent in customer info customer_info = REXML::XPath.first(@request_xml, "//CustomerInfo") ["Accept", "UserAgent"].each { |e| customer_info.delete_element e } # delete credit card details and add TransactionVerifier and TransactionReference from response xml # CC details are not needed anymore as verifier and reference are sufficient cc_details = REXML::XPath.first(@request_xml, "//CreditCard") ["Number", "Type", "SecurityCode", "StartDate", "ExpiryDate", "Issue"].each { |e| cc_details.delete_element e } cc_details.add_element("TransactionVerifier").text = REXML::XPath.first(@response_xml, "//TransactionVerifier").text cc_details.add_element("ParentTransactionReference").text = REXML::XPath.first(@response_xml, "//TransactionReference").text # unless it is an AUTH request, add additional required info for a 3DAUTH request unless auth_type == "AUTH" pm_method = REXML::XPath.first(@request_xml, "//PaymentMethod") threedsecure = pm_method.add_element("ThreeDSecure") threedsecure.add_element("Enrolled").text = REXML::XPath.first(@response_xml, "//Enrolled").text threedsecure.add_element("MD").text = REXML::XPath.first(@response_xml, "//MD").text rescue "" end true end
[ "def", "rewrite_request_block", "(", "auth_type", "=", "\"ST3DAUTH\"", ")", "# set the required AUTH type", "REXML", "::", "XPath", ".", "first", "(", "@request_xml", ",", "\"//Request\"", ")", ".", "attributes", "[", "\"Type\"", "]", "=", "auth_type", "# delete term url and merchant name", "ops", "=", "REXML", "::", "XPath", ".", "first", "(", "@request_xml", ",", "\"//Operation\"", ")", "[", "\"TermUrl\"", ",", "\"MerchantName\"", "]", ".", "each", "{", "|", "e", "|", "ops", ".", "delete_element", "e", "}", "# delete accept and user agent in customer info", "customer_info", "=", "REXML", "::", "XPath", ".", "first", "(", "@request_xml", ",", "\"//CustomerInfo\"", ")", "[", "\"Accept\"", ",", "\"UserAgent\"", "]", ".", "each", "{", "|", "e", "|", "customer_info", ".", "delete_element", "e", "}", "# delete credit card details and add TransactionVerifier and TransactionReference from response xml", "# CC details are not needed anymore as verifier and reference are sufficient", "cc_details", "=", "REXML", "::", "XPath", ".", "first", "(", "@request_xml", ",", "\"//CreditCard\"", ")", "[", "\"Number\"", ",", "\"Type\"", ",", "\"SecurityCode\"", ",", "\"StartDate\"", ",", "\"ExpiryDate\"", ",", "\"Issue\"", "]", ".", "each", "{", "|", "e", "|", "cc_details", ".", "delete_element", "e", "}", "cc_details", ".", "add_element", "(", "\"TransactionVerifier\"", ")", ".", "text", "=", "REXML", "::", "XPath", ".", "first", "(", "@response_xml", ",", "\"//TransactionVerifier\"", ")", ".", "text", "cc_details", ".", "add_element", "(", "\"ParentTransactionReference\"", ")", ".", "text", "=", "REXML", "::", "XPath", ".", "first", "(", "@response_xml", ",", "\"//TransactionReference\"", ")", ".", "text", "# unless it is an AUTH request, add additional required info for a 3DAUTH request", "unless", "auth_type", "==", "\"AUTH\"", "pm_method", "=", "REXML", "::", "XPath", ".", "first", "(", "@request_xml", ",", "\"//PaymentMethod\"", ")", "threedsecure", "=", "pm_method", ".", "add_element", "(", "\"ThreeDSecure\"", ")", "threedsecure", ".", "add_element", "(", "\"Enrolled\"", ")", ".", "text", "=", "REXML", "::", "XPath", ".", "first", "(", "@response_xml", ",", "\"//Enrolled\"", ")", ".", "text", "threedsecure", ".", "add_element", "(", "\"MD\"", ")", ".", "text", "=", "REXML", "::", "XPath", ".", "first", "(", "@response_xml", ",", "\"//MD\"", ")", ".", "text", "rescue", "\"\"", "end", "true", "end" ]
Rewrites the request according to the response coming from SecureTrading according to the required auth_type This only applies if the inital request was a ST3DCARDQUERY It deletes elements which are not needed for the subsequent request and adds the required additional information if an ST3DAUTH is needed
[ "Rewrites", "the", "request", "according", "to", "the", "response", "coming", "from", "SecureTrading", "according", "to", "the", "required", "auth_type", "This", "only", "applies", "if", "the", "inital", "request", "was", "a", "ST3DCARDQUERY", "It", "deletes", "elements", "which", "are", "not", "needed", "for", "the", "subsequent", "request", "and", "adds", "the", "required", "additional", "information", "if", "an", "ST3DAUTH", "is", "needed" ]
58c0b0f2600ed30ff44b84f97b96c74590474f3f
https://github.com/vpacher/xpay/blob/58c0b0f2600ed30ff44b84f97b96c74590474f3f/lib/xpay/payment.rb#L172-L200
7,149
OiNutter/skeletor
lib/skeletor/cli.rb
Skeletor.CLI.clean
def clean print 'Are you sure you want to clean this project directory? (Y|n): ' confirm = $stdin.gets.chomp if confirm != 'Y' && confirm != 'n' puts 'Please enter Y or n' elsif confirm == 'Y' path = options[:directory] || Dir.pwd Builder.clean path end end
ruby
def clean print 'Are you sure you want to clean this project directory? (Y|n): ' confirm = $stdin.gets.chomp if confirm != 'Y' && confirm != 'n' puts 'Please enter Y or n' elsif confirm == 'Y' path = options[:directory] || Dir.pwd Builder.clean path end end
[ "def", "clean", "print", "'Are you sure you want to clean this project directory? (Y|n): '", "confirm", "=", "$stdin", ".", "gets", ".", "chomp", "if", "confirm", "!=", "'Y'", "&&", "confirm", "!=", "'n'", "puts", "'Please enter Y or n'", "elsif", "confirm", "==", "'Y'", "path", "=", "options", "[", ":directory", "]", "||", "Dir", ".", "pwd", "Builder", ".", "clean", "path", "end", "end" ]
Cleans out the specified directory
[ "Cleans", "out", "the", "specified", "directory" ]
c3996c346bbf8009f7135855aabfd4f411aaa2e1
https://github.com/OiNutter/skeletor/blob/c3996c346bbf8009f7135855aabfd4f411aaa2e1/lib/skeletor/cli.rb#L32-L42
7,150
jamescook/layabout
lib/layabout/file_upload.rb
Layabout.FileUpload.wrap
def wrap(http_response) OpenStruct.new.tap do |obj| obj.code = http_response.code.to_i obj.body = http_response.body obj.headers = {} http_response.each_header{|k,v| obj.headers[k] = v } end end
ruby
def wrap(http_response) OpenStruct.new.tap do |obj| obj.code = http_response.code.to_i obj.body = http_response.body obj.headers = {} http_response.each_header{|k,v| obj.headers[k] = v } end end
[ "def", "wrap", "(", "http_response", ")", "OpenStruct", ".", "new", ".", "tap", "do", "|", "obj", "|", "obj", ".", "code", "=", "http_response", ".", "code", ".", "to_i", "obj", ".", "body", "=", "http_response", ".", "body", "obj", ".", "headers", "=", "{", "}", "http_response", ".", "each_header", "{", "|", "k", ",", "v", "|", "obj", ".", "headers", "[", "k", "]", "=", "v", "}", "end", "end" ]
HTTPI doesn't support multipart posts. We can work around it by using another gem and handing off something that looks like a HTTPI response
[ "HTTPI", "doesn", "t", "support", "multipart", "posts", ".", "We", "can", "work", "around", "it", "by", "using", "another", "gem", "and", "handing", "off", "something", "that", "looks", "like", "a", "HTTPI", "response" ]
87d4cf3f03cd617fba55112ef5339a43ddf828a3
https://github.com/jamescook/layabout/blob/87d4cf3f03cd617fba55112ef5339a43ddf828a3/lib/layabout/file_upload.rb#L30-L37
7,151
Montage-Inc/ruby-montage
lib/montage/query/order_parser.rb
Montage.OrderParser.clause_valid?
def clause_valid? if @clause.is_a?(Hash) @clause.flatten.find do |e| return true unless (/\basc\b|\bdesc\b/).match(e).nil? end else return true unless @clause.split.empty? end end
ruby
def clause_valid? if @clause.is_a?(Hash) @clause.flatten.find do |e| return true unless (/\basc\b|\bdesc\b/).match(e).nil? end else return true unless @clause.split.empty? end end
[ "def", "clause_valid?", "if", "@clause", ".", "is_a?", "(", "Hash", ")", "@clause", ".", "flatten", ".", "find", "do", "|", "e", "|", "return", "true", "unless", "(", "/", "\\b", "\\b", "\\b", "\\b", "/", ")", ".", "match", "(", "e", ")", ".", "nil?", "end", "else", "return", "true", "unless", "@clause", ".", "split", ".", "empty?", "end", "end" ]
Creates an OrderParser instance based on a clause argument. The instance can then be parsed into a valid ReQON string for queries * *Args* : - +clause+ -> A hash or string ordering value * *Returns* : - A Montage::OrderParser instance * *Raises* : - +ClauseFormatError+ -> If a blank string clause or a hash without a valid direction is found. Validates clause arguments by checking a hash for a full word match of "asc" or "desc". String clauses are rejected if they are blank or consist entirely of whitespace * *Returns* : - A boolean
[ "Creates", "an", "OrderParser", "instance", "based", "on", "a", "clause", "argument", ".", "The", "instance", "can", "then", "be", "parsed", "into", "a", "valid", "ReQON", "string", "for", "queries" ]
2e6f7e591f2f87158994c17ad9619fa29b716bad
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/order_parser.rb#L33-L41
7,152
Montage-Inc/ruby-montage
lib/montage/query/order_parser.rb
Montage.OrderParser.parse_hash
def parse_hash direction = clause.values.first field = clause.keys.first.to_s ["$order_by", ["$#{direction}", field]] end
ruby
def parse_hash direction = clause.values.first field = clause.keys.first.to_s ["$order_by", ["$#{direction}", field]] end
[ "def", "parse_hash", "direction", "=", "clause", ".", "values", ".", "first", "field", "=", "clause", ".", "keys", ".", "first", ".", "to_s", "[", "\"$order_by\"", ",", "[", "\"$#{direction}\"", ",", "field", "]", "]", "end" ]
Parses a hash clause * *Returns* : - A ReQON formatted array * *Examples* : @clause = { test: "asc"} @clause.parse => ["$order_by", ["$asc", "test"]]
[ "Parses", "a", "hash", "clause" ]
2e6f7e591f2f87158994c17ad9619fa29b716bad
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/order_parser.rb#L52-L56
7,153
Montage-Inc/ruby-montage
lib/montage/query/order_parser.rb
Montage.OrderParser.parse_string
def parse_string direction = clause.split[1] field = clause.split[0] direction = "asc" unless %w(asc desc).include?(direction) ["$order_by", ["$#{direction}", field]] end
ruby
def parse_string direction = clause.split[1] field = clause.split[0] direction = "asc" unless %w(asc desc).include?(direction) ["$order_by", ["$#{direction}", field]] end
[ "def", "parse_string", "direction", "=", "clause", ".", "split", "[", "1", "]", "field", "=", "clause", ".", "split", "[", "0", "]", "direction", "=", "\"asc\"", "unless", "%w(", "asc", "desc", ")", ".", "include?", "(", "direction", ")", "[", "\"$order_by\"", ",", "[", "\"$#{direction}\"", ",", "field", "]", "]", "end" ]
Parses a string clause, defaults direction to asc if missing or invalid * *Returns* : - A ReQON formatted array * *Examples* : @clause = "happy_trees desc" @clause.parse => ["$order_by", ["$desc", "happy_trees"]]
[ "Parses", "a", "string", "clause", "defaults", "direction", "to", "asc", "if", "missing", "or", "invalid" ]
2e6f7e591f2f87158994c17ad9619fa29b716bad
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/order_parser.rb#L67-L72
7,154
finn-no/zendesk-tools
lib/zendesk-tools/clean_suspended.rb
ZendeskTools.CleanSuspended.run
def run @client.suspended_tickets.each do |suspended_ticket| if should_delete?(suspended_ticket) log.info "Deleting: #{suspended_ticket.subject}" suspended_ticket.destroy else log.info "Keeping: #{suspended_ticket.subject}" end end end
ruby
def run @client.suspended_tickets.each do |suspended_ticket| if should_delete?(suspended_ticket) log.info "Deleting: #{suspended_ticket.subject}" suspended_ticket.destroy else log.info "Keeping: #{suspended_ticket.subject}" end end end
[ "def", "run", "@client", ".", "suspended_tickets", ".", "each", "do", "|", "suspended_ticket", "|", "if", "should_delete?", "(", "suspended_ticket", ")", "log", ".", "info", "\"Deleting: #{suspended_ticket.subject}\"", "suspended_ticket", ".", "destroy", "else", "log", ".", "info", "\"Keeping: #{suspended_ticket.subject}\"", "end", "end", "end" ]
Array with delete subjects. Defined in config file
[ "Array", "with", "delete", "subjects", ".", "Defined", "in", "config", "file" ]
cc12d59e28e20cddb220830a47125f8b277243aa
https://github.com/finn-no/zendesk-tools/blob/cc12d59e28e20cddb220830a47125f8b277243aa/lib/zendesk-tools/clean_suspended.rb#L26-L35
7,155
beccasaurus/simplecli
simplecli3/lib/simplecli/command.rb
SimpleCLI.Command.summary
def summary if @summary.nil? match = Command::SummaryMatcher.match documentation match.captures.first.strip if match else @summary end end
ruby
def summary if @summary.nil? match = Command::SummaryMatcher.match documentation match.captures.first.strip if match else @summary end end
[ "def", "summary", "if", "@summary", ".", "nil?", "match", "=", "Command", "::", "SummaryMatcher", ".", "match", "documentation", "match", ".", "captures", ".", "first", ".", "strip", "if", "match", "else", "@summary", "end", "end" ]
Returns a short summary for this Command Typically generated by parsing #documentation for 'Summary: something', but it can also be set manually :api: public
[ "Returns", "a", "short", "summary", "for", "this", "Command" ]
e50b7adf5e77e6bc3179b3b92eaf592ad073c812
https://github.com/beccasaurus/simplecli/blob/e50b7adf5e77e6bc3179b3b92eaf592ad073c812/simplecli3/lib/simplecli/command.rb#L115-L122
7,156
kbredemeier/hue_bridge
lib/hue_bridge/light_bulb.rb
HueBridge.LightBulb.set_color
def set_color(opts = {}) color = Color.new(opts) response = put('state', color.to_h) response_successful?(response) end
ruby
def set_color(opts = {}) color = Color.new(opts) response = put('state', color.to_h) response_successful?(response) end
[ "def", "set_color", "(", "opts", "=", "{", "}", ")", "color", "=", "Color", ".", "new", "(", "opts", ")", "response", "=", "put", "(", "'state'", ",", "color", ".", "to_h", ")", "response_successful?", "(", "response", ")", "end" ]
Sets the color for the lightbulp. @see Color#initialize @return [Boolean] success of the operation
[ "Sets", "the", "color", "for", "the", "lightbulp", "." ]
ce6f9c93602e919d9bda81762eea03c02698f698
https://github.com/kbredemeier/hue_bridge/blob/ce6f9c93602e919d9bda81762eea03c02698f698/lib/hue_bridge/light_bulb.rb#L64-L69
7,157
kbredemeier/hue_bridge
lib/hue_bridge/light_bulb.rb
HueBridge.LightBulb.store_state
def store_state response = get success = !!(response.body =~ %r(state)) data = JSON.parse(response.body) if success @state = data.fetch('state') delete_forbidden_stats success end
ruby
def store_state response = get success = !!(response.body =~ %r(state)) data = JSON.parse(response.body) if success @state = data.fetch('state') delete_forbidden_stats success end
[ "def", "store_state", "response", "=", "get", "success", "=", "!", "!", "(", "response", ".", "body", "=~", "%r(", ")", ")", "data", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", "if", "success", "@state", "=", "data", ".", "fetch", "(", "'state'", ")", "delete_forbidden_stats", "success", "end" ]
Stores the current state of the lightbulp. @return [Boolean] success of the operation
[ "Stores", "the", "current", "state", "of", "the", "lightbulp", "." ]
ce6f9c93602e919d9bda81762eea03c02698f698
https://github.com/kbredemeier/hue_bridge/blob/ce6f9c93602e919d9bda81762eea03c02698f698/lib/hue_bridge/light_bulb.rb#L74-L81
7,158
CruGlobal/cru_lib
lib/cru_lib/async.rb
CruLib.Async.perform
def perform(id, method, *args) if id begin self.class.find(id).send(method, *args) rescue ActiveRecord::RecordNotFound # If the record was deleted after the job was created, swallow it end else self.class.send(method, *args) end end
ruby
def perform(id, method, *args) if id begin self.class.find(id).send(method, *args) rescue ActiveRecord::RecordNotFound # If the record was deleted after the job was created, swallow it end else self.class.send(method, *args) end end
[ "def", "perform", "(", "id", ",", "method", ",", "*", "args", ")", "if", "id", "begin", "self", ".", "class", ".", "find", "(", "id", ")", ".", "send", "(", "method", ",", "args", ")", "rescue", "ActiveRecord", "::", "RecordNotFound", "# If the record was deleted after the job was created, swallow it", "end", "else", "self", ".", "class", ".", "send", "(", "method", ",", "args", ")", "end", "end" ]
This will be called by a worker when a job needs to be processed
[ "This", "will", "be", "called", "by", "a", "worker", "when", "a", "job", "needs", "to", "be", "processed" ]
9cc938579a479efe4e2510ccbcbe2e9b69b2b04a
https://github.com/CruGlobal/cru_lib/blob/9cc938579a479efe4e2510ccbcbe2e9b69b2b04a/lib/cru_lib/async.rb#L5-L15
7,159
rich-dtk/dtk-common
lib/gitolite/utils.rb
Gitolite.Utils.is_subset?
def is_subset?(array1, array2) result = array1 & array2 (array2.length == result.length) end
ruby
def is_subset?(array1, array2) result = array1 & array2 (array2.length == result.length) end
[ "def", "is_subset?", "(", "array1", ",", "array2", ")", "result", "=", "array1", "&", "array2", "(", "array2", ".", "length", "==", "result", ".", "length", ")", "end" ]
Checks to see if array2 is subset of array1
[ "Checks", "to", "see", "if", "array2", "is", "subset", "of", "array1" ]
18d312092e9060f01d271a603ad4b0c9bef318b1
https://github.com/rich-dtk/dtk-common/blob/18d312092e9060f01d271a603ad4b0c9bef318b1/lib/gitolite/utils.rb#L36-L39
7,160
rich-dtk/dtk-common
lib/gitolite/utils.rb
Gitolite.Utils.gitolite_friendly
def gitolite_friendly(permission) if permission.empty? return nil elsif permission.match(/^RWDP?/) return "RW+" elsif permission.match(/^RW/) return "RW+" elsif permission.match(/^R/) return 'R' else return nil end end
ruby
def gitolite_friendly(permission) if permission.empty? return nil elsif permission.match(/^RWDP?/) return "RW+" elsif permission.match(/^RW/) return "RW+" elsif permission.match(/^R/) return 'R' else return nil end end
[ "def", "gitolite_friendly", "(", "permission", ")", "if", "permission", ".", "empty?", "return", "nil", "elsif", "permission", ".", "match", "(", "/", "/", ")", "return", "\"RW+\"", "elsif", "permission", ".", "match", "(", "/", "/", ")", "return", "\"RW+\"", "elsif", "permission", ".", "match", "(", "/", "/", ")", "return", "'R'", "else", "return", "nil", "end", "end" ]
Converts permission to gitolite friendly permission
[ "Converts", "permission", "to", "gitolite", "friendly", "permission" ]
18d312092e9060f01d271a603ad4b0c9bef318b1
https://github.com/rich-dtk/dtk-common/blob/18d312092e9060f01d271a603ad4b0c9bef318b1/lib/gitolite/utils.rb#L44-L56
7,161
codescrum/bebox
lib/bebox/wizards/environment_wizard.rb
Bebox.EnvironmentWizard.create_new_environment
def create_new_environment(project_root, environment_name) # Check if the environment exist return error(_('wizard.environment.name_exist')%{environment: environment_name}) if Bebox::Environment.environment_exists?(project_root, environment_name) # Environment creation environment = Bebox::Environment.new(environment_name, project_root) output = environment.create ok _('wizard.environment.creation_success') return output end
ruby
def create_new_environment(project_root, environment_name) # Check if the environment exist return error(_('wizard.environment.name_exist')%{environment: environment_name}) if Bebox::Environment.environment_exists?(project_root, environment_name) # Environment creation environment = Bebox::Environment.new(environment_name, project_root) output = environment.create ok _('wizard.environment.creation_success') return output end
[ "def", "create_new_environment", "(", "project_root", ",", "environment_name", ")", "# Check if the environment exist", "return", "error", "(", "_", "(", "'wizard.environment.name_exist'", ")", "%", "{", "environment", ":", "environment_name", "}", ")", "if", "Bebox", "::", "Environment", ".", "environment_exists?", "(", "project_root", ",", "environment_name", ")", "# Environment creation", "environment", "=", "Bebox", "::", "Environment", ".", "new", "(", "environment_name", ",", "project_root", ")", "output", "=", "environment", ".", "create", "ok", "_", "(", "'wizard.environment.creation_success'", ")", "return", "output", "end" ]
Create a new environment
[ "Create", "a", "new", "environment" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/environment_wizard.rb#L8-L16
7,162
codescrum/bebox
lib/bebox/wizards/environment_wizard.rb
Bebox.EnvironmentWizard.remove_environment
def remove_environment(project_root, environment_name) # Check if the environment exist return error(_('wizard.environment.name_not_exist')%{environment: environment_name}) unless Bebox::Environment.environment_exists?(project_root, environment_name) # Confirm deletion return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.environment.confirm_deletion')) # Environment deletion environment = Bebox::Environment.new(environment_name, project_root) output = environment.remove ok _('wizard.environment.deletion_success') return output end
ruby
def remove_environment(project_root, environment_name) # Check if the environment exist return error(_('wizard.environment.name_not_exist')%{environment: environment_name}) unless Bebox::Environment.environment_exists?(project_root, environment_name) # Confirm deletion return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.environment.confirm_deletion')) # Environment deletion environment = Bebox::Environment.new(environment_name, project_root) output = environment.remove ok _('wizard.environment.deletion_success') return output end
[ "def", "remove_environment", "(", "project_root", ",", "environment_name", ")", "# Check if the environment exist", "return", "error", "(", "_", "(", "'wizard.environment.name_not_exist'", ")", "%", "{", "environment", ":", "environment_name", "}", ")", "unless", "Bebox", "::", "Environment", ".", "environment_exists?", "(", "project_root", ",", "environment_name", ")", "# Confirm deletion", "return", "warn", "(", "_", "(", "'wizard.no_changes'", ")", ")", "unless", "confirm_action?", "(", "_", "(", "'wizard.environment.confirm_deletion'", ")", ")", "# Environment deletion", "environment", "=", "Bebox", "::", "Environment", ".", "new", "(", "environment_name", ",", "project_root", ")", "output", "=", "environment", ".", "remove", "ok", "_", "(", "'wizard.environment.deletion_success'", ")", "return", "output", "end" ]
Removes an existing environment
[ "Removes", "an", "existing", "environment" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/environment_wizard.rb#L19-L29
7,163
fugroup/asset
lib/assets/item.rb
Asset.Item.write_cache
def write_cache compressed.tap{|c| File.atomic_write(cache_path){|f| f.write(c)}} end
ruby
def write_cache compressed.tap{|c| File.atomic_write(cache_path){|f| f.write(c)}} end
[ "def", "write_cache", "compressed", ".", "tap", "{", "|", "c", "|", "File", ".", "atomic_write", "(", "cache_path", ")", "{", "|", "f", "|", "f", ".", "write", "(", "c", ")", "}", "}", "end" ]
Store in cache
[ "Store", "in", "cache" ]
3cc1aad0926d80653f25d5f0a8c9154d00049bc4
https://github.com/fugroup/asset/blob/3cc1aad0926d80653f25d5f0a8c9154d00049bc4/lib/assets/item.rb#L45-L47
7,164
fugroup/asset
lib/assets/item.rb
Asset.Item.compressed
def compressed @compressed ||= case @type when 'css' Sass::Engine.new(joined, :syntax => :scss, :cache => false, :style => :compressed).render rescue joined when 'js' Uglifier.compile(joined, :mangle => false, :comments => :none) rescue joined end end
ruby
def compressed @compressed ||= case @type when 'css' Sass::Engine.new(joined, :syntax => :scss, :cache => false, :style => :compressed).render rescue joined when 'js' Uglifier.compile(joined, :mangle => false, :comments => :none) rescue joined end end
[ "def", "compressed", "@compressed", "||=", "case", "@type", "when", "'css'", "Sass", "::", "Engine", ".", "new", "(", "joined", ",", ":syntax", "=>", ":scss", ",", ":cache", "=>", "false", ",", ":style", "=>", ":compressed", ")", ".", "render", "rescue", "joined", "when", "'js'", "Uglifier", ".", "compile", "(", "joined", ",", ":mangle", "=>", "false", ",", ":comments", "=>", ":none", ")", "rescue", "joined", "end", "end" ]
Compressed joined files
[ "Compressed", "joined", "files" ]
3cc1aad0926d80653f25d5f0a8c9154d00049bc4
https://github.com/fugroup/asset/blob/3cc1aad0926d80653f25d5f0a8c9154d00049bc4/lib/assets/item.rb#L60-L67
7,165
fugroup/asset
lib/assets/item.rb
Asset.Item.joined
def joined @joined ||= files.map{|f| File.read(File.join(::Asset.path, @type, f))}.join end
ruby
def joined @joined ||= files.map{|f| File.read(File.join(::Asset.path, @type, f))}.join end
[ "def", "joined", "@joined", "||=", "files", ".", "map", "{", "|", "f", "|", "File", ".", "read", "(", "File", ".", "join", "(", "::", "Asset", ".", "path", ",", "@type", ",", "f", ")", ")", "}", ".", "join", "end" ]
All files joined
[ "All", "files", "joined" ]
3cc1aad0926d80653f25d5f0a8c9154d00049bc4
https://github.com/fugroup/asset/blob/3cc1aad0926d80653f25d5f0a8c9154d00049bc4/lib/assets/item.rb#L70-L72
7,166
miguelzf/zomato2
lib/zomato2/zomato.rb
Zomato2.Zomato.locations
def locations(params={}) args = [ :query, :lat, :lon, :count ] params.each do |k,v| if !args.include?(k) raise ArgumentError.new 'Search term not allowed: ' + k.to_s end end if !params.include?(:query) raise ArgumentError.new '"query" term with location name is required' end results = get('locations', params) if results.key?("location_suggestions") results["location_suggestions"].map { |l| Location.new(self, l) } else nil end end
ruby
def locations(params={}) args = [ :query, :lat, :lon, :count ] params.each do |k,v| if !args.include?(k) raise ArgumentError.new 'Search term not allowed: ' + k.to_s end end if !params.include?(:query) raise ArgumentError.new '"query" term with location name is required' end results = get('locations', params) if results.key?("location_suggestions") results["location_suggestions"].map { |l| Location.new(self, l) } else nil end end
[ "def", "locations", "(", "params", "=", "{", "}", ")", "args", "=", "[", ":query", ",", ":lat", ",", ":lon", ",", ":count", "]", "params", ".", "each", "do", "|", "k", ",", "v", "|", "if", "!", "args", ".", "include?", "(", "k", ")", "raise", "ArgumentError", ".", "new", "'Search term not allowed: '", "+", "k", ".", "to_s", "end", "end", "if", "!", "params", ".", "include?", "(", ":query", ")", "raise", "ArgumentError", ".", "new", "'\"query\" term with location name is required'", "end", "results", "=", "get", "(", "'locations'", ",", "params", ")", "if", "results", ".", "key?", "(", "\"location_suggestions\"", ")", "results", "[", "\"location_suggestions\"", "]", ".", "map", "{", "|", "l", "|", "Location", ".", "new", "(", "self", ",", "l", ")", "}", "else", "nil", "end", "end" ]
search for locations
[ "search", "for", "locations" ]
487d64af68a8b0f2735fe13edda3c4e9259504e6
https://github.com/miguelzf/zomato2/blob/487d64af68a8b0f2735fe13edda3c4e9259504e6/lib/zomato2/zomato.rb#L44-L62
7,167
miguelzf/zomato2
lib/zomato2/zomato.rb
Zomato2.Zomato.restaurants
def restaurants(params={}) args = [ :entity_id, :entity_type, # location :q, :start, :count, :lat, :lon, :radius, :cuisines, :establishment_type, :collection_id, :category, :sort, :order, :start, :count ] params.each do |k,v| if !args.include?(k) raise ArgumentError.new 'Search term not allowed: ' + k.to_s end end if params[:count] && params[:count].to_i > 20 warn 'Count maxes out at 20' end # these filters are already city-specific has_sub_city = params[:establishment_type] || params[:collection_id] || params[:cuisines] if (has_sub_city && params[:q]) || (has_sub_city && params[:entity_type] == 'city') || (params[:q] && params[:entity_type] == 'city') warn 'More than 2 different kinds of City searches cannot be combined' end results = get('search', params) results['restaurants'].map { |e| Restaurant.new(self, e['restaurant']) } end
ruby
def restaurants(params={}) args = [ :entity_id, :entity_type, # location :q, :start, :count, :lat, :lon, :radius, :cuisines, :establishment_type, :collection_id, :category, :sort, :order, :start, :count ] params.each do |k,v| if !args.include?(k) raise ArgumentError.new 'Search term not allowed: ' + k.to_s end end if params[:count] && params[:count].to_i > 20 warn 'Count maxes out at 20' end # these filters are already city-specific has_sub_city = params[:establishment_type] || params[:collection_id] || params[:cuisines] if (has_sub_city && params[:q]) || (has_sub_city && params[:entity_type] == 'city') || (params[:q] && params[:entity_type] == 'city') warn 'More than 2 different kinds of City searches cannot be combined' end results = get('search', params) results['restaurants'].map { |e| Restaurant.new(self, e['restaurant']) } end
[ "def", "restaurants", "(", "params", "=", "{", "}", ")", "args", "=", "[", ":entity_id", ",", ":entity_type", ",", "# location", ":q", ",", ":start", ",", ":count", ",", ":lat", ",", ":lon", ",", ":radius", ",", ":cuisines", ",", ":establishment_type", ",", ":collection_id", ",", ":category", ",", ":sort", ",", ":order", ",", ":start", ",", ":count", "]", "params", ".", "each", "do", "|", "k", ",", "v", "|", "if", "!", "args", ".", "include?", "(", "k", ")", "raise", "ArgumentError", ".", "new", "'Search term not allowed: '", "+", "k", ".", "to_s", "end", "end", "if", "params", "[", ":count", "]", "&&", "params", "[", ":count", "]", ".", "to_i", ">", "20", "warn", "'Count maxes out at 20'", "end", "# these filters are already city-specific", "has_sub_city", "=", "params", "[", ":establishment_type", "]", "||", "params", "[", ":collection_id", "]", "||", "params", "[", ":cuisines", "]", "if", "(", "has_sub_city", "&&", "params", "[", ":q", "]", ")", "||", "(", "has_sub_city", "&&", "params", "[", ":entity_type", "]", "==", "'city'", ")", "||", "(", "params", "[", ":q", "]", "&&", "params", "[", ":entity_type", "]", "==", "'city'", ")", "warn", "'More than 2 different kinds of City searches cannot be combined'", "end", "results", "=", "get", "(", "'search'", ",", "params", ")", "results", "[", "'restaurants'", "]", ".", "map", "{", "|", "e", "|", "Restaurant", ".", "new", "(", "self", ",", "e", "[", "'restaurant'", "]", ")", "}", "end" ]
general search for restaurants
[ "general", "search", "for", "restaurants" ]
487d64af68a8b0f2735fe13edda3c4e9259504e6
https://github.com/miguelzf/zomato2/blob/487d64af68a8b0f2735fe13edda3c4e9259504e6/lib/zomato2/zomato.rb#L65-L93
7,168
kurtisnelson/resumator
lib/resumator/client.rb
Resumator.Client.get
def get(object, options = {}) if options[:all_pages] options.delete(:all_pages) options[:page] = 1 out = [] begin data = get(object, options) out = out | data options[:page] += 1 end while data.count >= 100 return out else if options[:id] resp = @connection.get "#{object}/#{options[:id]}" elsif options.size > 0 resp = @connection.get "#{object}#{Client.parse_options(options)}" else resp = @connection.get object end raise "Bad response: #{resp.status}" unless resp.status == 200 Client.mash(JSON.parse(resp.body)) end end
ruby
def get(object, options = {}) if options[:all_pages] options.delete(:all_pages) options[:page] = 1 out = [] begin data = get(object, options) out = out | data options[:page] += 1 end while data.count >= 100 return out else if options[:id] resp = @connection.get "#{object}/#{options[:id]}" elsif options.size > 0 resp = @connection.get "#{object}#{Client.parse_options(options)}" else resp = @connection.get object end raise "Bad response: #{resp.status}" unless resp.status == 200 Client.mash(JSON.parse(resp.body)) end end
[ "def", "get", "(", "object", ",", "options", "=", "{", "}", ")", "if", "options", "[", ":all_pages", "]", "options", ".", "delete", "(", ":all_pages", ")", "options", "[", ":page", "]", "=", "1", "out", "=", "[", "]", "begin", "data", "=", "get", "(", "object", ",", "options", ")", "out", "=", "out", "|", "data", "options", "[", ":page", "]", "+=", "1", "end", "while", "data", ".", "count", ">=", "100", "return", "out", "else", "if", "options", "[", ":id", "]", "resp", "=", "@connection", ".", "get", "\"#{object}/#{options[:id]}\"", "elsif", "options", ".", "size", ">", "0", "resp", "=", "@connection", ".", "get", "\"#{object}#{Client.parse_options(options)}\"", "else", "resp", "=", "@connection", ".", "get", "object", "end", "raise", "\"Bad response: #{resp.status}\"", "unless", "resp", ".", "status", "==", "200", "Client", ".", "mash", "(", "JSON", ".", "parse", "(", "resp", ".", "body", ")", ")", "end", "end" ]
Sets up a client @param [String] API key Get any rest accessible object @param [String] object name @param [Hash] optional search parameters @return [Mash] your data
[ "Sets", "up", "a", "client" ]
7b8d6a312fa3d7cb4da8e20d373b34a61d01ec31
https://github.com/kurtisnelson/resumator/blob/7b8d6a312fa3d7cb4da8e20d373b34a61d01ec31/lib/resumator/client.rb#L29-L51
7,169
hinrik/ircsupport
lib/ircsupport/masks.rb
IRCSupport.Masks.matches_mask_array
def matches_mask_array(masks, strings, casemapping = :rfc1459) results = {} masks.each do |mask| strings.each do |string| if matches_mask(mask, string, casemapping) results[mask] ||= [] results[mask] << string end end end return results end
ruby
def matches_mask_array(masks, strings, casemapping = :rfc1459) results = {} masks.each do |mask| strings.each do |string| if matches_mask(mask, string, casemapping) results[mask] ||= [] results[mask] << string end end end return results end
[ "def", "matches_mask_array", "(", "masks", ",", "strings", ",", "casemapping", "=", ":rfc1459", ")", "results", "=", "{", "}", "masks", ".", "each", "do", "|", "mask", "|", "strings", ".", "each", "do", "|", "string", "|", "if", "matches_mask", "(", "mask", ",", "string", ",", "casemapping", ")", "results", "[", "mask", "]", "||=", "[", "]", "results", "[", "mask", "]", "<<", "string", "end", "end", "end", "return", "results", "end" ]
Match strings to multiple IRC masks. @param [Array] masks The masks to match against. @param [Array] strings The strings to match against the masks. @param [Symbol] casemapping The IRC casemapping to use in the match. @return [Hash] Each mask that was matched will be present as a key, and the values will be arrays of the strings that matched.
[ "Match", "strings", "to", "multiple", "IRC", "masks", "." ]
d028b7d5ccc604a6af175ee2264c18d25b1f7dff
https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/masks.rb#L36-L47
7,170
booqable/scoped_serializer
lib/scoped_serializer/scope.rb
ScopedSerializer.Scope.merge!
def merge!(scope) @options.merge!(scope.options) @attributes += scope.attributes @associations.merge!(scope.associations) @attributes.uniq! self end
ruby
def merge!(scope) @options.merge!(scope.options) @attributes += scope.attributes @associations.merge!(scope.associations) @attributes.uniq! self end
[ "def", "merge!", "(", "scope", ")", "@options", ".", "merge!", "(", "scope", ".", "options", ")", "@attributes", "+=", "scope", ".", "attributes", "@associations", ".", "merge!", "(", "scope", ".", "associations", ")", "@attributes", ".", "uniq!", "self", "end" ]
Merges data with given scope. @example scope.merge!(another_scope)
[ "Merges", "data", "with", "given", "scope", "." ]
fb163bbf61f54a5e8684e4aba3908592bdd986ac
https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/scope.rb#L47-L56
7,171
booqable/scoped_serializer
lib/scoped_serializer/scope.rb
ScopedSerializer.Scope._association
def _association(args, default_options={}) return if options.nil? options = args.first if options.is_a?(Hash) options = {}.merge(options) name = options.keys.first properties = options.delete(name) @associations[name] = default_options.merge({ :include => properties }).merge(options) elsif options.is_a?(Array) options.each do |option| association option end else @associations[options] = args[1] || {} end end
ruby
def _association(args, default_options={}) return if options.nil? options = args.first if options.is_a?(Hash) options = {}.merge(options) name = options.keys.first properties = options.delete(name) @associations[name] = default_options.merge({ :include => properties }).merge(options) elsif options.is_a?(Array) options.each do |option| association option end else @associations[options] = args[1] || {} end end
[ "def", "_association", "(", "args", ",", "default_options", "=", "{", "}", ")", "return", "if", "options", ".", "nil?", "options", "=", "args", ".", "first", "if", "options", ".", "is_a?", "(", "Hash", ")", "options", "=", "{", "}", ".", "merge", "(", "options", ")", "name", "=", "options", ".", "keys", ".", "first", "properties", "=", "options", ".", "delete", "(", "name", ")", "@associations", "[", "name", "]", "=", "default_options", ".", "merge", "(", "{", ":include", "=>", "properties", "}", ")", ".", "merge", "(", "options", ")", "elsif", "options", ".", "is_a?", "(", "Array", ")", "options", ".", "each", "do", "|", "option", "|", "association", "option", "end", "else", "@associations", "[", "options", "]", "=", "args", "[", "1", "]", "||", "{", "}", "end", "end" ]
Duplicates scope. Actually defines the association but without default_options.
[ "Duplicates", "scope", "." ]
fb163bbf61f54a5e8684e4aba3908592bdd986ac
https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/scope.rb#L114-L132
7,172
varyonic/pocus
lib/pocus/resource.rb
Pocus.Resource.get
def get(request_path, klass) response = session.send_request('GET', path + request_path) data = response.fetch(klass.tag) resource = klass.new(data.merge(parent: self)) resource.assign_errors(response) resource end
ruby
def get(request_path, klass) response = session.send_request('GET', path + request_path) data = response.fetch(klass.tag) resource = klass.new(data.merge(parent: self)) resource.assign_errors(response) resource end
[ "def", "get", "(", "request_path", ",", "klass", ")", "response", "=", "session", ".", "send_request", "(", "'GET'", ",", "path", "+", "request_path", ")", "data", "=", "response", ".", "fetch", "(", "klass", ".", "tag", ")", "resource", "=", "klass", ".", "new", "(", "data", ".", "merge", "(", "parent", ":", "self", ")", ")", "resource", ".", "assign_errors", "(", "response", ")", "resource", "end" ]
Fetch and instantiate a single resource from a path.
[ "Fetch", "and", "instantiate", "a", "single", "resource", "from", "a", "path", "." ]
84cbbda509456fc8afaffd6916dccfc585d23b41
https://github.com/varyonic/pocus/blob/84cbbda509456fc8afaffd6916dccfc585d23b41/lib/pocus/resource.rb#L66-L72
7,173
varyonic/pocus
lib/pocus/resource.rb
Pocus.Resource.reload
def reload response = session.send_request('GET', path) assign_attributes(response.fetch(self.class.tag)) assign_errors(response) self end
ruby
def reload response = session.send_request('GET', path) assign_attributes(response.fetch(self.class.tag)) assign_errors(response) self end
[ "def", "reload", "response", "=", "session", ".", "send_request", "(", "'GET'", ",", "path", ")", "assign_attributes", "(", "response", ".", "fetch", "(", "self", ".", "class", ".", "tag", ")", ")", "assign_errors", "(", "response", ")", "self", "end" ]
Fetch and update this resource from a path.
[ "Fetch", "and", "update", "this", "resource", "from", "a", "path", "." ]
84cbbda509456fc8afaffd6916dccfc585d23b41
https://github.com/varyonic/pocus/blob/84cbbda509456fc8afaffd6916dccfc585d23b41/lib/pocus/resource.rb#L114-L119
7,174
syborg/mme_tools
lib/mme_tools/enumerable.rb
MMETools.Enumerable.compose
def compose(*enumerables) res=[] enumerables.map(&:size).max.times do tupla=[] for enumerable in enumerables tupla << enumerable.shift end res << (block_given? ? yield(tupla) : tupla) end res end
ruby
def compose(*enumerables) res=[] enumerables.map(&:size).max.times do tupla=[] for enumerable in enumerables tupla << enumerable.shift end res << (block_given? ? yield(tupla) : tupla) end res end
[ "def", "compose", "(", "*", "enumerables", ")", "res", "=", "[", "]", "enumerables", ".", "map", "(", ":size", ")", ".", "max", ".", "times", "do", "tupla", "=", "[", "]", "for", "enumerable", "in", "enumerables", "tupla", "<<", "enumerable", ".", "shift", "end", "res", "<<", "(", "block_given?", "?", "yield", "(", "tupla", ")", ":", "tupla", ")", "end", "res", "end" ]
torna un array on cada element es una tupla formada per un element de cada enumerable. Si se li passa un bloc se li passa al bloc cada tupla i el resultat del bloc s'emmagatzema a l'array tornat.
[ "torna", "un", "array", "on", "cada", "element", "es", "una", "tupla", "formada", "per", "un", "element", "de", "cada", "enumerable", ".", "Si", "se", "li", "passa", "un", "bloc", "se", "li", "passa", "al", "bloc", "cada", "tupla", "i", "el", "resultat", "del", "bloc", "s", "emmagatzema", "a", "l", "array", "tornat", "." ]
e93919f7fcfb408b941d6144290991a7feabaa7d
https://github.com/syborg/mme_tools/blob/e93919f7fcfb408b941d6144290991a7feabaa7d/lib/mme_tools/enumerable.rb#L15-L25
7,175
zires/micro-spider
lib/spider_core/field_dsl.rb
SpiderCore.FieldDSL.field
def field(display, pattern, opts = {}, &block) actions << lambda { action_for(:field, {display: display, pattern: pattern}, opts, &block) } end
ruby
def field(display, pattern, opts = {}, &block) actions << lambda { action_for(:field, {display: display, pattern: pattern}, opts, &block) } end
[ "def", "field", "(", "display", ",", "pattern", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "actions", "<<", "lambda", "{", "action_for", "(", ":field", ",", "{", "display", ":", "display", ",", "pattern", ":", "pattern", "}", ",", "opts", ",", "block", ")", "}", "end" ]
Get a field on current page. @param display [String] display name
[ "Get", "a", "field", "on", "current", "page", "." ]
bcf3f371d8f16f6b9f7de4c4f62c3d588f9ce13d
https://github.com/zires/micro-spider/blob/bcf3f371d8f16f6b9f7de4c4f62c3d588f9ce13d/lib/spider_core/field_dsl.rb#L7-L11
7,176
nikhgupta/encruby
lib/encruby/message.rb
Encruby.Message.encrypt
def encrypt(message) raise Error, "data must not be empty" if message.to_s.strip.empty? # 1 @cipher.reset @cipher.encrypt aes_key = @cipher.random_key aes_iv = @cipher.random_iv encrypted = @cipher.update(message) + @cipher.final # 2 rsa_encrypted_aes_key = @rsa.public_encrypt(aes_key) rsa_encrypted_aes_iv = @rsa.public_encrypt(aes_iv) # 3 content = rsa_encrypted_aes_key + rsa_encrypted_aes_iv + encrypted # 4 hmac = hmac_signature(content) content = Base64.encode64(hmac + content) { signature: hmac, content: content } rescue OpenSSL::OpenSSLError => e raise Error.new(e.message) end
ruby
def encrypt(message) raise Error, "data must not be empty" if message.to_s.strip.empty? # 1 @cipher.reset @cipher.encrypt aes_key = @cipher.random_key aes_iv = @cipher.random_iv encrypted = @cipher.update(message) + @cipher.final # 2 rsa_encrypted_aes_key = @rsa.public_encrypt(aes_key) rsa_encrypted_aes_iv = @rsa.public_encrypt(aes_iv) # 3 content = rsa_encrypted_aes_key + rsa_encrypted_aes_iv + encrypted # 4 hmac = hmac_signature(content) content = Base64.encode64(hmac + content) { signature: hmac, content: content } rescue OpenSSL::OpenSSLError => e raise Error.new(e.message) end
[ "def", "encrypt", "(", "message", ")", "raise", "Error", ",", "\"data must not be empty\"", "if", "message", ".", "to_s", ".", "strip", ".", "empty?", "# 1", "@cipher", ".", "reset", "@cipher", ".", "encrypt", "aes_key", "=", "@cipher", ".", "random_key", "aes_iv", "=", "@cipher", ".", "random_iv", "encrypted", "=", "@cipher", ".", "update", "(", "message", ")", "+", "@cipher", ".", "final", "# 2", "rsa_encrypted_aes_key", "=", "@rsa", ".", "public_encrypt", "(", "aes_key", ")", "rsa_encrypted_aes_iv", "=", "@rsa", ".", "public_encrypt", "(", "aes_iv", ")", "# 3", "content", "=", "rsa_encrypted_aes_key", "+", "rsa_encrypted_aes_iv", "+", "encrypted", "# 4", "hmac", "=", "hmac_signature", "(", "content", ")", "content", "=", "Base64", ".", "encode64", "(", "hmac", "+", "content", ")", "{", "signature", ":", "hmac", ",", "content", ":", "content", "}", "rescue", "OpenSSL", "::", "OpenSSLError", "=>", "e", "raise", "Error", ".", "new", "(", "e", ".", "message", ")", "end" ]
1. Generate random AES key to encrypt message 2. Use Public Key from the Private key to encrypt AES Key 3. Prepend encrypted AES key to the encrypted message Output message format will look like the following: {RSA Encrypted AES Key}{RSA Encrypted IV}{AES Encrypted Message}
[ "1", ".", "Generate", "random", "AES", "key", "to", "encrypt", "message", "2", ".", "Use", "Public", "Key", "from", "the", "Private", "key", "to", "encrypt", "AES", "Key", "3", ".", "Prepend", "encrypted", "AES", "key", "to", "the", "encrypted", "message" ]
ded0276001f7672594a84d403f64dcd4ab906039
https://github.com/nikhgupta/encruby/blob/ded0276001f7672594a84d403f64dcd4ab906039/lib/encruby/message.rb#L36-L59
7,177
nikhgupta/encruby
lib/encruby/message.rb
Encruby.Message.decrypt
def decrypt(message, hash: nil) # 0 message = Base64.decode64(message) hmac = message[0..63] # 64 bits of hmac signature case when hash && hmac != hash raise Error, "Provided hash mismatch for encrypted file!" when hmac != hmac_signature(message[64..-1]) raise Error, "HMAC signature mismatch for encrypted file!" end # 1 rsa_encrypted_aes_key = message[64..319] # next 256 bits rsa_encrypted_aes_iv = message[320..575] # next 256 bits aes_encrypted_message = message[576..-1] # 2 aes_key = @rsa.private_decrypt rsa_encrypted_aes_key aes_iv = @rsa.private_decrypt rsa_encrypted_aes_iv # 3 @cipher.reset @cipher.decrypt @cipher.key = aes_key @cipher.iv = aes_iv content = @cipher.update(aes_encrypted_message) + @cipher.final { signature: hmac, content: content } rescue OpenSSL::OpenSSLError => e raise Error.new(e.message) end
ruby
def decrypt(message, hash: nil) # 0 message = Base64.decode64(message) hmac = message[0..63] # 64 bits of hmac signature case when hash && hmac != hash raise Error, "Provided hash mismatch for encrypted file!" when hmac != hmac_signature(message[64..-1]) raise Error, "HMAC signature mismatch for encrypted file!" end # 1 rsa_encrypted_aes_key = message[64..319] # next 256 bits rsa_encrypted_aes_iv = message[320..575] # next 256 bits aes_encrypted_message = message[576..-1] # 2 aes_key = @rsa.private_decrypt rsa_encrypted_aes_key aes_iv = @rsa.private_decrypt rsa_encrypted_aes_iv # 3 @cipher.reset @cipher.decrypt @cipher.key = aes_key @cipher.iv = aes_iv content = @cipher.update(aes_encrypted_message) + @cipher.final { signature: hmac, content: content } rescue OpenSSL::OpenSSLError => e raise Error.new(e.message) end
[ "def", "decrypt", "(", "message", ",", "hash", ":", "nil", ")", "# 0", "message", "=", "Base64", ".", "decode64", "(", "message", ")", "hmac", "=", "message", "[", "0", "..", "63", "]", "# 64 bits of hmac signature", "case", "when", "hash", "&&", "hmac", "!=", "hash", "raise", "Error", ",", "\"Provided hash mismatch for encrypted file!\"", "when", "hmac", "!=", "hmac_signature", "(", "message", "[", "64", "..", "-", "1", "]", ")", "raise", "Error", ",", "\"HMAC signature mismatch for encrypted file!\"", "end", "# 1", "rsa_encrypted_aes_key", "=", "message", "[", "64", "..", "319", "]", "# next 256 bits", "rsa_encrypted_aes_iv", "=", "message", "[", "320", "..", "575", "]", "# next 256 bits", "aes_encrypted_message", "=", "message", "[", "576", "..", "-", "1", "]", "# 2", "aes_key", "=", "@rsa", ".", "private_decrypt", "rsa_encrypted_aes_key", "aes_iv", "=", "@rsa", ".", "private_decrypt", "rsa_encrypted_aes_iv", "# 3", "@cipher", ".", "reset", "@cipher", ".", "decrypt", "@cipher", ".", "key", "=", "aes_key", "@cipher", ".", "iv", "=", "aes_iv", "content", "=", "@cipher", ".", "update", "(", "aes_encrypted_message", ")", "+", "@cipher", ".", "final", "{", "signature", ":", "hmac", ",", "content", ":", "content", "}", "rescue", "OpenSSL", "::", "OpenSSLError", "=>", "e", "raise", "Error", ".", "new", "(", "e", ".", "message", ")", "end" ]
0. Base64 decode the encrypted message 1. Split the string in to the AES key and the encrypted message 2. Decrypt the AES key using the private key 3. Decrypt the message using the AES key
[ "0", ".", "Base64", "decode", "the", "encrypted", "message", "1", ".", "Split", "the", "string", "in", "to", "the", "AES", "key", "and", "the", "encrypted", "message", "2", ".", "Decrypt", "the", "AES", "key", "using", "the", "private", "key", "3", ".", "Decrypt", "the", "message", "using", "the", "AES", "key" ]
ded0276001f7672594a84d403f64dcd4ab906039
https://github.com/nikhgupta/encruby/blob/ded0276001f7672594a84d403f64dcd4ab906039/lib/encruby/message.rb#L65-L96
7,178
Rafaherrero/lpp_11
lib/refBiblio/referencia.rb
RefBiblio.Referencia.titulo
def titulo (titulo) tit = titulo.split(' ') tit.each do |word| if word.length > 3 word.capitalize! else word.downcase! end if word == tit[0] word.capitalize! end @titulo = tit.join(' ') end # Metodo para guardar el editorial de la referencia # @param [editorial] editorial Editorial de la referencia a introducir def editorial(editorial) @editorial = editorial end # Metodo para guardar la fecha de publicacion de la referencia # @param [publicacion] publicacion Fecha de publicacion de la referencia a introducir def publicacion (publicacion) @publicacion = publicacion end # Metodo para obtener el titulo de la referencia # @return Titulo de la referencia def get_titulo @titulo end # Metodo para obtener el autor/autores de la referencia # @return Autor/autores de la referencia def get_autor @autor end # Metodo para obtener el editorial de la referencia # @return Editorial de la referencia def get_editorial @editorial end # Metodo para obtener la fecha de publicacion de la referencia # @return Fecha de publicacion de la referencia def get_publicacion @publicacion end # Método con el que podemos usar el modulo Enumerable # @param otro Otro elemento a comparar # @return Devuelve valores entre -1 y 1 segun el orden def <=> (otro) if(@autor == otro.get_autor) if(@publicacion == otro.get_publicacion) if(@titulo == otro.get_titulo) return 0 else arr = [@titulo, otro.get_titulo] arr.sort_by!{|t| t.downcase} if(arr.first == @titulo) return 1 end return -1 end elsif publicacion > otro.get_publicacion return -1 else return 1 end else arr = [@autor, otro.get_autor] arr.sort_by!{|t| t.downcase} if(arr.first == @autor) return -1 end return 1 end end end
ruby
def titulo (titulo) tit = titulo.split(' ') tit.each do |word| if word.length > 3 word.capitalize! else word.downcase! end if word == tit[0] word.capitalize! end @titulo = tit.join(' ') end # Metodo para guardar el editorial de la referencia # @param [editorial] editorial Editorial de la referencia a introducir def editorial(editorial) @editorial = editorial end # Metodo para guardar la fecha de publicacion de la referencia # @param [publicacion] publicacion Fecha de publicacion de la referencia a introducir def publicacion (publicacion) @publicacion = publicacion end # Metodo para obtener el titulo de la referencia # @return Titulo de la referencia def get_titulo @titulo end # Metodo para obtener el autor/autores de la referencia # @return Autor/autores de la referencia def get_autor @autor end # Metodo para obtener el editorial de la referencia # @return Editorial de la referencia def get_editorial @editorial end # Metodo para obtener la fecha de publicacion de la referencia # @return Fecha de publicacion de la referencia def get_publicacion @publicacion end # Método con el que podemos usar el modulo Enumerable # @param otro Otro elemento a comparar # @return Devuelve valores entre -1 y 1 segun el orden def <=> (otro) if(@autor == otro.get_autor) if(@publicacion == otro.get_publicacion) if(@titulo == otro.get_titulo) return 0 else arr = [@titulo, otro.get_titulo] arr.sort_by!{|t| t.downcase} if(arr.first == @titulo) return 1 end return -1 end elsif publicacion > otro.get_publicacion return -1 else return 1 end else arr = [@autor, otro.get_autor] arr.sort_by!{|t| t.downcase} if(arr.first == @autor) return -1 end return 1 end end end
[ "def", "titulo", "(", "titulo", ")", "tit", "=", "titulo", ".", "split", "(", "' '", ")", "tit", ".", "each", "do", "|", "word", "|", "if", "word", ".", "length", ">", "3", "word", ".", "capitalize!", "else", "word", ".", "downcase!", "end", "if", "word", "==", "tit", "[", "0", "]", "word", ".", "capitalize!", "end", "@titulo", "=", "tit", ".", "join", "(", "' '", ")", "end", "# Metodo para guardar el editorial de la referencia", "# @param [editorial] editorial Editorial de la referencia a introducir\t\t", "def", "editorial", "(", "editorial", ")", "@editorial", "=", "editorial", "end", "# Metodo para guardar la fecha de publicacion de la referencia", "# @param [publicacion] publicacion Fecha de publicacion de la referencia a introducir", "def", "publicacion", "(", "publicacion", ")", "@publicacion", "=", "publicacion", "end", "# Metodo para obtener el titulo de la referencia", "# @return Titulo de la referencia", "def", "get_titulo", "@titulo", "end", "# Metodo para obtener el autor/autores de la referencia", "# @return Autor/autores de la referencia", "def", "get_autor", "@autor", "end", "# Metodo para obtener el editorial de la referencia", "# @return Editorial de la referencia", "def", "get_editorial", "@editorial", "end", "# Metodo para obtener la fecha de publicacion de la referencia", "# @return Fecha de publicacion de la referencia", "def", "get_publicacion", "@publicacion", "end", "# Método con el que podemos usar el modulo Enumerable", "# @param otro Otro elemento a comparar", "# @return Devuelve valores entre -1 y 1 segun el orden", "def", "<=>", "(", "otro", ")", "if", "(", "@autor", "==", "otro", ".", "get_autor", ")", "if", "(", "@publicacion", "==", "otro", ".", "get_publicacion", ")", "if", "(", "@titulo", "==", "otro", ".", "get_titulo", ")", "return", "0", "else", "arr", "=", "[", "@titulo", ",", "otro", ".", "get_titulo", "]", "arr", ".", "sort_by!", "{", "|", "t", "|", "t", ".", "downcase", "}", "if", "(", "arr", ".", "first", "==", "@titulo", ")", "return", "1", "end", "return", "-", "1", "end", "elsif", "publicacion", ">", "otro", ".", "get_publicacion", "return", "-", "1", "else", "return", "1", "end", "else", "arr", "=", "[", "@autor", ",", "otro", ".", "get_autor", "]", "arr", ".", "sort_by!", "{", "|", "t", "|", "t", ".", "downcase", "}", "if", "(", "arr", ".", "first", "==", "@autor", ")", "return", "-", "1", "end", "return", "1", "end", "end", "end" ]
Metodo para guardar el titulo de la referencia @param [titulo] titulo Titulo de la referencia a introducir
[ "Metodo", "para", "guardar", "el", "titulo", "de", "la", "referencia" ]
7b9a89138db96d603f1f1b1b93735feee5e4c2a2
https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/refBiblio/referencia.rb#L34-L114
7,179
Rafaherrero/lpp_11
lib/refBiblio/referencia.rb
RefBiblio.ArtPeriodico.to_s
def to_s string = "" string << @autor << " (" << Date::MONTHNAMES[get_publicacion.month] << " " << get_publicacion.day.to_s << ", " << get_publicacion.year.to_s << "). " << @titulo << ". " << @editorial << ", pp. " << @formato << ", " << @paginas.to_s << " paginas" << "." end
ruby
def to_s string = "" string << @autor << " (" << Date::MONTHNAMES[get_publicacion.month] << " " << get_publicacion.day.to_s << ", " << get_publicacion.year.to_s << "). " << @titulo << ". " << @editorial << ", pp. " << @formato << ", " << @paginas.to_s << " paginas" << "." end
[ "def", "to_s", "string", "=", "\"\"", "string", "<<", "@autor", "<<", "\" (\"", "<<", "Date", "::", "MONTHNAMES", "[", "get_publicacion", ".", "month", "]", "<<", "\" \"", "<<", "get_publicacion", ".", "day", ".", "to_s", "<<", "\", \"", "<<", "get_publicacion", ".", "year", ".", "to_s", "<<", "\"). \"", "<<", "@titulo", "<<", "\". \"", "<<", "@editorial", "<<", "\", pp. \"", "<<", "@formato", "<<", "\", \"", "<<", "@paginas", ".", "to_s", "<<", "\" paginas\"", "<<", "\".\"", "end" ]
Metodo que nos devuelve la referencia del articulo periodistico formateado @return String de la referencia del articulo periodistico formateado
[ "Metodo", "que", "nos", "devuelve", "la", "referencia", "del", "articulo", "periodistico", "formateado" ]
7b9a89138db96d603f1f1b1b93735feee5e4c2a2
https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/refBiblio/referencia.rb#L189-L192
7,180
Rafaherrero/lpp_11
lib/refBiblio/referencia.rb
RefBiblio.DocElectronico.to_s
def to_s string = "" string << @autor << " (" << Date::MONTHNAMES[get_publicacion.month] << " " << get_publicacion.day.to_s << ", " << get_publicacion.year.to_s << "). " << @titulo << @formato << ". " << @editorial << ": " << @edicion << ". Disponible en: " << @url << " (" << Date::MONTHNAMES[get_fechacceso.month] << " " << get_fechacceso.day.to_s << ", " << get_fechacceso.year.to_s << "). " end
ruby
def to_s string = "" string << @autor << " (" << Date::MONTHNAMES[get_publicacion.month] << " " << get_publicacion.day.to_s << ", " << get_publicacion.year.to_s << "). " << @titulo << @formato << ". " << @editorial << ": " << @edicion << ". Disponible en: " << @url << " (" << Date::MONTHNAMES[get_fechacceso.month] << " " << get_fechacceso.day.to_s << ", " << get_fechacceso.year.to_s << "). " end
[ "def", "to_s", "string", "=", "\"\"", "string", "<<", "@autor", "<<", "\" (\"", "<<", "Date", "::", "MONTHNAMES", "[", "get_publicacion", ".", "month", "]", "<<", "\" \"", "<<", "get_publicacion", ".", "day", ".", "to_s", "<<", "\", \"", "<<", "get_publicacion", ".", "year", ".", "to_s", "<<", "\"). \"", "<<", "@titulo", "<<", "@formato", "<<", "\". \"", "<<", "@editorial", "<<", "\": \"", "<<", "@edicion", "<<", "\". Disponible en: \"", "<<", "@url", "<<", "\" (\"", "<<", "Date", "::", "MONTHNAMES", "[", "get_fechacceso", ".", "month", "]", "<<", "\" \"", "<<", "get_fechacceso", ".", "day", ".", "to_s", "<<", "\", \"", "<<", "get_fechacceso", ".", "year", ".", "to_s", "<<", "\"). \"", "end" ]
Metodo que nos devuelve la referencia del documento electronico formateado @return String de la referencia del documento electronico formateado
[ "Metodo", "que", "nos", "devuelve", "la", "referencia", "del", "documento", "electronico", "formateado" ]
7b9a89138db96d603f1f1b1b93735feee5e4c2a2
https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/refBiblio/referencia.rb#L237-L240
7,181
KatanaCode/evvnt
lib/evvnt/path_helpers.rb
Evvnt.PathHelpers.nest_path_within_parent
def nest_path_within_parent(path, params) return path unless params_include_parent_resource_id?(params) params.symbolize_keys! parent_resource = parent_resource_name(params) parent_id = params.delete(parent_resource_param(params)).try(:to_s) File.join(*[parent_resource, parent_id, path].compact).to_s end
ruby
def nest_path_within_parent(path, params) return path unless params_include_parent_resource_id?(params) params.symbolize_keys! parent_resource = parent_resource_name(params) parent_id = params.delete(parent_resource_param(params)).try(:to_s) File.join(*[parent_resource, parent_id, path].compact).to_s end
[ "def", "nest_path_within_parent", "(", "path", ",", "params", ")", "return", "path", "unless", "params_include_parent_resource_id?", "(", "params", ")", "params", ".", "symbolize_keys!", "parent_resource", "=", "parent_resource_name", "(", "params", ")", "parent_id", "=", "params", ".", "delete", "(", "parent_resource_param", "(", "params", ")", ")", ".", "try", "(", ":to_s", ")", "File", ".", "join", "(", "[", "parent_resource", ",", "parent_id", ",", "path", "]", ".", "compact", ")", ".", "to_s", "end" ]
Nest a given resource path within a parent resource. path - A String representing an API resource path. params - A Hash of params to send to the API. Examples nest_path_within_parent("bags/1", {user_id: "123"}) # => /users/123/bags/1 Returns String
[ "Nest", "a", "given", "resource", "path", "within", "a", "parent", "resource", "." ]
e13f6d84af09a71819356620fb25685a6cd159c9
https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/path_helpers.rb#L60-L66
7,182
3Crowd/dynamic_registrar
lib/dynamic_registrar/registrar.rb
DynamicRegistrar.Registrar.dispatch
def dispatch name, namespace = nil responses = Hash.new namespaces_to_search = namespace ? [namespace] : namespaces namespaces_to_search.each do |namespace| responses[namespace] ||= Hash.new responses[namespace][name] = @registered_callbacks[namespace][name].call if @registered_callbacks[namespace].has_key?(name) end responses end
ruby
def dispatch name, namespace = nil responses = Hash.new namespaces_to_search = namespace ? [namespace] : namespaces namespaces_to_search.each do |namespace| responses[namespace] ||= Hash.new responses[namespace][name] = @registered_callbacks[namespace][name].call if @registered_callbacks[namespace].has_key?(name) end responses end
[ "def", "dispatch", "name", ",", "namespace", "=", "nil", "responses", "=", "Hash", ".", "new", "namespaces_to_search", "=", "namespace", "?", "[", "namespace", "]", ":", "namespaces", "namespaces_to_search", ".", "each", "do", "|", "namespace", "|", "responses", "[", "namespace", "]", "||=", "Hash", ".", "new", "responses", "[", "namespace", "]", "[", "name", "]", "=", "@registered_callbacks", "[", "namespace", "]", "[", "name", "]", ".", "call", "if", "@registered_callbacks", "[", "namespace", "]", ".", "has_key?", "(", "name", ")", "end", "responses", "end" ]
Dispatch message to given callback. All named callbacks matching the name will be run in all namespaces in indeterminate order @param [ Symbol ] name The name of the callback @param [ Symbol ] namespace The namespace in which the named callback should be found. Optional, if omitted then all matching named callbacks in all namespaces will be executed @return [ Hash ] A hash whose keys are the namespaces in which callbacks were executed, and whose values are the results of those executions. If empty, then no callbacks were executed.
[ "Dispatch", "message", "to", "given", "callback", ".", "All", "named", "callbacks", "matching", "the", "name", "will", "be", "run", "in", "all", "namespaces", "in", "indeterminate", "order" ]
e8a87b543905e764e031ae7021b58905442bc35d
https://github.com/3Crowd/dynamic_registrar/blob/e8a87b543905e764e031ae7021b58905442bc35d/lib/dynamic_registrar/registrar.rb#L46-L54
7,183
3Crowd/dynamic_registrar
lib/dynamic_registrar/registrar.rb
DynamicRegistrar.Registrar.registered?
def registered? name registration_map = namespaces.map do |namespace| registered_in_namespace? name, namespace end registration_map.any? end
ruby
def registered? name registration_map = namespaces.map do |namespace| registered_in_namespace? name, namespace end registration_map.any? end
[ "def", "registered?", "name", "registration_map", "=", "namespaces", ".", "map", "do", "|", "namespace", "|", "registered_in_namespace?", "name", ",", "namespace", "end", "registration_map", ".", "any?", "end" ]
Query if a callback of given name is registered in any namespace @param [ Symbol ] name The name of the callback to check
[ "Query", "if", "a", "callback", "of", "given", "name", "is", "registered", "in", "any", "namespace" ]
e8a87b543905e764e031ae7021b58905442bc35d
https://github.com/3Crowd/dynamic_registrar/blob/e8a87b543905e764e031ae7021b58905442bc35d/lib/dynamic_registrar/registrar.rb#L58-L63
7,184
cjlucas/ruby-easytag
lib/easytag/attributes/mp3.rb
EasyTag.MP3AttributeAccessors.read_all_tags
def read_all_tags(taglib, id3v2_frames, id3v1_tag = nil, **opts) frames = [] id3v2_frames.each { |frame_id| frames += id3v2_frames(taglib, frame_id) } data = [] # only check id3v1 if no id3v2 frames found if frames.empty? data << id3v1_tag(taglib, id3v1_tag) unless id3v1_tag.nil? else frames.each { |frame| data << data_from_frame(frame, **opts) } end data.compact end
ruby
def read_all_tags(taglib, id3v2_frames, id3v1_tag = nil, **opts) frames = [] id3v2_frames.each { |frame_id| frames += id3v2_frames(taglib, frame_id) } data = [] # only check id3v1 if no id3v2 frames found if frames.empty? data << id3v1_tag(taglib, id3v1_tag) unless id3v1_tag.nil? else frames.each { |frame| data << data_from_frame(frame, **opts) } end data.compact end
[ "def", "read_all_tags", "(", "taglib", ",", "id3v2_frames", ",", "id3v1_tag", "=", "nil", ",", "**", "opts", ")", "frames", "=", "[", "]", "id3v2_frames", ".", "each", "{", "|", "frame_id", "|", "frames", "+=", "id3v2_frames", "(", "taglib", ",", "frame_id", ")", "}", "data", "=", "[", "]", "# only check id3v1 if no id3v2 frames found", "if", "frames", ".", "empty?", "data", "<<", "id3v1_tag", "(", "taglib", ",", "id3v1_tag", ")", "unless", "id3v1_tag", ".", "nil?", "else", "frames", ".", "each", "{", "|", "frame", "|", "data", "<<", "data_from_frame", "(", "frame", ",", "**", "opts", ")", "}", "end", "data", ".", "compact", "end" ]
gets data from each frame id given only falls back to the id3v1 tag if no id3v2 frames were found
[ "gets", "data", "from", "each", "frame", "id", "given", "only", "falls", "back", "to", "the", "id3v1", "tag", "if", "no", "id3v2", "frames", "were", "found" ]
7e61d2fd5450529b99bd2f817246d1741405c260
https://github.com/cjlucas/ruby-easytag/blob/7e61d2fd5450529b99bd2f817246d1741405c260/lib/easytag/attributes/mp3.rb#L52-L65
7,185
cknadler/rcomp
lib/rcomp/runner.rb
RComp.Runner.run
def run(suite, type, options={}) @conf = Conf.instance reporter = Reporter.new(type) reporter.header suite.each do |test| case type when :test run_test(test) if expected_exists?(test) when :generate if expected_exists?(test) run_test(test, true) if options[:overwrite] else run_test(test, true) end end reporter.report(test) end reporter.summary end
ruby
def run(suite, type, options={}) @conf = Conf.instance reporter = Reporter.new(type) reporter.header suite.each do |test| case type when :test run_test(test) if expected_exists?(test) when :generate if expected_exists?(test) run_test(test, true) if options[:overwrite] else run_test(test, true) end end reporter.report(test) end reporter.summary end
[ "def", "run", "(", "suite", ",", "type", ",", "options", "=", "{", "}", ")", "@conf", "=", "Conf", ".", "instance", "reporter", "=", "Reporter", ".", "new", "(", "type", ")", "reporter", ".", "header", "suite", ".", "each", "do", "|", "test", "|", "case", "type", "when", ":test", "run_test", "(", "test", ")", "if", "expected_exists?", "(", "test", ")", "when", ":generate", "if", "expected_exists?", "(", "test", ")", "run_test", "(", "test", ",", "true", ")", "if", "options", "[", ":overwrite", "]", "else", "run_test", "(", "test", ",", "true", ")", "end", "end", "reporter", ".", "report", "(", "test", ")", "end", "reporter", ".", "summary", "end" ]
Run a suite of tests suite - An Array of Test objects type - The type (Symbol) of the suite options - A Hash of runner options Returns nothing
[ "Run", "a", "suite", "of", "tests" ]
76fe71e1ef3b13923738ea6ab9cd502fe2f64f51
https://github.com/cknadler/rcomp/blob/76fe71e1ef3b13923738ea6ab9cd502fe2f64f51/lib/rcomp/runner.rb#L16-L39
7,186
cknadler/rcomp
lib/rcomp/runner.rb
RComp.Runner.cmp_output
def cmp_output(test) # test out and err if test.expected_out_exists? && test.expected_err_exists? cmp_out(test) cmp_err(test) return :success if (test.out_result && test.err_result) # test only out elsif test.expected_out_exists? cmp_out(test) return :success if test.out_result # test only err else cmp_err(test) return :success if test.err_result end return :failed end
ruby
def cmp_output(test) # test out and err if test.expected_out_exists? && test.expected_err_exists? cmp_out(test) cmp_err(test) return :success if (test.out_result && test.err_result) # test only out elsif test.expected_out_exists? cmp_out(test) return :success if test.out_result # test only err else cmp_err(test) return :success if test.err_result end return :failed end
[ "def", "cmp_output", "(", "test", ")", "# test out and err", "if", "test", ".", "expected_out_exists?", "&&", "test", ".", "expected_err_exists?", "cmp_out", "(", "test", ")", "cmp_err", "(", "test", ")", "return", ":success", "if", "(", "test", ".", "out_result", "&&", "test", ".", "err_result", ")", "# test only out", "elsif", "test", ".", "expected_out_exists?", "cmp_out", "(", "test", ")", "return", ":success", "if", "test", ".", "out_result", "# test only err", "else", "cmp_err", "(", "test", ")", "return", ":success", "if", "test", ".", "err_result", "end", "return", ":failed", "end" ]
Compare the result and expected output of a test that has been run test - A Test object that has been run precondition :: expected_exists?(test) is true Returns success or failure as a symbol
[ "Compare", "the", "result", "and", "expected", "output", "of", "a", "test", "that", "has", "been", "run" ]
76fe71e1ef3b13923738ea6ab9cd502fe2f64f51
https://github.com/cknadler/rcomp/blob/76fe71e1ef3b13923738ea6ab9cd502fe2f64f51/lib/rcomp/runner.rb#L86-L105
7,187
cknadler/rcomp
lib/rcomp/runner.rb
RComp.Runner.cmp_out
def cmp_out(test) test.out_result = FileUtils.cmp(test.expected_out_path, test.result_out_path) end
ruby
def cmp_out(test) test.out_result = FileUtils.cmp(test.expected_out_path, test.result_out_path) end
[ "def", "cmp_out", "(", "test", ")", "test", ".", "out_result", "=", "FileUtils", ".", "cmp", "(", "test", ".", "expected_out_path", ",", "test", ".", "result_out_path", ")", "end" ]
Compare a tests expected and result stdout Sets the result of the comparison to out_result in the test test - A test object that has been run Returns nothing
[ "Compare", "a", "tests", "expected", "and", "result", "stdout", "Sets", "the", "result", "of", "the", "comparison", "to", "out_result", "in", "the", "test" ]
76fe71e1ef3b13923738ea6ab9cd502fe2f64f51
https://github.com/cknadler/rcomp/blob/76fe71e1ef3b13923738ea6ab9cd502fe2f64f51/lib/rcomp/runner.rb#L113-L116
7,188
cknadler/rcomp
lib/rcomp/runner.rb
RComp.Runner.cmp_err
def cmp_err(test) test.err_result = FileUtils.cmp(test.expected_err_path, test.result_err_path) end
ruby
def cmp_err(test) test.err_result = FileUtils.cmp(test.expected_err_path, test.result_err_path) end
[ "def", "cmp_err", "(", "test", ")", "test", ".", "err_result", "=", "FileUtils", ".", "cmp", "(", "test", ".", "expected_err_path", ",", "test", ".", "result_err_path", ")", "end" ]
Compare a tests expected and result stderr Sets the result of the comparison to err_result in the test test - A test object that has been run Returns nothing
[ "Compare", "a", "tests", "expected", "and", "result", "stderr", "Sets", "the", "result", "of", "the", "comparison", "to", "err_result", "in", "the", "test" ]
76fe71e1ef3b13923738ea6ab9cd502fe2f64f51
https://github.com/cknadler/rcomp/blob/76fe71e1ef3b13923738ea6ab9cd502fe2f64f51/lib/rcomp/runner.rb#L124-L127
7,189
booqable/scoped_serializer
lib/scoped_serializer/base_serializer.rb
ScopedSerializer.BaseSerializer.default_root_key
def default_root_key(object_class) if (serializer = ScopedSerializer.find_serializer_by_class(object_class)) root_key = serializer.find_scope(:default).options[:root] end if root_key root_key.to_s elsif object_class.respond_to?(:model_name) object_class.model_name.element else object_class.name end end
ruby
def default_root_key(object_class) if (serializer = ScopedSerializer.find_serializer_by_class(object_class)) root_key = serializer.find_scope(:default).options[:root] end if root_key root_key.to_s elsif object_class.respond_to?(:model_name) object_class.model_name.element else object_class.name end end
[ "def", "default_root_key", "(", "object_class", ")", "if", "(", "serializer", "=", "ScopedSerializer", ".", "find_serializer_by_class", "(", "object_class", ")", ")", "root_key", "=", "serializer", ".", "find_scope", "(", ":default", ")", ".", "options", "[", ":root", "]", "end", "if", "root_key", "root_key", ".", "to_s", "elsif", "object_class", ".", "respond_to?", "(", ":model_name", ")", "object_class", ".", "model_name", ".", "element", "else", "object_class", ".", "name", "end", "end" ]
Tries to find the default root key. @example default_root_key(User) # => 'user'
[ "Tries", "to", "find", "the", "default", "root", "key", "." ]
fb163bbf61f54a5e8684e4aba3908592bdd986ac
https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/base_serializer.rb#L25-L37
7,190
riddopic/garcun
lib/garcon/task/timer_set.rb
Garcon.TimerSet.post
def post(delay, *args, &task) raise ArgumentError, 'no block given' unless block_given? delay = TimerSet.calculate_delay!(delay) mutex.synchronize do return false unless running? if (delay) <= 0.01 @task_executor.post(*args, &task) else @queue.push(Task.new(Garcon.monotonic_time + delay, args, task)) @timer_executor.post(&method(:process_tasks)) end end @condition.signal true end
ruby
def post(delay, *args, &task) raise ArgumentError, 'no block given' unless block_given? delay = TimerSet.calculate_delay!(delay) mutex.synchronize do return false unless running? if (delay) <= 0.01 @task_executor.post(*args, &task) else @queue.push(Task.new(Garcon.monotonic_time + delay, args, task)) @timer_executor.post(&method(:process_tasks)) end end @condition.signal true end
[ "def", "post", "(", "delay", ",", "*", "args", ",", "&", "task", ")", "raise", "ArgumentError", ",", "'no block given'", "unless", "block_given?", "delay", "=", "TimerSet", ".", "calculate_delay!", "(", "delay", ")", "mutex", ".", "synchronize", "do", "return", "false", "unless", "running?", "if", "(", "delay", ")", "<=", "0.01", "@task_executor", ".", "post", "(", "args", ",", "task", ")", "else", "@queue", ".", "push", "(", "Task", ".", "new", "(", "Garcon", ".", "monotonic_time", "+", "delay", ",", "args", ",", "task", ")", ")", "@timer_executor", ".", "post", "(", "method", "(", ":process_tasks", ")", ")", "end", "end", "@condition", ".", "signal", "true", "end" ]
Create a new set of timed tasks. @!macro [attach] executor_options @param [Hash] opts The options used to specify the executor on which to perform actions. @option opts [Executor] :executor When set use the given `Executor` instance. Three special values are also supported: `:task` returns the global task pool, `:operation` returns the global operation pool, and `:immediate` returns a new `ImmediateExecutor` object. Post a task to be execute run after a given delay (in seconds). If the delay is less than 1/100th of a second the task will be immediately post to the executor. @param [Float] delay The number of seconds to wait for before executing the task. @yield the task to be performed. @raise [ArgumentError] f the intended execution time is not in the future. @raise [ArgumentError] if no block is given. @return [Boolean] True if the message is post, false after shutdown.
[ "Create", "a", "new", "set", "of", "timed", "tasks", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/timer_set.rb#L76-L93
7,191
riddopic/garcun
lib/garcon/task/timer_set.rb
Garcon.TimerSet.process_tasks
def process_tasks loop do task = mutex.synchronize { @queue.peek } break unless task now = Garcon.monotonic_time diff = task.time - now if diff <= 0 # We need to remove the task from the queue before passing it to the # executor, to avoid race conditions where we pass the peek'ed task # to the executor and then pop a different one that's been added in # the meantime. # # Note that there's no race condition between the peek and this pop - # this pop could retrieve a different task from the peek, but that # task would be due to fire now anyway (because @queue is a priority # queue, and this thread is the only reader, so whatever timer is at # the head of the queue now must have the same pop time, or a closer # one, as when we peeked). # task = mutex.synchronize { @queue.pop } @task_executor.post(*task.args, &task.op) else mutex.synchronize do @condition.wait(mutex, [diff, 60].min) end end end end
ruby
def process_tasks loop do task = mutex.synchronize { @queue.peek } break unless task now = Garcon.monotonic_time diff = task.time - now if diff <= 0 # We need to remove the task from the queue before passing it to the # executor, to avoid race conditions where we pass the peek'ed task # to the executor and then pop a different one that's been added in # the meantime. # # Note that there's no race condition between the peek and this pop - # this pop could retrieve a different task from the peek, but that # task would be due to fire now anyway (because @queue is a priority # queue, and this thread is the only reader, so whatever timer is at # the head of the queue now must have the same pop time, or a closer # one, as when we peeked). # task = mutex.synchronize { @queue.pop } @task_executor.post(*task.args, &task.op) else mutex.synchronize do @condition.wait(mutex, [diff, 60].min) end end end end
[ "def", "process_tasks", "loop", "do", "task", "=", "mutex", ".", "synchronize", "{", "@queue", ".", "peek", "}", "break", "unless", "task", "now", "=", "Garcon", ".", "monotonic_time", "diff", "=", "task", ".", "time", "-", "now", "if", "diff", "<=", "0", "# We need to remove the task from the queue before passing it to the", "# executor, to avoid race conditions where we pass the peek'ed task", "# to the executor and then pop a different one that's been added in", "# the meantime.", "#", "# Note that there's no race condition between the peek and this pop -", "# this pop could retrieve a different task from the peek, but that", "# task would be due to fire now anyway (because @queue is a priority", "# queue, and this thread is the only reader, so whatever timer is at", "# the head of the queue now must have the same pop time, or a closer", "# one, as when we peeked).", "#", "task", "=", "mutex", ".", "synchronize", "{", "@queue", ".", "pop", "}", "@task_executor", ".", "post", "(", "task", ".", "args", ",", "task", ".", "op", ")", "else", "mutex", ".", "synchronize", "do", "@condition", ".", "wait", "(", "mutex", ",", "[", "diff", ",", "60", "]", ".", "min", ")", "end", "end", "end", "end" ]
Run a loop and execute tasks in the scheduled order and at the approximate scheduled time. If no tasks remain the thread will exit gracefully so that garbage collection can occur. If there are no ready tasks it will sleep for up to 60 seconds waiting for the next scheduled task. @!visibility private
[ "Run", "a", "loop", "and", "execute", "tasks", "in", "the", "scheduled", "order", "and", "at", "the", "approximate", "scheduled", "time", ".", "If", "no", "tasks", "remain", "the", "thread", "will", "exit", "gracefully", "so", "that", "garbage", "collection", "can", "occur", ".", "If", "there", "are", "no", "ready", "tasks", "it", "will", "sleep", "for", "up", "to", "60", "seconds", "waiting", "for", "the", "next", "scheduled", "task", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/timer_set.rb#L163-L192
7,192
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/administrators_controller.rb
Roroacms.Admin::AdministratorsController.create
def create @admin = Admin.new(administrator_params) respond_to do |format| if @admin.save profile_images(params, @admin) Emailer.profile(@admin).deliver format.html { redirect_to admin_administrators_path, notice: I18n.t("controllers.admin.administrators.create.flash.success") } else format.html { # add breadcrumb and set title add_breadcrumb I18n.t("generic.add_new_user") @action = 'create' flash[:error] = I18n.t('generic.validation.no_passed') render action: "new" } end end end
ruby
def create @admin = Admin.new(administrator_params) respond_to do |format| if @admin.save profile_images(params, @admin) Emailer.profile(@admin).deliver format.html { redirect_to admin_administrators_path, notice: I18n.t("controllers.admin.administrators.create.flash.success") } else format.html { # add breadcrumb and set title add_breadcrumb I18n.t("generic.add_new_user") @action = 'create' flash[:error] = I18n.t('generic.validation.no_passed') render action: "new" } end end end
[ "def", "create", "@admin", "=", "Admin", ".", "new", "(", "administrator_params", ")", "respond_to", "do", "|", "format", "|", "if", "@admin", ".", "save", "profile_images", "(", "params", ",", "@admin", ")", "Emailer", ".", "profile", "(", "@admin", ")", ".", "deliver", "format", ".", "html", "{", "redirect_to", "admin_administrators_path", ",", "notice", ":", "I18n", ".", "t", "(", "\"controllers.admin.administrators.create.flash.success\"", ")", "}", "else", "format", ".", "html", "{", "# add breadcrumb and set title", "add_breadcrumb", "I18n", ".", "t", "(", "\"generic.add_new_user\"", ")", "@action", "=", "'create'", "flash", "[", ":error", "]", "=", "I18n", ".", "t", "(", "'generic.validation.no_passed'", ")", "render", "action", ":", "\"new\"", "}", "end", "end", "end" ]
actually create the new admin with the given param data
[ "actually", "create", "the", "new", "admin", "with", "the", "given", "param", "data" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/administrators_controller.rb#L34-L57
7,193
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/administrators_controller.rb
Roroacms.Admin::AdministratorsController.edit
def edit @admin = current_admin.id == params[:id].to_i ? @current_admin : Admin.find(params[:id]) # add breadcrumb and set title set_title(I18n.t("controllers.admin.administrators.edit.title", username: @admin.username)) add_breadcrumb I18n.t("controllers.admin.administrators.edit.breadcrumb") # action for the form as both edit/new are using the same form. @action = 'update' # only allowed to edit the super user if you are the super user. if @admin.overlord == 'Y' && @admin.id != session[:admin_id] respond_to do |format| flash[:error] = I18n.t("controllers.admin.administrators.edit.flash.error") format.html { redirect_to admin_administrators_path } end end end
ruby
def edit @admin = current_admin.id == params[:id].to_i ? @current_admin : Admin.find(params[:id]) # add breadcrumb and set title set_title(I18n.t("controllers.admin.administrators.edit.title", username: @admin.username)) add_breadcrumb I18n.t("controllers.admin.administrators.edit.breadcrumb") # action for the form as both edit/new are using the same form. @action = 'update' # only allowed to edit the super user if you are the super user. if @admin.overlord == 'Y' && @admin.id != session[:admin_id] respond_to do |format| flash[:error] = I18n.t("controllers.admin.administrators.edit.flash.error") format.html { redirect_to admin_administrators_path } end end end
[ "def", "edit", "@admin", "=", "current_admin", ".", "id", "==", "params", "[", ":id", "]", ".", "to_i", "?", "@current_admin", ":", "Admin", ".", "find", "(", "params", "[", ":id", "]", ")", "# add breadcrumb and set title", "set_title", "(", "I18n", ".", "t", "(", "\"controllers.admin.administrators.edit.title\"", ",", "username", ":", "@admin", ".", "username", ")", ")", "add_breadcrumb", "I18n", ".", "t", "(", "\"controllers.admin.administrators.edit.breadcrumb\"", ")", "# action for the form as both edit/new are using the same form.", "@action", "=", "'update'", "# only allowed to edit the super user if you are the super user.", "if", "@admin", ".", "overlord", "==", "'Y'", "&&", "@admin", ".", "id", "!=", "session", "[", ":admin_id", "]", "respond_to", "do", "|", "format", "|", "flash", "[", ":error", "]", "=", "I18n", ".", "t", "(", "\"controllers.admin.administrators.edit.flash.error\"", ")", "format", ".", "html", "{", "redirect_to", "admin_administrators_path", "}", "end", "end", "end" ]
get and disply certain admin
[ "get", "and", "disply", "certain", "admin" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/administrators_controller.rb#L62-L83
7,194
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/administrators_controller.rb
Roroacms.Admin::AdministratorsController.update
def update @admin = Admin.find(params[:id]) @admin.deal_with_cover params respond_to do |format| admin_passed = if params[:admin][:password].blank? @admin.update_without_password(administrator_params) else @admin.update_attributes(administrator_params) end if admin_passed clear_cache profile_images(params, @admin) format.html { redirect_to edit_admin_administrator_path(@admin), notice: I18n.t("controllers.admin.administrators.update.flash.success") } else @action = 'update' format.html { # add breadcrumb and set title add_breadcrumb I18n.t("controllers.admin.administrators.edit.breadcrumb") flash[:error] = I18n.t('generic.validation.no_passed') render action: "edit" } end end end
ruby
def update @admin = Admin.find(params[:id]) @admin.deal_with_cover params respond_to do |format| admin_passed = if params[:admin][:password].blank? @admin.update_without_password(administrator_params) else @admin.update_attributes(administrator_params) end if admin_passed clear_cache profile_images(params, @admin) format.html { redirect_to edit_admin_administrator_path(@admin), notice: I18n.t("controllers.admin.administrators.update.flash.success") } else @action = 'update' format.html { # add breadcrumb and set title add_breadcrumb I18n.t("controllers.admin.administrators.edit.breadcrumb") flash[:error] = I18n.t('generic.validation.no_passed') render action: "edit" } end end end
[ "def", "update", "@admin", "=", "Admin", ".", "find", "(", "params", "[", ":id", "]", ")", "@admin", ".", "deal_with_cover", "params", "respond_to", "do", "|", "format", "|", "admin_passed", "=", "if", "params", "[", ":admin", "]", "[", ":password", "]", ".", "blank?", "@admin", ".", "update_without_password", "(", "administrator_params", ")", "else", "@admin", ".", "update_attributes", "(", "administrator_params", ")", "end", "if", "admin_passed", "clear_cache", "profile_images", "(", "params", ",", "@admin", ")", "format", ".", "html", "{", "redirect_to", "edit_admin_administrator_path", "(", "@admin", ")", ",", "notice", ":", "I18n", ".", "t", "(", "\"controllers.admin.administrators.update.flash.success\"", ")", "}", "else", "@action", "=", "'update'", "format", ".", "html", "{", "# add breadcrumb and set title", "add_breadcrumb", "I18n", ".", "t", "(", "\"controllers.admin.administrators.edit.breadcrumb\"", ")", "flash", "[", ":error", "]", "=", "I18n", ".", "t", "(", "'generic.validation.no_passed'", ")", "render", "action", ":", "\"edit\"", "}", "end", "end", "end" ]
update the admins object
[ "update", "the", "admins", "object" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/administrators_controller.rb#L92-L124
7,195
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/administrators_controller.rb
Roroacms.Admin::AdministratorsController.destroy
def destroy @admin = Admin.find(params[:id]) @admin.destroy if @admin.overlord == 'N' respond_to do |format| format.html { redirect_to admin_administrators_path, notice: I18n.t("controllers.admin.administrators.destroy.flash.success") } end end
ruby
def destroy @admin = Admin.find(params[:id]) @admin.destroy if @admin.overlord == 'N' respond_to do |format| format.html { redirect_to admin_administrators_path, notice: I18n.t("controllers.admin.administrators.destroy.flash.success") } end end
[ "def", "destroy", "@admin", "=", "Admin", ".", "find", "(", "params", "[", ":id", "]", ")", "@admin", ".", "destroy", "if", "@admin", ".", "overlord", "==", "'N'", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "redirect_to", "admin_administrators_path", ",", "notice", ":", "I18n", ".", "t", "(", "\"controllers.admin.administrators.destroy.flash.success\"", ")", "}", "end", "end" ]
Delete the admin, one thing to remember is you are not allowed to destory the overlord. You are only allowed to destroy yourself unless you are the overlord.
[ "Delete", "the", "admin", "one", "thing", "to", "remember", "is", "you", "are", "not", "allowed", "to", "destory", "the", "overlord", ".", "You", "are", "only", "allowed", "to", "destroy", "yourself", "unless", "you", "are", "the", "overlord", "." ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/administrators_controller.rb#L130-L137
7,196
barkerest/shells
lib/shells/pf_shell_wrapper.rb
Shells.PfShellWrapper.exec
def exec(*commands) ret = '' commands.each { |cmd| ret += shell.exec(cmd) } ret + shell.exec('exec') end
ruby
def exec(*commands) ret = '' commands.each { |cmd| ret += shell.exec(cmd) } ret + shell.exec('exec') end
[ "def", "exec", "(", "*", "commands", ")", "ret", "=", "''", "commands", ".", "each", "{", "|", "cmd", "|", "ret", "+=", "shell", ".", "exec", "(", "cmd", ")", "}", "ret", "+", "shell", ".", "exec", "(", "'exec'", ")", "end" ]
Creates the wrapper, executing the pfSense shell. The provided code block is yielded this wrapper for execution. Executes a series of commands on the pfSense shell.
[ "Creates", "the", "wrapper", "executing", "the", "pfSense", "shell", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/pf_shell_wrapper.rb#L72-L76
7,197
barkerest/shells
lib/shells/pf_shell_wrapper.rb
Shells.PfShellWrapper.set_config_section
def set_config_section(section_name, values, message = '') current_values = get_config_section(section_name) changes = generate_config_changes("$config[#{section_name.to_s.inspect}]", current_values, values) if changes&.any? if message.to_s.strip == '' message = "Updating #{section_name} section." end changes << "write_config(#{message.inspect});" exec(*changes) (changes.size - 1) else 0 end end
ruby
def set_config_section(section_name, values, message = '') current_values = get_config_section(section_name) changes = generate_config_changes("$config[#{section_name.to_s.inspect}]", current_values, values) if changes&.any? if message.to_s.strip == '' message = "Updating #{section_name} section." end changes << "write_config(#{message.inspect});" exec(*changes) (changes.size - 1) else 0 end end
[ "def", "set_config_section", "(", "section_name", ",", "values", ",", "message", "=", "''", ")", "current_values", "=", "get_config_section", "(", "section_name", ")", "changes", "=", "generate_config_changes", "(", "\"$config[#{section_name.to_s.inspect}]\"", ",", "current_values", ",", "values", ")", "if", "changes", "&.", "any?", "if", "message", ".", "to_s", ".", "strip", "==", "''", "message", "=", "\"Updating #{section_name} section.\"", "end", "changes", "<<", "\"write_config(#{message.inspect});\"", "exec", "(", "changes", ")", "(", "changes", ".", "size", "-", "1", ")", "else", "0", "end", "end" ]
Sets a configuration section to the pfSense device. Returns the number of changes made to the configuration.
[ "Sets", "a", "configuration", "section", "to", "the", "pfSense", "device", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/pf_shell_wrapper.rb#L102-L117
7,198
barkerest/shells
lib/shells/pf_shell_wrapper.rb
Shells.PfShellWrapper.enable_cert_auth
def enable_cert_auth(public_key = '~/.ssh/id_rsa.pub') cert_regex = /^ssh-[rd]sa (?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)? \S*$/m # get our cert unless the user provided a full cert for us. unless public_key =~ cert_regex public_key = File.expand_path(public_key) if File.exist?(public_key) public_key = File.read(public_key).to_s.strip else raise Shells::PfSenseCommon::PublicKeyNotFound end raise Shells::PfSenseCommon::PublicKeyInvalid unless public_key =~ cert_regex end cfg = get_config_section 'system' user_id = nil user_name = options[:user].downcase cfg['user'].each_with_index do |user,index| if user['name'].downcase == user_name user_id = index authkeys = Base64.decode64(user['authorizedkeys'].to_s).gsub("\r\n", "\n").strip unless authkeys == '' || authkeys =~ cert_regex warn "Existing authorized keys for user #{options[:user]} are invalid and are being reset." authkeys = '' end if authkeys == '' user['authorizedkeys'] = Base64.strict_encode64(public_key) else authkeys = authkeys.split("\n") unless authkeys.include?(public_key) authkeys << public_key unless authkeys.include?(public_key) user['authorizedkeys'] = Base64.strict_encode64(authkeys.join("\n")) end end break end end raise Shells::PfSenseCommon::UserNotFound unless user_id set_config_section 'system', cfg, "Enable certificate authentication for #{options[:user]}." apply_user_config user_id end
ruby
def enable_cert_auth(public_key = '~/.ssh/id_rsa.pub') cert_regex = /^ssh-[rd]sa (?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)? \S*$/m # get our cert unless the user provided a full cert for us. unless public_key =~ cert_regex public_key = File.expand_path(public_key) if File.exist?(public_key) public_key = File.read(public_key).to_s.strip else raise Shells::PfSenseCommon::PublicKeyNotFound end raise Shells::PfSenseCommon::PublicKeyInvalid unless public_key =~ cert_regex end cfg = get_config_section 'system' user_id = nil user_name = options[:user].downcase cfg['user'].each_with_index do |user,index| if user['name'].downcase == user_name user_id = index authkeys = Base64.decode64(user['authorizedkeys'].to_s).gsub("\r\n", "\n").strip unless authkeys == '' || authkeys =~ cert_regex warn "Existing authorized keys for user #{options[:user]} are invalid and are being reset." authkeys = '' end if authkeys == '' user['authorizedkeys'] = Base64.strict_encode64(public_key) else authkeys = authkeys.split("\n") unless authkeys.include?(public_key) authkeys << public_key unless authkeys.include?(public_key) user['authorizedkeys'] = Base64.strict_encode64(authkeys.join("\n")) end end break end end raise Shells::PfSenseCommon::UserNotFound unless user_id set_config_section 'system', cfg, "Enable certificate authentication for #{options[:user]}." apply_user_config user_id end
[ "def", "enable_cert_auth", "(", "public_key", "=", "'~/.ssh/id_rsa.pub'", ")", "cert_regex", "=", "/", "\\/", "\\/", "\\/", "\\S", "/m", "# get our cert unless the user provided a full cert for us.\r", "unless", "public_key", "=~", "cert_regex", "public_key", "=", "File", ".", "expand_path", "(", "public_key", ")", "if", "File", ".", "exist?", "(", "public_key", ")", "public_key", "=", "File", ".", "read", "(", "public_key", ")", ".", "to_s", ".", "strip", "else", "raise", "Shells", "::", "PfSenseCommon", "::", "PublicKeyNotFound", "end", "raise", "Shells", "::", "PfSenseCommon", "::", "PublicKeyInvalid", "unless", "public_key", "=~", "cert_regex", "end", "cfg", "=", "get_config_section", "'system'", "user_id", "=", "nil", "user_name", "=", "options", "[", ":user", "]", ".", "downcase", "cfg", "[", "'user'", "]", ".", "each_with_index", "do", "|", "user", ",", "index", "|", "if", "user", "[", "'name'", "]", ".", "downcase", "==", "user_name", "user_id", "=", "index", "authkeys", "=", "Base64", ".", "decode64", "(", "user", "[", "'authorizedkeys'", "]", ".", "to_s", ")", ".", "gsub", "(", "\"\\r\\n\"", ",", "\"\\n\"", ")", ".", "strip", "unless", "authkeys", "==", "''", "||", "authkeys", "=~", "cert_regex", "warn", "\"Existing authorized keys for user #{options[:user]} are invalid and are being reset.\"", "authkeys", "=", "''", "end", "if", "authkeys", "==", "''", "user", "[", "'authorizedkeys'", "]", "=", "Base64", ".", "strict_encode64", "(", "public_key", ")", "else", "authkeys", "=", "authkeys", ".", "split", "(", "\"\\n\"", ")", "unless", "authkeys", ".", "include?", "(", "public_key", ")", "authkeys", "<<", "public_key", "unless", "authkeys", ".", "include?", "(", "public_key", ")", "user", "[", "'authorizedkeys'", "]", "=", "Base64", ".", "strict_encode64", "(", "authkeys", ".", "join", "(", "\"\\n\"", ")", ")", "end", "end", "break", "end", "end", "raise", "Shells", "::", "PfSenseCommon", "::", "UserNotFound", "unless", "user_id", "set_config_section", "'system'", ",", "cfg", ",", "\"Enable certificate authentication for #{options[:user]}.\"", "apply_user_config", "user_id", "end" ]
Enabled public key authentication for the current pfSense user. Once this has been done you should be able to connect without using a password.
[ "Enabled", "public", "key", "authentication", "for", "the", "current", "pfSense", "user", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/pf_shell_wrapper.rb#L155-L202
7,199
barkerest/barkest_core
app/helpers/barkest_core/html_helper.rb
BarkestCore.HtmlHelper.glyph
def glyph(name, size = nil) size = size.to_s.downcase if %w(small smaller big bigger).include?(size) size = ' glyph-' + size else size = '' end "<i class=\"glyphicon glyphicon-#{h name}#{size}\"></i>".html_safe end
ruby
def glyph(name, size = nil) size = size.to_s.downcase if %w(small smaller big bigger).include?(size) size = ' glyph-' + size else size = '' end "<i class=\"glyphicon glyphicon-#{h name}#{size}\"></i>".html_safe end
[ "def", "glyph", "(", "name", ",", "size", "=", "nil", ")", "size", "=", "size", ".", "to_s", ".", "downcase", "if", "%w(", "small", "smaller", "big", "bigger", ")", ".", "include?", "(", "size", ")", "size", "=", "' glyph-'", "+", "size", "else", "size", "=", "''", "end", "\"<i class=\\\"glyphicon glyphicon-#{h name}#{size}\\\"></i>\"", ".", "html_safe", "end" ]
Creates a glyph icon using the specified +name+ and +size+. The +size+ can be nil, :small, :smaller, :big, or :bigger. The default size is nil.
[ "Creates", "a", "glyph", "icon", "using", "the", "specified", "+", "name", "+", "and", "+", "size", "+", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/html_helper.rb#L11-L19