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,000
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.send_mail
def send_mail return unless @options[:email] @log.info "Emailing #{@options[:email]}..." begin RDSBackup::Email.new(self).send! @log.info "Email sent to #{@options[:email]} for job #{backup_id}" rescue Exception => e @log.warn "Error sending email: #{e.message.split("\n").first}" end end
ruby
def send_mail return unless @options[:email] @log.info "Emailing #{@options[:email]}..." begin RDSBackup::Email.new(self).send! @log.info "Email sent to #{@options[:email]} for job #{backup_id}" rescue Exception => e @log.warn "Error sending email: #{e.message.split("\n").first}" end end
[ "def", "send_mail", "return", "unless", "@options", "[", ":email", "]", "@log", ".", "info", "\"Emailing #{@options[:email]}...\"", "begin", "RDSBackup", "::", "Email", ".", "new", "(", "self", ")", ".", "send!", "@log", ".", "info", "\"Email sent to #{@options[:email]} for job #{backup_id}\"", "rescue", "Exception", "=>", "e", "@log", ".", "warn", "\"Error sending email: #{e.message.split(\"\\n\").first}\"", "end", "end" ]
Sends a status email
[ "Sends", "a", "status", "email" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L238-L247
7,001
chef-workflow/chef-workflow-testlib
lib/chef-workflow/helpers/chef.rb
ChefWorkflow.ChefHelper.perform_search
def perform_search(type, query) Chef::Search::Query.new.search(type, query).first.map(&:name) end
ruby
def perform_search(type, query) Chef::Search::Query.new.search(type, query).first.map(&:name) end
[ "def", "perform_search", "(", "type", ",", "query", ")", "Chef", "::", "Search", "::", "Query", ".", "new", ".", "search", "(", "type", ",", "query", ")", ".", "first", ".", "map", "(", ":name", ")", "end" ]
Perform a search and return the names of the nodes that match the search.
[ "Perform", "a", "search", "and", "return", "the", "names", "of", "the", "nodes", "that", "match", "the", "search", "." ]
39e9dee4e75d3165cad866babb643df0c519414a
https://github.com/chef-workflow/chef-workflow-testlib/blob/39e9dee4e75d3165cad866babb643df0c519414a/lib/chef-workflow/helpers/chef.rb#L13-L15
7,002
notCalle/ruby-keytree
lib/key_tree/tree.rb
KeyTree.Tree.keys
def keys @hash.deep.each_with_object([]) do |(key_path, value), result| result << key_path.to_key_path unless value.is_a?(Hash) end end
ruby
def keys @hash.deep.each_with_object([]) do |(key_path, value), result| result << key_path.to_key_path unless value.is_a?(Hash) end end
[ "def", "keys", "@hash", ".", "deep", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "(", "key_path", ",", "value", ")", ",", "result", "|", "result", "<<", "key_path", ".", "to_key_path", "unless", "value", ".", "is_a?", "(", "Hash", ")", "end", "end" ]
Return all maximal key paths in a tree :call-seq: keys => Array of KeyTree::Path
[ "Return", "all", "maximal", "key", "paths", "in", "a", "tree" ]
1a88c902c8b5d14f21fd350338776fc094eae8e3
https://github.com/notCalle/ruby-keytree/blob/1a88c902c8b5d14f21fd350338776fc094eae8e3/lib/key_tree/tree.rb#L97-L101
7,003
progressions/ymdt
lib/ymdt.rb
YMDT.Base.invoke
def invoke(command, params={}) command_string = compile_command(command, params) output_command(command_string) execute(command_string, params) end
ruby
def invoke(command, params={}) command_string = compile_command(command, params) output_command(command_string) execute(command_string, params) end
[ "def", "invoke", "(", "command", ",", "params", "=", "{", "}", ")", "command_string", "=", "compile_command", "(", "command", ",", "params", ")", "output_command", "(", "command_string", ")", "execute", "(", "command_string", ",", "params", ")", "end" ]
prepares the commands to correctly reference the application and path
[ "prepares", "the", "commands", "to", "correctly", "reference", "the", "application", "and", "path" ]
9345bc07380176ac94e300ce9c4f9f9f20ffbcd0
https://github.com/progressions/ymdt/blob/9345bc07380176ac94e300ce9c4f9f9f20ffbcd0/lib/ymdt.rb#L74-L78
7,004
progressions/ymdt
lib/ymdt.rb
YMDT.Base.output_command
def output_command(command_string) $stdout.puts $stdout.puts StringMasker.new(command_string, :username => username, :password => password).to_s end
ruby
def output_command(command_string) $stdout.puts $stdout.puts StringMasker.new(command_string, :username => username, :password => password).to_s end
[ "def", "output_command", "(", "command_string", ")", "$stdout", ".", "puts", "$stdout", ".", "puts", "StringMasker", ".", "new", "(", "command_string", ",", ":username", "=>", "username", ",", ":password", "=>", "password", ")", ".", "to_s", "end" ]
print the command on the screen
[ "print", "the", "command", "on", "the", "screen" ]
9345bc07380176ac94e300ce9c4f9f9f20ffbcd0
https://github.com/progressions/ymdt/blob/9345bc07380176ac94e300ce9c4f9f9f20ffbcd0/lib/ymdt.rb#L84-L87
7,005
progressions/ymdt
lib/ymdt.rb
YMDT.Base.execute
def execute(command, params={}) unless params[:dry_run] if params[:return] System.execute(command, :return => true) else $stdout.puts System.execute(command) end end end
ruby
def execute(command, params={}) unless params[:dry_run] if params[:return] System.execute(command, :return => true) else $stdout.puts System.execute(command) end end end
[ "def", "execute", "(", "command", ",", "params", "=", "{", "}", ")", "unless", "params", "[", ":dry_run", "]", "if", "params", "[", ":return", "]", "System", ".", "execute", "(", "command", ",", ":return", "=>", "true", ")", "else", "$stdout", ".", "puts", "System", ".", "execute", "(", "command", ")", "end", "end", "end" ]
execute the command, or not, and return the results, or not
[ "execute", "the", "command", "or", "not", "and", "return", "the", "results", "or", "not" ]
9345bc07380176ac94e300ce9c4f9f9f20ffbcd0
https://github.com/progressions/ymdt/blob/9345bc07380176ac94e300ce9c4f9f9f20ffbcd0/lib/ymdt.rb#L138-L147
7,006
belsonheng/spidercrawl
lib/spidercrawl/page.rb
Spidercrawl.Page.doc
def doc @document = Nokogiri::HTML(@body) rescue Exception => e puts e.inspect puts e.backtrace end
ruby
def doc @document = Nokogiri::HTML(@body) rescue Exception => e puts e.inspect puts e.backtrace end
[ "def", "doc", "@document", "=", "Nokogiri", "::", "HTML", "(", "@body", ")", "rescue", "Exception", "=>", "e", "puts", "e", ".", "inspect", "puts", "e", ".", "backtrace", "end" ]
Return the Nokogiri html document
[ "Return", "the", "Nokogiri", "html", "document" ]
195b067f551597657ad61251dc8d485ec0b0b9c7
https://github.com/belsonheng/spidercrawl/blob/195b067f551597657ad61251dc8d485ec0b0b9c7/lib/spidercrawl/page.rb#L51-L56
7,007
belsonheng/spidercrawl
lib/spidercrawl/page.rb
Spidercrawl.Page.links
def links @links = doc.css('a').map { |link| link['href'].to_s }.uniq.delete_if { |href| href.empty? }.map { |url| absolutify(url.strip) } end
ruby
def links @links = doc.css('a').map { |link| link['href'].to_s }.uniq.delete_if { |href| href.empty? }.map { |url| absolutify(url.strip) } end
[ "def", "links", "@links", "=", "doc", ".", "css", "(", "'a'", ")", ".", "map", "{", "|", "link", "|", "link", "[", "'href'", "]", ".", "to_s", "}", ".", "uniq", ".", "delete_if", "{", "|", "href", "|", "href", ".", "empty?", "}", ".", "map", "{", "|", "url", "|", "absolutify", "(", "url", ".", "strip", ")", "}", "end" ]
Return the entire links found in the page; exclude empty links
[ "Return", "the", "entire", "links", "found", "in", "the", "page", ";", "exclude", "empty", "links" ]
195b067f551597657ad61251dc8d485ec0b0b9c7
https://github.com/belsonheng/spidercrawl/blob/195b067f551597657ad61251dc8d485ec0b0b9c7/lib/spidercrawl/page.rb#L75-L77
7,008
belsonheng/spidercrawl
lib/spidercrawl/page.rb
Spidercrawl.Page.images
def images @images = doc.css('img').map { |img| img['src'].to_s }.uniq.delete_if { |src| src.empty? }.map { |url| absolutify(url.strip) } end
ruby
def images @images = doc.css('img').map { |img| img['src'].to_s }.uniq.delete_if { |src| src.empty? }.map { |url| absolutify(url.strip) } end
[ "def", "images", "@images", "=", "doc", ".", "css", "(", "'img'", ")", ".", "map", "{", "|", "img", "|", "img", "[", "'src'", "]", ".", "to_s", "}", ".", "uniq", ".", "delete_if", "{", "|", "src", "|", "src", ".", "empty?", "}", ".", "map", "{", "|", "url", "|", "absolutify", "(", "url", ".", "strip", ")", "}", "end" ]
Return all images found in the page
[ "Return", "all", "images", "found", "in", "the", "page" ]
195b067f551597657ad61251dc8d485ec0b0b9c7
https://github.com/belsonheng/spidercrawl/blob/195b067f551597657ad61251dc8d485ec0b0b9c7/lib/spidercrawl/page.rb#L103-L105
7,009
belsonheng/spidercrawl
lib/spidercrawl/page.rb
Spidercrawl.Page.text
def text temp_doc = doc temp_doc.css('script, noscript, style, link').each { |node| node.remove } @text = temp_doc.css('body').text.split("\n").collect { |line| line.strip }.join("\n") end
ruby
def text temp_doc = doc temp_doc.css('script, noscript, style, link').each { |node| node.remove } @text = temp_doc.css('body').text.split("\n").collect { |line| line.strip }.join("\n") end
[ "def", "text", "temp_doc", "=", "doc", "temp_doc", ".", "css", "(", "'script, noscript, style, link'", ")", ".", "each", "{", "|", "node", "|", "node", ".", "remove", "}", "@text", "=", "temp_doc", ".", "css", "(", "'body'", ")", ".", "text", ".", "split", "(", "\"\\n\"", ")", ".", "collect", "{", "|", "line", "|", "line", ".", "strip", "}", ".", "join", "(", "\"\\n\"", ")", "end" ]
Return plain text of the page without html tags
[ "Return", "plain", "text", "of", "the", "page", "without", "html", "tags" ]
195b067f551597657ad61251dc8d485ec0b0b9c7
https://github.com/belsonheng/spidercrawl/blob/195b067f551597657ad61251dc8d485ec0b0b9c7/lib/spidercrawl/page.rb#L144-L148
7,010
bluevialabs/connfu-client
lib/connfu/dispatcher.rb
Connfu.Dispatcher.set_channels!
def set_channels!(message) # :doc: channel_type = message.channel_type # select channels with the same channel_type as the incoming message channels = @app_channels.select { |channel| channel["channel_type"].eql?(channel_type) } # filter channels case message.channel_type when "twitter" # filter by from or to account channels = channels.select { |channel| channel["accounts"].select { |item| item["name"].eql?(message.from) or item["name"].eql?(message.to) }.length > 0 } when "voice" # filter by did channels = channels.select { |channel| channel["uid"].eql?(message.channel_name) #channel["phones"].select{|item| # item["phone_number"].eql?(message.to) #}.length > 0 } when "sms" channels = channels.select { |channel| channel["phones"].select{|item| item["phone_number"].eql?(message.to) }.length > 0 } when "rss" channels = channels.select { |channel| channel["uri"].eql?(message.channel_name) } else logger.warn("This code should not be executed because the first select should avoid this") logger.info("Unexpected message: #{message.channel_type}") channels = [] end # get only the channel unique identifier channels = channels.map { |channel| channel["uid"] } logger.debug "Setting channels in the incoming message to #{channels}" message.channel_name = channels end
ruby
def set_channels!(message) # :doc: channel_type = message.channel_type # select channels with the same channel_type as the incoming message channels = @app_channels.select { |channel| channel["channel_type"].eql?(channel_type) } # filter channels case message.channel_type when "twitter" # filter by from or to account channels = channels.select { |channel| channel["accounts"].select { |item| item["name"].eql?(message.from) or item["name"].eql?(message.to) }.length > 0 } when "voice" # filter by did channels = channels.select { |channel| channel["uid"].eql?(message.channel_name) #channel["phones"].select{|item| # item["phone_number"].eql?(message.to) #}.length > 0 } when "sms" channels = channels.select { |channel| channel["phones"].select{|item| item["phone_number"].eql?(message.to) }.length > 0 } when "rss" channels = channels.select { |channel| channel["uri"].eql?(message.channel_name) } else logger.warn("This code should not be executed because the first select should avoid this") logger.info("Unexpected message: #{message.channel_type}") channels = [] end # get only the channel unique identifier channels = channels.map { |channel| channel["uid"] } logger.debug "Setting channels in the incoming message to #{channels}" message.channel_name = channels end
[ "def", "set_channels!", "(", "message", ")", "# :doc:", "channel_type", "=", "message", ".", "channel_type", "# select channels with the same channel_type as the incoming message", "channels", "=", "@app_channels", ".", "select", "{", "|", "channel", "|", "channel", "[", "\"channel_type\"", "]", ".", "eql?", "(", "channel_type", ")", "}", "# filter channels", "case", "message", ".", "channel_type", "when", "\"twitter\"", "# filter by from or to account", "channels", "=", "channels", ".", "select", "{", "|", "channel", "|", "channel", "[", "\"accounts\"", "]", ".", "select", "{", "|", "item", "|", "item", "[", "\"name\"", "]", ".", "eql?", "(", "message", ".", "from", ")", "or", "item", "[", "\"name\"", "]", ".", "eql?", "(", "message", ".", "to", ")", "}", ".", "length", ">", "0", "}", "when", "\"voice\"", "# filter by did", "channels", "=", "channels", ".", "select", "{", "|", "channel", "|", "channel", "[", "\"uid\"", "]", ".", "eql?", "(", "message", ".", "channel_name", ")", "#channel[\"phones\"].select{|item| ", "# item[\"phone_number\"].eql?(message.to)", "#}.length > 0 ", "}", "when", "\"sms\"", "channels", "=", "channels", ".", "select", "{", "|", "channel", "|", "channel", "[", "\"phones\"", "]", ".", "select", "{", "|", "item", "|", "item", "[", "\"phone_number\"", "]", ".", "eql?", "(", "message", ".", "to", ")", "}", ".", "length", ">", "0", "}", "when", "\"rss\"", "channels", "=", "channels", ".", "select", "{", "|", "channel", "|", "channel", "[", "\"uri\"", "]", ".", "eql?", "(", "message", ".", "channel_name", ")", "}", "else", "logger", ".", "warn", "(", "\"This code should not be executed because the first select should avoid this\"", ")", "logger", ".", "info", "(", "\"Unexpected message: #{message.channel_type}\"", ")", "channels", "=", "[", "]", "end", "# get only the channel unique identifier", "channels", "=", "channels", ".", "map", "{", "|", "channel", "|", "channel", "[", "\"uid\"", "]", "}", "logger", ".", "debug", "\"Setting channels in the incoming message to #{channels}\"", "message", ".", "channel_name", "=", "channels", "end" ]
Sets the message channel_name attribute. The result is a list of application channels that should be advised about the inbound message * if message["type"].eql?("twitter"): message["channel_type"] is an array of all the application twitter channels that has associated the message twitter account. i.e. Application channels: @app_channels = [ {"uid"=>"twitter-channel-1", "type"=>"twitter", "accounts"=>[{"name"=>"juandebravo"}, {"name"=>"connfudev"}]}, {"uid"=>"twitter-channel-2", "type"=>"twitter", "accounts"=>[{"name"=>"telefonicaid"}]}] Incoming message: message.channel_type = "twitter" message.from = "juandebravo" set_channels!(message) => message.channel_name = ["twitter-channel-1"] ==== Parameters * +message+ Connfu::Message with no channel_name info ==== Return * Connfu::Message with the channel_name filled with the relevant app channels
[ "Sets", "the", "message", "channel_name", "attribute", ".", "The", "result", "is", "a", "list", "of", "application", "channels", "that", "should", "be", "advised", "about", "the", "inbound", "message" ]
b62a0f5176afa203ba1eecccc7994d6bc61af3a7
https://github.com/bluevialabs/connfu-client/blob/b62a0f5176afa203ba1eecccc7994d6bc61af3a7/lib/connfu/dispatcher.rb#L115-L157
7,011
bluevialabs/connfu-client
lib/connfu/dispatcher.rb
Connfu.Dispatcher.process_message
def process_message(message) logger.info("Calling event #{message.message_type} in the channel #{message.channel_type}") @listener_channels[message.channel_type.to_sym].message(message.message_type.to_sym, message) end
ruby
def process_message(message) logger.info("Calling event #{message.message_type} in the channel #{message.channel_type}") @listener_channels[message.channel_type.to_sym].message(message.message_type.to_sym, message) end
[ "def", "process_message", "(", "message", ")", "logger", ".", "info", "(", "\"Calling event #{message.message_type} in the channel #{message.channel_type}\"", ")", "@listener_channels", "[", "message", ".", "channel_type", ".", "to_sym", "]", ".", "message", "(", "message", ".", "message_type", ".", "to_sym", ",", "message", ")", "end" ]
Executes the blocks that are associated to that channel and event type @param *message* incoming message to be processed
[ "Executes", "the", "blocks", "that", "are", "associated", "to", "that", "channel", "and", "event", "type" ]
b62a0f5176afa203ba1eecccc7994d6bc61af3a7
https://github.com/bluevialabs/connfu-client/blob/b62a0f5176afa203ba1eecccc7994d6bc61af3a7/lib/connfu/dispatcher.rb#L161-L164
7,012
feduxorg/the_array_comparator
lib/the_array_comparator/comparator.rb
TheArrayComparator.Comparator.add_check
def add_check(data, type, keywords, options = {}) t = type.to_sym fail Exceptions::UnknownCheckType, "Unknown check type \":#{t}\" given. Did you register it in advance?" unless comparators.key?(t) opts = { exceptions: [], tag: '' }.merge options sample = Sample.new(data, keywords, opts[:exceptions], opts[:tag]) strategy_klass = comparators[t] check = Check.new(strategy_klass, sample) @cache[:checks].add check end
ruby
def add_check(data, type, keywords, options = {}) t = type.to_sym fail Exceptions::UnknownCheckType, "Unknown check type \":#{t}\" given. Did you register it in advance?" unless comparators.key?(t) opts = { exceptions: [], tag: '' }.merge options sample = Sample.new(data, keywords, opts[:exceptions], opts[:tag]) strategy_klass = comparators[t] check = Check.new(strategy_klass, sample) @cache[:checks].add check end
[ "def", "add_check", "(", "data", ",", "type", ",", "keywords", ",", "options", "=", "{", "}", ")", "t", "=", "type", ".", "to_sym", "fail", "Exceptions", "::", "UnknownCheckType", ",", "\"Unknown check type \\\":#{t}\\\" given. Did you register it in advance?\"", "unless", "comparators", ".", "key?", "(", "t", ")", "opts", "=", "{", "exceptions", ":", "[", "]", ",", "tag", ":", "''", "}", ".", "merge", "options", "sample", "=", "Sample", ".", "new", "(", "data", ",", "keywords", ",", "opts", "[", ":exceptions", "]", ",", "opts", "[", ":tag", "]", ")", "strategy_klass", "=", "comparators", "[", "t", "]", "check", "=", "Check", ".", "new", "(", "strategy_klass", ",", "sample", ")", "@cache", "[", ":checks", "]", ".", "add", "check", "end" ]
Add a check to test against @param [Array] data the data which should be used as check, will be passed to the concrete comparator strategy @param [Symbol] type the comparator strategy (needs to be registered first) @param [Array] keywords what to look for in the data, will be passed to the concrete comparator strategy @param [Hash] options exception, should not be considered as match @option options [Hash] exceptions the exceptions from keywords @option options [String] tag a tag to identify the check @raise [Exceptions::UnknownCheckType] if a unknown strategy is given (needs to be registered first)
[ "Add", "a", "check", "to", "test", "against" ]
66cdaf953909a34366cbee2b519dfcf306bc03c7
https://github.com/feduxorg/the_array_comparator/blob/66cdaf953909a34366cbee2b519dfcf306bc03c7/lib/the_array_comparator/comparator.rb#L69-L83
7,013
feduxorg/the_array_comparator
lib/the_array_comparator/comparator.rb
TheArrayComparator.Comparator.result
def result if @cache[:checks].new_objects? @cache[:checks].stored_objects.each do |c| @result = Result.new(c.sample) unless c.success? end end @result end
ruby
def result if @cache[:checks].new_objects? @cache[:checks].stored_objects.each do |c| @result = Result.new(c.sample) unless c.success? end end @result end
[ "def", "result", "if", "@cache", "[", ":checks", "]", ".", "new_objects?", "@cache", "[", ":checks", "]", ".", "stored_objects", ".", "each", "do", "|", "c", "|", "@result", "=", "Result", ".", "new", "(", "c", ".", "sample", ")", "unless", "c", ".", "success?", "end", "end", "@result", "end" ]
The result of all checks defined @return [Result] the result class with all the data need for further analysis
[ "The", "result", "of", "all", "checks", "defined" ]
66cdaf953909a34366cbee2b519dfcf306bc03c7
https://github.com/feduxorg/the_array_comparator/blob/66cdaf953909a34366cbee2b519dfcf306bc03c7/lib/the_array_comparator/comparator.rb#L89-L97
7,014
jinx/migrate
examples/family/lib/shims.rb
Family.Parent.migrate
def migrate(row, migrated) super if spouse then spouse.household = migrated.detect { |m| Household === m } end end
ruby
def migrate(row, migrated) super if spouse then spouse.household = migrated.detect { |m| Household === m } end end
[ "def", "migrate", "(", "row", ",", "migrated", ")", "super", "if", "spouse", "then", "spouse", ".", "household", "=", "migrated", ".", "detect", "{", "|", "m", "|", "Household", "===", "m", "}", "end", "end" ]
Augments the migration by setting the spouse household. @param [{Symbol => Object}] row the input row field => value hash @param [<Resource>] migrated the migrated instances
[ "Augments", "the", "migration", "by", "setting", "the", "spouse", "household", "." ]
309957a470d72da3bd074f8173dbbe2f12449883
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/examples/family/lib/shims.rb#L10-L15
7,015
jns/Aims
lib/aims/output.rb
Aims.Timings.add!
def add!(timings) timings.descriptions.each{|d| add_cpu_time(d, timings.cpu_time(d)) add_wall_time(d, timings.wall_time(d)) } end
ruby
def add!(timings) timings.descriptions.each{|d| add_cpu_time(d, timings.cpu_time(d)) add_wall_time(d, timings.wall_time(d)) } end
[ "def", "add!", "(", "timings", ")", "timings", ".", "descriptions", ".", "each", "{", "|", "d", "|", "add_cpu_time", "(", "d", ",", "timings", ".", "cpu_time", "(", "d", ")", ")", "add_wall_time", "(", "d", ",", "timings", ".", "wall_time", "(", "d", ")", ")", "}", "end" ]
Add another timings object to this one
[ "Add", "another", "timings", "object", "to", "this", "one" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/output.rb#L98-L103
7,016
jns/Aims
lib/aims/output.rb
Aims.AimsOutput.total_energy
def total_energy etot = self.geometry_steps.collect{|gs| gs.total_energy }.compact.last if etot.nil? Float::NAN else etot end end
ruby
def total_energy etot = self.geometry_steps.collect{|gs| gs.total_energy }.compact.last if etot.nil? Float::NAN else etot end end
[ "def", "total_energy", "etot", "=", "self", ".", "geometry_steps", ".", "collect", "{", "|", "gs", "|", "gs", ".", "total_energy", "}", ".", "compact", ".", "last", "if", "etot", ".", "nil?", "Float", "::", "NAN", "else", "etot", "end", "end" ]
Returns the best available value of the total energy
[ "Returns", "the", "best", "available", "value", "of", "the", "total", "energy" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/output.rb#L240-L247
7,017
itisnotdone/gogetit
lib/executionhooks.rb
Gogetit.ExecutionHooks.method_added
def method_added(method_name) # do nothing if the method that was added was an actual hook method, or # if it already had hooks added to it return if hooks.include?(method_name) || hooked_methods.include?(method_name) add_hooks_to(method_name) end
ruby
def method_added(method_name) # do nothing if the method that was added was an actual hook method, or # if it already had hooks added to it return if hooks.include?(method_name) || hooked_methods.include?(method_name) add_hooks_to(method_name) end
[ "def", "method_added", "(", "method_name", ")", "# do nothing if the method that was added was an actual hook method, or", "# if it already had hooks added to it", "return", "if", "hooks", ".", "include?", "(", "method_name", ")", "||", "hooked_methods", ".", "include?", "(", "method_name", ")", "add_hooks_to", "(", "method_name", ")", "end" ]
this method is invoked whenever a new instance method is added to a class
[ "this", "method", "is", "invoked", "whenever", "a", "new", "instance", "method", "is", "added", "to", "a", "class" ]
62628c04c0310567178c4738aa5b64645ed5c4bd
https://github.com/itisnotdone/gogetit/blob/62628c04c0310567178c4738aa5b64645ed5c4bd/lib/executionhooks.rb#L5-L10
7,018
burlesona/nform
lib/nform/core_ext.rb
NForm.Hashable.hash_of
def hash_of(*keys) keys.each.with_object({}){|k,h| h[k] = send(k) } end
ruby
def hash_of(*keys) keys.each.with_object({}){|k,h| h[k] = send(k) } end
[ "def", "hash_of", "(", "*", "keys", ")", "keys", ".", "each", ".", "with_object", "(", "{", "}", ")", "{", "|", "k", ",", "h", "|", "h", "[", "k", "]", "=", "send", "(", "k", ")", "}", "end" ]
A convenience method for making a hash with the given methods on self as the keys and return for the given methods as the values
[ "A", "convenience", "method", "for", "making", "a", "hash", "with", "the", "given", "methods", "on", "self", "as", "the", "keys", "and", "return", "for", "the", "given", "methods", "as", "the", "values" ]
3ba467b55e9fbb480856d069c1792c2ad41da921
https://github.com/burlesona/nform/blob/3ba467b55e9fbb480856d069c1792c2ad41da921/lib/nform/core_ext.rb#L8-L10
7,019
blambeau/yargi
lib/yargi/element_set.rb
Yargi.ElementSet.set_mark
def set_mark(key, value, dup=true) self.each {|elm| elm.set_mark(key, (dup and not(Symbol===value)) ? value.dup : value)} end
ruby
def set_mark(key, value, dup=true) self.each {|elm| elm.set_mark(key, (dup and not(Symbol===value)) ? value.dup : value)} end
[ "def", "set_mark", "(", "key", ",", "value", ",", "dup", "=", "true", ")", "self", ".", "each", "{", "|", "elm", "|", "elm", ".", "set_mark", "(", "key", ",", "(", "dup", "and", "not", "(", "Symbol", "===", "value", ")", ")", "?", "value", ".", "dup", ":", "value", ")", "}", "end" ]
Fired to each element of the group. Values are duplicated by default. Put dup to false to avoid this behavior.
[ "Fired", "to", "each", "element", "of", "the", "group", ".", "Values", "are", "duplicated", "by", "default", ".", "Put", "dup", "to", "false", "to", "avoid", "this", "behavior", "." ]
100141e96d245a0a8211cd4f7590909be149bc3c
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/element_set.rb#L125-L127
7,020
openplaces/bigindex
lib/big_index/model.rb
BigIndex.Model.rebuild_index
def rebuild_index(options={}, finder_options={}) logger.info "=== Rebuilding index for: #{self.index_type}" unless options[:silent] if options[:drop] logger.info "Dropping index for: #{self.index_type}" unless options[:silent] index_adapter.drop_index(self) end finder_options[:batch_size] ||= 100 finder_options[:view] ||= :all finder_options[:bypass_index] = true options[:batch_size] ||= 100 options[:commit] = true unless options.has_key?(:commit) options[:optimize] = true unless options.has_key?(:optimize) logger.info "Offset: #{finder_options[:offset]}" unless options[:silent] logger.info "Stop row: #{finder_options[:stop_row]}" unless options[:silent] buffer = [] items_processed = 0 loop = 0 # Depending on whether the model has a scan or find method, use that. # scan is from Bigrecord models, and find is from Activerecord. if self.respond_to?(:scan) self.scan(finder_options) do |r| items_processed += 1 buffer << r if buffer.size > options[:batch_size] loop += 1 index_adapter.process_index_batch(buffer, loop, options) buffer.clear end end index_adapter.process_index_batch(buffer, loop, options) unless buffer.empty? elsif self.respond_to?(:find) ar_options = {:limit => finder_options[:batch_size]} while loop += 1 buffer = self.find_without_index(:all, ar_options) break if buffer.empty? items_processed += buffer.size index_adapter.process_index_batch(buffer, loop, options) break if buffer.size < finder_options[:batch_size] buffer.clear ar_options[:offset] = (loop * finder_options[:batch_size])+1 end else raise "Your model needs at least a scan() or find() method" end if items_processed > 0 logger.info "Index for #{self.index_type} has been rebuilt (#{items_processed} records)." unless options[:silent] else logger.info "Nothing to index for #{self.index_type}." unless options[:silent] end logger.info "=== Finished rebuilding index for: #{self.index_type}" unless options[:silent] return items_processed end
ruby
def rebuild_index(options={}, finder_options={}) logger.info "=== Rebuilding index for: #{self.index_type}" unless options[:silent] if options[:drop] logger.info "Dropping index for: #{self.index_type}" unless options[:silent] index_adapter.drop_index(self) end finder_options[:batch_size] ||= 100 finder_options[:view] ||= :all finder_options[:bypass_index] = true options[:batch_size] ||= 100 options[:commit] = true unless options.has_key?(:commit) options[:optimize] = true unless options.has_key?(:optimize) logger.info "Offset: #{finder_options[:offset]}" unless options[:silent] logger.info "Stop row: #{finder_options[:stop_row]}" unless options[:silent] buffer = [] items_processed = 0 loop = 0 # Depending on whether the model has a scan or find method, use that. # scan is from Bigrecord models, and find is from Activerecord. if self.respond_to?(:scan) self.scan(finder_options) do |r| items_processed += 1 buffer << r if buffer.size > options[:batch_size] loop += 1 index_adapter.process_index_batch(buffer, loop, options) buffer.clear end end index_adapter.process_index_batch(buffer, loop, options) unless buffer.empty? elsif self.respond_to?(:find) ar_options = {:limit => finder_options[:batch_size]} while loop += 1 buffer = self.find_without_index(:all, ar_options) break if buffer.empty? items_processed += buffer.size index_adapter.process_index_batch(buffer, loop, options) break if buffer.size < finder_options[:batch_size] buffer.clear ar_options[:offset] = (loop * finder_options[:batch_size])+1 end else raise "Your model needs at least a scan() or find() method" end if items_processed > 0 logger.info "Index for #{self.index_type} has been rebuilt (#{items_processed} records)." unless options[:silent] else logger.info "Nothing to index for #{self.index_type}." unless options[:silent] end logger.info "=== Finished rebuilding index for: #{self.index_type}" unless options[:silent] return items_processed end
[ "def", "rebuild_index", "(", "options", "=", "{", "}", ",", "finder_options", "=", "{", "}", ")", "logger", ".", "info", "\"=== Rebuilding index for: #{self.index_type}\"", "unless", "options", "[", ":silent", "]", "if", "options", "[", ":drop", "]", "logger", ".", "info", "\"Dropping index for: #{self.index_type}\"", "unless", "options", "[", ":silent", "]", "index_adapter", ".", "drop_index", "(", "self", ")", "end", "finder_options", "[", ":batch_size", "]", "||=", "100", "finder_options", "[", ":view", "]", "||=", ":all", "finder_options", "[", ":bypass_index", "]", "=", "true", "options", "[", ":batch_size", "]", "||=", "100", "options", "[", ":commit", "]", "=", "true", "unless", "options", ".", "has_key?", "(", ":commit", ")", "options", "[", ":optimize", "]", "=", "true", "unless", "options", ".", "has_key?", "(", ":optimize", ")", "logger", ".", "info", "\"Offset: #{finder_options[:offset]}\"", "unless", "options", "[", ":silent", "]", "logger", ".", "info", "\"Stop row: #{finder_options[:stop_row]}\"", "unless", "options", "[", ":silent", "]", "buffer", "=", "[", "]", "items_processed", "=", "0", "loop", "=", "0", "# Depending on whether the model has a scan or find method, use that.", "# scan is from Bigrecord models, and find is from Activerecord.", "if", "self", ".", "respond_to?", "(", ":scan", ")", "self", ".", "scan", "(", "finder_options", ")", "do", "|", "r", "|", "items_processed", "+=", "1", "buffer", "<<", "r", "if", "buffer", ".", "size", ">", "options", "[", ":batch_size", "]", "loop", "+=", "1", "index_adapter", ".", "process_index_batch", "(", "buffer", ",", "loop", ",", "options", ")", "buffer", ".", "clear", "end", "end", "index_adapter", ".", "process_index_batch", "(", "buffer", ",", "loop", ",", "options", ")", "unless", "buffer", ".", "empty?", "elsif", "self", ".", "respond_to?", "(", ":find", ")", "ar_options", "=", "{", ":limit", "=>", "finder_options", "[", ":batch_size", "]", "}", "while", "loop", "+=", "1", "buffer", "=", "self", ".", "find_without_index", "(", ":all", ",", "ar_options", ")", "break", "if", "buffer", ".", "empty?", "items_processed", "+=", "buffer", ".", "size", "index_adapter", ".", "process_index_batch", "(", "buffer", ",", "loop", ",", "options", ")", "break", "if", "buffer", ".", "size", "<", "finder_options", "[", ":batch_size", "]", "buffer", ".", "clear", "ar_options", "[", ":offset", "]", "=", "(", "loop", "*", "finder_options", "[", ":batch_size", "]", ")", "+", "1", "end", "else", "raise", "\"Your model needs at least a scan() or find() method\"", "end", "if", "items_processed", ">", "0", "logger", ".", "info", "\"Index for #{self.index_type} has been rebuilt (#{items_processed} records).\"", "unless", "options", "[", ":silent", "]", "else", "logger", ".", "info", "\"Nothing to index for #{self.index_type}.\"", "unless", "options", "[", ":silent", "]", "end", "logger", ".", "info", "\"=== Finished rebuilding index for: #{self.index_type}\"", "unless", "options", "[", ":silent", "]", "return", "items_processed", "end" ]
Dispatches a command to the current adapter to rebuild the index. @return <Integer> representing number of items processed.
[ "Dispatches", "a", "command", "to", "the", "current", "adapter", "to", "rebuild", "the", "index", "." ]
c2612327b31dfd3271dfcde17389f0852459f565
https://github.com/openplaces/bigindex/blob/c2612327b31dfd3271dfcde17389f0852459f565/lib/big_index/model.rb#L102-L169
7,021
openplaces/bigindex
lib/big_index/model.rb
BigIndex.Model.index
def index(*params, &block) index_field = IndexField.new(params, block) add_index_field(index_field) # Create the attribute finder method define_finder index_field[:finder_name] end
ruby
def index(*params, &block) index_field = IndexField.new(params, block) add_index_field(index_field) # Create the attribute finder method define_finder index_field[:finder_name] end
[ "def", "index", "(", "*", "params", ",", "&", "block", ")", "index_field", "=", "IndexField", ".", "new", "(", "params", ",", "block", ")", "add_index_field", "(", "index_field", ")", "# Create the attribute finder method", "define_finder", "index_field", "[", ":finder_name", "]", "end" ]
Macro for defining a class attribute as an indexed field. Also creates the corresponding attribute finder method, which defaults to the field name. This can be defined with the :finder_name => "anothername" option. Refer to {IndexField} for more information on defining fields.
[ "Macro", "for", "defining", "a", "class", "attribute", "as", "an", "indexed", "field", "." ]
c2612327b31dfd3271dfcde17389f0852459f565
https://github.com/openplaces/bigindex/blob/c2612327b31dfd3271dfcde17389f0852459f565/lib/big_index/model.rb#L227-L234
7,022
DigitPaint/html_mockup
lib/html_mockup/server.rb
HtmlMockup.Server.application
def application return @app if @app @stack.use Rack::HtmlValidator if self.options[:validate] @stack.run Rack::HtmlMockup.new(self.project) @app = @stack end
ruby
def application return @app if @app @stack.use Rack::HtmlValidator if self.options[:validate] @stack.run Rack::HtmlMockup.new(self.project) @app = @stack end
[ "def", "application", "return", "@app", "if", "@app", "@stack", ".", "use", "Rack", "::", "HtmlValidator", "if", "self", ".", "options", "[", ":validate", "]", "@stack", ".", "run", "Rack", "::", "HtmlMockup", ".", "new", "(", "self", ".", "project", ")", "@app", "=", "@stack", "end" ]
Build the final application that get's run by the Rack Handler
[ "Build", "the", "final", "application", "that", "get", "s", "run", "by", "the", "Rack", "Handler" ]
976edadc01216b82a8cea177f53fb32559eaf41e
https://github.com/DigitPaint/html_mockup/blob/976edadc01216b82a8cea177f53fb32559eaf41e/lib/html_mockup/server.rb#L73-L80
7,023
briandamaged/unobservable
lib/unobservable.rb
Unobservable.ModuleSupport.define_event
def define_event(name, args = {}) args = {:create_method => true}.merge(args) name = name.to_sym if args[:create_method] define_method name do return event(name) end end @unobservable_instance_events ||= Set.new if @unobservable_instance_events.include? name return false else @unobservable_instance_events.add name return true end end
ruby
def define_event(name, args = {}) args = {:create_method => true}.merge(args) name = name.to_sym if args[:create_method] define_method name do return event(name) end end @unobservable_instance_events ||= Set.new if @unobservable_instance_events.include? name return false else @unobservable_instance_events.add name return true end end
[ "def", "define_event", "(", "name", ",", "args", "=", "{", "}", ")", "args", "=", "{", ":create_method", "=>", "true", "}", ".", "merge", "(", "args", ")", "name", "=", "name", ".", "to_sym", "if", "args", "[", ":create_method", "]", "define_method", "name", "do", "return", "event", "(", "name", ")", "end", "end", "@unobservable_instance_events", "||=", "Set", ".", "new", "if", "@unobservable_instance_events", ".", "include?", "name", "return", "false", "else", "@unobservable_instance_events", ".", "add", "name", "return", "true", "end", "end" ]
Returns true if the instance event is defined. Returns false otherwise.
[ "Returns", "true", "if", "the", "instance", "event", "is", "defined", ".", "Returns", "false", "otherwise", "." ]
787b02d08019b269c472cb7f2c63526774762796
https://github.com/briandamaged/unobservable/blob/787b02d08019b269c472cb7f2c63526774762796/lib/unobservable.rb#L84-L101
7,024
briandamaged/unobservable
lib/unobservable.rb
Unobservable.ModuleSupport.attr_event
def attr_event(*names) args = (names[-1].is_a? Hash) ? names.pop : {} names.each {|n| define_event(n, args) } return nil end
ruby
def attr_event(*names) args = (names[-1].is_a? Hash) ? names.pop : {} names.each {|n| define_event(n, args) } return nil end
[ "def", "attr_event", "(", "*", "names", ")", "args", "=", "(", "names", "[", "-", "1", "]", ".", "is_a?", "Hash", ")", "?", "names", ".", "pop", ":", "{", "}", "names", ".", "each", "{", "|", "n", "|", "define_event", "(", "n", ",", "args", ")", "}", "return", "nil", "end" ]
This helper method is similar to attr_reader and attr_accessor. It allows for instance events to be declared inside the body of the class.
[ "This", "helper", "method", "is", "similar", "to", "attr_reader", "and", "attr_accessor", ".", "It", "allows", "for", "instance", "events", "to", "be", "declared", "inside", "the", "body", "of", "the", "class", "." ]
787b02d08019b269c472cb7f2c63526774762796
https://github.com/briandamaged/unobservable/blob/787b02d08019b269c472cb7f2c63526774762796/lib/unobservable.rb#L106-L110
7,025
briandamaged/unobservable
lib/unobservable.rb
Unobservable.Support.singleton_events
def singleton_events(all = true) if all contributors = self.singleton_class.included_modules contributors -= self.class.included_modules contributors.push self.singleton_class Unobservable.collect_instance_events_defined_by(contributors) else Unobservable.collect_instance_events_defined_by([self.singleton_class]) end end
ruby
def singleton_events(all = true) if all contributors = self.singleton_class.included_modules contributors -= self.class.included_modules contributors.push self.singleton_class Unobservable.collect_instance_events_defined_by(contributors) else Unobservable.collect_instance_events_defined_by([self.singleton_class]) end end
[ "def", "singleton_events", "(", "all", "=", "true", ")", "if", "all", "contributors", "=", "self", ".", "singleton_class", ".", "included_modules", "contributors", "-=", "self", ".", "class", ".", "included_modules", "contributors", ".", "push", "self", ".", "singleton_class", "Unobservable", ".", "collect_instance_events_defined_by", "(", "contributors", ")", "else", "Unobservable", ".", "collect_instance_events_defined_by", "(", "[", "self", ".", "singleton_class", "]", ")", "end", "end" ]
Obtains the list of events that are unique to this object. If all = true, then this list will also include events that were defined within a module that the object extended.
[ "Obtains", "the", "list", "of", "events", "that", "are", "unique", "to", "this", "object", ".", "If", "all", "=", "true", "then", "this", "list", "will", "also", "include", "events", "that", "were", "defined", "within", "a", "module", "that", "the", "object", "extended", "." ]
787b02d08019b269c472cb7f2c63526774762796
https://github.com/briandamaged/unobservable/blob/787b02d08019b269c472cb7f2c63526774762796/lib/unobservable.rb#L135-L144
7,026
briandamaged/unobservable
lib/unobservable.rb
Unobservable.Support.event
def event(name) @unobservable_events_map ||= {} e = @unobservable_events_map[name] if not e if self.events.include? name e = Event.new @unobservable_events_map[name] = e else raise NameError, "Undefined event: #{name}" end end return e end
ruby
def event(name) @unobservable_events_map ||= {} e = @unobservable_events_map[name] if not e if self.events.include? name e = Event.new @unobservable_events_map[name] = e else raise NameError, "Undefined event: #{name}" end end return e end
[ "def", "event", "(", "name", ")", "@unobservable_events_map", "||=", "{", "}", "e", "=", "@unobservable_events_map", "[", "name", "]", "if", "not", "e", "if", "self", ".", "events", ".", "include?", "name", "e", "=", "Event", ".", "new", "@unobservable_events_map", "[", "name", "]", "=", "e", "else", "raise", "NameError", ",", "\"Undefined event: #{name}\"", "end", "end", "return", "e", "end" ]
Returns the Event that has the specified name. A NameError will be raised if the object does not define any event that has the given name.
[ "Returns", "the", "Event", "that", "has", "the", "specified", "name", ".", "A", "NameError", "will", "be", "raised", "if", "the", "object", "does", "not", "define", "any", "event", "that", "has", "the", "given", "name", "." ]
787b02d08019b269c472cb7f2c63526774762796
https://github.com/briandamaged/unobservable/blob/787b02d08019b269c472cb7f2c63526774762796/lib/unobservable.rb#L161-L173
7,027
briandamaged/unobservable
lib/unobservable.rb
Unobservable.Event.register
def register(*args, &block) h = Unobservable.handler_for(*args, &block) @handlers << h return h end
ruby
def register(*args, &block) h = Unobservable.handler_for(*args, &block) @handlers << h return h end
[ "def", "register", "(", "*", "args", ",", "&", "block", ")", "h", "=", "Unobservable", ".", "handler_for", "(", "args", ",", "block", ")", "@handlers", "<<", "h", "return", "h", "end" ]
Registers the given event handler so that it will be invoked when the event is raised.
[ "Registers", "the", "given", "event", "handler", "so", "that", "it", "will", "be", "invoked", "when", "the", "event", "is", "raised", "." ]
787b02d08019b269c472cb7f2c63526774762796
https://github.com/briandamaged/unobservable/blob/787b02d08019b269c472cb7f2c63526774762796/lib/unobservable.rb#L209-L213
7,028
briandamaged/unobservable
lib/unobservable.rb
Unobservable.Event.unregister
def unregister(*args, &block) h = Unobservable.handler_for(*args, &block) index = @handlers.index(h) if index @handlers.slice!(index) return h else return nil end end
ruby
def unregister(*args, &block) h = Unobservable.handler_for(*args, &block) index = @handlers.index(h) if index @handlers.slice!(index) return h else return nil end end
[ "def", "unregister", "(", "*", "args", ",", "&", "block", ")", "h", "=", "Unobservable", ".", "handler_for", "(", "args", ",", "block", ")", "index", "=", "@handlers", ".", "index", "(", "h", ")", "if", "index", "@handlers", ".", "slice!", "(", "index", ")", "return", "h", "else", "return", "nil", "end", "end" ]
Removes a single instance of the specified event handler from the list of event handlers. Therefore, if you've registered the same event handler 3 times, then you will need to unregister it 3 times as well.
[ "Removes", "a", "single", "instance", "of", "the", "specified", "event", "handler", "from", "the", "list", "of", "event", "handlers", ".", "Therefore", "if", "you", "ve", "registered", "the", "same", "event", "handler", "3", "times", "then", "you", "will", "need", "to", "unregister", "it", "3", "times", "as", "well", "." ]
787b02d08019b269c472cb7f2c63526774762796
https://github.com/briandamaged/unobservable/blob/787b02d08019b269c472cb7f2c63526774762796/lib/unobservable.rb#L222-L231
7,029
mrsimonfletcher/roroacms
app/helpers/roroacms/view_helper.rb
Roroacms.ViewHelper.is_month_archive?
def is_month_archive? segments = params[:slug].split('/') (get_type_by_url == 'AR' && !segments[2].blank? && segments[3].blank?) ? true : false end
ruby
def is_month_archive? segments = params[:slug].split('/') (get_type_by_url == 'AR' && !segments[2].blank? && segments[3].blank?) ? true : false end
[ "def", "is_month_archive?", "segments", "=", "params", "[", ":slug", "]", ".", "split", "(", "'/'", ")", "(", "get_type_by_url", "==", "'AR'", "&&", "!", "segments", "[", "2", "]", ".", "blank?", "&&", "segments", "[", "3", "]", ".", "blank?", ")", "?", "true", ":", "false", "end" ]
returns a boolean as to whether the current view is a month archive
[ "returns", "a", "boolean", "as", "to", "whether", "the", "current", "view", "is", "a", "month", "archive" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/view_helper.rb#L653-L656
7,030
mrsimonfletcher/roroacms
app/helpers/roroacms/view_helper.rb
Roroacms.ViewHelper.is_year_archive?
def is_year_archive? segments = params[:slug].split('/') (get_type_by_url == 'AR' && !segments[1].blank? && segments[2].blank? && segments[3].blank?) ? true : false end
ruby
def is_year_archive? segments = params[:slug].split('/') (get_type_by_url == 'AR' && !segments[1].blank? && segments[2].blank? && segments[3].blank?) ? true : false end
[ "def", "is_year_archive?", "segments", "=", "params", "[", ":slug", "]", ".", "split", "(", "'/'", ")", "(", "get_type_by_url", "==", "'AR'", "&&", "!", "segments", "[", "1", "]", ".", "blank?", "&&", "segments", "[", "2", "]", ".", "blank?", "&&", "segments", "[", "3", "]", ".", "blank?", ")", "?", "true", ":", "false", "end" ]
returns a boolean as to whether the current view is a year archive
[ "returns", "a", "boolean", "as", "to", "whether", "the", "current", "view", "is", "a", "year", "archive" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/view_helper.rb#L660-L663
7,031
mrsimonfletcher/roroacms
app/helpers/roroacms/view_helper.rb
Roroacms.ViewHelper.is_homepage?
def is_homepage? return false if (!defined?(@content.length).blank? || @content.blank?) @content.id == Setting.get('home_page').to_i ? true : false end
ruby
def is_homepage? return false if (!defined?(@content.length).blank? || @content.blank?) @content.id == Setting.get('home_page').to_i ? true : false end
[ "def", "is_homepage?", "return", "false", "if", "(", "!", "defined?", "(", "@content", ".", "length", ")", ".", "blank?", "||", "@content", ".", "blank?", ")", "@content", ".", "id", "==", "Setting", ".", "get", "(", "'home_page'", ")", ".", "to_i", "?", "true", ":", "false", "end" ]
returns a boolean as to whether the current view is the homepage
[ "returns", "a", "boolean", "as", "to", "whether", "the", "current", "view", "is", "the", "homepage" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/view_helper.rb#L680-L683
7,032
mrsimonfletcher/roroacms
app/helpers/roroacms/view_helper.rb
Roroacms.ViewHelper.obtain_comments_form
def obtain_comments_form if Setting.get('article_comments') == 'Y' type = Setting.get('article_comment_type') @new_comment = Comment.new if File.exists?("#{Rails.root}/app/views/themes/#{current_theme}/comments_form." + get_theme_ext) render(:template => "themes/#{current_theme}/comments_form." + get_theme_ext , :layout => nil, :locals => { type: type }).to_s else render :inline => 'comments_form.html.erb does not exist in current theme' end end end
ruby
def obtain_comments_form if Setting.get('article_comments') == 'Y' type = Setting.get('article_comment_type') @new_comment = Comment.new if File.exists?("#{Rails.root}/app/views/themes/#{current_theme}/comments_form." + get_theme_ext) render(:template => "themes/#{current_theme}/comments_form." + get_theme_ext , :layout => nil, :locals => { type: type }).to_s else render :inline => 'comments_form.html.erb does not exist in current theme' end end end
[ "def", "obtain_comments_form", "if", "Setting", ".", "get", "(", "'article_comments'", ")", "==", "'Y'", "type", "=", "Setting", ".", "get", "(", "'article_comment_type'", ")", "@new_comment", "=", "Comment", ".", "new", "if", "File", ".", "exists?", "(", "\"#{Rails.root}/app/views/themes/#{current_theme}/comments_form.\"", "+", "get_theme_ext", ")", "render", "(", ":template", "=>", "\"themes/#{current_theme}/comments_form.\"", "+", "get_theme_ext", ",", ":layout", "=>", "nil", ",", ":locals", "=>", "{", "type", ":", "type", "}", ")", ".", "to_s", "else", "render", ":inline", "=>", "'comments_form.html.erb does not exist in current theme'", "end", "end", "end" ]
returns the comment form that is created in the theme folder.
[ "returns", "the", "comment", "form", "that", "is", "created", "in", "the", "theme", "folder", "." ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/view_helper.rb#L837-L849
7,033
mrsimonfletcher/roroacms
app/helpers/roroacms/view_helper.rb
Roroacms.ViewHelper.obtain_term_type
def obtain_term_type return nil if params[:slug].blank? segments = params[:slug].split('/') if !segments[1].blank? term = TermAnatomy.where(:taxonomy => segments[1]).last term.taxonomy if !term.blank? else nil end end
ruby
def obtain_term_type return nil if params[:slug].blank? segments = params[:slug].split('/') if !segments[1].blank? term = TermAnatomy.where(:taxonomy => segments[1]).last term.taxonomy if !term.blank? else nil end end
[ "def", "obtain_term_type", "return", "nil", "if", "params", "[", ":slug", "]", ".", "blank?", "segments", "=", "params", "[", ":slug", "]", ".", "split", "(", "'/'", ")", "if", "!", "segments", "[", "1", "]", ".", "blank?", "term", "=", "TermAnatomy", ".", "where", "(", ":taxonomy", "=>", "segments", "[", "1", "]", ")", ".", "last", "term", ".", "taxonomy", "if", "!", "term", ".", "blank?", "else", "nil", "end", "end" ]
return what type of taxonomy it is either - category or tag
[ "return", "what", "type", "of", "taxonomy", "it", "is", "either", "-", "category", "or", "tag" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/view_helper.rb#L918-L929
7,034
fugroup/pushfile
lib/pushfile/data.rb
Pushfile.Data.mimetype
def mimetype(path) extension = File.basename(path).split('.')[-1] Rack::Mime.mime_type(".#{extension}") end
ruby
def mimetype(path) extension = File.basename(path).split('.')[-1] Rack::Mime.mime_type(".#{extension}") end
[ "def", "mimetype", "(", "path", ")", "extension", "=", "File", ".", "basename", "(", "path", ")", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "Rack", "::", "Mime", ".", "mime_type", "(", "\".#{extension}\"", ")", "end" ]
Get the mime type from a file name
[ "Get", "the", "mime", "type", "from", "a", "file", "name" ]
dd06bd6b023514a1446544986b1ce85b7bae3f78
https://github.com/fugroup/pushfile/blob/dd06bd6b023514a1446544986b1ce85b7bae3f78/lib/pushfile/data.rb#L74-L77
7,035
cbetta/snapshotify
lib/snapshotify/scraper.rb
Snapshotify.Scraper.process
def process document return unless document.valid # If we're debugging, output the canonical_url emitter.log(document.url.canonical_url.colorize(:green)) # Attach the emitter to the document document.emitter = emitter # enqueue any other pages being linked to enqueue(document.links) # rewrite all absolute links, asset urls, etc # to use local, relative paths # document.rewrite # Write the document to file document.write! # Mark this document's canonical_url as processed processed_urls << document.url.canonical_url end
ruby
def process document return unless document.valid # If we're debugging, output the canonical_url emitter.log(document.url.canonical_url.colorize(:green)) # Attach the emitter to the document document.emitter = emitter # enqueue any other pages being linked to enqueue(document.links) # rewrite all absolute links, asset urls, etc # to use local, relative paths # document.rewrite # Write the document to file document.write! # Mark this document's canonical_url as processed processed_urls << document.url.canonical_url end
[ "def", "process", "document", "return", "unless", "document", ".", "valid", "# If we're debugging, output the canonical_url", "emitter", ".", "log", "(", "document", ".", "url", ".", "canonical_url", ".", "colorize", "(", ":green", ")", ")", "# Attach the emitter to the document", "document", ".", "emitter", "=", "emitter", "# enqueue any other pages being linked to", "enqueue", "(", "document", ".", "links", ")", "# rewrite all absolute links, asset urls, etc", "# to use local, relative paths", "# document.rewrite", "# Write the document to file", "document", ".", "write!", "# Mark this document's canonical_url as processed", "processed_urls", "<<", "document", ".", "url", ".", "canonical_url", "end" ]
Process a document, fetching its content and enqueueing it for sub processing
[ "Process", "a", "document", "fetching", "its", "content", "and", "enqueueing", "it", "for", "sub", "processing" ]
7f5553f4281ffc5bf0e54da1141574bd15af45b6
https://github.com/cbetta/snapshotify/blob/7f5553f4281ffc5bf0e54da1141574bd15af45b6/lib/snapshotify/scraper.rb#L40-L58
7,036
cbetta/snapshotify
lib/snapshotify/scraper.rb
Snapshotify.Scraper.enqueue
def enqueue links # Loop over each document links.each_with_index do |document, index| next unless can_be_enqueued?(document) emitter.log("> Enqueueing: #{document.url.canonical_url}") unprocessed_documents << document unprocessed_urls << document.url.canonical_url end end
ruby
def enqueue links # Loop over each document links.each_with_index do |document, index| next unless can_be_enqueued?(document) emitter.log("> Enqueueing: #{document.url.canonical_url}") unprocessed_documents << document unprocessed_urls << document.url.canonical_url end end
[ "def", "enqueue", "links", "# Loop over each document", "links", ".", "each_with_index", "do", "|", "document", ",", "index", "|", "next", "unless", "can_be_enqueued?", "(", "document", ")", "emitter", ".", "log", "(", "\"> Enqueueing: #{document.url.canonical_url}\"", ")", "unprocessed_documents", "<<", "document", "unprocessed_urls", "<<", "document", ".", "url", ".", "canonical_url", "end", "end" ]
Enqueue new documents for each link found in the current document
[ "Enqueue", "new", "documents", "for", "each", "link", "found", "in", "the", "current", "document" ]
7f5553f4281ffc5bf0e54da1141574bd15af45b6
https://github.com/cbetta/snapshotify/blob/7f5553f4281ffc5bf0e54da1141574bd15af45b6/lib/snapshotify/scraper.rb#L62-L72
7,037
cbetta/snapshotify
lib/snapshotify/scraper.rb
Snapshotify.Scraper.can_be_enqueued?
def can_be_enqueued?(document) archivable?(document) && # ensure the next document is on an allowable domain valid_domains.include?(document.url.host) && # ensure the next document hasn't been processed yet !processed_urls.include?(document.url.canonical_url) && # ensure the next document hasn't been enqueued yet !unprocessed_urls.include?(document.url.canonical_url) end
ruby
def can_be_enqueued?(document) archivable?(document) && # ensure the next document is on an allowable domain valid_domains.include?(document.url.host) && # ensure the next document hasn't been processed yet !processed_urls.include?(document.url.canonical_url) && # ensure the next document hasn't been enqueued yet !unprocessed_urls.include?(document.url.canonical_url) end
[ "def", "can_be_enqueued?", "(", "document", ")", "archivable?", "(", "document", ")", "&&", "# ensure the next document is on an allowable domain", "valid_domains", ".", "include?", "(", "document", ".", "url", ".", "host", ")", "&&", "# ensure the next document hasn't been processed yet", "!", "processed_urls", ".", "include?", "(", "document", ".", "url", ".", "canonical_url", ")", "&&", "# ensure the next document hasn't been enqueued yet", "!", "unprocessed_urls", ".", "include?", "(", "document", ".", "url", ".", "canonical_url", ")", "end" ]
Determine if a document can be enqueued
[ "Determine", "if", "a", "document", "can", "be", "enqueued" ]
7f5553f4281ffc5bf0e54da1141574bd15af45b6
https://github.com/cbetta/snapshotify/blob/7f5553f4281ffc5bf0e54da1141574bd15af45b6/lib/snapshotify/scraper.rb#L75-L83
7,038
cbetta/snapshotify
lib/snapshotify/scraper.rb
Snapshotify.Scraper.archivable?
def archivable?(document) # check if the document is likely to be a html page archivable_document = document.url.valid # check of the document hasn't already been evaluated and discarded has_been_marked_as_invalid = self.invalid_urls.include?(document.url.raw_url) # Add the dpcument to the list of needed if !archivable_document && !has_been_marked_as_invalid emitter.warning("> Invalid URL: #{document.url.raw_url}") invalid_urls << document.url.raw_url end archivable_document end
ruby
def archivable?(document) # check if the document is likely to be a html page archivable_document = document.url.valid # check of the document hasn't already been evaluated and discarded has_been_marked_as_invalid = self.invalid_urls.include?(document.url.raw_url) # Add the dpcument to the list of needed if !archivable_document && !has_been_marked_as_invalid emitter.warning("> Invalid URL: #{document.url.raw_url}") invalid_urls << document.url.raw_url end archivable_document end
[ "def", "archivable?", "(", "document", ")", "# check if the document is likely to be a html page", "archivable_document", "=", "document", ".", "url", ".", "valid", "# check of the document hasn't already been evaluated and discarded", "has_been_marked_as_invalid", "=", "self", ".", "invalid_urls", ".", "include?", "(", "document", ".", "url", ".", "raw_url", ")", "# Add the dpcument to the list of needed", "if", "!", "archivable_document", "&&", "!", "has_been_marked_as_invalid", "emitter", ".", "warning", "(", "\"> Invalid URL: #{document.url.raw_url}\"", ")", "invalid_urls", "<<", "document", ".", "url", ".", "raw_url", "end", "archivable_document", "end" ]
Determine if a document is actually the type of document that can be archived
[ "Determine", "if", "a", "document", "is", "actually", "the", "type", "of", "document", "that", "can", "be", "archived" ]
7f5553f4281ffc5bf0e54da1141574bd15af45b6
https://github.com/cbetta/snapshotify/blob/7f5553f4281ffc5bf0e54da1141574bd15af45b6/lib/snapshotify/scraper.rb#L87-L100
7,039
arvicco/amqp-spec
lib/amqp-spec/evented_example.rb
AMQP.SpecHelper.done
def done(delay=nil) super(delay) do yield if block_given? EM.next_tick do run_em_hooks :amqp_after if AMQP.conn and not AMQP.closing AMQP.stop_connection do AMQP.cleanup_state finish_em_loop end else AMQP.cleanup_state finish_em_loop end end end end
ruby
def done(delay=nil) super(delay) do yield if block_given? EM.next_tick do run_em_hooks :amqp_after if AMQP.conn and not AMQP.closing AMQP.stop_connection do AMQP.cleanup_state finish_em_loop end else AMQP.cleanup_state finish_em_loop end end end end
[ "def", "done", "(", "delay", "=", "nil", ")", "super", "(", "delay", ")", "do", "yield", "if", "block_given?", "EM", ".", "next_tick", "do", "run_em_hooks", ":amqp_after", "if", "AMQP", ".", "conn", "and", "not", "AMQP", ".", "closing", "AMQP", ".", "stop_connection", "do", "AMQP", ".", "cleanup_state", "finish_em_loop", "end", "else", "AMQP", ".", "cleanup_state", "finish_em_loop", "end", "end", "end", "end" ]
Breaks the event loop and finishes the spec. It yields to any given block first, then stops AMQP, EM event loop and cleans up AMQP state.
[ "Breaks", "the", "event", "loop", "and", "finishes", "the", "spec", ".", "It", "yields", "to", "any", "given", "block", "first", "then", "stops", "AMQP", "EM", "event", "loop", "and", "cleans", "up", "AMQP", "state", "." ]
db0bd8670259b81f085ed6e28b62ad0b76df752f
https://github.com/arvicco/amqp-spec/blob/db0bd8670259b81f085ed6e28b62ad0b76df752f/lib/amqp-spec/evented_example.rb#L135-L151
7,040
barkerest/barkest_core
app/models/barkest_core/user_manager.rb
BarkestCore.UserManager.primary_source
def primary_source return :ldap if using_ldap? && !using_db? return :db if using_db? && !using_ldap? source = @options[:primary_source] source = source.to_sym if source.is_a?(String) return source if [:ldap, :db].include?(source) return :ldap if using_ldap? :db end
ruby
def primary_source return :ldap if using_ldap? && !using_db? return :db if using_db? && !using_ldap? source = @options[:primary_source] source = source.to_sym if source.is_a?(String) return source if [:ldap, :db].include?(source) return :ldap if using_ldap? :db end
[ "def", "primary_source", "return", ":ldap", "if", "using_ldap?", "&&", "!", "using_db?", "return", ":db", "if", "using_db?", "&&", "!", "using_ldap?", "source", "=", "@options", "[", ":primary_source", "]", "source", "=", "source", ".", "to_sym", "if", "source", ".", "is_a?", "(", "String", ")", "return", "source", "if", "[", ":ldap", ",", ":db", "]", ".", "include?", "(", "source", ")", "return", ":ldap", "if", "using_ldap?", ":db", "end" ]
Gets the first authentication source for this user manager.
[ "Gets", "the", "first", "authentication", "source", "for", "this", "user", "manager", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/user_manager.rb#L47-L59
7,041
barkerest/barkest_core
app/models/barkest_core/user_manager.rb
BarkestCore.UserManager.authenticate
def authenticate(email, password, client_ip) return nil unless email && BarkestCore::EmailTester.valid_email?(email, false) email = email.downcase sources.each do |source| if source == :ldap entry = @ldap.search(filter: "(&(objectClass=user)(mail=#{email}))") if entry && entry.count == 1 # we found a match. user = User.find_by(email: email, ldap: true) # make sure it authenticates correctly. entry = @ldap.bind_as(filter: "(&(objectClass=user)(mail=#{email}))", password: password) # do not allow authenticating against the DB now. unless entry && entry.count == 1 add_failure_to user || email, '(LDAP) failed to authenticate', client_ip return nil end # load the user and return. user = load_ldap_user(entry.first, true, client_ip) unless user.enabled? add_failure_to user, '(LDAP) account disabled', client_ip return nil end add_success_to user, '(LDAP)', client_ip return user end else user = User.find_by(email: email) if user # user must be enabled, cannot be LDAP, and the password must match. if user.ldap? add_failure_to user, '(DB) cannot authenticate LDAP user', client_ip return nil end unless user.enabled? add_failure_to user, '(DB) account disabled', client_ip return nil end if user.authenticate(password) add_success_to user, '(DB)', client_ip return user else add_failure_to user, '(DB) invalid password', client_ip return nil end end end end add_failure_to email, 'invalid email', client_ip nil end
ruby
def authenticate(email, password, client_ip) return nil unless email && BarkestCore::EmailTester.valid_email?(email, false) email = email.downcase sources.each do |source| if source == :ldap entry = @ldap.search(filter: "(&(objectClass=user)(mail=#{email}))") if entry && entry.count == 1 # we found a match. user = User.find_by(email: email, ldap: true) # make sure it authenticates correctly. entry = @ldap.bind_as(filter: "(&(objectClass=user)(mail=#{email}))", password: password) # do not allow authenticating against the DB now. unless entry && entry.count == 1 add_failure_to user || email, '(LDAP) failed to authenticate', client_ip return nil end # load the user and return. user = load_ldap_user(entry.first, true, client_ip) unless user.enabled? add_failure_to user, '(LDAP) account disabled', client_ip return nil end add_success_to user, '(LDAP)', client_ip return user end else user = User.find_by(email: email) if user # user must be enabled, cannot be LDAP, and the password must match. if user.ldap? add_failure_to user, '(DB) cannot authenticate LDAP user', client_ip return nil end unless user.enabled? add_failure_to user, '(DB) account disabled', client_ip return nil end if user.authenticate(password) add_success_to user, '(DB)', client_ip return user else add_failure_to user, '(DB) invalid password', client_ip return nil end end end end add_failure_to email, 'invalid email', client_ip nil end
[ "def", "authenticate", "(", "email", ",", "password", ",", "client_ip", ")", "return", "nil", "unless", "email", "&&", "BarkestCore", "::", "EmailTester", ".", "valid_email?", "(", "email", ",", "false", ")", "email", "=", "email", ".", "downcase", "sources", ".", "each", "do", "|", "source", "|", "if", "source", "==", ":ldap", "entry", "=", "@ldap", ".", "search", "(", "filter", ":", "\"(&(objectClass=user)(mail=#{email}))\"", ")", "if", "entry", "&&", "entry", ".", "count", "==", "1", "# we found a match.", "user", "=", "User", ".", "find_by", "(", "email", ":", "email", ",", "ldap", ":", "true", ")", "# make sure it authenticates correctly.", "entry", "=", "@ldap", ".", "bind_as", "(", "filter", ":", "\"(&(objectClass=user)(mail=#{email}))\"", ",", "password", ":", "password", ")", "# do not allow authenticating against the DB now.", "unless", "entry", "&&", "entry", ".", "count", "==", "1", "add_failure_to", "user", "||", "email", ",", "'(LDAP) failed to authenticate'", ",", "client_ip", "return", "nil", "end", "# load the user and return.", "user", "=", "load_ldap_user", "(", "entry", ".", "first", ",", "true", ",", "client_ip", ")", "unless", "user", ".", "enabled?", "add_failure_to", "user", ",", "'(LDAP) account disabled'", ",", "client_ip", "return", "nil", "end", "add_success_to", "user", ",", "'(LDAP)'", ",", "client_ip", "return", "user", "end", "else", "user", "=", "User", ".", "find_by", "(", "email", ":", "email", ")", "if", "user", "# user must be enabled, cannot be LDAP, and the password must match.", "if", "user", ".", "ldap?", "add_failure_to", "user", ",", "'(DB) cannot authenticate LDAP user'", ",", "client_ip", "return", "nil", "end", "unless", "user", ".", "enabled?", "add_failure_to", "user", ",", "'(DB) account disabled'", ",", "client_ip", "return", "nil", "end", "if", "user", ".", "authenticate", "(", "password", ")", "add_success_to", "user", ",", "'(DB)'", ",", "client_ip", "return", "user", "else", "add_failure_to", "user", ",", "'(DB) invalid password'", ",", "client_ip", "return", "nil", "end", "end", "end", "end", "add_failure_to", "email", ",", "'invalid email'", ",", "client_ip", "nil", "end" ]
Attempts to authenticate the user and returns the model on success.
[ "Attempts", "to", "authenticate", "the", "user", "and", "returns", "the", "model", "on", "success", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/user_manager.rb#L69-L122
7,042
barkerest/barkest_core
app/models/barkest_core/user_manager.rb
BarkestCore.UserManager.ldap_system_admin_groups
def ldap_system_admin_groups @ldap_system_admin_groups ||= begin val = @options[:ldap_system_admin_groups] val.blank? ? [] : val.strip.gsub(',', ';').split(';').map{|v| v.strip.upcase} end end
ruby
def ldap_system_admin_groups @ldap_system_admin_groups ||= begin val = @options[:ldap_system_admin_groups] val.blank? ? [] : val.strip.gsub(',', ';').split(';').map{|v| v.strip.upcase} end end
[ "def", "ldap_system_admin_groups", "@ldap_system_admin_groups", "||=", "begin", "val", "=", "@options", "[", ":ldap_system_admin_groups", "]", "val", ".", "blank?", "?", "[", "]", ":", "val", ".", "strip", ".", "gsub", "(", "','", ",", "';'", ")", ".", "split", "(", "';'", ")", ".", "map", "{", "|", "v", "|", "v", ".", "strip", ".", "upcase", "}", "end", "end" ]
Gets the list of ldap groups that map to system administrators.
[ "Gets", "the", "list", "of", "ldap", "groups", "that", "map", "to", "system", "administrators", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/user_manager.rb#L144-L150
7,043
byu/serf
lib/serf/serfer.rb
Serf.Serfer.call
def call(parcel) # 1. Execute interactor response_kind, response_message, response_headers = interactor.call parcel # 2. Extract a possible version embedded in the response_kind. # This is sugar syntax for kind and version. if response_kind kind_part, version_part = response_kind.split '#', 2 response_kind = kind_part if version_part if version_part response_headers ||= {} response_headers[:version] = version_part end end # 3. Return a new response parcel with: # a. uuids set from parent parcel # b. kind set to response kind # c. the message set to response_message # d. add extra headers to the parcel return parcel_factory.create( parent: parcel, kind: response_kind, message: response_message, headers: response_headers) end
ruby
def call(parcel) # 1. Execute interactor response_kind, response_message, response_headers = interactor.call parcel # 2. Extract a possible version embedded in the response_kind. # This is sugar syntax for kind and version. if response_kind kind_part, version_part = response_kind.split '#', 2 response_kind = kind_part if version_part if version_part response_headers ||= {} response_headers[:version] = version_part end end # 3. Return a new response parcel with: # a. uuids set from parent parcel # b. kind set to response kind # c. the message set to response_message # d. add extra headers to the parcel return parcel_factory.create( parent: parcel, kind: response_kind, message: response_message, headers: response_headers) end
[ "def", "call", "(", "parcel", ")", "# 1. Execute interactor", "response_kind", ",", "response_message", ",", "response_headers", "=", "interactor", ".", "call", "parcel", "# 2. Extract a possible version embedded in the response_kind.", "# This is sugar syntax for kind and version.", "if", "response_kind", "kind_part", ",", "version_part", "=", "response_kind", ".", "split", "'#'", ",", "2", "response_kind", "=", "kind_part", "if", "version_part", "if", "version_part", "response_headers", "||=", "{", "}", "response_headers", "[", ":version", "]", "=", "version_part", "end", "end", "# 3. Return a new response parcel with:", "# a. uuids set from parent parcel", "# b. kind set to response kind", "# c. the message set to response_message", "# d. add extra headers to the parcel", "return", "parcel_factory", ".", "create", "(", "parent", ":", "parcel", ",", "kind", ":", "response_kind", ",", "message", ":", "response_message", ",", "headers", ":", "response_headers", ")", "end" ]
Rack-like call to run the Interactor's use-case.
[ "Rack", "-", "like", "call", "to", "run", "the", "Interactor", "s", "use", "-", "case", "." ]
0ab177be4784846e0b8ed093cc8580c877184bbf
https://github.com/byu/serf/blob/0ab177be4784846e0b8ed093cc8580c877184bbf/lib/serf/serfer.rb#L27-L52
7,044
factor-io/pivotal-api
lib/pivotal_api/client.rb
PivotalApi.Client.me
def me data = get("/me").body Resources::Me.new({ client: self }.merge(data)) end
ruby
def me data = get("/me").body Resources::Me.new({ client: self }.merge(data)) end
[ "def", "me", "data", "=", "get", "(", "\"/me\"", ")", ".", "body", "Resources", "::", "Me", ".", "new", "(", "{", "client", ":", "self", "}", ".", "merge", "(", "data", ")", ")", "end" ]
Get information about the authenticated user @return [PivotalApi::Resources::Me]
[ "Get", "information", "about", "the", "authenticated", "user" ]
e51d16689ad49894cba7f136e02d6758cc38fde0
https://github.com/factor-io/pivotal-api/blob/e51d16689ad49894cba7f136e02d6758cc38fde0/lib/pivotal_api/client.rb#L131-L135
7,045
jgoizueta/numerals
lib/numerals/format/symbols.rb
Numerals.Format::Symbols.regexp
def regexp(*args) options = args.pop if args.last.is_a?(Hash) options ||= {} symbols = args digits = symbols.delete(:digits) grouped_digits = symbols.delete(:grouped_digits) symbols = symbols.map { |s| s.is_a?(Symbol) ? send(s) : s } if grouped_digits symbols += [group_separator, insignificant_digit] elsif digits symbols += [insignificant_digit] end if digits || grouped_digits symbols += @digits.digits(options) end regexp_group(symbols, options) end
ruby
def regexp(*args) options = args.pop if args.last.is_a?(Hash) options ||= {} symbols = args digits = symbols.delete(:digits) grouped_digits = symbols.delete(:grouped_digits) symbols = symbols.map { |s| s.is_a?(Symbol) ? send(s) : s } if grouped_digits symbols += [group_separator, insignificant_digit] elsif digits symbols += [insignificant_digit] end if digits || grouped_digits symbols += @digits.digits(options) end regexp_group(symbols, options) end
[ "def", "regexp", "(", "*", "args", ")", "options", "=", "args", ".", "pop", "if", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "options", "||=", "{", "}", "symbols", "=", "args", "digits", "=", "symbols", ".", "delete", "(", ":digits", ")", "grouped_digits", "=", "symbols", ".", "delete", "(", ":grouped_digits", ")", "symbols", "=", "symbols", ".", "map", "{", "|", "s", "|", "s", ".", "is_a?", "(", "Symbol", ")", "?", "send", "(", "s", ")", ":", "s", "}", "if", "grouped_digits", "symbols", "+=", "[", "group_separator", ",", "insignificant_digit", "]", "elsif", "digits", "symbols", "+=", "[", "insignificant_digit", "]", "end", "if", "digits", "||", "grouped_digits", "symbols", "+=", "@digits", ".", "digits", "(", "options", ")", "end", "regexp_group", "(", "symbols", ",", "options", ")", "end" ]
Generate a regular expression to match any of the passed symbols. symbols.regexp(:nan, :plus, :minus) #=> "(NaN|+|-)" The special symbol :digits can also be passed to generate all the digits, in which case the :base option can be used to generate digits only for some base smaller than the maximum defined for digits. symbols.regexp(:digits, :point, base: 10) # => "(0|1|...|9)" The option :no_capture can be used to avoid generating a capturing group; otherwise the result is captured group (surrounded by parenthesis) symbols.regexp(:digits, no_capture: true) # => "(?:...)" The :case_sensitivity option is used to generate a regular expression that matches the case of the text as defined by ghe case_sensitive attribute of the Symbols. If this option is used the result should not be used in a case-insensitive regular expression (/.../i). /#{symbols.regexp(:digits, case_sensitivity: true)}/ If the options is not used, than the regular expression should be be made case-insensitive according to the Symbols: if symbols.case_sensitive? /#{symbols.regexp(:digits)}/ else /#{symbols.regexp(:digits)}/i
[ "Generate", "a", "regular", "expression", "to", "match", "any", "of", "the", "passed", "symbols", "." ]
a195e75f689af926537f791441bf8d11590c99c0
https://github.com/jgoizueta/numerals/blob/a195e75f689af926537f791441bf8d11590c99c0/lib/numerals/format/symbols.rb#L343-L361
7,046
octopress/filters
lib/octopress-filters.rb
Octopress.Filters.expand_url
def expand_url(input, url=nil) url ||= root url = if input.start_with?("http", url) input else File.join(url, input) end smart_slash(url) end
ruby
def expand_url(input, url=nil) url ||= root url = if input.start_with?("http", url) input else File.join(url, input) end smart_slash(url) end
[ "def", "expand_url", "(", "input", ",", "url", "=", "nil", ")", "url", "||=", "root", "url", "=", "if", "input", ".", "start_with?", "(", "\"http\"", ",", "url", ")", "input", "else", "File", ".", "join", "(", "url", ",", "input", ")", "end", "smart_slash", "(", "url", ")", "end" ]
Prepends input with a url fragment input - An absolute url, e.g. /images/awesome.gif url - The fragment to prepend the input, e.g. /blog Returns the modified url, e.g /blog
[ "Prepends", "input", "with", "a", "url", "fragment" ]
c39238f40881c66db9a7ea648f81df5560cf872e
https://github.com/octopress/filters/blob/c39238f40881c66db9a7ea648f81df5560cf872e/lib/octopress-filters.rb#L124-L134
7,047
DogParkLabs/json_rspec_match_maker
lib/json_rspec_match_maker/base.rb
JsonRspecMatchMaker.Base.expand_definition
def expand_definition(definition) return definition if definition.is_a? Hash definition.each_with_object({}) do |key, result| if key.is_a? String result[key] = :default elsif key.is_a? Hash result.merge!(expand_sub_definitions(key)) end end end
ruby
def expand_definition(definition) return definition if definition.is_a? Hash definition.each_with_object({}) do |key, result| if key.is_a? String result[key] = :default elsif key.is_a? Hash result.merge!(expand_sub_definitions(key)) end end end
[ "def", "expand_definition", "(", "definition", ")", "return", "definition", "if", "definition", ".", "is_a?", "Hash", "definition", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "key", ",", "result", "|", "if", "key", ".", "is_a?", "String", "result", "[", "key", "]", "=", ":default", "elsif", "key", ".", "is_a?", "Hash", "result", ".", "merge!", "(", "expand_sub_definitions", "(", "key", ")", ")", "end", "end", "end" ]
expands simple arrays into full hash definitions @api private @param definition [Array<String,Hash>] @return [Hash]
[ "expands", "simple", "arrays", "into", "full", "hash", "definitions" ]
7d9f299a0097c4eca3a4d22cecd28852bde8e8bc
https://github.com/DogParkLabs/json_rspec_match_maker/blob/7d9f299a0097c4eca3a4d22cecd28852bde8e8bc/lib/json_rspec_match_maker/base.rb#L63-L72
7,048
DogParkLabs/json_rspec_match_maker
lib/json_rspec_match_maker/base.rb
JsonRspecMatchMaker.Base.expand_sub_definitions
def expand_sub_definitions(sub_definitions) sub_definitions.each_with_object({}) do |(subkey, value), result| result[subkey] = value next if value.respond_to? :call result[subkey][:attributes] = expand_definition(value[:attributes]) end end
ruby
def expand_sub_definitions(sub_definitions) sub_definitions.each_with_object({}) do |(subkey, value), result| result[subkey] = value next if value.respond_to? :call result[subkey][:attributes] = expand_definition(value[:attributes]) end end
[ "def", "expand_sub_definitions", "(", "sub_definitions", ")", "sub_definitions", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "subkey", ",", "value", ")", ",", "result", "|", "result", "[", "subkey", "]", "=", "value", "next", "if", "value", ".", "respond_to?", ":call", "result", "[", "subkey", "]", "[", ":attributes", "]", "=", "expand_definition", "(", "value", "[", ":attributes", "]", ")", "end", "end" ]
expands nested simple definition into a full hash @api private @param definition [Hash] @return [Hash]
[ "expands", "nested", "simple", "definition", "into", "a", "full", "hash" ]
7d9f299a0097c4eca3a4d22cecd28852bde8e8bc
https://github.com/DogParkLabs/json_rspec_match_maker/blob/7d9f299a0097c4eca3a4d22cecd28852bde8e8bc/lib/json_rspec_match_maker/base.rb#L78-L84
7,049
DogParkLabs/json_rspec_match_maker
lib/json_rspec_match_maker/base.rb
JsonRspecMatchMaker.Base.check_definition
def check_definition(definition, current_expected, current_key = nil) definition.each do |error_key, match_def| if match_def.is_a? Hash key = [current_key, error_key].compact.join('.') check_each(key, match_def, current_expected) else check_values(current_key, error_key, match_def, current_expected) end end end
ruby
def check_definition(definition, current_expected, current_key = nil) definition.each do |error_key, match_def| if match_def.is_a? Hash key = [current_key, error_key].compact.join('.') check_each(key, match_def, current_expected) else check_values(current_key, error_key, match_def, current_expected) end end end
[ "def", "check_definition", "(", "definition", ",", "current_expected", ",", "current_key", "=", "nil", ")", "definition", ".", "each", "do", "|", "error_key", ",", "match_def", "|", "if", "match_def", ".", "is_a?", "Hash", "key", "=", "[", "current_key", ",", "error_key", "]", ".", "compact", ".", "join", "(", "'.'", ")", "check_each", "(", "key", ",", "match_def", ",", "current_expected", ")", "else", "check_values", "(", "current_key", ",", "error_key", ",", "match_def", ",", "current_expected", ")", "end", "end", "end" ]
Walks through the match definition, collecting errors for each field @api private @param definition [Hash] defines how to lookup value in json and on object @param current_expected [Object] the serialized object being checked @current_key [String,nil] optional parent key passed while checking nested definitions @return [nil] returns nothing, adds to error list as side effect
[ "Walks", "through", "the", "match", "definition", "collecting", "errors", "for", "each", "field" ]
7d9f299a0097c4eca3a4d22cecd28852bde8e8bc
https://github.com/DogParkLabs/json_rspec_match_maker/blob/7d9f299a0097c4eca3a4d22cecd28852bde8e8bc/lib/json_rspec_match_maker/base.rb#L92-L101
7,050
DogParkLabs/json_rspec_match_maker
lib/json_rspec_match_maker/base.rb
JsonRspecMatchMaker.Base.check_each
def check_each(error_key, each_definition, current_expected) enumerable = each_definition[:each].call(current_expected) enumerable.each_with_index do |each_instance, idx| full_key = [error_key, idx].join('.') check_definition(each_definition[:attributes], each_instance, full_key) end end
ruby
def check_each(error_key, each_definition, current_expected) enumerable = each_definition[:each].call(current_expected) enumerable.each_with_index do |each_instance, idx| full_key = [error_key, idx].join('.') check_definition(each_definition[:attributes], each_instance, full_key) end end
[ "def", "check_each", "(", "error_key", ",", "each_definition", ",", "current_expected", ")", "enumerable", "=", "each_definition", "[", ":each", "]", ".", "call", "(", "current_expected", ")", "enumerable", ".", "each_with_index", "do", "|", "each_instance", ",", "idx", "|", "full_key", "=", "[", "error_key", ",", "idx", "]", ".", "join", "(", "'.'", ")", "check_definition", "(", "each_definition", "[", ":attributes", "]", ",", "each_instance", ",", "full_key", ")", "end", "end" ]
Iterates through a list of objects while checking fields @api private @param error_key [String] the first name of the field reported in the error each errors are reported #{error_key}[#{idx}].#{each_key} @param each_definition [Hash] :each is a function that returns the list of items :attributes is a hash with the same structure as the top-level match_def hash @return [nil] returns nothing, adds to error list as side effect
[ "Iterates", "through", "a", "list", "of", "objects", "while", "checking", "fields" ]
7d9f299a0097c4eca3a4d22cecd28852bde8e8bc
https://github.com/DogParkLabs/json_rspec_match_maker/blob/7d9f299a0097c4eca3a4d22cecd28852bde8e8bc/lib/json_rspec_match_maker/base.rb#L112-L118
7,051
DogParkLabs/json_rspec_match_maker
lib/json_rspec_match_maker/base.rb
JsonRspecMatchMaker.Base.check_values
def check_values(key_prefix, error_key, match_function, expected_instance = expected) expected_value = ExpectedValue.new(match_function, expected_instance, error_key, @prefix) target_value = TargetValue.new([key_prefix, error_key].compact.join('.'), target) add_error(expected_value, target_value) unless expected_value == target_value end
ruby
def check_values(key_prefix, error_key, match_function, expected_instance = expected) expected_value = ExpectedValue.new(match_function, expected_instance, error_key, @prefix) target_value = TargetValue.new([key_prefix, error_key].compact.join('.'), target) add_error(expected_value, target_value) unless expected_value == target_value end
[ "def", "check_values", "(", "key_prefix", ",", "error_key", ",", "match_function", ",", "expected_instance", "=", "expected", ")", "expected_value", "=", "ExpectedValue", ".", "new", "(", "match_function", ",", "expected_instance", ",", "error_key", ",", "@prefix", ")", "target_value", "=", "TargetValue", ".", "new", "(", "[", "key_prefix", ",", "error_key", "]", ".", "compact", ".", "join", "(", "'.'", ")", ",", "target", ")", "add_error", "(", "expected_value", ",", "target_value", ")", "unless", "expected_value", "==", "target_value", "end" ]
Checks fields on a single instance @api private @param key_prefix [String] optional parent key if iterating through nested association @param error_key [String] the name of the field reported in the error @param match_function [Hash] a function returning the value for the key for the object being serialized @param expected_instance [Object] the top level instance, or an each instance from #check_each the index if iterating through a list, otherwise nil @return [nil] returns nothing, adds to error list as side effect
[ "Checks", "fields", "on", "a", "single", "instance" ]
7d9f299a0097c4eca3a4d22cecd28852bde8e8bc
https://github.com/DogParkLabs/json_rspec_match_maker/blob/7d9f299a0097c4eca3a4d22cecd28852bde8e8bc/lib/json_rspec_match_maker/base.rb#L130-L134
7,052
albertosaurus/us_bank_holidays
lib/us_bank_holidays.rb
UsBankHolidays.DateMethods.add_banking_days
def add_banking_days(days) day = self if days > 0 days.times { day = day.next_banking_day } elsif days < 0 (-days).times { day = day.previous_banking_day } end day end
ruby
def add_banking_days(days) day = self if days > 0 days.times { day = day.next_banking_day } elsif days < 0 (-days).times { day = day.previous_banking_day } end day end
[ "def", "add_banking_days", "(", "days", ")", "day", "=", "self", "if", "days", ">", "0", "days", ".", "times", "{", "day", "=", "day", ".", "next_banking_day", "}", "elsif", "days", "<", "0", "(", "-", "days", ")", ".", "times", "{", "day", "=", "day", ".", "previous_banking_day", "}", "end", "day", "end" ]
Adds the given number of banking days, i.e. bank holidays don't count. If days is negative, subtracts the given number of banking days. If days is zero, returns self.
[ "Adds", "the", "given", "number", "of", "banking", "days", "i", ".", "e", ".", "bank", "holidays", "don", "t", "count", ".", "If", "days", "is", "negative", "subtracts", "the", "given", "number", "of", "banking", "days", ".", "If", "days", "is", "zero", "returns", "self", "." ]
506269159bfaf0737955b2cca2d43c627ac9704e
https://github.com/albertosaurus/us_bank_holidays/blob/506269159bfaf0737955b2cca2d43c627ac9704e/lib/us_bank_holidays.rb#L85-L93
7,053
bblack16/bblib-ruby
lib/bblib/classes/fuzzy_matcher.rb
BBLib.FuzzyMatcher.similarity
def similarity(string_a, string_b) string_a, string_b = prep_strings(string_a, string_b) return 100.0 if string_a == string_b score = 0 total_weight = algorithms.values.inject { |sum, weight| sum + weight } algorithms.each do |algorithm, weight| next unless weight.positive? score+= string_a.send("#{algorithm}_similarity", string_b) * weight end score / total_weight end
ruby
def similarity(string_a, string_b) string_a, string_b = prep_strings(string_a, string_b) return 100.0 if string_a == string_b score = 0 total_weight = algorithms.values.inject { |sum, weight| sum + weight } algorithms.each do |algorithm, weight| next unless weight.positive? score+= string_a.send("#{algorithm}_similarity", string_b) * weight end score / total_weight end
[ "def", "similarity", "(", "string_a", ",", "string_b", ")", "string_a", ",", "string_b", "=", "prep_strings", "(", "string_a", ",", "string_b", ")", "return", "100.0", "if", "string_a", "==", "string_b", "score", "=", "0", "total_weight", "=", "algorithms", ".", "values", ".", "inject", "{", "|", "sum", ",", "weight", "|", "sum", "+", "weight", "}", "algorithms", ".", "each", "do", "|", "algorithm", ",", "weight", "|", "next", "unless", "weight", ".", "positive?", "score", "+=", "string_a", ".", "send", "(", "\"#{algorithm}_similarity\"", ",", "string_b", ")", "*", "weight", "end", "score", "/", "total_weight", "end" ]
Calculates a percentage match between string a and string b.
[ "Calculates", "a", "percentage", "match", "between", "string", "a", "and", "string", "b", "." ]
274eedeb583cc56243884fd041645488d5bd08a9
https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/classes/fuzzy_matcher.rb#L12-L22
7,054
bblack16/bblib-ruby
lib/bblib/classes/fuzzy_matcher.rb
BBLib.FuzzyMatcher.best_match
def best_match(string_a, *string_b) similarities(string_a, *string_b).max_by { |_k, v| v }[0] end
ruby
def best_match(string_a, *string_b) similarities(string_a, *string_b).max_by { |_k, v| v }[0] end
[ "def", "best_match", "(", "string_a", ",", "*", "string_b", ")", "similarities", "(", "string_a", ",", "string_b", ")", ".", "max_by", "{", "|", "_k", ",", "v", "|", "v", "}", "[", "0", "]", "end" ]
Returns the best match from array b to string a based on percent.
[ "Returns", "the", "best", "match", "from", "array", "b", "to", "string", "a", "based", "on", "percent", "." ]
274eedeb583cc56243884fd041645488d5bd08a9
https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/classes/fuzzy_matcher.rb#L30-L32
7,055
bblack16/bblib-ruby
lib/bblib/classes/fuzzy_matcher.rb
BBLib.FuzzyMatcher.similarities
def similarities(string_a, *string_b) [*string_b].map { |word| [word, matches[word] = similarity(string_a, word)] } end
ruby
def similarities(string_a, *string_b) [*string_b].map { |word| [word, matches[word] = similarity(string_a, word)] } end
[ "def", "similarities", "(", "string_a", ",", "*", "string_b", ")", "[", "string_b", "]", ".", "map", "{", "|", "word", "|", "[", "word", ",", "matches", "[", "word", "]", "=", "similarity", "(", "string_a", ",", "word", ")", "]", "}", "end" ]
Returns a hash of array 'b' with the percentage match to a. If sort is true, the hash is sorted desc by match percent.
[ "Returns", "a", "hash", "of", "array", "b", "with", "the", "percentage", "match", "to", "a", ".", "If", "sort", "is", "true", "the", "hash", "is", "sorted", "desc", "by", "match", "percent", "." ]
274eedeb583cc56243884fd041645488d5bd08a9
https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/classes/fuzzy_matcher.rb#L36-L38
7,056
OHSU-FM/reindeer-etl
lib/reindeer-etl/transforms/simple_transforms.rb
ReindeerETL::Transforms.SimpleTransforms.st_only_cols
def st_only_cols dict (dict.keys.to_set - @only_cols).each{|col|dict.delete(col)} dict end
ruby
def st_only_cols dict (dict.keys.to_set - @only_cols).each{|col|dict.delete(col)} dict end
[ "def", "st_only_cols", "dict", "(", "dict", ".", "keys", ".", "to_set", "-", "@only_cols", ")", ".", "each", "{", "|", "col", "|", "dict", ".", "delete", "(", "col", ")", "}", "dict", "end" ]
Filter out everything except these columns
[ "Filter", "out", "everything", "except", "these", "columns" ]
bff48c999b17850681346d500f2a05900252e21f
https://github.com/OHSU-FM/reindeer-etl/blob/bff48c999b17850681346d500f2a05900252e21f/lib/reindeer-etl/transforms/simple_transforms.rb#L18-L21
7,057
OHSU-FM/reindeer-etl
lib/reindeer-etl/transforms/simple_transforms.rb
ReindeerETL::Transforms.SimpleTransforms.st_require_cols
def st_require_cols dict dcols = dict.keys.to_set unless @require_cols.subset? dict.keys.to_set missing_cols = (@require_cols - dcols).to_a raise ReindeerETL::Errors::RecordInvalid.new("Missing required columns: #{missing_cols}") end end
ruby
def st_require_cols dict dcols = dict.keys.to_set unless @require_cols.subset? dict.keys.to_set missing_cols = (@require_cols - dcols).to_a raise ReindeerETL::Errors::RecordInvalid.new("Missing required columns: #{missing_cols}") end end
[ "def", "st_require_cols", "dict", "dcols", "=", "dict", ".", "keys", ".", "to_set", "unless", "@require_cols", ".", "subset?", "dict", ".", "keys", ".", "to_set", "missing_cols", "=", "(", "@require_cols", "-", "dcols", ")", ".", "to_a", "raise", "ReindeerETL", "::", "Errors", "::", "RecordInvalid", ".", "new", "(", "\"Missing required columns: #{missing_cols}\"", ")", "end", "end" ]
require these columns
[ "require", "these", "columns" ]
bff48c999b17850681346d500f2a05900252e21f
https://github.com/OHSU-FM/reindeer-etl/blob/bff48c999b17850681346d500f2a05900252e21f/lib/reindeer-etl/transforms/simple_transforms.rb#L25-L31
7,058
salesking/sk_sdk
lib/sk_sdk/ar_patches/ar3/validations.rb
ActiveResource.Errors.from_array
def from_array(messages, save_cache=false) clear unless save_cache messages.each do |msg| add msg[0], msg[1] end end
ruby
def from_array(messages, save_cache=false) clear unless save_cache messages.each do |msg| add msg[0], msg[1] end end
[ "def", "from_array", "(", "messages", ",", "save_cache", "=", "false", ")", "clear", "unless", "save_cache", "messages", ".", "each", "do", "|", "msg", "|", "add", "msg", "[", "0", "]", ",", "msg", "[", "1", "]", "end", "end" ]
Patched cause we dont need no attribute name magic .. and its just simpler orig version is looking up the humanized name of the attribute in the error message, which we dont supply => only field name is used in returned error msg
[ "Patched", "cause", "we", "dont", "need", "no", "attribute", "name", "magic", "..", "and", "its", "just", "simpler", "orig", "version", "is", "looking", "up", "the", "humanized", "name", "of", "the", "attribute", "in", "the", "error", "message", "which", "we", "dont", "supply", "=", ">", "only", "field", "name", "is", "used", "in", "returned", "error", "msg" ]
03170b2807cc4e1f1ba44c704c308370c6563dbc
https://github.com/salesking/sk_sdk/blob/03170b2807cc4e1f1ba44c704c308370c6563dbc/lib/sk_sdk/ar_patches/ar3/validations.rb#L6-L11
7,059
hinrik/ircsupport
lib/ircsupport/modes.rb
IRCSupport.Modes.parse_modes
def parse_modes(modes) mode_changes = [] modes.scan(/[-+]\w+/).each do |modegroup| set, modegroup = modegroup.split '', 2 set = set == '+' ? true : false modegroup.split('').each do |mode| mode_changes << { set: set, mode: mode } end end return mode_changes end
ruby
def parse_modes(modes) mode_changes = [] modes.scan(/[-+]\w+/).each do |modegroup| set, modegroup = modegroup.split '', 2 set = set == '+' ? true : false modegroup.split('').each do |mode| mode_changes << { set: set, mode: mode } end end return mode_changes end
[ "def", "parse_modes", "(", "modes", ")", "mode_changes", "=", "[", "]", "modes", ".", "scan", "(", "/", "\\w", "/", ")", ".", "each", "do", "|", "modegroup", "|", "set", ",", "modegroup", "=", "modegroup", ".", "split", "''", ",", "2", "set", "=", "set", "==", "'+'", "?", "true", ":", "false", "modegroup", ".", "split", "(", "''", ")", ".", "each", "do", "|", "mode", "|", "mode_changes", "<<", "{", "set", ":", "set", ",", "mode", ":", "mode", "}", "end", "end", "return", "mode_changes", "end" ]
Parse mode changes. @param [Array] modes The modes you want to parse. A string of mode changes (e.g. `'-i+k+l'`) followed by any arguments (e.g. `'secret', 25`). @return [Array] Each element will be a hash with two keys: `:set`, a boolean indicating whether the mode is being set (instead of unset); and `:mode`, the mode character.
[ "Parse", "mode", "changes", "." ]
d028b7d5ccc604a6af175ee2264c18d25b1f7dff
https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/modes.rb#L11-L21
7,060
hinrik/ircsupport
lib/ircsupport/modes.rb
IRCSupport.Modes.parse_channel_modes
def parse_channel_modes(modes, opts = {}) chanmodes = opts[:chanmodes] || { 'A' => %w{b e I}.to_set, 'B' => %w{k}.to_set, 'C' => %w{l}.to_set, 'D' => %w{i m n p s t a q r}.to_set, } statmodes = opts[:statmodes] || %w{o h v}.to_set mode_changes = [] modelist, *args = modes parse_modes(modelist).each do |mode_change| set, mode = mode_change[:set], mode_change[:mode] case when chanmodes["A"].include?(mode) || chanmodes["B"].include?(mode) mode_changes << { mode: mode, set: set, argument: args.shift } when chanmodes["C"].include?(mode) mode_changes << { mode: mode, set: set, argument: args.shift.to_i } when chanmodes["D"].include?(mode) mode_changes << { mode: mode, set: set, } else raise ArgumentError, "Unknown mode: #{mode}" end end return mode_changes end
ruby
def parse_channel_modes(modes, opts = {}) chanmodes = opts[:chanmodes] || { 'A' => %w{b e I}.to_set, 'B' => %w{k}.to_set, 'C' => %w{l}.to_set, 'D' => %w{i m n p s t a q r}.to_set, } statmodes = opts[:statmodes] || %w{o h v}.to_set mode_changes = [] modelist, *args = modes parse_modes(modelist).each do |mode_change| set, mode = mode_change[:set], mode_change[:mode] case when chanmodes["A"].include?(mode) || chanmodes["B"].include?(mode) mode_changes << { mode: mode, set: set, argument: args.shift } when chanmodes["C"].include?(mode) mode_changes << { mode: mode, set: set, argument: args.shift.to_i } when chanmodes["D"].include?(mode) mode_changes << { mode: mode, set: set, } else raise ArgumentError, "Unknown mode: #{mode}" end end return mode_changes end
[ "def", "parse_channel_modes", "(", "modes", ",", "opts", "=", "{", "}", ")", "chanmodes", "=", "opts", "[", ":chanmodes", "]", "||", "{", "'A'", "=>", "%w{", "b", "e", "I", "}", ".", "to_set", ",", "'B'", "=>", "%w{", "k", "}", ".", "to_set", ",", "'C'", "=>", "%w{", "l", "}", ".", "to_set", ",", "'D'", "=>", "%w{", "i", "m", "n", "p", "s", "t", "a", "q", "r", "}", ".", "to_set", ",", "}", "statmodes", "=", "opts", "[", ":statmodes", "]", "||", "%w{", "o", "h", "v", "}", ".", "to_set", "mode_changes", "=", "[", "]", "modelist", ",", "*", "args", "=", "modes", "parse_modes", "(", "modelist", ")", ".", "each", "do", "|", "mode_change", "|", "set", ",", "mode", "=", "mode_change", "[", ":set", "]", ",", "mode_change", "[", ":mode", "]", "case", "when", "chanmodes", "[", "\"A\"", "]", ".", "include?", "(", "mode", ")", "||", "chanmodes", "[", "\"B\"", "]", ".", "include?", "(", "mode", ")", "mode_changes", "<<", "{", "mode", ":", "mode", ",", "set", ":", "set", ",", "argument", ":", "args", ".", "shift", "}", "when", "chanmodes", "[", "\"C\"", "]", ".", "include?", "(", "mode", ")", "mode_changes", "<<", "{", "mode", ":", "mode", ",", "set", ":", "set", ",", "argument", ":", "args", ".", "shift", ".", "to_i", "}", "when", "chanmodes", "[", "\"D\"", "]", ".", "include?", "(", "mode", ")", "mode_changes", "<<", "{", "mode", ":", "mode", ",", "set", ":", "set", ",", "}", "else", "raise", "ArgumentError", ",", "\"Unknown mode: #{mode}\"", "end", "end", "return", "mode_changes", "end" ]
Parse channel mode changes. @param [Array] modes The modes you want to parse. @option opts [Hash] :chanmodes The channel modes which are allowed. This is the same as the "CHANMODES" isupport option. @option opts [Hash] :statmodes The channel modes which are allowed. This is the same as the keys of the "PREFIX" isupport option. @return [Array] Each element will be a hash with three keys: `:set`, a boolean indicating whether the mode is being set (instead of unset); `:mode`, the mode character; and `:argument`, the argument to the mode, if any.
[ "Parse", "channel", "mode", "changes", "." ]
d028b7d5ccc604a6af175ee2264c18d25b1f7dff
https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/modes.rb#L33-L70
7,061
hinrik/ircsupport
lib/ircsupport/modes.rb
IRCSupport.Modes.condense_modes
def condense_modes(modes) action = nil result = '' modes.split(//).each do |mode| if mode =~ /[+-]/ and (!action or mode != action) result += mode action = mode next end result += mode if mode =~ /[^+-]/ end result.sub!(/[+-]\z/, '') return result end
ruby
def condense_modes(modes) action = nil result = '' modes.split(//).each do |mode| if mode =~ /[+-]/ and (!action or mode != action) result += mode action = mode next end result += mode if mode =~ /[^+-]/ end result.sub!(/[+-]\z/, '') return result end
[ "def", "condense_modes", "(", "modes", ")", "action", "=", "nil", "result", "=", "''", "modes", ".", "split", "(", "/", "/", ")", ".", "each", "do", "|", "mode", "|", "if", "mode", "=~", "/", "/", "and", "(", "!", "action", "or", "mode", "!=", "action", ")", "result", "+=", "mode", "action", "=", "mode", "next", "end", "result", "+=", "mode", "if", "mode", "=~", "/", "/", "end", "result", ".", "sub!", "(", "/", "\\z", "/", ",", "''", ")", "return", "result", "end" ]
Condense mode string by removing duplicates. @param [String] modes A string of modes you want condensed. @return [Strings] A condensed mode string.
[ "Condense", "mode", "string", "by", "removing", "duplicates", "." ]
d028b7d5ccc604a6af175ee2264c18d25b1f7dff
https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/modes.rb#L75-L88
7,062
hinrik/ircsupport
lib/ircsupport/modes.rb
IRCSupport.Modes.diff_modes
def diff_modes(before, after) before_modes = before.split(//) after_modes = after.split(//) removed = before_modes - after_modes added = after_modes - before_modes result = removed.map { |m| '-' + m }.join result << added.map { |m| '+' + m }.join return condense_modes(result) end
ruby
def diff_modes(before, after) before_modes = before.split(//) after_modes = after.split(//) removed = before_modes - after_modes added = after_modes - before_modes result = removed.map { |m| '-' + m }.join result << added.map { |m| '+' + m }.join return condense_modes(result) end
[ "def", "diff_modes", "(", "before", ",", "after", ")", "before_modes", "=", "before", ".", "split", "(", "/", "/", ")", "after_modes", "=", "after", ".", "split", "(", "/", "/", ")", "removed", "=", "before_modes", "-", "after_modes", "added", "=", "after_modes", "-", "before_modes", "result", "=", "removed", ".", "map", "{", "|", "m", "|", "'-'", "+", "m", "}", ".", "join", "result", "<<", "added", ".", "map", "{", "|", "m", "|", "'+'", "+", "m", "}", ".", "join", "return", "condense_modes", "(", "result", ")", "end" ]
Calculate the difference between two mode strings. @param [String] before The "before" mode string. @param [String] after The "after" mode string. @return [String] A modestring representing the difference between the two mode strings.
[ "Calculate", "the", "difference", "between", "two", "mode", "strings", "." ]
d028b7d5ccc604a6af175ee2264c18d25b1f7dff
https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/modes.rb#L95-L103
7,063
jinx/core
lib/jinx/metadata/java_property.rb
Jinx.JavaProperty.infer_collection_type_from_name
def infer_collection_type_from_name # the property name pname = @property_descriptor.name # The potential class name is the capitalized property name without a 'Collection' suffix. cname = pname.capitalize_first.sub(/Collection$/, '') jname = [@declarer.parent_module, cname].join('::') klass = eval jname rescue nil if klass then logger.debug { "Inferred #{declarer.qp} #{self} collection domain type #{klass.qp} from the property name." } end klass end
ruby
def infer_collection_type_from_name # the property name pname = @property_descriptor.name # The potential class name is the capitalized property name without a 'Collection' suffix. cname = pname.capitalize_first.sub(/Collection$/, '') jname = [@declarer.parent_module, cname].join('::') klass = eval jname rescue nil if klass then logger.debug { "Inferred #{declarer.qp} #{self} collection domain type #{klass.qp} from the property name." } end klass end
[ "def", "infer_collection_type_from_name", "# the property name", "pname", "=", "@property_descriptor", ".", "name", "# The potential class name is the capitalized property name without a 'Collection' suffix.", "cname", "=", "pname", ".", "capitalize_first", ".", "sub", "(", "/", "/", ",", "''", ")", "jname", "=", "[", "@declarer", ".", "parent_module", ",", "cname", "]", ".", "join", "(", "'::'", ")", "klass", "=", "eval", "jname", "rescue", "nil", "if", "klass", "then", "logger", ".", "debug", "{", "\"Inferred #{declarer.qp} #{self} collection domain type #{klass.qp} from the property name.\"", "}", "end", "klass", "end" ]
Returns the domain type for this property's collection Java property descriptor name. By convention, Jinx domain collection propertys often begin with a domain type name and end in 'Collection'. This method strips the Collection suffix and checks whether the prefix is a domain class. For example, the type of the property named +distributionProtocolCollection+ is inferred as +DistributionProtocol+ by stripping the +Collection+ suffix, capitalizing the prefix and looking for a class of that name in this classifier's domain_module. @return [Class] the collection item type
[ "Returns", "the", "domain", "type", "for", "this", "property", "s", "collection", "Java", "property", "descriptor", "name", ".", "By", "convention", "Jinx", "domain", "collection", "propertys", "often", "begin", "with", "a", "domain", "type", "name", "and", "end", "in", "Collection", ".", "This", "method", "strips", "the", "Collection", "suffix", "and", "checks", "whether", "the", "prefix", "is", "a", "domain", "class", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/java_property.rb#L147-L156
7,064
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.define_plugin_types
def define_plugin_types(namespace, type_info) if type_info.is_a?(Hash) type_info.each do |plugin_type, default_provider| define_plugin_type(namespace, plugin_type, default_provider) end end self end
ruby
def define_plugin_types(namespace, type_info) if type_info.is_a?(Hash) type_info.each do |plugin_type, default_provider| define_plugin_type(namespace, plugin_type, default_provider) end end self end
[ "def", "define_plugin_types", "(", "namespace", ",", "type_info", ")", "if", "type_info", ".", "is_a?", "(", "Hash", ")", "type_info", ".", "each", "do", "|", "plugin_type", ",", "default_provider", "|", "define_plugin_type", "(", "namespace", ",", "plugin_type", ",", "default_provider", ")", "end", "end", "self", "end" ]
Define one or more new plugin types in a specified namespace. * *Parameters* - [String, Symbol] *namespace* Namespace that contains plugin types - [Hash<String, Symbol|String, Symbol>] *type_info* Plugin type, default provider pairs * *Returns* - [Nucleon::Environment] Returns reference to self for compound operations * *Errors* See: - #define_plugin_type
[ "Define", "one", "or", "more", "new", "plugin", "types", "in", "a", "specified", "namespace", "." ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L146-L153
7,065
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.loaded_plugin
def loaded_plugin(namespace, plugin_type, provider) get([ :load_info, namespace, sanitize_id(plugin_type), sanitize_id(provider) ], nil) end
ruby
def loaded_plugin(namespace, plugin_type, provider) get([ :load_info, namespace, sanitize_id(plugin_type), sanitize_id(provider) ], nil) end
[ "def", "loaded_plugin", "(", "namespace", ",", "plugin_type", ",", "provider", ")", "get", "(", "[", ":load_info", ",", "namespace", ",", "sanitize_id", "(", "plugin_type", ")", ",", "sanitize_id", "(", "provider", ")", "]", ",", "nil", ")", "end" ]
Return the load information for a specified plugin provider if it exists * *Parameters* - [String, Symbol] *namespace* Namespace that contains plugin types - [String, Symbol] *plugin_type* Plugin type name of provider - [String, Symbol] *provider* Plugin provider to return load information * *Returns* - [nil, Hash<Symbol|ANY>] Returns provider load information if provider exists, nil otherwise * *Errors* See: - Nucleon::Config#get See also: - #sanitize_id
[ "Return", "the", "load", "information", "for", "a", "specified", "plugin", "provider", "if", "it", "exists" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L265-L267
7,066
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.loaded_plugins
def loaded_plugins(namespace = nil, plugin_type = nil, provider = nil, default = {}) load_info = get_hash(:load_info) namespace = namespace.to_sym if namespace plugin_type = sanitize_id(plugin_type) if plugin_type provider = sanitize_id(provider) if provider results = default if namespace && load_info.has_key?(namespace) if plugin_type && load_info[namespace].has_key?(plugin_type) if provider && load_info[namespace][plugin_type].has_key?(provider) results = load_info[namespace][plugin_type][provider] elsif ! provider results = load_info[namespace][plugin_type] end elsif ! plugin_type results = load_info[namespace] end elsif ! namespace results = load_info end results end
ruby
def loaded_plugins(namespace = nil, plugin_type = nil, provider = nil, default = {}) load_info = get_hash(:load_info) namespace = namespace.to_sym if namespace plugin_type = sanitize_id(plugin_type) if plugin_type provider = sanitize_id(provider) if provider results = default if namespace && load_info.has_key?(namespace) if plugin_type && load_info[namespace].has_key?(plugin_type) if provider && load_info[namespace][plugin_type].has_key?(provider) results = load_info[namespace][plugin_type][provider] elsif ! provider results = load_info[namespace][plugin_type] end elsif ! plugin_type results = load_info[namespace] end elsif ! namespace results = load_info end results end
[ "def", "loaded_plugins", "(", "namespace", "=", "nil", ",", "plugin_type", "=", "nil", ",", "provider", "=", "nil", ",", "default", "=", "{", "}", ")", "load_info", "=", "get_hash", "(", ":load_info", ")", "namespace", "=", "namespace", ".", "to_sym", "if", "namespace", "plugin_type", "=", "sanitize_id", "(", "plugin_type", ")", "if", "plugin_type", "provider", "=", "sanitize_id", "(", "provider", ")", "if", "provider", "results", "=", "default", "if", "namespace", "&&", "load_info", ".", "has_key?", "(", "namespace", ")", "if", "plugin_type", "&&", "load_info", "[", "namespace", "]", ".", "has_key?", "(", "plugin_type", ")", "if", "provider", "&&", "load_info", "[", "namespace", "]", "[", "plugin_type", "]", ".", "has_key?", "(", "provider", ")", "results", "=", "load_info", "[", "namespace", "]", "[", "plugin_type", "]", "[", "provider", "]", "elsif", "!", "provider", "results", "=", "load_info", "[", "namespace", "]", "[", "plugin_type", "]", "end", "elsif", "!", "plugin_type", "results", "=", "load_info", "[", "namespace", "]", "end", "elsif", "!", "namespace", "results", "=", "load_info", "end", "results", "end" ]
Return the load information for namespaces, plugin types, providers if it exists * *Parameters* - [nil, String, Symbol] *namespace* Namespace to return load information - [nil, String, Symbol] *plugin_type* Plugin type name to return load information - [nil, String, Symbol] *provider* Plugin provider to return load information - [ANY] *default* Default results if nothing found (empty hash by default) * *Returns* - [nil, Hash<Symbol|Symbol|Symbol|Symbol|ANY>] Returns all load information if no parameters given - [nil, Hash<Symbol|Symbol|Symbol|ANY>] Returns namespace load information if only namespace given - [nil, Hash<Symbol|Symbol|ANY>] Returns plugin type load information if namespace and plugin type given - [nil, Hash<Symbol|ANY>] Returns provider load information if namespace, plugin type, and provider given * *Errors* See: - Nucleon::Config#get_hash See also: - #sanitize_id
[ "Return", "the", "load", "information", "for", "namespaces", "plugin", "types", "providers", "if", "it", "exists" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L291-L313
7,067
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.plugin_has_provider?
def plugin_has_provider?(namespace, plugin_type, provider) get_hash([ :load_info, namespace, sanitize_id(plugin_type) ]).has_key?(sanitize_id(provider)) end
ruby
def plugin_has_provider?(namespace, plugin_type, provider) get_hash([ :load_info, namespace, sanitize_id(plugin_type) ]).has_key?(sanitize_id(provider)) end
[ "def", "plugin_has_provider?", "(", "namespace", ",", "plugin_type", ",", "provider", ")", "get_hash", "(", "[", ":load_info", ",", "namespace", ",", "sanitize_id", "(", "plugin_type", ")", "]", ")", ".", "has_key?", "(", "sanitize_id", "(", "provider", ")", ")", "end" ]
Check if a specified plugin provider has been loaded * *Parameters* - [String, Symbol] *namespace* Namespace that contains plugin types - [String, Symbol] *plugin_type* Plugin type name to check - [String, Symbol] *provider* Plugin provider name to check * *Returns* - [Boolean] Returns true if plugin provider has been loaded, false otherwise * *Errors* See: - Nucleon::Config#get_hash See also: - #sanitize_id
[ "Check", "if", "a", "specified", "plugin", "provider", "has", "been", "loaded" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L354-L356
7,068
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.get_plugin
def get_plugin(namespace, plugin_type, plugin_name) namespace = namespace.to_sym plugin_type = sanitize_id(plugin_type) instances = get_hash([ :active_info, namespace, plugin_type ]) instance_ids = array(@instance_map.get([ namespace, plugin_type, plugin_name.to_s.to_sym ])) if instance_ids.size return instances[instance_ids[0]] end nil end
ruby
def get_plugin(namespace, plugin_type, plugin_name) namespace = namespace.to_sym plugin_type = sanitize_id(plugin_type) instances = get_hash([ :active_info, namespace, plugin_type ]) instance_ids = array(@instance_map.get([ namespace, plugin_type, plugin_name.to_s.to_sym ])) if instance_ids.size return instances[instance_ids[0]] end nil end
[ "def", "get_plugin", "(", "namespace", ",", "plugin_type", ",", "plugin_name", ")", "namespace", "=", "namespace", ".", "to_sym", "plugin_type", "=", "sanitize_id", "(", "plugin_type", ")", "instances", "=", "get_hash", "(", "[", ":active_info", ",", "namespace", ",", "plugin_type", "]", ")", "instance_ids", "=", "array", "(", "@instance_map", ".", "get", "(", "[", "namespace", ",", "plugin_type", ",", "plugin_name", ".", "to_s", ".", "to_sym", "]", ")", ")", "if", "instance_ids", ".", "size", "return", "instances", "[", "instance_ids", "[", "0", "]", "]", "end", "nil", "end" ]
Return a plugin instance by name if it exists * *Parameters* - [String, Symbol] *namespace* Namespace that contains the plugin - [String, Symbol] *plugin_type* Plugin type name - [String, Symbol] *plugin_name* Plugin name to return * *Returns* - [nil, Nucleon::Plugin::Base] Returns a plugin instance of name specified if it exists * *Errors* See: - Nucleon::Plugin::Base - Nucleon::Config#get_hash See also: - #sanitize_id
[ "Return", "a", "plugin", "instance", "by", "name", "if", "it", "exists" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L488-L499
7,069
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.remove_plugin
def remove_plugin(namespace, plugin_type, instance_name, &code) # :yields: plugin plugin = delete([ :active_info, namespace, sanitize_id(plugin_type), instance_name ]) code.call(plugin) if code && plugin plugin end
ruby
def remove_plugin(namespace, plugin_type, instance_name, &code) # :yields: plugin plugin = delete([ :active_info, namespace, sanitize_id(plugin_type), instance_name ]) code.call(plugin) if code && plugin plugin end
[ "def", "remove_plugin", "(", "namespace", ",", "plugin_type", ",", "instance_name", ",", "&", "code", ")", "# :yields: plugin", "plugin", "=", "delete", "(", "[", ":active_info", ",", "namespace", ",", "sanitize_id", "(", "plugin_type", ")", ",", "instance_name", "]", ")", "code", ".", "call", "(", "plugin", ")", "if", "code", "&&", "plugin", "plugin", "end" ]
Remove a plugin instance from the environment * *Parameters* - [String, Symbol] *namespace* Namespace that contains the plugin - [String, Symbol] *plugin_type* Plugin type name - [String, Symbol] *instance_name* Plugin instance name to tremove * *Returns* - [nil, Nucleon::Plugin::Base] Returns the plugin instance that was removed from environment * *Errors* * *Yields* - [Nucleon::Plugin::Base] *plugin* Plugin object being removed (cleanup) See: - Nucleon::Plugin::Base - Nucleon::Config#delete See also: - #sanitize_id
[ "Remove", "a", "plugin", "instance", "from", "the", "environment" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L523-L527
7,070
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.active_plugins
def active_plugins(namespace = nil, plugin_type = nil, provider = nil) active_info = get_hash(:active_info) namespace = namespace.to_sym if namespace plugin_type = sanitize_id(plugin_type) if plugin_type provider = sanitize_id(provider) if provider results = {} if namespace && active_info.has_key?(namespace) if plugin_type && active_info[namespace].has_key?(plugin_type) if provider && ! active_info[namespace][plugin_type].keys.empty? active_info[namespace][plugin_type].each do |instance_name, plugin| plugin = active_info[namespace][plugin_type][instance_name] results[instance_name] = plugin if plugin.plugin_provider == provider end elsif ! provider results = active_info[namespace][plugin_type] end elsif ! plugin_type results = active_info[namespace] end elsif ! namespace results = active_info end results end
ruby
def active_plugins(namespace = nil, plugin_type = nil, provider = nil) active_info = get_hash(:active_info) namespace = namespace.to_sym if namespace plugin_type = sanitize_id(plugin_type) if plugin_type provider = sanitize_id(provider) if provider results = {} if namespace && active_info.has_key?(namespace) if plugin_type && active_info[namespace].has_key?(plugin_type) if provider && ! active_info[namespace][plugin_type].keys.empty? active_info[namespace][plugin_type].each do |instance_name, plugin| plugin = active_info[namespace][plugin_type][instance_name] results[instance_name] = plugin if plugin.plugin_provider == provider end elsif ! provider results = active_info[namespace][plugin_type] end elsif ! plugin_type results = active_info[namespace] end elsif ! namespace results = active_info end results end
[ "def", "active_plugins", "(", "namespace", "=", "nil", ",", "plugin_type", "=", "nil", ",", "provider", "=", "nil", ")", "active_info", "=", "get_hash", "(", ":active_info", ")", "namespace", "=", "namespace", ".", "to_sym", "if", "namespace", "plugin_type", "=", "sanitize_id", "(", "plugin_type", ")", "if", "plugin_type", "provider", "=", "sanitize_id", "(", "provider", ")", "if", "provider", "results", "=", "{", "}", "if", "namespace", "&&", "active_info", ".", "has_key?", "(", "namespace", ")", "if", "plugin_type", "&&", "active_info", "[", "namespace", "]", ".", "has_key?", "(", "plugin_type", ")", "if", "provider", "&&", "!", "active_info", "[", "namespace", "]", "[", "plugin_type", "]", ".", "keys", ".", "empty?", "active_info", "[", "namespace", "]", "[", "plugin_type", "]", ".", "each", "do", "|", "instance_name", ",", "plugin", "|", "plugin", "=", "active_info", "[", "namespace", "]", "[", "plugin_type", "]", "[", "instance_name", "]", "results", "[", "instance_name", "]", "=", "plugin", "if", "plugin", ".", "plugin_provider", "==", "provider", "end", "elsif", "!", "provider", "results", "=", "active_info", "[", "namespace", "]", "[", "plugin_type", "]", "end", "elsif", "!", "plugin_type", "results", "=", "active_info", "[", "namespace", "]", "end", "elsif", "!", "namespace", "results", "=", "active_info", "end", "results", "end" ]
Return active plugins for namespaces, plugin types, providers if specified * *Parameters* - [nil, String, Symbol] *namespace* Namespace to return plugin instance - [nil, String, Symbol] *plugin_type* Plugin type name to return plugin instance - [nil, String, Symbol] *provider* Plugin provider to return plugin instance * *Returns* - [nil, Hash<Symbol|Symbol|Symbol|Symbol|Nucleon::Plugin::Base>] Returns all plugin instances if no parameters given - [nil, Hash<Symbol|Symbol|Symbol|Nucleon::Plugin::Base>] Returns namespace plugin instances if only namespace given - [nil, Hash<Symbol|Symbol|Nucleon::Plugin::Base>] Returns plugin type instances if namespace and plugin type given - [nil, Hash<Symbol|Nucleon::Plugin::Base>] Returns provider instances if namespace, plugin type, and provider given * *Errors* See: - Nucleon::Config#get_hash See also: - #sanitize_id
[ "Return", "active", "plugins", "for", "namespaces", "plugin", "types", "providers", "if", "specified" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L550-L575
7,071
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.class_const
def class_const(name, separator = '::') components = class_name(name, separator, TRUE) constant = Object components.each do |component| constant = constant.const_defined?(component) ? constant.const_get(component) : constant.const_missing(component) end constant end
ruby
def class_const(name, separator = '::') components = class_name(name, separator, TRUE) constant = Object components.each do |component| constant = constant.const_defined?(component) ? constant.const_get(component) : constant.const_missing(component) end constant end
[ "def", "class_const", "(", "name", ",", "separator", "=", "'::'", ")", "components", "=", "class_name", "(", "name", ",", "separator", ",", "TRUE", ")", "constant", "=", "Object", "components", ".", "each", "do", "|", "component", "|", "constant", "=", "constant", ".", "const_defined?", "(", "component", ")", "?", "constant", ".", "const_get", "(", "component", ")", ":", "constant", ".", "const_missing", "(", "component", ")", "end", "constant", "end" ]
Return a fully formed class name as a machine usable constant * *Parameters* - [String, Symbol, Array] *name* Class name components - [String, Symbol] *separator* Class component separator (default '::') * *Returns* - [Class Constant] Returns class constant for fully formed class name of given components * *Errors* See also: - #class_name
[ "Return", "a", "fully", "formed", "class", "name", "as", "a", "machine", "usable", "constant" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L629-L639
7,072
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.sanitize_class
def sanitize_class(class_component) class_component.to_s.split('_').collect {|elem| elem.slice(0,1).capitalize + elem.slice(1..-1) }.join('') end
ruby
def sanitize_class(class_component) class_component.to_s.split('_').collect {|elem| elem.slice(0,1).capitalize + elem.slice(1..-1) }.join('') end
[ "def", "sanitize_class", "(", "class_component", ")", "class_component", ".", "to_s", ".", "split", "(", "'_'", ")", ".", "collect", "{", "|", "elem", "|", "elem", ".", "slice", "(", "0", ",", "1", ")", ".", "capitalize", "+", "elem", ".", "slice", "(", "1", "..", "-", "1", ")", "}", ".", "join", "(", "''", ")", "end" ]
Sanitize a class identifier for internal use. * *Parameters* - [String, Symbol] *class_component* Class identifier to sanitize * *Returns* - [String] Returns a sanitized string representing the given class component * *Errors*
[ "Sanitize", "a", "class", "identifier", "for", "internal", "use", "." ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L666-L668
7,073
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.provider_class
def provider_class(namespace, plugin_type, provider) class_const([ sanitize_class(namespace), sanitize_class(plugin_type), provider ]) end
ruby
def provider_class(namespace, plugin_type, provider) class_const([ sanitize_class(namespace), sanitize_class(plugin_type), provider ]) end
[ "def", "provider_class", "(", "namespace", ",", "plugin_type", ",", "provider", ")", "class_const", "(", "[", "sanitize_class", "(", "namespace", ")", ",", "sanitize_class", "(", "plugin_type", ")", ",", "provider", "]", ")", "end" ]
Return a class constant representing a plugin provider class generated from namespace, plugin_type, and provider name. The provider name can be entered as an array if it is included in sub modules. * *Parameters* - [String, Symbol] *namespace* Plugin namespace to constantize - [String, Symbol] *plugin_type* Plugin type to constantize - [String, Symbol, Array] *provider* Plugin provider name to constantize * *Returns* - [String] Returns a class constant representing the plugin provider * *Errors* See also: - #class_const - #sanitize_class
[ "Return", "a", "class", "constant", "representing", "a", "plugin", "provider", "class", "generated", "from", "namespace", "plugin_type", "and", "provider", "name", "." ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L709-L711
7,074
codescrum/bebox
lib/bebox/wizards/role_wizard.rb
Bebox.RoleWizard.create_new_role
def create_new_role(project_root, role_name) # Check if the role name is valid return error _('wizard.role.invalid_name')%{words: Bebox::RESERVED_WORDS.join(', ')} unless valid_puppet_class_name?(role_name) # Check if the role exist return error(_('wizard.role.name_exist')%{role: role_name}) if role_exists?(project_root, role_name) # Role creation role = Bebox::Role.new(role_name, project_root) output = role.create ok _('wizard.role.creation_success') return output end
ruby
def create_new_role(project_root, role_name) # Check if the role name is valid return error _('wizard.role.invalid_name')%{words: Bebox::RESERVED_WORDS.join(', ')} unless valid_puppet_class_name?(role_name) # Check if the role exist return error(_('wizard.role.name_exist')%{role: role_name}) if role_exists?(project_root, role_name) # Role creation role = Bebox::Role.new(role_name, project_root) output = role.create ok _('wizard.role.creation_success') return output end
[ "def", "create_new_role", "(", "project_root", ",", "role_name", ")", "# Check if the role name is valid", "return", "error", "_", "(", "'wizard.role.invalid_name'", ")", "%", "{", "words", ":", "Bebox", "::", "RESERVED_WORDS", ".", "join", "(", "', '", ")", "}", "unless", "valid_puppet_class_name?", "(", "role_name", ")", "# Check if the role exist", "return", "error", "(", "_", "(", "'wizard.role.name_exist'", ")", "%", "{", "role", ":", "role_name", "}", ")", "if", "role_exists?", "(", "project_root", ",", "role_name", ")", "# Role creation", "role", "=", "Bebox", "::", "Role", ".", "new", "(", "role_name", ",", "project_root", ")", "output", "=", "role", ".", "create", "ok", "_", "(", "'wizard.role.creation_success'", ")", "return", "output", "end" ]
Create a new role
[ "Create", "a", "new", "role" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/role_wizard.rb#L8-L18
7,075
codescrum/bebox
lib/bebox/wizards/role_wizard.rb
Bebox.RoleWizard.remove_role
def remove_role(project_root) # Choose a role from the availables roles = Bebox::Role.list(project_root) # Get a role if exist. if roles.count > 0 role_name = choose_option(roles, _('wizard.role.choose_deletion_role')) else return error _('wizard.role.no_deletion_roles') end # Ask for deletion confirmation return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.role.confirm_deletion')) # Role deletion role = Bebox::Role.new(role_name, project_root) output = role.remove ok _('wizard.role.deletion_success') return output end
ruby
def remove_role(project_root) # Choose a role from the availables roles = Bebox::Role.list(project_root) # Get a role if exist. if roles.count > 0 role_name = choose_option(roles, _('wizard.role.choose_deletion_role')) else return error _('wizard.role.no_deletion_roles') end # Ask for deletion confirmation return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.role.confirm_deletion')) # Role deletion role = Bebox::Role.new(role_name, project_root) output = role.remove ok _('wizard.role.deletion_success') return output end
[ "def", "remove_role", "(", "project_root", ")", "# Choose a role from the availables", "roles", "=", "Bebox", "::", "Role", ".", "list", "(", "project_root", ")", "# Get a role if exist.", "if", "roles", ".", "count", ">", "0", "role_name", "=", "choose_option", "(", "roles", ",", "_", "(", "'wizard.role.choose_deletion_role'", ")", ")", "else", "return", "error", "_", "(", "'wizard.role.no_deletion_roles'", ")", "end", "# Ask for deletion confirmation", "return", "warn", "(", "_", "(", "'wizard.no_changes'", ")", ")", "unless", "confirm_action?", "(", "_", "(", "'wizard.role.confirm_deletion'", ")", ")", "# Role deletion", "role", "=", "Bebox", "::", "Role", ".", "new", "(", "role_name", ",", "project_root", ")", "output", "=", "role", ".", "remove", "ok", "_", "(", "'wizard.role.deletion_success'", ")", "return", "output", "end" ]
Removes an existing role
[ "Removes", "an", "existing", "role" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/role_wizard.rb#L21-L37
7,076
codescrum/bebox
lib/bebox/wizards/role_wizard.rb
Bebox.RoleWizard.add_profile
def add_profile(project_root) roles = Bebox::Role.list(project_root) profiles = Bebox::Profile.list(project_root) role = choose_option(roles, _('wizard.choose_role')) profile = choose_option(profiles, _('wizard.role.choose_add_profile')) if Bebox::Role.profile_in_role?(project_root, role, profile) warn _('wizard.role.profile_exist')%{profile: profile, role: role} output = false else output = Bebox::Role.add_profile(project_root, role, profile) ok _('wizard.role.add_profile_success')%{profile: profile, role: role} end return output end
ruby
def add_profile(project_root) roles = Bebox::Role.list(project_root) profiles = Bebox::Profile.list(project_root) role = choose_option(roles, _('wizard.choose_role')) profile = choose_option(profiles, _('wizard.role.choose_add_profile')) if Bebox::Role.profile_in_role?(project_root, role, profile) warn _('wizard.role.profile_exist')%{profile: profile, role: role} output = false else output = Bebox::Role.add_profile(project_root, role, profile) ok _('wizard.role.add_profile_success')%{profile: profile, role: role} end return output end
[ "def", "add_profile", "(", "project_root", ")", "roles", "=", "Bebox", "::", "Role", ".", "list", "(", "project_root", ")", "profiles", "=", "Bebox", "::", "Profile", ".", "list", "(", "project_root", ")", "role", "=", "choose_option", "(", "roles", ",", "_", "(", "'wizard.choose_role'", ")", ")", "profile", "=", "choose_option", "(", "profiles", ",", "_", "(", "'wizard.role.choose_add_profile'", ")", ")", "if", "Bebox", "::", "Role", ".", "profile_in_role?", "(", "project_root", ",", "role", ",", "profile", ")", "warn", "_", "(", "'wizard.role.profile_exist'", ")", "%", "{", "profile", ":", "profile", ",", "role", ":", "role", "}", "output", "=", "false", "else", "output", "=", "Bebox", "::", "Role", ".", "add_profile", "(", "project_root", ",", "role", ",", "profile", ")", "ok", "_", "(", "'wizard.role.add_profile_success'", ")", "%", "{", "profile", ":", "profile", ",", "role", ":", "role", "}", "end", "return", "output", "end" ]
Add a profile to a role
[ "Add", "a", "profile", "to", "a", "role" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/role_wizard.rb#L40-L53
7,077
kindlinglabs/bullring
lib/bullring/util/drubied_process.rb
Bullring.DrubiedProcess.connect_to_process!
def connect_to_process! Bullring.logger.debug{"#{caller_name}: Connecting to process..."} if !process_port_active? Bullring.logger.debug {"#{caller_name}: Spawning process..."} # Spawn the process in its own process group so it stays alive even if this process dies pid = Process.spawn([@options[:process][:command], @options[:process][:args]].flatten.join(" "), {:pgroup => true}) Process.detach(pid) time_sleeping = 0 while (!process_port_active?) sleep(0.2) if (time_sleeping += 0.2) > @options[:process][:max_bringup_time] Bullring.logger.error {"#{caller_name}: Timed out waiting to bring up the process"} raise StandardError, "#{caller_name}: Timed out waiting to bring up the process", caller end end end if !@local_service.nil? @local_service.stop_service Bullring.logger.debug {"#{caller_name}: Stopped local service on #{@local_service.uri}"} end @local_service = DRb.start_service "druby://127.0.0.1:0" Bullring.logger.debug {"#{caller_name}: Started local service on #{@local_service.uri}"} @process = DRbObject.new nil, "druby://#{host}:#{port}" @after_connect_block.call(@process) if !@after_connect_block.nil? end
ruby
def connect_to_process! Bullring.logger.debug{"#{caller_name}: Connecting to process..."} if !process_port_active? Bullring.logger.debug {"#{caller_name}: Spawning process..."} # Spawn the process in its own process group so it stays alive even if this process dies pid = Process.spawn([@options[:process][:command], @options[:process][:args]].flatten.join(" "), {:pgroup => true}) Process.detach(pid) time_sleeping = 0 while (!process_port_active?) sleep(0.2) if (time_sleeping += 0.2) > @options[:process][:max_bringup_time] Bullring.logger.error {"#{caller_name}: Timed out waiting to bring up the process"} raise StandardError, "#{caller_name}: Timed out waiting to bring up the process", caller end end end if !@local_service.nil? @local_service.stop_service Bullring.logger.debug {"#{caller_name}: Stopped local service on #{@local_service.uri}"} end @local_service = DRb.start_service "druby://127.0.0.1:0" Bullring.logger.debug {"#{caller_name}: Started local service on #{@local_service.uri}"} @process = DRbObject.new nil, "druby://#{host}:#{port}" @after_connect_block.call(@process) if !@after_connect_block.nil? end
[ "def", "connect_to_process!", "Bullring", ".", "logger", ".", "debug", "{", "\"#{caller_name}: Connecting to process...\"", "}", "if", "!", "process_port_active?", "Bullring", ".", "logger", ".", "debug", "{", "\"#{caller_name}: Spawning process...\"", "}", "# Spawn the process in its own process group so it stays alive even if this process dies", "pid", "=", "Process", ".", "spawn", "(", "[", "@options", "[", ":process", "]", "[", ":command", "]", ",", "@options", "[", ":process", "]", "[", ":args", "]", "]", ".", "flatten", ".", "join", "(", "\" \"", ")", ",", "{", ":pgroup", "=>", "true", "}", ")", "Process", ".", "detach", "(", "pid", ")", "time_sleeping", "=", "0", "while", "(", "!", "process_port_active?", ")", "sleep", "(", "0.2", ")", "if", "(", "time_sleeping", "+=", "0.2", ")", ">", "@options", "[", ":process", "]", "[", ":max_bringup_time", "]", "Bullring", ".", "logger", ".", "error", "{", "\"#{caller_name}: Timed out waiting to bring up the process\"", "}", "raise", "StandardError", ",", "\"#{caller_name}: Timed out waiting to bring up the process\"", ",", "caller", "end", "end", "end", "if", "!", "@local_service", ".", "nil?", "@local_service", ".", "stop_service", "Bullring", ".", "logger", ".", "debug", "{", "\"#{caller_name}: Stopped local service on #{@local_service.uri}\"", "}", "end", "@local_service", "=", "DRb", ".", "start_service", "\"druby://127.0.0.1:0\"", "Bullring", ".", "logger", ".", "debug", "{", "\"#{caller_name}: Started local service on #{@local_service.uri}\"", "}", "@process", "=", "DRbObject", ".", "new", "nil", ",", "\"druby://#{host}:#{port}\"", "@after_connect_block", ".", "call", "(", "@process", ")", "if", "!", "@after_connect_block", ".", "nil?", "end" ]
Creates a druby connection to the process, starting it up if necessary
[ "Creates", "a", "druby", "connection", "to", "the", "process", "starting", "it", "up", "if", "necessary" ]
30ea55f7ad3de4c8af710d141cf5dfda0f9c8a44
https://github.com/kindlinglabs/bullring/blob/30ea55f7ad3de4c8af710d141cf5dfda0f9c8a44/lib/bullring/util/drubied_process.rb#L69-L100
7,078
pilaf/recaptcha-mailhide
lib/recaptcha_mailhide/helpers/action_view_helper.rb
RecaptchaMailhide.ActionViewHelper.recaptcha_mailhide
def recaptcha_mailhide(*args, &block) options = args.extract_options! raise ArgumentError, "at least one argument is required (not counting options)" if args.empty? if block_given? url = RecaptchaMailhide.url_for(args.first) link_to(url, recaptcha_mailhide_options(url, options), &block) else if args.length == 1 content = truncate_email(args.first, options) url = RecaptchaMailhide.url_for(args.first) else content = args.first url = RecaptchaMailhide.url_for(args.second) end link_to(content, url, recaptcha_mailhide_options(url, options)) end end
ruby
def recaptcha_mailhide(*args, &block) options = args.extract_options! raise ArgumentError, "at least one argument is required (not counting options)" if args.empty? if block_given? url = RecaptchaMailhide.url_for(args.first) link_to(url, recaptcha_mailhide_options(url, options), &block) else if args.length == 1 content = truncate_email(args.first, options) url = RecaptchaMailhide.url_for(args.first) else content = args.first url = RecaptchaMailhide.url_for(args.second) end link_to(content, url, recaptcha_mailhide_options(url, options)) end end
[ "def", "recaptcha_mailhide", "(", "*", "args", ",", "&", "block", ")", "options", "=", "args", ".", "extract_options!", "raise", "ArgumentError", ",", "\"at least one argument is required (not counting options)\"", "if", "args", ".", "empty?", "if", "block_given?", "url", "=", "RecaptchaMailhide", ".", "url_for", "(", "args", ".", "first", ")", "link_to", "(", "url", ",", "recaptcha_mailhide_options", "(", "url", ",", "options", ")", ",", "block", ")", "else", "if", "args", ".", "length", "==", "1", "content", "=", "truncate_email", "(", "args", ".", "first", ",", "options", ")", "url", "=", "RecaptchaMailhide", ".", "url_for", "(", "args", ".", "first", ")", "else", "content", "=", "args", ".", "first", "url", "=", "RecaptchaMailhide", ".", "url_for", "(", "args", ".", "second", ")", "end", "link_to", "(", "content", ",", "url", ",", "recaptcha_mailhide_options", "(", "url", ",", "options", ")", ")", "end", "end" ]
Generates a link tag to a ReCAPTCHA Mailhide URL for the given email address. If a block is given it will use it to generate the content, and takes these attributes: * +email+ - The email address to hide * +options+ - See options below When no block is given it accepts two forms: # Just email recaptcha_mailhide(email, options = {}) # Email and content recaptcha_mailhide(content, email, options = {}) In the first instance it will process the email with <code>truncate_email</code> and use it as the link content. ==== Options Accepts every option supported by <code>link_to</code>, plus: [:popup] Set it to <code>true</code> to have the link open a popup window (through JavaScript and the <code>onclick</code> event). Can also be a hash of sub-options, which can be <code>:width</code> and <code>:height</code>, setting the size of the popup window. In case of not supplying your own content you can also pass options for <code>truncate_email</code>, e.g.: recaptcha_mailhide('[email protected]', omission: '-', truncate_domain: true)
[ "Generates", "a", "link", "tag", "to", "a", "ReCAPTCHA", "Mailhide", "URL", "for", "the", "given", "email", "address", "." ]
f3dbee2141a2849de52addec7959dbb270adaa4c
https://github.com/pilaf/recaptcha-mailhide/blob/f3dbee2141a2849de52addec7959dbb270adaa4c/lib/recaptcha_mailhide/helpers/action_view_helper.rb#L40-L57
7,079
raid5/agilezen
lib/agilezen/projects.rb
AgileZen.Projects.projects
def projects(options={}) response = connection.get do |req| req.url "/api/v1/projects", options end response.body end
ruby
def projects(options={}) response = connection.get do |req| req.url "/api/v1/projects", options end response.body end
[ "def", "projects", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"/api/v1/projects\"", ",", "options", "end", "response", ".", "body", "end" ]
Retrieve information for all projects.
[ "Retrieve", "information", "for", "all", "projects", "." ]
36fcef642c82b35c8c8664ee6a2ff22ce52054c0
https://github.com/raid5/agilezen/blob/36fcef642c82b35c8c8664ee6a2ff22ce52054c0/lib/agilezen/projects.rb#L6-L11
7,080
saclark/lite_page
lib/lite_page/element_factory.rb
LitePage.ElementFactory.def_elements
def def_elements(root_elem_var_name, element_definitions = {}) element_definitions.each do |name, definition| define_method(name) do |other_selectors = {}| definition[1].merge!(other_selectors) instance_variable_get(root_elem_var_name.to_sym).send(*definition) end end end
ruby
def def_elements(root_elem_var_name, element_definitions = {}) element_definitions.each do |name, definition| define_method(name) do |other_selectors = {}| definition[1].merge!(other_selectors) instance_variable_get(root_elem_var_name.to_sym).send(*definition) end end end
[ "def", "def_elements", "(", "root_elem_var_name", ",", "element_definitions", "=", "{", "}", ")", "element_definitions", ".", "each", "do", "|", "name", ",", "definition", "|", "define_method", "(", "name", ")", "do", "|", "other_selectors", "=", "{", "}", "|", "definition", "[", "1", "]", ".", "merge!", "(", "other_selectors", ")", "instance_variable_get", "(", "root_elem_var_name", ".", "to_sym", ")", ".", "send", "(", "definition", ")", "end", "end", "end" ]
Provides convenient method for concisely defining element getters @param root_elem_var_name [Symbol] the name of the instance variable containing the element on which methods should be caleld (typically the browser instance). @param element_definitions [Hash] the hash used to define element getters on the class instance where each key represents the name of the method to be defined and whose value is an array containing first, the element tag name and second, the selectors with which to locate it.
[ "Provides", "convenient", "method", "for", "concisely", "defining", "element", "getters" ]
efa3ae28a49428ee60c6ee95b51c5d79f603acec
https://github.com/saclark/lite_page/blob/efa3ae28a49428ee60c6ee95b51c5d79f603acec/lib/lite_page/element_factory.rb#L12-L19
7,081
rndstr/halffare
lib/halffare/price_sbb.rb
Halffare.PriceSbb.price_scale
def price_scale(definition, order) return definition['scale'][price_paid][0] * order.price, definition['scale'][price_paid][1] * order.price end
ruby
def price_scale(definition, order) return definition['scale'][price_paid][0] * order.price, definition['scale'][price_paid][1] * order.price end
[ "def", "price_scale", "(", "definition", ",", "order", ")", "return", "definition", "[", "'scale'", "]", "[", "price_paid", "]", "[", "0", "]", "*", "order", ".", "price", ",", "definition", "[", "'scale'", "]", "[", "price_paid", "]", "[", "1", "]", "*", "order", ".", "price", "end" ]
Calculates the prices according to the `scale` definition.
[ "Calculates", "the", "prices", "according", "to", "the", "scale", "definition", "." ]
2c4c7563a9e0834e5d2d93c15bd052bb67f8996a
https://github.com/rndstr/halffare/blob/2c4c7563a9e0834e5d2d93c15bd052bb67f8996a/lib/halffare/price_sbb.rb#L47-L49
7,082
rndstr/halffare
lib/halffare/price_sbb.rb
Halffare.PriceSbb.price_set
def price_set(definition, order) if order.price != definition['set'][price_paid] log_order(order) log_error 'order matched but price differs; ignoring this order.' p order p definition return 0, 0 else return definition['set']['half'], definition['set']['full'] end end
ruby
def price_set(definition, order) if order.price != definition['set'][price_paid] log_order(order) log_error 'order matched but price differs; ignoring this order.' p order p definition return 0, 0 else return definition['set']['half'], definition['set']['full'] end end
[ "def", "price_set", "(", "definition", ",", "order", ")", "if", "order", ".", "price", "!=", "definition", "[", "'set'", "]", "[", "price_paid", "]", "log_order", "(", "order", ")", "log_error", "'order matched but price differs; ignoring this order.'", "p", "order", "p", "definition", "return", "0", ",", "0", "else", "return", "definition", "[", "'set'", "]", "[", "'half'", "]", ",", "definition", "[", "'set'", "]", "[", "'full'", "]", "end", "end" ]
Calculates the prices according to the `set` definition.
[ "Calculates", "the", "prices", "according", "to", "the", "set", "definition", "." ]
2c4c7563a9e0834e5d2d93c15bd052bb67f8996a
https://github.com/rndstr/halffare/blob/2c4c7563a9e0834e5d2d93c15bd052bb67f8996a/lib/halffare/price_sbb.rb#L52-L62
7,083
rndstr/halffare
lib/halffare/price_sbb.rb
Halffare.PriceSbb.price_choices
def price_choices(definition, order) # auto select definition['choices'].each { |name,prices| return prices['half'], prices['full'] if prices[price_paid] == order.price } return price_guess_get(order) if @force_guess_fallback choose do |menu| menu.prompt = "\nSelect the choice that applies to your travels? " log_info "\n" definition['choices'].each do |name,prices| menu.choice "#{name} (half-fare: #{currency(prices['half'])}, full: #{currency(prices['full'])})" do end end menu.choice "…or enter manually" do ask_for_price(order) end end end
ruby
def price_choices(definition, order) # auto select definition['choices'].each { |name,prices| return prices['half'], prices['full'] if prices[price_paid] == order.price } return price_guess_get(order) if @force_guess_fallback choose do |menu| menu.prompt = "\nSelect the choice that applies to your travels? " log_info "\n" definition['choices'].each do |name,prices| menu.choice "#{name} (half-fare: #{currency(prices['half'])}, full: #{currency(prices['full'])})" do end end menu.choice "…or enter manually" do ask_for_price(order) end end end
[ "def", "price_choices", "(", "definition", ",", "order", ")", "# auto select", "definition", "[", "'choices'", "]", ".", "each", "{", "|", "name", ",", "prices", "|", "return", "prices", "[", "'half'", "]", ",", "prices", "[", "'full'", "]", "if", "prices", "[", "price_paid", "]", "==", "order", ".", "price", "}", "return", "price_guess_get", "(", "order", ")", "if", "@force_guess_fallback", "choose", "do", "|", "menu", "|", "menu", ".", "prompt", "=", "\"\\nSelect the choice that applies to your travels? \"", "log_info", "\"\\n\"", "definition", "[", "'choices'", "]", ".", "each", "do", "|", "name", ",", "prices", "|", "menu", ".", "choice", "\"#{name} (half-fare: #{currency(prices['half'])}, full: #{currency(prices['full'])})\"", "do", "end", "end", "menu", ".", "choice", "\"…or enter manually\" d", " a", "k_for_price(o", "r", "der) ", "e", "d", "end", "end" ]
Calculates the prices according to the `choices` definition.
[ "Calculates", "the", "prices", "according", "to", "the", "choices", "definition", "." ]
2c4c7563a9e0834e5d2d93c15bd052bb67f8996a
https://github.com/rndstr/halffare/blob/2c4c7563a9e0834e5d2d93c15bd052bb67f8996a/lib/halffare/price_sbb.rb#L65-L81
7,084
rndstr/halffare
lib/halffare/price_sbb.rb
Halffare.PriceSbb.ask_for_price
def ask_for_price(order) guesshalf, guessfull = price_guess_get(order) if !Halffare.debug # was already logged log_order(order) end if @halffare other = ask("What would have been the full price? ", Float) { |q| q.default = guessfull } return order.price, other else other = ask("What would have been the half-fare price? ", Float) { |q| q.default = guesshalf } return other, order.price end end
ruby
def ask_for_price(order) guesshalf, guessfull = price_guess_get(order) if !Halffare.debug # was already logged log_order(order) end if @halffare other = ask("What would have been the full price? ", Float) { |q| q.default = guessfull } return order.price, other else other = ask("What would have been the half-fare price? ", Float) { |q| q.default = guesshalf } return other, order.price end end
[ "def", "ask_for_price", "(", "order", ")", "guesshalf", ",", "guessfull", "=", "price_guess_get", "(", "order", ")", "if", "!", "Halffare", ".", "debug", "# was already logged", "log_order", "(", "order", ")", "end", "if", "@halffare", "other", "=", "ask", "(", "\"What would have been the full price? \"", ",", "Float", ")", "{", "|", "q", "|", "q", ".", "default", "=", "guessfull", "}", "return", "order", ".", "price", ",", "other", "else", "other", "=", "ask", "(", "\"What would have been the half-fare price? \"", ",", "Float", ")", "{", "|", "q", "|", "q", ".", "default", "=", "guesshalf", "}", "return", "other", ",", "order", ".", "price", "end", "end" ]
Ask the user for the price.
[ "Ask", "the", "user", "for", "the", "price", "." ]
2c4c7563a9e0834e5d2d93c15bd052bb67f8996a
https://github.com/rndstr/halffare/blob/2c4c7563a9e0834e5d2d93c15bd052bb67f8996a/lib/halffare/price_sbb.rb#L84-L99
7,085
jns/Aims
lib/aims/volume.rb
Aims.Volume.bounding_box
def bounding_box unless @bbox p = @points[0] minX = p[0] maxX = p[0] minY = p[1] maxY = p[1] minZ = p[2] maxZ = p[2] @points.each{|p| minX = p[0] if p[0] < minX maxX = p[0] if p[0] > maxX minY = p[1] if p[1] < minY maxY = p[1] if p[1] > maxY minZ = p[2] if p[2] < minZ maxZ = p[2] if p[2] > maxZ } @max = Vector[maxX, maxY,maxZ] @min = Vector[minX, minY, minZ] @bbox = Volume.new([Plane.new(-1,0,0, minX, minY, minZ), Plane.new(0,-1,0, minX, minY, minZ), Plane.new(0,0,-1, minX, minY, minZ), Plane.new(1,0,0, maxX, maxY, maxZ), Plane.new(0,1,0, maxX, maxY, maxZ), Plane.new(0,0,1, maxX, maxY, maxZ)]) end @bbox end
ruby
def bounding_box unless @bbox p = @points[0] minX = p[0] maxX = p[0] minY = p[1] maxY = p[1] minZ = p[2] maxZ = p[2] @points.each{|p| minX = p[0] if p[0] < minX maxX = p[0] if p[0] > maxX minY = p[1] if p[1] < minY maxY = p[1] if p[1] > maxY minZ = p[2] if p[2] < minZ maxZ = p[2] if p[2] > maxZ } @max = Vector[maxX, maxY,maxZ] @min = Vector[minX, minY, minZ] @bbox = Volume.new([Plane.new(-1,0,0, minX, minY, minZ), Plane.new(0,-1,0, minX, minY, minZ), Plane.new(0,0,-1, minX, minY, minZ), Plane.new(1,0,0, maxX, maxY, maxZ), Plane.new(0,1,0, maxX, maxY, maxZ), Plane.new(0,0,1, maxX, maxY, maxZ)]) end @bbox end
[ "def", "bounding_box", "unless", "@bbox", "p", "=", "@points", "[", "0", "]", "minX", "=", "p", "[", "0", "]", "maxX", "=", "p", "[", "0", "]", "minY", "=", "p", "[", "1", "]", "maxY", "=", "p", "[", "1", "]", "minZ", "=", "p", "[", "2", "]", "maxZ", "=", "p", "[", "2", "]", "@points", ".", "each", "{", "|", "p", "|", "minX", "=", "p", "[", "0", "]", "if", "p", "[", "0", "]", "<", "minX", "maxX", "=", "p", "[", "0", "]", "if", "p", "[", "0", "]", ">", "maxX", "minY", "=", "p", "[", "1", "]", "if", "p", "[", "1", "]", "<", "minY", "maxY", "=", "p", "[", "1", "]", "if", "p", "[", "1", "]", ">", "maxY", "minZ", "=", "p", "[", "2", "]", "if", "p", "[", "2", "]", "<", "minZ", "maxZ", "=", "p", "[", "2", "]", "if", "p", "[", "2", "]", ">", "maxZ", "}", "@max", "=", "Vector", "[", "maxX", ",", "maxY", ",", "maxZ", "]", "@min", "=", "Vector", "[", "minX", ",", "minY", ",", "minZ", "]", "@bbox", "=", "Volume", ".", "new", "(", "[", "Plane", ".", "new", "(", "-", "1", ",", "0", ",", "0", ",", "minX", ",", "minY", ",", "minZ", ")", ",", "Plane", ".", "new", "(", "0", ",", "-", "1", ",", "0", ",", "minX", ",", "minY", ",", "minZ", ")", ",", "Plane", ".", "new", "(", "0", ",", "0", ",", "-", "1", ",", "minX", ",", "minY", ",", "minZ", ")", ",", "Plane", ".", "new", "(", "1", ",", "0", ",", "0", ",", "maxX", ",", "maxY", ",", "maxZ", ")", ",", "Plane", ".", "new", "(", "0", ",", "1", ",", "0", ",", "maxX", ",", "maxY", ",", "maxZ", ")", ",", "Plane", ".", "new", "(", "0", ",", "0", ",", "1", ",", "maxX", ",", "maxY", ",", "maxZ", ")", "]", ")", "end", "@bbox", "end" ]
Return the bounding box for this volume
[ "Return", "the", "bounding", "box", "for", "this", "volume" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/volume.rb#L83-L110
7,086
jns/Aims
lib/aims/volume.rb
Aims.Volume.contains_point
def contains_point(x,y,z) behind = true @planes.each{|p| behind = (0 >= p.distance_to_point(x,y,z)) break if not behind } return behind end
ruby
def contains_point(x,y,z) behind = true @planes.each{|p| behind = (0 >= p.distance_to_point(x,y,z)) break if not behind } return behind end
[ "def", "contains_point", "(", "x", ",", "y", ",", "z", ")", "behind", "=", "true", "@planes", ".", "each", "{", "|", "p", "|", "behind", "=", "(", "0", ">=", "p", ".", "distance_to_point", "(", "x", ",", "y", ",", "z", ")", ")", "break", "if", "not", "behind", "}", "return", "behind", "end" ]
A volume contains a point if it lies behind all the planes
[ "A", "volume", "contains", "a", "point", "if", "it", "lies", "behind", "all", "the", "planes" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/volume.rb#L131-L138
7,087
NU-CBITS/bit_core
app/models/bit_core/content_module.rb
BitCore.ContentModule.provider
def provider(position) content_providers.find_by(position: position) || ContentProviders::Null.new(self, position) end
ruby
def provider(position) content_providers.find_by(position: position) || ContentProviders::Null.new(self, position) end
[ "def", "provider", "(", "position", ")", "content_providers", ".", "find_by", "(", "position", ":", "position", ")", "||", "ContentProviders", "::", "Null", ".", "new", "(", "self", ",", "position", ")", "end" ]
Returns the `ContentProvider` at the given position, or a `Null` `ContentProvider` if none exists.
[ "Returns", "the", "ContentProvider", "at", "the", "given", "position", "or", "a", "Null", "ContentProvider", "if", "none", "exists", "." ]
25954c9f9ba0867e7bcd987d9626632b8607cf12
https://github.com/NU-CBITS/bit_core/blob/25954c9f9ba0867e7bcd987d9626632b8607cf12/app/models/bit_core/content_module.rb#L21-L24
7,088
triglav-dataflow/triglav-client-ruby
lib/triglav_client/api/jobs_api.rb
TriglavClient.JobsApi.create_or_update_job
def create_or_update_job(job, opts = {}) data, _status_code, _headers = create_or_update_job_with_http_info(job, opts) return data end
ruby
def create_or_update_job(job, opts = {}) data, _status_code, _headers = create_or_update_job_with_http_info(job, opts) return data end
[ "def", "create_or_update_job", "(", "job", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "create_or_update_job_with_http_info", "(", "job", ",", "opts", ")", "return", "data", "end" ]
Creates or Updates a single job @param job Job parameters @param [Hash] opts the optional parameters @return [JobResponse]
[ "Creates", "or", "Updates", "a", "single", "job" ]
b2f3781d65ee032ba96eb703fbd789c713a5e0bd
https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/jobs_api.rb#L39-L42
7,089
triglav-dataflow/triglav-client-ruby
lib/triglav_client/api/jobs_api.rb
TriglavClient.JobsApi.get_job
def get_job(id_or_uri, opts = {}) data, _status_code, _headers = get_job_with_http_info(id_or_uri, opts) return data end
ruby
def get_job(id_or_uri, opts = {}) data, _status_code, _headers = get_job_with_http_info(id_or_uri, opts) return data end
[ "def", "get_job", "(", "id_or_uri", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_job_with_http_info", "(", "id_or_uri", ",", "opts", ")", "return", "data", "end" ]
Returns a single job @param id_or_uri ID or URI of job to fetch @param [Hash] opts the optional parameters @return [JobResponse]
[ "Returns", "a", "single", "job" ]
b2f3781d65ee032ba96eb703fbd789c713a5e0bd
https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/jobs_api.rb#L152-L155
7,090
jochenseeber/rubble
lib/rubble/environment.rb
Rubble.Environment.server
def server(*names, &block) names.each do |name| server = @tool.provide_server(name) scope = Scope.new(self, server) if not block.nil? then Docile.dsl_eval(scope, &block) end end end
ruby
def server(*names, &block) names.each do |name| server = @tool.provide_server(name) scope = Scope.new(self, server) if not block.nil? then Docile.dsl_eval(scope, &block) end end end
[ "def", "server", "(", "*", "names", ",", "&", "block", ")", "names", ".", "each", "do", "|", "name", "|", "server", "=", "@tool", ".", "provide_server", "(", "name", ")", "scope", "=", "Scope", ".", "new", "(", "self", ",", "server", ")", "if", "not", "block", ".", "nil?", "then", "Docile", ".", "dsl_eval", "(", "scope", ",", "block", ")", "end", "end", "end" ]
Action statt plan
[ "Action", "statt", "plan" ]
62f9b45bc1322a1bc4261f162768f6f3008c50ab
https://github.com/jochenseeber/rubble/blob/62f9b45bc1322a1bc4261f162768f6f3008c50ab/lib/rubble/environment.rb#L18-L26
7,091
codescrum/bebox
lib/bebox/wizards/wizards_helper.rb
Bebox.WizardsHelper.confirm_action?
def confirm_action?(message) require 'highline/import' quest message response = ask(highline_quest('(y/n)')) do |q| q.default = "n" end return response == 'y' ? true : false end
ruby
def confirm_action?(message) require 'highline/import' quest message response = ask(highline_quest('(y/n)')) do |q| q.default = "n" end return response == 'y' ? true : false end
[ "def", "confirm_action?", "(", "message", ")", "require", "'highline/import'", "quest", "message", "response", "=", "ask", "(", "highline_quest", "(", "'(y/n)'", ")", ")", "do", "|", "q", "|", "q", ".", "default", "=", "\"n\"", "end", "return", "response", "==", "'y'", "?", "true", ":", "false", "end" ]
Ask for confirmation of any action
[ "Ask", "for", "confirmation", "of", "any", "action" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/wizards_helper.rb#L5-L12
7,092
codescrum/bebox
lib/bebox/wizards/wizards_helper.rb
Bebox.WizardsHelper.write_input
def write_input(message, default=nil, validator=nil, not_valid_message=nil) require 'highline/import' response = ask(highline_quest(message)) do |q| q.default = default if default q.validate = /\.(.*)/ if validator q.responses[:not_valid] = highline_warn(not_valid_message) if not_valid_message end return response end
ruby
def write_input(message, default=nil, validator=nil, not_valid_message=nil) require 'highline/import' response = ask(highline_quest(message)) do |q| q.default = default if default q.validate = /\.(.*)/ if validator q.responses[:not_valid] = highline_warn(not_valid_message) if not_valid_message end return response end
[ "def", "write_input", "(", "message", ",", "default", "=", "nil", ",", "validator", "=", "nil", ",", "not_valid_message", "=", "nil", ")", "require", "'highline/import'", "response", "=", "ask", "(", "highline_quest", "(", "message", ")", ")", "do", "|", "q", "|", "q", ".", "default", "=", "default", "if", "default", "q", ".", "validate", "=", "/", "\\.", "/", "if", "validator", "q", ".", "responses", "[", ":not_valid", "]", "=", "highline_warn", "(", "not_valid_message", ")", "if", "not_valid_message", "end", "return", "response", "end" ]
Ask to write some input with validation
[ "Ask", "to", "write", "some", "input", "with", "validation" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/wizards_helper.rb#L15-L23
7,093
codescrum/bebox
lib/bebox/wizards/wizards_helper.rb
Bebox.WizardsHelper.choose_option
def choose_option(options, question) require 'highline/import' choose do |menu| menu.header = title(question) options.each do |option| menu.choice(option) end end end
ruby
def choose_option(options, question) require 'highline/import' choose do |menu| menu.header = title(question) options.each do |option| menu.choice(option) end end end
[ "def", "choose_option", "(", "options", ",", "question", ")", "require", "'highline/import'", "choose", "do", "|", "menu", "|", "menu", ".", "header", "=", "title", "(", "question", ")", "options", ".", "each", "do", "|", "option", "|", "menu", ".", "choice", "(", "option", ")", "end", "end", "end" ]
Asks to choose an option
[ "Asks", "to", "choose", "an", "option" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/wizards_helper.rb#L26-L34
7,094
codescrum/bebox
lib/bebox/wizards/wizards_helper.rb
Bebox.WizardsHelper.valid_puppet_class_name?
def valid_puppet_class_name?(name) valid_name = (name =~ /\A[a-z][a-z0-9_]*\Z/).nil? ? false : true valid_name && !Bebox::RESERVED_WORDS.include?(name) end
ruby
def valid_puppet_class_name?(name) valid_name = (name =~ /\A[a-z][a-z0-9_]*\Z/).nil? ? false : true valid_name && !Bebox::RESERVED_WORDS.include?(name) end
[ "def", "valid_puppet_class_name?", "(", "name", ")", "valid_name", "=", "(", "name", "=~", "/", "\\A", "\\Z", "/", ")", ".", "nil?", "?", "false", ":", "true", "valid_name", "&&", "!", "Bebox", "::", "RESERVED_WORDS", ".", "include?", "(", "name", ")", "end" ]
Check if the puppet resource has a valid name
[ "Check", "if", "the", "puppet", "resource", "has", "a", "valid", "name" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/wizards_helper.rb#L37-L40
7,095
treeder/quicky
lib/quicky/timer.rb
Quicky.Timer.loop_for
def loop_for(name, seconds, options={}, &blk) end_at = Time.now + seconds if options[:warmup] options[:warmup].times do |i| #puts "Warming up... #{i}" yield i end end i = 0 while Time.now < end_at time_i(i, name, options, &blk) i += 1 end end
ruby
def loop_for(name, seconds, options={}, &blk) end_at = Time.now + seconds if options[:warmup] options[:warmup].times do |i| #puts "Warming up... #{i}" yield i end end i = 0 while Time.now < end_at time_i(i, name, options, &blk) i += 1 end end
[ "def", "loop_for", "(", "name", ",", "seconds", ",", "options", "=", "{", "}", ",", "&", "blk", ")", "end_at", "=", "Time", ".", "now", "+", "seconds", "if", "options", "[", ":warmup", "]", "options", "[", ":warmup", "]", ".", "times", "do", "|", "i", "|", "#puts \"Warming up... #{i}\"", "yield", "i", "end", "end", "i", "=", "0", "while", "Time", ".", "now", "<", "end_at", "time_i", "(", "i", ",", "name", ",", "options", ",", "blk", ")", "i", "+=", "1", "end", "end" ]
will loop for number of seconds
[ "will", "loop", "for", "number", "of", "seconds" ]
4ac89408c28ca04745280a4cef2db4f97ed5b6d2
https://github.com/treeder/quicky/blob/4ac89408c28ca04745280a4cef2db4f97ed5b6d2/lib/quicky/timer.rb#L24-L37
7,096
Bastes/CellularMap
lib/cellular_map/zone.rb
CellularMap.Zone.relative
def relative(x, y) if x.respond_to?(:to_i) && y.respond_to?(:to_i) [@x.min + x.to_i, @y.min + y.to_i] else x, y = rangeize(x, y) [ (@x.min + x.min)..(@x.min + x.max), (@y.min + y.min)..(@y.min + y.max) ] end end
ruby
def relative(x, y) if x.respond_to?(:to_i) && y.respond_to?(:to_i) [@x.min + x.to_i, @y.min + y.to_i] else x, y = rangeize(x, y) [ (@x.min + x.min)..(@x.min + x.max), (@y.min + y.min)..(@y.min + y.max) ] end end
[ "def", "relative", "(", "x", ",", "y", ")", "if", "x", ".", "respond_to?", "(", ":to_i", ")", "&&", "y", ".", "respond_to?", "(", ":to_i", ")", "[", "@x", ".", "min", "+", "x", ".", "to_i", ",", "@y", ".", "min", "+", "y", ".", "to_i", "]", "else", "x", ",", "y", "=", "rangeize", "(", "x", ",", "y", ")", "[", "(", "@x", ".", "min", "+", "x", ".", "min", ")", "..", "(", "@x", ".", "min", "+", "x", ".", "max", ")", ",", "(", "@y", ".", "min", "+", "y", ".", "min", ")", "..", "(", "@y", ".", "min", "+", "y", ".", "max", ")", "]", "end", "end" ]
Converts coordinates to coordinates relative to inside the map.
[ "Converts", "coordinates", "to", "coordinates", "relative", "to", "inside", "the", "map", "." ]
e9cfa44ce820b16cdc5ca5b59291e80e53363d1f
https://github.com/Bastes/CellularMap/blob/e9cfa44ce820b16cdc5ca5b59291e80e53363d1f/lib/cellular_map/zone.rb#L68-L76
7,097
Bastes/CellularMap
lib/cellular_map/zone.rb
CellularMap.Zone.rangeize
def rangeize(x, y) [x, y].collect { |i| i.respond_to?(:to_i) ? (i.to_i..i.to_i) : i } end
ruby
def rangeize(x, y) [x, y].collect { |i| i.respond_to?(:to_i) ? (i.to_i..i.to_i) : i } end
[ "def", "rangeize", "(", "x", ",", "y", ")", "[", "x", ",", "y", "]", ".", "collect", "{", "|", "i", "|", "i", ".", "respond_to?", "(", ":to_i", ")", "?", "(", "i", ".", "to_i", "..", "i", ".", "to_i", ")", ":", "i", "}", "end" ]
Converts given coordinates to ranges if necessary.
[ "Converts", "given", "coordinates", "to", "ranges", "if", "necessary", "." ]
e9cfa44ce820b16cdc5ca5b59291e80e53363d1f
https://github.com/Bastes/CellularMap/blob/e9cfa44ce820b16cdc5ca5b59291e80e53363d1f/lib/cellular_map/zone.rb#L79-L81
7,098
jinx/core
lib/jinx/metadata/inverse.rb
Jinx.Inverse.set_attribute_inverse
def set_attribute_inverse(attribute, inverse) prop = property(attribute) # the standard attribute pa = prop.attribute # return if inverse is already set return if prop.inverse == inverse # the default inverse inverse ||= prop.type.detect_inverse_attribute(self) # If the attribute is not declared by this class, then make a new attribute # metadata specialized for this class. unless prop.declarer == self then prop = restrict_attribute_inverse(prop, inverse) end logger.debug { "Setting #{qp}.#{pa} inverse to #{inverse}..." } # the inverse attribute meta-data inv_prop = prop.type.property(inverse) # If the attribute is the many side of a 1:M relation, then delegate to the one side. if prop.collection? and not inv_prop.collection? then return prop.type.set_attribute_inverse(inverse, pa) end # This class must be the same as or a subclass of the inverse attribute type. unless self <= inv_prop.type then raise TypeError.new("Cannot set #{qp}.#{pa} inverse to #{prop.type.qp}.#{pa} with incompatible type #{inv_prop.type.qp}") end # Set the inverse in the attribute metadata. prop.inverse = inverse # If attribute is the one side of a 1:M or non-reflexive 1:1 relation, then add the inverse updater. unless prop.collection? then # Inject adding to the inverse collection into the attribute writer method. add_inverse_updater(pa) unless prop.type == inv_prop.type or inv_prop.collection? then prop.type.delegate_writer_to_inverse(inverse, pa) end end logger.debug { "Set #{qp}.#{pa} inverse to #{inverse}." } end
ruby
def set_attribute_inverse(attribute, inverse) prop = property(attribute) # the standard attribute pa = prop.attribute # return if inverse is already set return if prop.inverse == inverse # the default inverse inverse ||= prop.type.detect_inverse_attribute(self) # If the attribute is not declared by this class, then make a new attribute # metadata specialized for this class. unless prop.declarer == self then prop = restrict_attribute_inverse(prop, inverse) end logger.debug { "Setting #{qp}.#{pa} inverse to #{inverse}..." } # the inverse attribute meta-data inv_prop = prop.type.property(inverse) # If the attribute is the many side of a 1:M relation, then delegate to the one side. if prop.collection? and not inv_prop.collection? then return prop.type.set_attribute_inverse(inverse, pa) end # This class must be the same as or a subclass of the inverse attribute type. unless self <= inv_prop.type then raise TypeError.new("Cannot set #{qp}.#{pa} inverse to #{prop.type.qp}.#{pa} with incompatible type #{inv_prop.type.qp}") end # Set the inverse in the attribute metadata. prop.inverse = inverse # If attribute is the one side of a 1:M or non-reflexive 1:1 relation, then add the inverse updater. unless prop.collection? then # Inject adding to the inverse collection into the attribute writer method. add_inverse_updater(pa) unless prop.type == inv_prop.type or inv_prop.collection? then prop.type.delegate_writer_to_inverse(inverse, pa) end end logger.debug { "Set #{qp}.#{pa} inverse to #{inverse}." } end
[ "def", "set_attribute_inverse", "(", "attribute", ",", "inverse", ")", "prop", "=", "property", "(", "attribute", ")", "# the standard attribute", "pa", "=", "prop", ".", "attribute", "# return if inverse is already set", "return", "if", "prop", ".", "inverse", "==", "inverse", "# the default inverse", "inverse", "||=", "prop", ".", "type", ".", "detect_inverse_attribute", "(", "self", ")", "# If the attribute is not declared by this class, then make a new attribute", "# metadata specialized for this class.", "unless", "prop", ".", "declarer", "==", "self", "then", "prop", "=", "restrict_attribute_inverse", "(", "prop", ",", "inverse", ")", "end", "logger", ".", "debug", "{", "\"Setting #{qp}.#{pa} inverse to #{inverse}...\"", "}", "# the inverse attribute meta-data", "inv_prop", "=", "prop", ".", "type", ".", "property", "(", "inverse", ")", "# If the attribute is the many side of a 1:M relation, then delegate to the one side.", "if", "prop", ".", "collection?", "and", "not", "inv_prop", ".", "collection?", "then", "return", "prop", ".", "type", ".", "set_attribute_inverse", "(", "inverse", ",", "pa", ")", "end", "# This class must be the same as or a subclass of the inverse attribute type.", "unless", "self", "<=", "inv_prop", ".", "type", "then", "raise", "TypeError", ".", "new", "(", "\"Cannot set #{qp}.#{pa} inverse to #{prop.type.qp}.#{pa} with incompatible type #{inv_prop.type.qp}\"", ")", "end", "# Set the inverse in the attribute metadata.", "prop", ".", "inverse", "=", "inverse", "# If attribute is the one side of a 1:M or non-reflexive 1:1 relation, then add the inverse updater.", "unless", "prop", ".", "collection?", "then", "# Inject adding to the inverse collection into the attribute writer method. ", "add_inverse_updater", "(", "pa", ")", "unless", "prop", ".", "type", "==", "inv_prop", ".", "type", "or", "inv_prop", ".", "collection?", "then", "prop", ".", "type", ".", "delegate_writer_to_inverse", "(", "inverse", ",", "pa", ")", "end", "end", "logger", ".", "debug", "{", "\"Set #{qp}.#{pa} inverse to #{inverse}.\"", "}", "end" ]
Sets the given bi-directional association attribute's inverse. @param [Symbol] attribute the subject attribute @param [Symbol] the attribute inverse @raise [TypeError] if the inverse type is incompatible with this Resource
[ "Sets", "the", "given", "bi", "-", "directional", "association", "attribute", "s", "inverse", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/inverse.rb#L40-L75
7,099
jinx/core
lib/jinx/metadata/inverse.rb
Jinx.Inverse.clear_inverse
def clear_inverse(property) # the inverse property ip = property.inverse_property || return # If the property is a collection and the inverse is not, then delegate to # the inverse. if property.collection? then return ip.declarer.clear_inverse(ip) unless ip.collection? else # Restore the property reader and writer to the Java reader and writer, resp. alias_property_accessors(property) end # Unset the inverse. property.inverse = nil end
ruby
def clear_inverse(property) # the inverse property ip = property.inverse_property || return # If the property is a collection and the inverse is not, then delegate to # the inverse. if property.collection? then return ip.declarer.clear_inverse(ip) unless ip.collection? else # Restore the property reader and writer to the Java reader and writer, resp. alias_property_accessors(property) end # Unset the inverse. property.inverse = nil end
[ "def", "clear_inverse", "(", "property", ")", "# the inverse property", "ip", "=", "property", ".", "inverse_property", "||", "return", "# If the property is a collection and the inverse is not, then delegate to", "# the inverse.", "if", "property", ".", "collection?", "then", "return", "ip", ".", "declarer", ".", "clear_inverse", "(", "ip", ")", "unless", "ip", ".", "collection?", "else", "# Restore the property reader and writer to the Java reader and writer, resp.", "alias_property_accessors", "(", "property", ")", "end", "# Unset the inverse.", "property", ".", "inverse", "=", "nil", "end" ]
Clears the property inverse, if there is one.
[ "Clears", "the", "property", "inverse", "if", "there", "is", "one", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/inverse.rb#L78-L91