repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
maxim/has_price
lib/has_price/price_builder.rb
HasPrice.PriceBuilder.group
def group(group_name, &block) group_key = group_name.to_s @current_nesting_level[group_key] ||= {} if block_given? within_group(group_key) do instance_eval &block end end end
ruby
def group(group_name, &block) group_key = group_name.to_s @current_nesting_level[group_key] ||= {} if block_given? within_group(group_key) do instance_eval &block end end end
[ "def", "group", "(", "group_name", ",", "&", "block", ")", "group_key", "=", "group_name", ".", "to_s", "@current_nesting_level", "[", "group_key", "]", "||=", "{", "}", "if", "block_given?", "within_group", "(", "group_key", ")", "do", "instance_eval", "block", "end", "end", "end" ]
Adds price group to the current nesting level of price definition. Groups are useful for price breakdown categorization and easy subtotal values. @example Using group subtotals class Product include HasPrice def base_price; 100 end def federal_tax; 15 end def state_tax; 10 end has_price do item base_price, "base" group "tax" do item federal_tax, "federal" item state_tax, "state" end end end @product = Product.new @product.price.total # => 125 @product.price.tax.total # => 25 @param [#to_s] group_name a name for the price group @yield The yielded block is executed within the group, such that all groups and items declared within the block appear nested under this group. This behavior is recursive. @see #item
[ "Adds", "price", "group", "to", "the", "current", "nesting", "level", "of", "price", "definition", ".", "Groups", "are", "useful", "for", "price", "breakdown", "categorization", "and", "easy", "subtotal", "values", "." ]
671c5c7463b0e6540cbb8ac3114da08b99c697bd
https://github.com/maxim/has_price/blob/671c5c7463b0e6540cbb8ac3114da08b99c697bd/lib/has_price/price_builder.rb#L55-L65
train
fissionxuiptz/kat
lib/kat/search.rb
Kat.Search.query=
def query=(search_term) @search_term = case search_term when nil, '' then [] when String, Symbol then [search_term] when Array then search_term.flatten.select { |e| [String, Symbol].include? e.class } else fail ArgumentError, 'search_term must be a String, Symbol or Array. ' \ "#{ search_term.inspect } given." end build_query end
ruby
def query=(search_term) @search_term = case search_term when nil, '' then [] when String, Symbol then [search_term] when Array then search_term.flatten.select { |e| [String, Symbol].include? e.class } else fail ArgumentError, 'search_term must be a String, Symbol or Array. ' \ "#{ search_term.inspect } given." end build_query end
[ "def", "query", "=", "(", "search_term", ")", "@search_term", "=", "case", "search_term", "when", "nil", ",", "''", "then", "[", "]", "when", "String", ",", "Symbol", "then", "[", "search_term", "]", "when", "Array", "then", "search_term", ".", "flatten", ".", "select", "{", "|", "e", "|", "[", "String", ",", "Symbol", "]", ".", "include?", "e", ".", "class", "}", "else", "fail", "ArgumentError", ",", "'search_term must be a String, Symbol or Array. '", "\"#{ search_term.inspect } given.\"", "end", "build_query", "end" ]
Change the search term, triggering a query rebuild and clearing past results. Raises ArgumentError if search_term is not a String, Symbol or Array
[ "Change", "the", "search", "term", "triggering", "a", "query", "rebuild", "and", "clearing", "past", "results", "." ]
8f9e43c5dbeb2462e00fd841c208764380f6983b
https://github.com/fissionxuiptz/kat/blob/8f9e43c5dbeb2462e00fd841c208764380f6983b/lib/kat/search.rb#L97-L108
train
fissionxuiptz/kat
lib/kat/search.rb
Kat.Search.options=
def options=(options) fail ArgumentError, 'options must be a Hash. ' \ "#{ options.inspect } given." unless options.is_a?(Hash) @options.merge! options build_query end
ruby
def options=(options) fail ArgumentError, 'options must be a Hash. ' \ "#{ options.inspect } given." unless options.is_a?(Hash) @options.merge! options build_query end
[ "def", "options", "=", "(", "options", ")", "fail", "ArgumentError", ",", "'options must be a Hash. '", "\"#{ options.inspect } given.\"", "unless", "options", ".", "is_a?", "(", "Hash", ")", "@options", ".", "merge!", "options", "build_query", "end" ]
Change search options with a hash, triggering a query string rebuild and clearing past results. Raises ArgumentError if options is not a Hash
[ "Change", "search", "options", "with", "a", "hash", "triggering", "a", "query", "string", "rebuild", "and", "clearing", "past", "results", "." ]
8f9e43c5dbeb2462e00fd841c208764380f6983b
https://github.com/fissionxuiptz/kat/blob/8f9e43c5dbeb2462e00fd841c208764380f6983b/lib/kat/search.rb#L123-L130
train
fissionxuiptz/kat
lib/kat/search.rb
Kat.Search.build_query
def build_query @query = @search_term.dup @pages = -1 @results = [] @query << "\"#{ @options[:exact] }\"" if @options[:exact] @query << @options[:or].join(' OR ') unless @options[:or].nil? or @options[:or].empty? @query += @options[:without].map { |s| "-#{ s }" } if @options[:without] @query += inputs.select { |k, v| @options[k] }.map { |k, v| "#{ k }:#{ @options[k] }" } @query += checks.select { |k, v| @options[k] }.map { |k, v| "#{ k }:1" } byzantine = selects.select do |k, v| (v[:id].to_s[/^.*_id$/] && @options[k].to_s.to_i > 0) || (v[:id].to_s[/^[^_]+$/] && @options[k]) end @query += byzantine.map { |k, v| "#{ v[:id] }:#{ @options[k] }" } end
ruby
def build_query @query = @search_term.dup @pages = -1 @results = [] @query << "\"#{ @options[:exact] }\"" if @options[:exact] @query << @options[:or].join(' OR ') unless @options[:or].nil? or @options[:or].empty? @query += @options[:without].map { |s| "-#{ s }" } if @options[:without] @query += inputs.select { |k, v| @options[k] }.map { |k, v| "#{ k }:#{ @options[k] }" } @query += checks.select { |k, v| @options[k] }.map { |k, v| "#{ k }:1" } byzantine = selects.select do |k, v| (v[:id].to_s[/^.*_id$/] && @options[k].to_s.to_i > 0) || (v[:id].to_s[/^[^_]+$/] && @options[k]) end @query += byzantine.map { |k, v| "#{ v[:id] }:#{ @options[k] }" } end
[ "def", "build_query", "@query", "=", "@search_term", ".", "dup", "@pages", "=", "-", "1", "@results", "=", "[", "]", "@query", "<<", "\"\\\"#{ @options[:exact] }\\\"\"", "if", "@options", "[", ":exact", "]", "@query", "<<", "@options", "[", ":or", "]", ".", "join", "(", "' OR '", ")", "unless", "@options", "[", ":or", "]", ".", "nil?", "or", "@options", "[", ":or", "]", ".", "empty?", "@query", "+=", "@options", "[", ":without", "]", ".", "map", "{", "|", "s", "|", "\"-#{ s }\"", "}", "if", "@options", "[", ":without", "]", "@query", "+=", "inputs", ".", "select", "{", "|", "k", ",", "v", "|", "@options", "[", "k", "]", "}", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{ k }:#{ @options[k] }\"", "}", "@query", "+=", "checks", ".", "select", "{", "|", "k", ",", "v", "|", "@options", "[", "k", "]", "}", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{ k }:1\"", "}", "byzantine", "=", "selects", ".", "select", "do", "|", "k", ",", "v", "|", "(", "v", "[", ":id", "]", ".", "to_s", "[", "/", "/", "]", "&&", "@options", "[", "k", "]", ".", "to_s", ".", "to_i", ">", "0", ")", "||", "(", "v", "[", ":id", "]", ".", "to_s", "[", "/", "/", "]", "&&", "@options", "[", "k", "]", ")", "end", "@query", "+=", "byzantine", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{ v[:id] }:#{ @options[k] }\"", "}", "end" ]
Clear out the query and rebuild it from the various stored options. Also clears out the results set and sets pages back to -1
[ "Clear", "out", "the", "query", "and", "rebuild", "it", "from", "the", "various", "stored", "options", ".", "Also", "clears", "out", "the", "results", "set", "and", "sets", "pages", "back", "to", "-", "1" ]
8f9e43c5dbeb2462e00fd841c208764380f6983b
https://github.com/fissionxuiptz/kat/blob/8f9e43c5dbeb2462e00fd841c208764380f6983b/lib/kat/search.rb#L283-L301
train
fissionxuiptz/kat
lib/kat/search.rb
Kat.Search.results_column
def results_column(name) @results.compact.map do |rs| rs.map { |r| r[name] || r[name[0...-1].intern] } end.flatten end
ruby
def results_column(name) @results.compact.map do |rs| rs.map { |r| r[name] || r[name[0...-1].intern] } end.flatten end
[ "def", "results_column", "(", "name", ")", "@results", ".", "compact", ".", "map", "do", "|", "rs", "|", "rs", ".", "map", "{", "|", "r", "|", "r", "[", "name", "]", "||", "r", "[", "name", "[", "0", "...", "-", "1", "]", ".", "intern", "]", "}", "end", ".", "flatten", "end" ]
Fetch a list of values from the results set given by name
[ "Fetch", "a", "list", "of", "values", "from", "the", "results", "set", "given", "by", "name" ]
8f9e43c5dbeb2462e00fd841c208764380f6983b
https://github.com/fissionxuiptz/kat/blob/8f9e43c5dbeb2462e00fd841c208764380f6983b/lib/kat/search.rb#L306-L310
train
NUBIC/aker
lib/aker/user.rb
Aker.User.full_name
def full_name display_name_parts = [first_name, last_name].compact if display_name_parts.empty? username else display_name_parts.join(' ') end end
ruby
def full_name display_name_parts = [first_name, last_name].compact if display_name_parts.empty? username else display_name_parts.join(' ') end end
[ "def", "full_name", "display_name_parts", "=", "[", "first_name", ",", "last_name", "]", ".", "compact", "if", "display_name_parts", ".", "empty?", "username", "else", "display_name_parts", ".", "join", "(", "' '", ")", "end", "end" ]
A display-friendly name for this user. Uses `first_name` and `last_name` if available, otherwise it just uses the username. @return [String]
[ "A", "display", "-", "friendly", "name", "for", "this", "user", ".", "Uses", "first_name", "and", "last_name", "if", "available", "otherwise", "it", "just", "uses", "the", "username", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/user.rb#L109-L116
train
on-site/Easy-Partials
lib/easy_partials/helper_additions.rb
EasyPartials.HelperAdditions.concat_partial
def concat_partial(partial, *args, &block) rendered = invoke_partial partial, *args, &block concat rendered end
ruby
def concat_partial(partial, *args, &block) rendered = invoke_partial partial, *args, &block concat rendered end
[ "def", "concat_partial", "(", "partial", ",", "*", "args", ",", "&", "block", ")", "rendered", "=", "invoke_partial", "partial", ",", "args", ",", "block", "concat", "rendered", "end" ]
Used to create nice templated "tags" while keeping the html out of our helpers. Additionally, this can be invoked implicitly by invoking the partial as a method with "_" prepended to the name. Invoking the method: <% concat_partial "my_partial", { :var => "value" } do %> <strong>Contents stored as a "body" local</strong> <% end %> Or invoking implicitly: <% _my_partial :var => "value" do %> <strong>Contents stored as a "body" local</strong> <% end %> Note that with the implicit partials the partial will first be searched for locally within the current view directory, and then additional directories defined by the controller level 'additional_partials' method, and finally within the views/shared directory.
[ "Used", "to", "create", "nice", "templated", "tags", "while", "keeping", "the", "html", "out", "of", "our", "helpers", ".", "Additionally", "this", "can", "be", "invoked", "implicitly", "by", "invoking", "the", "partial", "as", "a", "method", "with", "_", "prepended", "to", "the", "name", "." ]
ce4a1a47175dbf135d2a07e8f15f178b2076bbd8
https://github.com/on-site/Easy-Partials/blob/ce4a1a47175dbf135d2a07e8f15f178b2076bbd8/lib/easy_partials/helper_additions.rb#L101-L104
train
NUBIC/aker
lib/aker/authorities/static.rb
Aker::Authorities.Static.valid_credentials?
def valid_credentials?(kind, *credentials) found_username = (all_credentials(kind).detect { |c| c[:credentials] == credentials } || {})[:username] @users[found_username] end
ruby
def valid_credentials?(kind, *credentials) found_username = (all_credentials(kind).detect { |c| c[:credentials] == credentials } || {})[:username] @users[found_username] end
[ "def", "valid_credentials?", "(", "kind", ",", "*", "credentials", ")", "found_username", "=", "(", "all_credentials", "(", "kind", ")", ".", "detect", "{", "|", "c", "|", "c", "[", ":credentials", "]", "==", "credentials", "}", "||", "{", "}", ")", "[", ":username", "]", "@users", "[", "found_username", "]", "end" ]
AUTHORITY API IMPLEMENTATION Verifies the credentials against the set provided by calls to {#valid_credentials!} and {#load!}. Supports all kinds. @return [Aker::User, nil]
[ "AUTHORITY", "API", "IMPLEMENTATION" ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/authorities/static.rb#L43-L47
train
NUBIC/aker
lib/aker/authorities/static.rb
Aker::Authorities.Static.load!
def load!(io) doc = YAML.load(io) return self unless doc (doc["groups"] || {}).each do |portal, top_level_groups| @groups[portal.to_sym] = top_level_groups.collect { |group_data| build_group(group_data) } end (doc["users"] || {}).each do |username, config| attr_keys = config.keys - ["password", "portals", "identifiers"] valid_credentials!(:user, username, config["password"]) do |u| attr_keys.each do |k| begin u.send("#{k}=", config[k]) rescue NoMethodError raise NoMethodError, "#{k} is not a recognized user attribute" end end portal_data = config["portals"] || [] portals_and_groups_from_yaml(portal_data) do |portal, group, affiliate_ids| u.default_portal = portal unless u.default_portal u.in_portal!(portal) if group if affiliate_ids u.in_group!(portal, group, :affiliate_ids => affiliate_ids) else u.in_group!(portal, group) end end end (config["identifiers"] || {}).each do |ident, value| u.identifiers[ident.to_sym] = value end end end self end
ruby
def load!(io) doc = YAML.load(io) return self unless doc (doc["groups"] || {}).each do |portal, top_level_groups| @groups[portal.to_sym] = top_level_groups.collect { |group_data| build_group(group_data) } end (doc["users"] || {}).each do |username, config| attr_keys = config.keys - ["password", "portals", "identifiers"] valid_credentials!(:user, username, config["password"]) do |u| attr_keys.each do |k| begin u.send("#{k}=", config[k]) rescue NoMethodError raise NoMethodError, "#{k} is not a recognized user attribute" end end portal_data = config["portals"] || [] portals_and_groups_from_yaml(portal_data) do |portal, group, affiliate_ids| u.default_portal = portal unless u.default_portal u.in_portal!(portal) if group if affiliate_ids u.in_group!(portal, group, :affiliate_ids => affiliate_ids) else u.in_group!(portal, group) end end end (config["identifiers"] || {}).each do |ident, value| u.identifiers[ident.to_sym] = value end end end self end
[ "def", "load!", "(", "io", ")", "doc", "=", "YAML", ".", "load", "(", "io", ")", "return", "self", "unless", "doc", "(", "doc", "[", "\"groups\"", "]", "||", "{", "}", ")", ".", "each", "do", "|", "portal", ",", "top_level_groups", "|", "@groups", "[", "portal", ".", "to_sym", "]", "=", "top_level_groups", ".", "collect", "{", "|", "group_data", "|", "build_group", "(", "group_data", ")", "}", "end", "(", "doc", "[", "\"users\"", "]", "||", "{", "}", ")", ".", "each", "do", "|", "username", ",", "config", "|", "attr_keys", "=", "config", ".", "keys", "-", "[", "\"password\"", ",", "\"portals\"", ",", "\"identifiers\"", "]", "valid_credentials!", "(", ":user", ",", "username", ",", "config", "[", "\"password\"", "]", ")", "do", "|", "u", "|", "attr_keys", ".", "each", "do", "|", "k", "|", "begin", "u", ".", "send", "(", "\"#{k}=\"", ",", "config", "[", "k", "]", ")", "rescue", "NoMethodError", "raise", "NoMethodError", ",", "\"#{k} is not a recognized user attribute\"", "end", "end", "portal_data", "=", "config", "[", "\"portals\"", "]", "||", "[", "]", "portals_and_groups_from_yaml", "(", "portal_data", ")", "do", "|", "portal", ",", "group", ",", "affiliate_ids", "|", "u", ".", "default_portal", "=", "portal", "unless", "u", ".", "default_portal", "u", ".", "in_portal!", "(", "portal", ")", "if", "group", "if", "affiliate_ids", "u", ".", "in_group!", "(", "portal", ",", "group", ",", ":affiliate_ids", "=>", "affiliate_ids", ")", "else", "u", ".", "in_group!", "(", "portal", ",", "group", ")", "end", "end", "end", "(", "config", "[", "\"identifiers\"", "]", "||", "{", "}", ")", ".", "each", "do", "|", "ident", ",", "value", "|", "u", ".", "identifiers", "[", "ident", ".", "to_sym", "]", "=", "value", "end", "end", "end", "self", "end" ]
Loads a YAML doc and uses its contents to initialize the authority's authentication and authorization data. Sample doc: users: wakibbe: # username password: ekibder # password for :user auth (optional) first_name: Warren # any attributes from Aker::User may last_name: Kibbe # be set here identifiers: # identifiers will be loaded with employee_id: 4 # symbolized keys portals: # portal & group auth info (optional) - SQLSubmit # A groupless portal - ENU: # A portal with simple groups - User - NOTIS: # A portal with affiliated groups - Manager: [23] - User # you can mix affiliated and simple groups: # groups for hierarchical portals NOTIS: # (these aren't real NOTIS groups) - Admin: - Manager: - User - Auditor @param [#read] io a readable handle (something that can be passed to `YAML.load`) @return [Static] self
[ "Loads", "a", "YAML", "doc", "and", "uses", "its", "contents", "to", "initialize", "the", "authority", "s", "authentication", "and", "authorization", "data", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/authorities/static.rb#L204-L245
train
jimjh/reaction
lib/reaction/client/client.rb
Reaction.Client.broadcast
def broadcast(name, message, opts={}) # encapsulation encap = { n: name, m: message, t: opts[:to] || /.*/, e: opts[:except] || [] } EM.next_tick { @faye.publish BROADCAST, Base64.urlsafe_encode64(Marshal.dump(encap)) } end
ruby
def broadcast(name, message, opts={}) # encapsulation encap = { n: name, m: message, t: opts[:to] || /.*/, e: opts[:except] || [] } EM.next_tick { @faye.publish BROADCAST, Base64.urlsafe_encode64(Marshal.dump(encap)) } end
[ "def", "broadcast", "(", "name", ",", "message", ",", "opts", "=", "{", "}", ")", "# encapsulation", "encap", "=", "{", "n", ":", "name", ",", "m", ":", "message", ",", "t", ":", "opts", "[", ":to", "]", "||", "/", "/", ",", "e", ":", "opts", "[", ":except", "]", "||", "[", "]", "}", "EM", ".", "next_tick", "{", "@faye", ".", "publish", "BROADCAST", ",", "Base64", ".", "urlsafe_encode64", "(", "Marshal", ".", "dump", "(", "encap", ")", ")", "}", "end" ]
Creates a new reaction client. @param [Faye::Client] client bayeux client @param [String] salt secret salt, used to generate access tokens Publishes message to zero or more channels. @param [String] name controller name @param [String] message message to send @option opts :to can be a regular expression or an array, defaults to all. @option opts :except can be a regular expression or an array, defaults to none.
[ "Creates", "a", "new", "reaction", "client", "." ]
8aff9633dbd177ea536b79f59115a2825b5adf0a
https://github.com/jimjh/reaction/blob/8aff9633dbd177ea536b79f59115a2825b5adf0a/lib/reaction/client/client.rb#L26-L39
train
empowerunited/manage
app/helpers/manage/resource_helper.rb
Manage.ResourceHelper.action_link
def action_link(scope, link_data) value = nil case link_data when Proc value = link_data.call(scope) when Hash relation = link_data.keys.first entity = Fields::Reader.field_value(scope, relation) unless entity.present? return '' end if link_data[relation][:label_field].present? value = field_value(scope, link_data[relation][:label_field]) elsif link_data[relation][:label].present? value = link_data[relation][:label] end path = entity.class.name.dasherize.pluralize.downcase return link_to value, [scope.public_send(relation)] when *[Symbol, String] relation = link_data.to_s assocation = scope.class.reflect_on_association(link_data.to_sym) raise "assocation #{link_data} not found on #{scope.class}" unless assocation if assocation.options[:class_name].present? rel_name = scope.class.reflect_on_association(link_data.to_sym).options[:class_name] relation = rel_name.downcase.dasherize.pluralize end if scope.class.reflect_on_association(link_data.to_sym).options[:as].present? key = scope.class.reflect_on_association(link_data.to_sym).options[:as].to_s + '_id' else key = scope.class.name.downcase.dasherize + '_id' end return "<a href=\"#{relation}?f%5B#{key}%5D=#{scope.id}\">#{resource_class.human_attribute_name(link_data.to_s)}</a>".html_safe else raise 'Unsupported link data' end end
ruby
def action_link(scope, link_data) value = nil case link_data when Proc value = link_data.call(scope) when Hash relation = link_data.keys.first entity = Fields::Reader.field_value(scope, relation) unless entity.present? return '' end if link_data[relation][:label_field].present? value = field_value(scope, link_data[relation][:label_field]) elsif link_data[relation][:label].present? value = link_data[relation][:label] end path = entity.class.name.dasherize.pluralize.downcase return link_to value, [scope.public_send(relation)] when *[Symbol, String] relation = link_data.to_s assocation = scope.class.reflect_on_association(link_data.to_sym) raise "assocation #{link_data} not found on #{scope.class}" unless assocation if assocation.options[:class_name].present? rel_name = scope.class.reflect_on_association(link_data.to_sym).options[:class_name] relation = rel_name.downcase.dasherize.pluralize end if scope.class.reflect_on_association(link_data.to_sym).options[:as].present? key = scope.class.reflect_on_association(link_data.to_sym).options[:as].to_s + '_id' else key = scope.class.name.downcase.dasherize + '_id' end return "<a href=\"#{relation}?f%5B#{key}%5D=#{scope.id}\">#{resource_class.human_attribute_name(link_data.to_s)}</a>".html_safe else raise 'Unsupported link data' end end
[ "def", "action_link", "(", "scope", ",", "link_data", ")", "value", "=", "nil", "case", "link_data", "when", "Proc", "value", "=", "link_data", ".", "call", "(", "scope", ")", "when", "Hash", "relation", "=", "link_data", ".", "keys", ".", "first", "entity", "=", "Fields", "::", "Reader", ".", "field_value", "(", "scope", ",", "relation", ")", "unless", "entity", ".", "present?", "return", "''", "end", "if", "link_data", "[", "relation", "]", "[", ":label_field", "]", ".", "present?", "value", "=", "field_value", "(", "scope", ",", "link_data", "[", "relation", "]", "[", ":label_field", "]", ")", "elsif", "link_data", "[", "relation", "]", "[", ":label", "]", ".", "present?", "value", "=", "link_data", "[", "relation", "]", "[", ":label", "]", "end", "path", "=", "entity", ".", "class", ".", "name", ".", "dasherize", ".", "pluralize", ".", "downcase", "return", "link_to", "value", ",", "[", "scope", ".", "public_send", "(", "relation", ")", "]", "when", "[", "Symbol", ",", "String", "]", "relation", "=", "link_data", ".", "to_s", "assocation", "=", "scope", ".", "class", ".", "reflect_on_association", "(", "link_data", ".", "to_sym", ")", "raise", "\"assocation #{link_data} not found on #{scope.class}\"", "unless", "assocation", "if", "assocation", ".", "options", "[", ":class_name", "]", ".", "present?", "rel_name", "=", "scope", ".", "class", ".", "reflect_on_association", "(", "link_data", ".", "to_sym", ")", ".", "options", "[", ":class_name", "]", "relation", "=", "rel_name", ".", "downcase", ".", "dasherize", ".", "pluralize", "end", "if", "scope", ".", "class", ".", "reflect_on_association", "(", "link_data", ".", "to_sym", ")", ".", "options", "[", ":as", "]", ".", "present?", "key", "=", "scope", ".", "class", ".", "reflect_on_association", "(", "link_data", ".", "to_sym", ")", ".", "options", "[", ":as", "]", ".", "to_s", "+", "'_id'", "else", "key", "=", "scope", ".", "class", ".", "name", ".", "downcase", ".", "dasherize", "+", "'_id'", "end", "return", "\"<a href=\\\"#{relation}?f%5B#{key}%5D=#{scope.id}\\\">#{resource_class.human_attribute_name(link_data.to_s)}</a>\"", ".", "html_safe", "else", "raise", "'Unsupported link data'", "end", "end" ]
to customise the actions for a resource define a list of actions example: action_links :posts, :tickets, ->(resource) {link_to "#{resource.name}"} @param scope [type] [description] @param link_data [type] [description] @return [type] [description]
[ "to", "customise", "the", "actions", "for", "a", "resource", "define", "a", "list", "of", "actions" ]
aac8580208513afd180a0fbbc067865deff765fe
https://github.com/empowerunited/manage/blob/aac8580208513afd180a0fbbc067865deff765fe/app/helpers/manage/resource_helper.rb#L34-L74
train
binarylogic/addresslogic
lib/addresslogic.rb
Addresslogic.ClassMethods.apply_addresslogic
def apply_addresslogic(options = {}) n = options[:namespace] options[:fields] ||= [ "#{n}street1".to_sym, "#{n}street2".to_sym, ["#{n}city".to_sym, ["#{n}state".to_sym, "#{n}zip".to_sym]], "#{n}country".to_sym ] self.addresslogic_options = options include Addresslogic::InstanceMethods end
ruby
def apply_addresslogic(options = {}) n = options[:namespace] options[:fields] ||= [ "#{n}street1".to_sym, "#{n}street2".to_sym, ["#{n}city".to_sym, ["#{n}state".to_sym, "#{n}zip".to_sym]], "#{n}country".to_sym ] self.addresslogic_options = options include Addresslogic::InstanceMethods end
[ "def", "apply_addresslogic", "(", "options", "=", "{", "}", ")", "n", "=", "options", "[", ":namespace", "]", "options", "[", ":fields", "]", "||=", "[", "\"#{n}street1\"", ".", "to_sym", ",", "\"#{n}street2\"", ".", "to_sym", ",", "[", "\"#{n}city\"", ".", "to_sym", ",", "[", "\"#{n}state\"", ".", "to_sym", ",", "\"#{n}zip\"", ".", "to_sym", "]", "]", ",", "\"#{n}country\"", ".", "to_sym", "]", "self", ".", "addresslogic_options", "=", "options", "include", "Addresslogic", "::", "InstanceMethods", "end" ]
Mixes in useful methods for handling addresses. === Options * <tt>fields:</tt> array of fields (default: [:street1, :street2, [:city, [:state, :zip]], :country]) * <tt>namespace:</tt> prefixes fields names with this, great for use with composed_of in ActiveRecord.
[ "Mixes", "in", "useful", "methods", "for", "handling", "addresses", "." ]
8ba73d6f56ca80d24d4b0c050944d5a06dcc33be
https://github.com/binarylogic/addresslogic/blob/8ba73d6f56ca80d24d4b0c050944d5a06dcc33be/lib/addresslogic.rb#L16-L27
train
wwood/yargraph
lib/yargraph.rb
Yargraph.UndirectedGraph.hamiltonian_cycles_dynamic_programming
def hamiltonian_cycles_dynamic_programming(operational_limit=nil) stack = DS::Stack.new return [] if @vertices.empty? origin_vertex = @vertices.to_a[0] hamiltonians = [] num_operations = 0 # This hash keeps track of subproblems that have already been # solved. ie is there a path through vertices that ends in the # endpoint # Hash of [vertex_set,endpoint] => Array of Path objects. # If no path is found, then the key is false # The endpoint is not stored in the vertex set to make the programming # easier. dp_cache = {} # First problem is the whole problem. We get the Hamiltonian paths, # and then after reject those paths that are not cycles. initial_vertex_set = Set.new(@vertices.reject{|v| v==origin_vertex}) initial_problem = [initial_vertex_set, origin_vertex] stack.push initial_problem while next_problem = stack.pop vertices = next_problem[0] destination = next_problem[1] if dp_cache[next_problem] # No need to do anything - problem already solved elsif vertices.empty? # The bottom of the problem. Only return a path # if there is an edge between the destination and the origin # node if edge?(destination, origin_vertex) path = Path.new [destination] dp_cache[next_problem] = [path] else # Reached dead end dp_cache[next_problem] = false end else # This is an unsolved problem and there are at least 2 vertices in the vertex set. # Work out which vertices in the set are neighbours neighs = Set.new neighbours(destination) possibilities = neighs.intersection(vertices) if possibilities.length > 0 # There is still the possibility to go further into this unsolved problem subproblems_unsolved = [] subproblems = [] possibilities.each do |new_destination| new_vertex_set = Set.new(vertices.to_a.reject{|v| v==new_destination}) subproblem = [new_vertex_set, new_destination] subproblems.push subproblem if !dp_cache.key?(subproblem) subproblems_unsolved.push subproblem end end # if solved all the subproblems, then we can make a decision about this problem if subproblems_unsolved.empty? answers = [] subproblems.each do |problem| paths = dp_cache[problem] if paths == false # Nothing to see here else # Add the found sub-paths to the set of answers paths.each do |path| answers.push Path.new(path+[destination]) end end end if answers.empty? # No paths have been found here dp_cache[next_problem] = false else dp_cache[next_problem] = answers end else # More problems to be solved before a decision can be made stack.push next_problem #We have only delayed solving this problem, need to keep going in the future subproblems_unsolved.each do |prob| unless operational_limit.nil? num_operations += 1 raise OperationalLimitReachedException if num_operations > operational_limit end stack.push prob end end else # No neighbours in the set, so reached a dead end, can go no further dp_cache[next_problem] = false end end end if block_given? dp_cache[initial_problem].each do |hpath| yield hpath end return else return dp_cache[initial_problem] end end
ruby
def hamiltonian_cycles_dynamic_programming(operational_limit=nil) stack = DS::Stack.new return [] if @vertices.empty? origin_vertex = @vertices.to_a[0] hamiltonians = [] num_operations = 0 # This hash keeps track of subproblems that have already been # solved. ie is there a path through vertices that ends in the # endpoint # Hash of [vertex_set,endpoint] => Array of Path objects. # If no path is found, then the key is false # The endpoint is not stored in the vertex set to make the programming # easier. dp_cache = {} # First problem is the whole problem. We get the Hamiltonian paths, # and then after reject those paths that are not cycles. initial_vertex_set = Set.new(@vertices.reject{|v| v==origin_vertex}) initial_problem = [initial_vertex_set, origin_vertex] stack.push initial_problem while next_problem = stack.pop vertices = next_problem[0] destination = next_problem[1] if dp_cache[next_problem] # No need to do anything - problem already solved elsif vertices.empty? # The bottom of the problem. Only return a path # if there is an edge between the destination and the origin # node if edge?(destination, origin_vertex) path = Path.new [destination] dp_cache[next_problem] = [path] else # Reached dead end dp_cache[next_problem] = false end else # This is an unsolved problem and there are at least 2 vertices in the vertex set. # Work out which vertices in the set are neighbours neighs = Set.new neighbours(destination) possibilities = neighs.intersection(vertices) if possibilities.length > 0 # There is still the possibility to go further into this unsolved problem subproblems_unsolved = [] subproblems = [] possibilities.each do |new_destination| new_vertex_set = Set.new(vertices.to_a.reject{|v| v==new_destination}) subproblem = [new_vertex_set, new_destination] subproblems.push subproblem if !dp_cache.key?(subproblem) subproblems_unsolved.push subproblem end end # if solved all the subproblems, then we can make a decision about this problem if subproblems_unsolved.empty? answers = [] subproblems.each do |problem| paths = dp_cache[problem] if paths == false # Nothing to see here else # Add the found sub-paths to the set of answers paths.each do |path| answers.push Path.new(path+[destination]) end end end if answers.empty? # No paths have been found here dp_cache[next_problem] = false else dp_cache[next_problem] = answers end else # More problems to be solved before a decision can be made stack.push next_problem #We have only delayed solving this problem, need to keep going in the future subproblems_unsolved.each do |prob| unless operational_limit.nil? num_operations += 1 raise OperationalLimitReachedException if num_operations > operational_limit end stack.push prob end end else # No neighbours in the set, so reached a dead end, can go no further dp_cache[next_problem] = false end end end if block_given? dp_cache[initial_problem].each do |hpath| yield hpath end return else return dp_cache[initial_problem] end end
[ "def", "hamiltonian_cycles_dynamic_programming", "(", "operational_limit", "=", "nil", ")", "stack", "=", "DS", "::", "Stack", ".", "new", "return", "[", "]", "if", "@vertices", ".", "empty?", "origin_vertex", "=", "@vertices", ".", "to_a", "[", "0", "]", "hamiltonians", "=", "[", "]", "num_operations", "=", "0", "# This hash keeps track of subproblems that have already been", "# solved. ie is there a path through vertices that ends in the", "# endpoint", "# Hash of [vertex_set,endpoint] => Array of Path objects.", "# If no path is found, then the key is false", "# The endpoint is not stored in the vertex set to make the programming", "# easier.", "dp_cache", "=", "{", "}", "# First problem is the whole problem. We get the Hamiltonian paths,", "# and then after reject those paths that are not cycles.", "initial_vertex_set", "=", "Set", ".", "new", "(", "@vertices", ".", "reject", "{", "|", "v", "|", "v", "==", "origin_vertex", "}", ")", "initial_problem", "=", "[", "initial_vertex_set", ",", "origin_vertex", "]", "stack", ".", "push", "initial_problem", "while", "next_problem", "=", "stack", ".", "pop", "vertices", "=", "next_problem", "[", "0", "]", "destination", "=", "next_problem", "[", "1", "]", "if", "dp_cache", "[", "next_problem", "]", "# No need to do anything - problem already solved", "elsif", "vertices", ".", "empty?", "# The bottom of the problem. Only return a path", "# if there is an edge between the destination and the origin", "# node", "if", "edge?", "(", "destination", ",", "origin_vertex", ")", "path", "=", "Path", ".", "new", "[", "destination", "]", "dp_cache", "[", "next_problem", "]", "=", "[", "path", "]", "else", "# Reached dead end", "dp_cache", "[", "next_problem", "]", "=", "false", "end", "else", "# This is an unsolved problem and there are at least 2 vertices in the vertex set.", "# Work out which vertices in the set are neighbours", "neighs", "=", "Set", ".", "new", "neighbours", "(", "destination", ")", "possibilities", "=", "neighs", ".", "intersection", "(", "vertices", ")", "if", "possibilities", ".", "length", ">", "0", "# There is still the possibility to go further into this unsolved problem", "subproblems_unsolved", "=", "[", "]", "subproblems", "=", "[", "]", "possibilities", ".", "each", "do", "|", "new_destination", "|", "new_vertex_set", "=", "Set", ".", "new", "(", "vertices", ".", "to_a", ".", "reject", "{", "|", "v", "|", "v", "==", "new_destination", "}", ")", "subproblem", "=", "[", "new_vertex_set", ",", "new_destination", "]", "subproblems", ".", "push", "subproblem", "if", "!", "dp_cache", ".", "key?", "(", "subproblem", ")", "subproblems_unsolved", ".", "push", "subproblem", "end", "end", "# if solved all the subproblems, then we can make a decision about this problem", "if", "subproblems_unsolved", ".", "empty?", "answers", "=", "[", "]", "subproblems", ".", "each", "do", "|", "problem", "|", "paths", "=", "dp_cache", "[", "problem", "]", "if", "paths", "==", "false", "# Nothing to see here", "else", "# Add the found sub-paths to the set of answers", "paths", ".", "each", "do", "|", "path", "|", "answers", ".", "push", "Path", ".", "new", "(", "path", "+", "[", "destination", "]", ")", "end", "end", "end", "if", "answers", ".", "empty?", "# No paths have been found here", "dp_cache", "[", "next_problem", "]", "=", "false", "else", "dp_cache", "[", "next_problem", "]", "=", "answers", "end", "else", "# More problems to be solved before a decision can be made", "stack", ".", "push", "next_problem", "#We have only delayed solving this problem, need to keep going in the future", "subproblems_unsolved", ".", "each", "do", "|", "prob", "|", "unless", "operational_limit", ".", "nil?", "num_operations", "+=", "1", "raise", "OperationalLimitReachedException", "if", "num_operations", ">", "operational_limit", "end", "stack", ".", "push", "prob", "end", "end", "else", "# No neighbours in the set, so reached a dead end, can go no further", "dp_cache", "[", "next_problem", "]", "=", "false", "end", "end", "end", "if", "block_given?", "dp_cache", "[", "initial_problem", "]", ".", "each", "do", "|", "hpath", "|", "yield", "hpath", "end", "return", "else", "return", "dp_cache", "[", "initial_problem", "]", "end", "end" ]
Use dynamic programming to find all the Hamiltonian cycles in this graph
[ "Use", "dynamic", "programming", "to", "find", "all", "the", "Hamiltonian", "cycles", "in", "this", "graph" ]
7991279040f9674cfd3f7b40b056d03fed584a96
https://github.com/wwood/yargraph/blob/7991279040f9674cfd3f7b40b056d03fed584a96/lib/yargraph.rb#L215-L325
train
fusor/egon
lib/egon/overcloud/undercloud_handle/node.rb
Overcloud.Node.introspect_node
def introspect_node(node_uuid) workflow = 'tripleo.baremetal.v1.introspect' input = { node_uuids: [node_uuid] } execute_workflow(workflow, input, false) end
ruby
def introspect_node(node_uuid) workflow = 'tripleo.baremetal.v1.introspect' input = { node_uuids: [node_uuid] } execute_workflow(workflow, input, false) end
[ "def", "introspect_node", "(", "node_uuid", ")", "workflow", "=", "'tripleo.baremetal.v1.introspect'", "input", "=", "{", "node_uuids", ":", "[", "node_uuid", "]", "}", "execute_workflow", "(", "workflow", ",", "input", ",", "false", ")", "end" ]
THESE METHODS ARE TEMPORARY UNTIL IRONIC-DISCOVERD IS ADDED TO OPENSTACK AND KEYSTONE
[ "THESE", "METHODS", "ARE", "TEMPORARY", "UNTIL", "IRONIC", "-", "DISCOVERD", "IS", "ADDED", "TO", "OPENSTACK", "AND", "KEYSTONE" ]
e3a57d8748964989b7a0aacd2be4fec4a0a760e4
https://github.com/fusor/egon/blob/e3a57d8748964989b7a0aacd2be4fec4a0a760e4/lib/egon/overcloud/undercloud_handle/node.rb#L152-L156
train
Mordorreal/SiteAnalyzer
lib/site_analyzer/site.rb
SiteAnalyzer.Site.add_pages_for_scan!
def add_pages_for_scan! @pages_for_scan = [] @bad_pages = [] @pages.each do |page| @bad_pages << page.page_url unless page.page_a_tags next unless page.page_a_tags page.home_a.each do |link| @pages_for_scan << link end end end
ruby
def add_pages_for_scan! @pages_for_scan = [] @bad_pages = [] @pages.each do |page| @bad_pages << page.page_url unless page.page_a_tags next unless page.page_a_tags page.home_a.each do |link| @pages_for_scan << link end end end
[ "def", "add_pages_for_scan!", "@pages_for_scan", "=", "[", "]", "@bad_pages", "=", "[", "]", "@pages", ".", "each", "do", "|", "page", "|", "@bad_pages", "<<", "page", ".", "page_url", "unless", "page", ".", "page_a_tags", "next", "unless", "page", ".", "page_a_tags", "page", ".", "home_a", ".", "each", "do", "|", "link", "|", "@pages_for_scan", "<<", "link", "end", "end", "end" ]
add pages for scan array, also add bad pages to bad_pages array
[ "add", "pages", "for", "scan", "array", "also", "add", "bad", "pages", "to", "bad_pages", "array" ]
7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb
https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/site.rb#L41-L51
train
Mordorreal/SiteAnalyzer
lib/site_analyzer/site.rb
SiteAnalyzer.Site.add_page
def add_page(url) unless robot_txt_allowed?(url) @scanned_pages << url return nil end page = Page.new(url) @pages << page @scanned_pages << url end
ruby
def add_page(url) unless robot_txt_allowed?(url) @scanned_pages << url return nil end page = Page.new(url) @pages << page @scanned_pages << url end
[ "def", "add_page", "(", "url", ")", "unless", "robot_txt_allowed?", "(", "url", ")", "@scanned_pages", "<<", "url", "return", "nil", "end", "page", "=", "Page", ".", "new", "(", "url", ")", "@pages", "<<", "page", "@scanned_pages", "<<", "url", "end" ]
create Page and add to to site
[ "create", "Page", "and", "add", "to", "to", "site" ]
7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb
https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/site.rb#L53-L61
train
Mordorreal/SiteAnalyzer
lib/site_analyzer/site.rb
SiteAnalyzer.Site.all_titles
def all_titles result = [] @pages.each do |page| result << [page.page_url, page.all_titles] if page.page_a_tags end result end
ruby
def all_titles result = [] @pages.each do |page| result << [page.page_url, page.all_titles] if page.page_a_tags end result end
[ "def", "all_titles", "result", "=", "[", "]", "@pages", ".", "each", "do", "|", "page", "|", "result", "<<", "[", "page", ".", "page_url", ",", "page", ".", "all_titles", "]", "if", "page", ".", "page_a_tags", "end", "result", "end" ]
get all titles on site and return array of them
[ "get", "all", "titles", "on", "site", "and", "return", "array", "of", "them" ]
7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb
https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/site.rb#L63-L69
train
Mordorreal/SiteAnalyzer
lib/site_analyzer/site.rb
SiteAnalyzer.Site.all_descriptions
def all_descriptions result = [] @pages.each do |page| result << [page.page_url, page.meta_desc_content] if page.page_a_tags end result end
ruby
def all_descriptions result = [] @pages.each do |page| result << [page.page_url, page.meta_desc_content] if page.page_a_tags end result end
[ "def", "all_descriptions", "result", "=", "[", "]", "@pages", ".", "each", "do", "|", "page", "|", "result", "<<", "[", "page", ".", "page_url", ",", "page", ".", "meta_desc_content", "]", "if", "page", ".", "page_a_tags", "end", "result", "end" ]
get all meta description tags content and return it as array
[ "get", "all", "meta", "description", "tags", "content", "and", "return", "it", "as", "array" ]
7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb
https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/site.rb#L71-L77
train
Mordorreal/SiteAnalyzer
lib/site_analyzer/site.rb
SiteAnalyzer.Site.all_h2
def all_h2 result = [] @pages.each do |page| result << [page.page_url, page.h2_text] unless page.page_a_tags end result end
ruby
def all_h2 result = [] @pages.each do |page| result << [page.page_url, page.h2_text] unless page.page_a_tags end result end
[ "def", "all_h2", "result", "=", "[", "]", "@pages", ".", "each", "do", "|", "page", "|", "result", "<<", "[", "page", ".", "page_url", ",", "page", ".", "h2_text", "]", "unless", "page", ".", "page_a_tags", "end", "result", "end" ]
get all h2 tags and return array of it
[ "get", "all", "h2", "tags", "and", "return", "array", "of", "it" ]
7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb
https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/site.rb#L79-L85
train
Mordorreal/SiteAnalyzer
lib/site_analyzer/site.rb
SiteAnalyzer.Site.all_a
def all_a result = [] @pages.each do |page| next unless page.page_a_tags page.page_a_tags.compact.each do |tag| tag[0] = '-' unless tag[0] tag[1] = '-' unless tag[1] tag[2] = '-' unless tag[2] result << [page.page_url, tag[0], tag[1], tag[2]] end end result.compact end
ruby
def all_a result = [] @pages.each do |page| next unless page.page_a_tags page.page_a_tags.compact.each do |tag| tag[0] = '-' unless tag[0] tag[1] = '-' unless tag[1] tag[2] = '-' unless tag[2] result << [page.page_url, tag[0], tag[1], tag[2]] end end result.compact end
[ "def", "all_a", "result", "=", "[", "]", "@pages", ".", "each", "do", "|", "page", "|", "next", "unless", "page", ".", "page_a_tags", "page", ".", "page_a_tags", ".", "compact", ".", "each", "do", "|", "tag", "|", "tag", "[", "0", "]", "=", "'-'", "unless", "tag", "[", "0", "]", "tag", "[", "1", "]", "=", "'-'", "unless", "tag", "[", "1", "]", "tag", "[", "2", "]", "=", "'-'", "unless", "tag", "[", "2", "]", "result", "<<", "[", "page", ".", "page_url", ",", "tag", "[", "0", "]", ",", "tag", "[", "1", "]", ",", "tag", "[", "2", "]", "]", "end", "end", "result", ".", "compact", "end" ]
get all a tags and return array of it
[ "get", "all", "a", "tags", "and", "return", "array", "of", "it" ]
7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb
https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/site.rb#L87-L99
train
Mordorreal/SiteAnalyzer
lib/site_analyzer/site.rb
SiteAnalyzer.Site.convert_to_valid
def convert_to_valid(url) return nil if url =~ /.jpg$/i url.insert(0, @main_url.first(5)) if url.start_with? '//' link = URI(url) main_page = URI(@main_url) if link && link.scheme && link.scheme.empty? link.scheme = main_page.scheme elsif link.nil? return nil end if link.scheme =~ /^http/ request = link.to_s else request = nil end request rescue link end
ruby
def convert_to_valid(url) return nil if url =~ /.jpg$/i url.insert(0, @main_url.first(5)) if url.start_with? '//' link = URI(url) main_page = URI(@main_url) if link && link.scheme && link.scheme.empty? link.scheme = main_page.scheme elsif link.nil? return nil end if link.scheme =~ /^http/ request = link.to_s else request = nil end request rescue link end
[ "def", "convert_to_valid", "(", "url", ")", "return", "nil", "if", "url", "=~", "/", "/i", "url", ".", "insert", "(", "0", ",", "@main_url", ".", "first", "(", "5", ")", ")", "if", "url", ".", "start_with?", "'//'", "link", "=", "URI", "(", "url", ")", "main_page", "=", "URI", "(", "@main_url", ")", "if", "link", "&&", "link", ".", "scheme", "&&", "link", ".", "scheme", ".", "empty?", "link", ".", "scheme", "=", "main_page", ".", "scheme", "elsif", "link", ".", "nil?", "return", "nil", "end", "if", "link", ".", "scheme", "=~", "/", "/", "request", "=", "link", ".", "to_s", "else", "request", "=", "nil", "end", "request", "rescue", "link", "end" ]
check url and try to convert it to valid, remove .jpg links, add scheme to url
[ "check", "url", "and", "try", "to", "convert", "it", "to", "valid", "remove", ".", "jpg", "links", "add", "scheme", "to", "url" ]
7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb
https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/site.rb#L115-L133
train
anshulverma/sawaal
lib/sawaal/selections.rb
Sawaal.Selections.read_char
def read_char input = $stdin.getch return input unless input == "\e" begin Timeout.timeout(0.01) do input += $stdin.getch input += $stdin.getch end rescue Timeout::Error # ignored end input end
ruby
def read_char input = $stdin.getch return input unless input == "\e" begin Timeout.timeout(0.01) do input += $stdin.getch input += $stdin.getch end rescue Timeout::Error # ignored end input end
[ "def", "read_char", "input", "=", "$stdin", ".", "getch", "return", "input", "unless", "input", "==", "\"\\e\"", "begin", "Timeout", ".", "timeout", "(", "0.01", ")", "do", "input", "+=", "$stdin", ".", "getch", "input", "+=", "$stdin", ".", "getch", "end", "rescue", "Timeout", "::", "Error", "# ignored", "end", "input", "end" ]
Reads keypresses from the user including 2 and 3 escape character sequences.
[ "Reads", "keypresses", "from", "the", "user", "including", "2", "and", "3", "escape", "character", "sequences", "." ]
ccbfc7997024ba7e13e565d778dccb9af80dbb5d
https://github.com/anshulverma/sawaal/blob/ccbfc7997024ba7e13e565d778dccb9af80dbb5d/lib/sawaal/selections.rb#L56-L68
train
maxjacobson/todo_lint
lib/todo_lint/reporter.rb
TodoLint.Reporter.number_of_spaces
def number_of_spaces todo.character_number - 1 - (todo.line.length - todo.line.lstrip.length) end
ruby
def number_of_spaces todo.character_number - 1 - (todo.line.length - todo.line.lstrip.length) end
[ "def", "number_of_spaces", "todo", ".", "character_number", "-", "1", "-", "(", "todo", ".", "line", ".", "length", "-", "todo", ".", "line", ".", "lstrip", ".", "length", ")", "end" ]
How many spaces before the carets should there be? @return [Fixnum] @api private
[ "How", "many", "spaces", "before", "the", "carets", "should", "there", "be?" ]
0d1061383ea205ef4c74edc64568e308ac1af990
https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/reporter.rb#L71-L73
train
shanna/swift
lib/swift/adapter.rb
Swift.Adapter.create
def create record, resources result = [resources].flatten.map do |resource| resource = record.new(resource) unless resource.kind_of?(record) result = execute(command_create(record), *resource.tuple.values_at(*record.header.insertable)) resource.tuple[record.header.serial] = result.insert_id if record.header.serial resource end resources.kind_of?(Array) ? result : result.first end
ruby
def create record, resources result = [resources].flatten.map do |resource| resource = record.new(resource) unless resource.kind_of?(record) result = execute(command_create(record), *resource.tuple.values_at(*record.header.insertable)) resource.tuple[record.header.serial] = result.insert_id if record.header.serial resource end resources.kind_of?(Array) ? result : result.first end
[ "def", "create", "record", ",", "resources", "result", "=", "[", "resources", "]", ".", "flatten", ".", "map", "do", "|", "resource", "|", "resource", "=", "record", ".", "new", "(", "resource", ")", "unless", "resource", ".", "kind_of?", "(", "record", ")", "result", "=", "execute", "(", "command_create", "(", "record", ")", ",", "resource", ".", "tuple", ".", "values_at", "(", "record", ".", "header", ".", "insertable", ")", ")", "resource", ".", "tuple", "[", "record", ".", "header", ".", "serial", "]", "=", "result", ".", "insert_id", "if", "record", ".", "header", ".", "serial", "resource", "end", "resources", ".", "kind_of?", "(", "Array", ")", "?", "result", ":", "result", ".", "first", "end" ]
Create one or more. @example Record. user = User.new(name: 'Apply Arthurton', age: 32) Swift.db.create(User, user) #=> Swift::Record @example Coerce hash to record. Swif.db.create(User, name: 'Apple Arthurton', age: 32) #=> Swift::Record @example Multiple resources. apple = User.new(name: 'Apple Arthurton', age: 32) benny = User.new(name: 'Benny Arthurton', age: 30) Swift.db.create(User, [apple, benny]) #=> Array<Swift::Record> @example Coerce multiple resources. Swift.db.create(User, [{name: 'Apple Arthurton', age: 32}, {name: 'Benny Arthurton', age: 30}]) #=> Array<Swift::Record> @param [Swift::Record] record Concrete record subclass to load. @param [Swift::Record, Hash, Array<Swift::Record, Hash>] resources The resources to be saved. @return [Swift::Record, Array<Swift::Record>] @note Hashes will be coerced into a Swift::Record resource via Swift::Record#new @note Passing a scalar will result in a scalar. @see Swift::Record.create
[ "Create", "one", "or", "more", "." ]
c9488d5594da546958ab9cf3602d69d0ca51b021
https://github.com/shanna/swift/blob/c9488d5594da546958ab9cf3602d69d0ca51b021/lib/swift/adapter.rb#L59-L67
train
shanna/swift
lib/swift/adapter.rb
Swift.Adapter.update
def update record, resources result = [resources].flatten.map do |resource| resource = record.new(resource) unless resource.kind_of?(record) keys = resource.tuple.values_at(*record.header.keys) # TODO: Name the key field(s) missing. raise ArgumentError, "#{record} resource has incomplete key: #{resource.inspect}" \ unless keys.select(&:nil?).empty? execute(command_update(record), *resource.tuple.values_at(*record.header.updatable), *keys) resource end resources.kind_of?(Array) ? result : result.first end
ruby
def update record, resources result = [resources].flatten.map do |resource| resource = record.new(resource) unless resource.kind_of?(record) keys = resource.tuple.values_at(*record.header.keys) # TODO: Name the key field(s) missing. raise ArgumentError, "#{record} resource has incomplete key: #{resource.inspect}" \ unless keys.select(&:nil?).empty? execute(command_update(record), *resource.tuple.values_at(*record.header.updatable), *keys) resource end resources.kind_of?(Array) ? result : result.first end
[ "def", "update", "record", ",", "resources", "result", "=", "[", "resources", "]", ".", "flatten", ".", "map", "do", "|", "resource", "|", "resource", "=", "record", ".", "new", "(", "resource", ")", "unless", "resource", ".", "kind_of?", "(", "record", ")", "keys", "=", "resource", ".", "tuple", ".", "values_at", "(", "record", ".", "header", ".", "keys", ")", "# TODO: Name the key field(s) missing.", "raise", "ArgumentError", ",", "\"#{record} resource has incomplete key: #{resource.inspect}\"", "unless", "keys", ".", "select", "(", ":nil?", ")", ".", "empty?", "execute", "(", "command_update", "(", "record", ")", ",", "resource", ".", "tuple", ".", "values_at", "(", "record", ".", "header", ".", "updatable", ")", ",", "keys", ")", "resource", "end", "resources", ".", "kind_of?", "(", "Array", ")", "?", "result", ":", "result", ".", "first", "end" ]
Update one or more. @example Record. user = Swift.db.create(User, name: 'Apply Arthurton', age: 32) user.name = 'Arthur Appleton' Swift.db.update(User, user) #=> Swift::Record @example Coerce hash to record. user = Swift.db.create(User, name: 'Apply Arthurton', age: 32) user.name = 'Arthur Appleton' Swif.db.update(User, user.tuple) #=> Swift::Record @example Multiple resources. apple = Swift.db.create(User, name: 'Apple Arthurton', age: 32) benny = Swift.db.create(User, name: 'Benny Arthurton', age: 30) Swift.db.update(User, [apple, benny]) #=> Array<Swift::Record> @example Coerce multiple resources. apple = Swift.db.create(User, name: 'Apple Arthurton', age: 32) benny = Swift.db.create(User, name: 'Benny Arthurton', age: 30) Swift.db.update(User, [apple.tuple, benny.tuple]) #=> Array<Swift::Record> @param [Swift::Record] record Concrete record subclass to load. @param [Swift::Record, Hash, Array<Swift::Record, Hash>] resources The resources to be updated. @return [Swift::Record, Swift::Result] @note Hashes will be coerced into a Swift::Record resource via Swift::Record#new @note Passing a scalar will result in a scalar. @see Swift::Record#update
[ "Update", "one", "or", "more", "." ]
c9488d5594da546958ab9cf3602d69d0ca51b021
https://github.com/shanna/swift/blob/c9488d5594da546958ab9cf3602d69d0ca51b021/lib/swift/adapter.rb#L98-L111
train
shanna/swift
lib/swift/adapter.rb
Swift.Adapter.delete
def delete record, resources result = [resources].flatten.map do |resource| resource = record.new(resource) unless resource.kind_of?(record) keys = resource.tuple.values_at(*record.header.keys) # TODO: Name the key field(s) missing. raise ArgumentError, "#{record} resource has incomplete key: #{resource.inspect}" \ unless keys.select(&:nil?).empty? if result = execute(command_delete(record), *keys) resource.freeze end result end resources.kind_of?(Array) ? result : result.first end
ruby
def delete record, resources result = [resources].flatten.map do |resource| resource = record.new(resource) unless resource.kind_of?(record) keys = resource.tuple.values_at(*record.header.keys) # TODO: Name the key field(s) missing. raise ArgumentError, "#{record} resource has incomplete key: #{resource.inspect}" \ unless keys.select(&:nil?).empty? if result = execute(command_delete(record), *keys) resource.freeze end result end resources.kind_of?(Array) ? result : result.first end
[ "def", "delete", "record", ",", "resources", "result", "=", "[", "resources", "]", ".", "flatten", ".", "map", "do", "|", "resource", "|", "resource", "=", "record", ".", "new", "(", "resource", ")", "unless", "resource", ".", "kind_of?", "(", "record", ")", "keys", "=", "resource", ".", "tuple", ".", "values_at", "(", "record", ".", "header", ".", "keys", ")", "# TODO: Name the key field(s) missing.", "raise", "ArgumentError", ",", "\"#{record} resource has incomplete key: #{resource.inspect}\"", "unless", "keys", ".", "select", "(", ":nil?", ")", ".", "empty?", "if", "result", "=", "execute", "(", "command_delete", "(", "record", ")", ",", "keys", ")", "resource", ".", "freeze", "end", "result", "end", "resources", ".", "kind_of?", "(", "Array", ")", "?", "result", ":", "result", ".", "first", "end" ]
Delete one or more. @example Record. user = Swift.db.create(User, name: 'Apply Arthurton', age: 32) user.name = 'Arthur Appleton' Swift.db.delete(User, user) @example Coerce hash to record. user = Swift.db.create(User, name: 'Apply Arthurton', age: 32) user.name = 'Arthur Appleton' Swif.db.delete(User, user.tuple) @example Multiple resources. apple = Swift.db.create(User, name: 'Apple Arthurton', age: 32) benny = Swift.db.create(User, name: 'Benny Arthurton', age: 30) Swift.db.delete(User, [apple, benny]) @example Coerce multiple resources. apple = Swift.db.create(User, name: 'Apple Arthurton', age: 32) benny = Swift.db.create(User, name: 'Benny Arthurton', age: 30) Swift.db.delete(User, [apple.tuple, benny.tuple]) @param [Swift::Record] record Concrete record subclass to load. @param [Swift::Record, Hash, Array<Swift::Record, Hash>] resources The resources to be deleteed. @return [Swift::Record, Array<Swift::Record>] @note Hashes will be coerced into a Swift::Record resource via Swift::Record#new @note Passing a scalar will result in a scalar. @see Swift::Record#delete
[ "Delete", "one", "or", "more", "." ]
c9488d5594da546958ab9cf3602d69d0ca51b021
https://github.com/shanna/swift/blob/c9488d5594da546958ab9cf3602d69d0ca51b021/lib/swift/adapter.rb#L138-L153
train
shanna/swift
lib/swift/adapter.rb
Swift.Adapter.prepare
def prepare record = nil, command record ? Statement.new(record, command) : db.prepare(command) end
ruby
def prepare record = nil, command record ? Statement.new(record, command) : db.prepare(command) end
[ "def", "prepare", "record", "=", "nil", ",", "command", "record", "?", "Statement", ".", "new", "(", "record", ",", "command", ")", ":", "db", ".", "prepare", "(", "command", ")", "end" ]
Create a server side prepared statement @example finder = Swift.db.prepare(User, "select * from users where id > ?") user = finder.execute(1).first user.id @overload prepare(record, command) @param [Swift::Record] record Concrete record subclass to load. @param [String] command Command to be prepared by the underlying concrete adapter. @overload prepare(command) @param [String] command Command to be prepared by the underlying concrete adapter. @return [Swift::Statement, Swift::DB::Mysql::Statement, Swift::DB::Sqlite3::Statement, ...]
[ "Create", "a", "server", "side", "prepared", "statement" ]
c9488d5594da546958ab9cf3602d69d0ca51b021
https://github.com/shanna/swift/blob/c9488d5594da546958ab9cf3602d69d0ca51b021/lib/swift/adapter.rb#L169-L171
train
shanna/swift
lib/swift/adapter.rb
Swift.Adapter.execute
def execute command, *bind start = Time.now record, command = command, bind.shift if command.kind_of?(Class) && command < Record record ? Result.new(record, db.execute(command, *bind)) : db.execute(command, *bind) ensure log_command(start, command, bind) if @trace end
ruby
def execute command, *bind start = Time.now record, command = command, bind.shift if command.kind_of?(Class) && command < Record record ? Result.new(record, db.execute(command, *bind)) : db.execute(command, *bind) ensure log_command(start, command, bind) if @trace end
[ "def", "execute", "command", ",", "*", "bind", "start", "=", "Time", ".", "now", "record", ",", "command", "=", "command", ",", "bind", ".", "shift", "if", "command", ".", "kind_of?", "(", "Class", ")", "&&", "command", "<", "Record", "record", "?", "Result", ".", "new", "(", "record", ",", "db", ".", "execute", "(", "command", ",", "bind", ")", ")", ":", "db", ".", "execute", "(", "command", ",", "bind", ")", "ensure", "log_command", "(", "start", ",", "command", ",", "bind", ")", "if", "@trace", "end" ]
Execute a command using the underlying concrete adapter. @example Swift.db.execute("select * from users") @example Swift.db.execute(User, "select * from users where id = ?", 1) @overload execute(record, command, *bind) @param [Swift::Record] record Concrete record subclass to load. @param [String] command Command to be executed by the adapter. @param [*Object] bind Bind values. @overload execute(command, *bind) @param [String] command Command to be executed by the adapter. @param [*Object] bind Bind values. @return [Swift::Result, Swift::DB::Mysql::Result, Swift::DB::Sqlite3::Result, ...]
[ "Execute", "a", "command", "using", "the", "underlying", "concrete", "adapter", "." ]
c9488d5594da546958ab9cf3602d69d0ca51b021
https://github.com/shanna/swift/blob/c9488d5594da546958ab9cf3602d69d0ca51b021/lib/swift/adapter.rb#L214-L220
train
fnando/troy
lib/troy/page.rb
Troy.Page.method_missing
def method_missing(name, *args, &block) return meta[name.to_s] if meta.key?(name.to_s) super end
ruby
def method_missing(name, *args, &block) return meta[name.to_s] if meta.key?(name.to_s) super end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "return", "meta", "[", "name", ".", "to_s", "]", "if", "meta", ".", "key?", "(", "name", ".", "to_s", ")", "super", "end" ]
Initialize a new page, which can be simply rendered or persisted to the filesystem.
[ "Initialize", "a", "new", "page", "which", "can", "be", "simply", "rendered", "or", "persisted", "to", "the", "filesystem", "." ]
6940116610abef3490da168c31a19fc26840cb99
https://github.com/fnando/troy/blob/6940116610abef3490da168c31a19fc26840cb99/lib/troy/page.rb#L32-L35
train
fnando/troy
lib/troy/page.rb
Troy.Page.render
def render ExtensionMatcher.new(path) .default { content } .on("html") { compress render_erb } .on("md") { compress render_erb } .on("erb") { compress render_erb } .match end
ruby
def render ExtensionMatcher.new(path) .default { content } .on("html") { compress render_erb } .on("md") { compress render_erb } .on("erb") { compress render_erb } .match end
[ "def", "render", "ExtensionMatcher", ".", "new", "(", "path", ")", ".", "default", "{", "content", "}", ".", "on", "(", "\"html\"", ")", "{", "compress", "render_erb", "}", ".", "on", "(", "\"md\"", ")", "{", "compress", "render_erb", "}", ".", "on", "(", "\"erb\"", ")", "{", "compress", "render_erb", "}", ".", "match", "end" ]
Render the current page.
[ "Render", "the", "current", "page", "." ]
6940116610abef3490da168c31a19fc26840cb99
https://github.com/fnando/troy/blob/6940116610abef3490da168c31a19fc26840cb99/lib/troy/page.rb#L73-L80
train
fnando/troy
lib/troy/page.rb
Troy.Page.save_to
def save_to(path) File.open(path, "w") do |file| I18n.with_locale(meta.locale) do file << render end end end
ruby
def save_to(path) File.open(path, "w") do |file| I18n.with_locale(meta.locale) do file << render end end end
[ "def", "save_to", "(", "path", ")", "File", ".", "open", "(", "path", ",", "\"w\"", ")", "do", "|", "file", "|", "I18n", ".", "with_locale", "(", "meta", ".", "locale", ")", "do", "file", "<<", "render", "end", "end", "end" ]
Save current page to the specified path.
[ "Save", "current", "page", "to", "the", "specified", "path", "." ]
6940116610abef3490da168c31a19fc26840cb99
https://github.com/fnando/troy/blob/6940116610abef3490da168c31a19fc26840cb99/lib/troy/page.rb#L120-L126
train
zeevex/zeevex_threadsafe
lib/zeevex_threadsafe/thread_locals.rb
ZeevexThreadsafe::ThreadLocals.InstanceMethods._thread_local_clean
def _thread_local_clean ids = Thread.list.map &:object_id (@_thread_local_threads.keys - ids).each { |key| @_thread_local_threads.delete(key) } end
ruby
def _thread_local_clean ids = Thread.list.map &:object_id (@_thread_local_threads.keys - ids).each { |key| @_thread_local_threads.delete(key) } end
[ "def", "_thread_local_clean", "ids", "=", "Thread", ".", "list", ".", "map", ":object_id", "(", "@_thread_local_threads", ".", "keys", "-", "ids", ")", ".", "each", "{", "|", "key", "|", "@_thread_local_threads", ".", "delete", "(", "key", ")", "}", "end" ]
remove the thread local maps for threads that are no longer active. likely to be painful if many threads are running. must be called manually; otherwise this object may accumulate lots of garbage if it is used from many different threads.
[ "remove", "the", "thread", "local", "maps", "for", "threads", "that", "are", "no", "longer", "active", ".", "likely", "to", "be", "painful", "if", "many", "threads", "are", "running", "." ]
a486da9094204c8fb9007bf7a4668a17f97a1f22
https://github.com/zeevex/zeevex_threadsafe/blob/a486da9094204c8fb9007bf7a4668a17f97a1f22/lib/zeevex_threadsafe/thread_locals.rb#L38-L41
train
caruby/core
lib/caruby/helpers/properties.rb
CaRuby.Properties.[]=
def []=(key, value) return super if has_key?(key) alt = alternate_key(key) has_key?(alt) ? super(alt, value) : super end
ruby
def []=(key, value) return super if has_key?(key) alt = alternate_key(key) has_key?(alt) ? super(alt, value) : super end
[ "def", "[]=", "(", "key", ",", "value", ")", "return", "super", "if", "has_key?", "(", "key", ")", "alt", "=", "alternate_key", "(", "key", ")", "has_key?", "(", "alt", ")", "?", "super", "(", "alt", ",", "value", ")", ":", "super", "end" ]
Returns the property value for the key. If there is no key entry but there is an alternate key entry, then alternate key entry is set.
[ "Returns", "the", "property", "value", "for", "the", "key", ".", "If", "there", "is", "no", "key", "entry", "but", "there", "is", "an", "alternate", "key", "entry", "then", "alternate", "key", "entry", "is", "set", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/helpers/properties.rb#L47-L51
train
caruby/core
lib/caruby/helpers/properties.rb
CaRuby.Properties.load_properties
def load_properties(file) raise ConfigurationError.new("Properties file not found: #{File.expand_path(file)}") unless File.exists?(file) properties = {} begin YAML.load_file(file).each { |key, value| properties[key.to_sym] = value } rescue raise ConfigurationError.new("Could not read properties file #{file}: " + $!) end # Uncomment the following line to print detail properties. #logger.debug { "#{file} properties:\n#{properties.pp_s}" } # parse comma-delimited string values of array properties into arrays @array_properties.each do |key| value = properties[key] if String === value then properties[key] = value.split(/,\s*/) end end # if the key is a merge property key, then perform a deep merge. # otherwise, do a shallow merge of the property value into this property hash. deep, shallow = properties.split { |key, value| @merge_properties.include?(key) } merge!(deep, :deep) merge!(shallow) end
ruby
def load_properties(file) raise ConfigurationError.new("Properties file not found: #{File.expand_path(file)}") unless File.exists?(file) properties = {} begin YAML.load_file(file).each { |key, value| properties[key.to_sym] = value } rescue raise ConfigurationError.new("Could not read properties file #{file}: " + $!) end # Uncomment the following line to print detail properties. #logger.debug { "#{file} properties:\n#{properties.pp_s}" } # parse comma-delimited string values of array properties into arrays @array_properties.each do |key| value = properties[key] if String === value then properties[key] = value.split(/,\s*/) end end # if the key is a merge property key, then perform a deep merge. # otherwise, do a shallow merge of the property value into this property hash. deep, shallow = properties.split { |key, value| @merge_properties.include?(key) } merge!(deep, :deep) merge!(shallow) end
[ "def", "load_properties", "(", "file", ")", "raise", "ConfigurationError", ".", "new", "(", "\"Properties file not found: #{File.expand_path(file)}\"", ")", "unless", "File", ".", "exists?", "(", "file", ")", "properties", "=", "{", "}", "begin", "YAML", ".", "load_file", "(", "file", ")", ".", "each", "{", "|", "key", ",", "value", "|", "properties", "[", "key", ".", "to_sym", "]", "=", "value", "}", "rescue", "raise", "ConfigurationError", ".", "new", "(", "\"Could not read properties file #{file}: \"", "+", "$!", ")", "end", "# Uncomment the following line to print detail properties.", "#logger.debug { \"#{file} properties:\\n#{properties.pp_s}\" }", "# parse comma-delimited string values of array properties into arrays", "@array_properties", ".", "each", "do", "|", "key", "|", "value", "=", "properties", "[", "key", "]", "if", "String", "===", "value", "then", "properties", "[", "key", "]", "=", "value", ".", "split", "(", "/", "\\s", "/", ")", "end", "end", "# if the key is a merge property key, then perform a deep merge.", "# otherwise, do a shallow merge of the property value into this property hash.", "deep", ",", "shallow", "=", "properties", ".", "split", "{", "|", "key", ",", "value", "|", "@merge_properties", ".", "include?", "(", "key", ")", "}", "merge!", "(", "deep", ",", ":deep", ")", "merge!", "(", "shallow", ")", "end" ]
Loads the specified properties file, replacing any existing properties. If a key is included in this Properties merge_properties array, then the old value for that key will be merged with the new value for that key rather than replaced. This method reloads a property file that has already been loaded. Raises ConfigurationError if file doesn't exist or couldn't be parsed.
[ "Loads", "the", "specified", "properties", "file", "replacing", "any", "existing", "properties", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/helpers/properties.rb#L68-L90
train
sugaryourcoffee/syclink
lib/syclink/infrastructure.rb
SycLink.Infrastructure.copy_file_if_missing
def copy_file_if_missing(file, to_directory) unless File.exists? File.join(to_directory, File.basename(file)) FileUtils.cp(file, to_directory) end end
ruby
def copy_file_if_missing(file, to_directory) unless File.exists? File.join(to_directory, File.basename(file)) FileUtils.cp(file, to_directory) end end
[ "def", "copy_file_if_missing", "(", "file", ",", "to_directory", ")", "unless", "File", ".", "exists?", "File", ".", "join", "(", "to_directory", ",", "File", ".", "basename", "(", "file", ")", ")", "FileUtils", ".", "cp", "(", "file", ",", "to_directory", ")", "end", "end" ]
Copies a file to a target directory
[ "Copies", "a", "file", "to", "a", "target", "directory" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/infrastructure.rb#L15-L19
train
sugaryourcoffee/syclink
lib/syclink/infrastructure.rb
SycLink.Infrastructure.load_config
def load_config(file) unless File.exists? file File.open(file, 'w') do |f| YAML.dump({ default_website: 'default' }, f) end end YAML.load_file(file) end
ruby
def load_config(file) unless File.exists? file File.open(file, 'w') do |f| YAML.dump({ default_website: 'default' }, f) end end YAML.load_file(file) end
[ "def", "load_config", "(", "file", ")", "unless", "File", ".", "exists?", "file", "File", ".", "open", "(", "file", ",", "'w'", ")", "do", "|", "f", "|", "YAML", ".", "dump", "(", "{", "default_website", ":", "'default'", "}", ",", "f", ")", "end", "end", "YAML", ".", "load_file", "(", "file", ")", "end" ]
Loads the configuration from a file
[ "Loads", "the", "configuration", "from", "a", "file" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/infrastructure.rb#L22-L29
train
stevedowney/rails_view_helpers
app/helpers/rails_view_helpers/datetime_helper.rb
RailsViewHelpers.DatetimeHelper.datetime_to_s
def datetime_to_s(date_or_datetime, format) return '' if date_or_datetime.blank? return date_or_datetime.to_s(format) if date_or_datetime.instance_of?(Date) date_or_datetime.localtime.to_s(format) end
ruby
def datetime_to_s(date_or_datetime, format) return '' if date_or_datetime.blank? return date_or_datetime.to_s(format) if date_or_datetime.instance_of?(Date) date_or_datetime.localtime.to_s(format) end
[ "def", "datetime_to_s", "(", "date_or_datetime", ",", "format", ")", "return", "''", "if", "date_or_datetime", ".", "blank?", "return", "date_or_datetime", ".", "to_s", "(", "format", ")", "if", "date_or_datetime", ".", "instance_of?", "(", "Date", ")", "date_or_datetime", ".", "localtime", ".", "to_s", "(", "format", ")", "end" ]
Return _date_or_datetime_ converted to _format_. Reminder: * you can add formats (e.g. in an initializer) * this gem has monkey-patched +NilClass+ so you can just do this: +datetime.to_s(:short)+ without worrying if +datetime+ is +nil+. @example datetime_to_s(record.created_at, :long) datetime_to_s(Date.today, :short) @param date_or_datetime [Date, Datetime] the date/time to convert to string @param format [Symbol] one of +Date::DATE_FORMATS+ or +Time::DATE_FORMATS+ @return [String]
[ "Return", "_date_or_datetime_", "converted", "to", "_format_", "." ]
715c7daca9434c763b777be25b1069ecc50df287
https://github.com/stevedowney/rails_view_helpers/blob/715c7daca9434c763b777be25b1069ecc50df287/app/helpers/rails_view_helpers/datetime_helper.rb#L19-L23
train
pwnall/authpwn_rails
lib/authpwn_rails/http_token.rb
Authpwn.HttpTokenControllerInstanceMethods.authenticate_using_http_token
def authenticate_using_http_token return if current_user authenticate_with_http_token do |token_code, options| auth = Tokens::Api.authenticate token_code # NOTE: Setting the instance variable directly bypasses the session # setup. Tokens are generally used in API contexts, so the session # cookie would get ignored anyway. @current_user = auth unless auth.kind_of? Symbol end end
ruby
def authenticate_using_http_token return if current_user authenticate_with_http_token do |token_code, options| auth = Tokens::Api.authenticate token_code # NOTE: Setting the instance variable directly bypasses the session # setup. Tokens are generally used in API contexts, so the session # cookie would get ignored anyway. @current_user = auth unless auth.kind_of? Symbol end end
[ "def", "authenticate_using_http_token", "return", "if", "current_user", "authenticate_with_http_token", "do", "|", "token_code", ",", "options", "|", "auth", "=", "Tokens", "::", "Api", ".", "authenticate", "token_code", "# NOTE: Setting the instance variable directly bypasses the session", "# setup. Tokens are generally used in API contexts, so the session", "# cookie would get ignored anyway.", "@current_user", "=", "auth", "unless", "auth", ".", "kind_of?", "Symbol", "end", "end" ]
The before_action that implements authenticates_using_http_token. If your ApplicationController contains authenticates_using_http_token, you can opt out in individual controllers using skip_before_action. skip_before_action :authenticate_using_http_token
[ "The", "before_action", "that", "implements", "authenticates_using_http_token", "." ]
de3bd612a00025e8dc8296a73abe3acba948db17
https://github.com/pwnall/authpwn_rails/blob/de3bd612a00025e8dc8296a73abe3acba948db17/lib/authpwn_rails/http_token.rb#L29-L39
train
pione/ruby-xes
lib/xes/document.rb
XES.Document.format
def format raise FormatError.new(self) unless formattable? REXML::Document.new.tap do |doc| doc << REXML::XMLDecl.new doc.elements << @log.format end end
ruby
def format raise FormatError.new(self) unless formattable? REXML::Document.new.tap do |doc| doc << REXML::XMLDecl.new doc.elements << @log.format end end
[ "def", "format", "raise", "FormatError", ".", "new", "(", "self", ")", "unless", "formattable?", "REXML", "::", "Document", ".", "new", ".", "tap", "do", "|", "doc", "|", "doc", "<<", "REXML", "::", "XMLDecl", ".", "new", "doc", ".", "elements", "<<", "@log", ".", "format", "end", "end" ]
Format as a XML document. @return [REXML::Document] XML document @raise FormatError format error when the document is not formattable
[ "Format", "as", "a", "XML", "document", "." ]
61501a8fd8027708f670264a150b1ce74fdccd74
https://github.com/pione/ruby-xes/blob/61501a8fd8027708f670264a150b1ce74fdccd74/lib/xes/document.rb#L27-L34
train
kgnzt/polyseerio-ruby
lib/request.rb
Polyseerio.Request.execute
def execute(method, *args) new_args = args @pre_request.each do |middleware| new_args = middleware.call(*new_args) end path = new_args.empty? ? '' : new_args.shift req = proc do || @resource[path].send(method, *new_args) end post = proc do |result| @post_request.each do |middleware| result = middleware.call(result) end result end Concurrent::Promise.new(&req).on_success(&post) end
ruby
def execute(method, *args) new_args = args @pre_request.each do |middleware| new_args = middleware.call(*new_args) end path = new_args.empty? ? '' : new_args.shift req = proc do || @resource[path].send(method, *new_args) end post = proc do |result| @post_request.each do |middleware| result = middleware.call(result) end result end Concurrent::Promise.new(&req).on_success(&post) end
[ "def", "execute", "(", "method", ",", "*", "args", ")", "new_args", "=", "args", "@pre_request", ".", "each", "do", "|", "middleware", "|", "new_args", "=", "middleware", ".", "call", "(", "new_args", ")", "end", "path", "=", "new_args", ".", "empty?", "?", "''", ":", "new_args", ".", "shift", "req", "=", "proc", "do", "|", "|", "@resource", "[", "path", "]", ".", "send", "(", "method", ",", "new_args", ")", "end", "post", "=", "proc", "do", "|", "result", "|", "@post_request", ".", "each", "do", "|", "middleware", "|", "result", "=", "middleware", ".", "call", "(", "result", ")", "end", "result", "end", "Concurrent", "::", "Promise", ".", "new", "(", "req", ")", ".", "on_success", "(", "post", ")", "end" ]
Execute a request using pre, post, and reject middleware. method - The HTTP method. ... - Arguments to forward to execute. Returns a promise.
[ "Execute", "a", "request", "using", "pre", "post", "and", "reject", "middleware", "." ]
ec2d87ce0056692b74e26a85ca5a66f21c599152
https://github.com/kgnzt/polyseerio-ruby/blob/ec2d87ce0056692b74e26a85ca5a66f21c599152/lib/request.rb#L58-L80
train
gotqn/thumbnail_hover_effect
lib/thumbnail_hover_effect/image.rb
ThumbnailHoverEffect.Image.render
def render(parameters = {}) has_thumbnail = parameters.fetch(:has_thumbnail, true) effect_number = parameters.fetch(:effect_number, false) thumbnail_template = self.get_template(effect_number) if has_thumbnail @attributes.map { |key, value| thumbnail_template["###{key}##"] &&= value } thumbnail_template.gsub!('##url##', @url).html_safe else self.to_s.html_safe end end
ruby
def render(parameters = {}) has_thumbnail = parameters.fetch(:has_thumbnail, true) effect_number = parameters.fetch(:effect_number, false) thumbnail_template = self.get_template(effect_number) if has_thumbnail @attributes.map { |key, value| thumbnail_template["###{key}##"] &&= value } thumbnail_template.gsub!('##url##', @url).html_safe else self.to_s.html_safe end end
[ "def", "render", "(", "parameters", "=", "{", "}", ")", "has_thumbnail", "=", "parameters", ".", "fetch", "(", ":has_thumbnail", ",", "true", ")", "effect_number", "=", "parameters", ".", "fetch", "(", ":effect_number", ",", "false", ")", "thumbnail_template", "=", "self", ".", "get_template", "(", "effect_number", ")", "if", "has_thumbnail", "@attributes", ".", "map", "{", "|", "key", ",", "value", "|", "thumbnail_template", "[", "\"###{key}##\"", "]", "&&=", "value", "}", "thumbnail_template", ".", "gsub!", "(", "'##url##'", ",", "@url", ")", ".", "html_safe", "else", "self", ".", "to_s", ".", "html_safe", "end", "end" ]
rendering image with thumbnail effect applied
[ "rendering", "image", "with", "thumbnail", "effect", "applied" ]
29588d7b31927710a8a79564ea7913bb4b14beb1
https://github.com/gotqn/thumbnail_hover_effect/blob/29588d7b31927710a8a79564ea7913bb4b14beb1/lib/thumbnail_hover_effect/image.rb#L37-L50
train
mudasobwa/itudes
lib/itudes.rb
Geo.Itudes.distance
def distance other, units = :km o = Itudes.new other raise ArgumentError.new "operand must be lat-/longitudable" if (o.latitude.nil? || o.longitude.nil?) dlat = Itudes.radians(o.latitude - @latitude) dlon = Itudes.radians(o.longitude - @longitude) lat1 = Itudes.radians(@latitude) lat2 = Itudes.radians(o.latitude); a = Math::sin(dlat/2)**2 + Math::sin(dlon/2)**2 * Math::cos(lat1) * Math::cos(lat2) (RADIUS[units] * 2.0 * Math::atan2(Math.sqrt(a), Math.sqrt(1-a))).abs end
ruby
def distance other, units = :km o = Itudes.new other raise ArgumentError.new "operand must be lat-/longitudable" if (o.latitude.nil? || o.longitude.nil?) dlat = Itudes.radians(o.latitude - @latitude) dlon = Itudes.radians(o.longitude - @longitude) lat1 = Itudes.radians(@latitude) lat2 = Itudes.radians(o.latitude); a = Math::sin(dlat/2)**2 + Math::sin(dlon/2)**2 * Math::cos(lat1) * Math::cos(lat2) (RADIUS[units] * 2.0 * Math::atan2(Math.sqrt(a), Math.sqrt(1-a))).abs end
[ "def", "distance", "other", ",", "units", "=", ":km", "o", "=", "Itudes", ".", "new", "other", "raise", "ArgumentError", ".", "new", "\"operand must be lat-/longitudable\"", "if", "(", "o", ".", "latitude", ".", "nil?", "||", "o", ".", "longitude", ".", "nil?", ")", "dlat", "=", "Itudes", ".", "radians", "(", "o", ".", "latitude", "-", "@latitude", ")", "dlon", "=", "Itudes", ".", "radians", "(", "o", ".", "longitude", "-", "@longitude", ")", "lat1", "=", "Itudes", ".", "radians", "(", "@latitude", ")", "lat2", "=", "Itudes", ".", "radians", "(", "o", ".", "latitude", ")", ";", "a", "=", "Math", "::", "sin", "(", "dlat", "/", "2", ")", "**", "2", "+", "Math", "::", "sin", "(", "dlon", "/", "2", ")", "**", "2", "*", "Math", "::", "cos", "(", "lat1", ")", "*", "Math", "::", "cos", "(", "lat2", ")", "(", "RADIUS", "[", "units", "]", "*", "2.0", "*", "Math", "::", "atan2", "(", "Math", ".", "sqrt", "(", "a", ")", ",", "Math", ".", "sqrt", "(", "1", "-", "a", ")", ")", ")", ".", "abs", "end" ]
Calculates distance between two points on the Earth. @param other the place on the Earth to calculate distance to @return [Float] the distance between two places on the Earth
[ "Calculates", "distance", "between", "two", "points", "on", "the", "Earth", "." ]
047d976e6cae0e01cde41217fab910cd3ad75ac6
https://github.com/mudasobwa/itudes/blob/047d976e6cae0e01cde41217fab910cd3ad75ac6/lib/itudes.rb#L94-L105
train
checkdin/checkdin-ruby
lib/checkdin/promotions.rb
Checkdin.Promotions.promotions
def promotions(options={}) response = connection.get do |req| req.url "promotions", options end return_error_or_body(response) end
ruby
def promotions(options={}) response = connection.get do |req| req.url "promotions", options end return_error_or_body(response) end
[ "def", "promotions", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"promotions\"", ",", "options", "end", "return_error_or_body", "(", "response", ")", "end" ]
Get a list of all promotions for the authenticating client. @param [Hash] options @option options Integer :campaign_id - Only return promotions for this campaign. @option options String :active - Return either active or inactive promotions, use true or false value. @option options Integer :limit - The maximum number of records to return.
[ "Get", "a", "list", "of", "all", "promotions", "for", "the", "authenticating", "client", "." ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/promotions.rb#L20-L25
train
checkdin/checkdin-ruby
lib/checkdin/promotions.rb
Checkdin.Promotions.promotion_votes_leaderboard
def promotion_votes_leaderboard(id, options={}) response = connection.get do |req| req.url "promotions/#{id}/votes_leaderboard", options end return_error_or_body(response) end
ruby
def promotion_votes_leaderboard(id, options={}) response = connection.get do |req| req.url "promotions/#{id}/votes_leaderboard", options end return_error_or_body(response) end
[ "def", "promotion_votes_leaderboard", "(", "id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"promotions/#{id}/votes_leaderboard\"", ",", "options", "end", "return_error_or_body", "(", "response", ")", "end" ]
Get a list of activities for a promotion ordered by the number of votes they have received param [Integer] id The ID of the promotion @param [Hash] options @option options Integer :limit - The maximum number of records to return. @option options Integer :page - The page of results to return.
[ "Get", "a", "list", "of", "activities", "for", "a", "promotion", "ordered", "by", "the", "number", "of", "votes", "they", "have", "received" ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/promotions.rb#L34-L39
train
elifoster/fishbans-rb
lib/player_skins.rb
Fishbans.PlayerSkins.get_player_image
def get_player_image(username, type, size) url = "http://i.fishbans.com/#{type}/#{username}/#{size}" response = get(url, false) ChunkyPNG::Image.from_blob(response.body) end
ruby
def get_player_image(username, type, size) url = "http://i.fishbans.com/#{type}/#{username}/#{size}" response = get(url, false) ChunkyPNG::Image.from_blob(response.body) end
[ "def", "get_player_image", "(", "username", ",", "type", ",", "size", ")", "url", "=", "\"http://i.fishbans.com/#{type}/#{username}/#{size}\"", "response", "=", "get", "(", "url", ",", "false", ")", "ChunkyPNG", "::", "Image", ".", "from_blob", "(", "response", ".", "body", ")", "end" ]
Gets the player image for the type. @param username [String] See #get_player_head. @param type [String] The type of image to get. Can be 'helm', 'player', or 'skin' as defined by the Fishbans Player Skins API. @param size [Integer] See #get_player_head. @return [ChunkyPNG::Image] The ChunkyPNG::Image instance for the params. @raise see #get
[ "Gets", "the", "player", "image", "for", "the", "type", "." ]
652016694176ade8767ac6a3b4dea2dc631be747
https://github.com/elifoster/fishbans-rb/blob/652016694176ade8767ac6a3b4dea2dc631be747/lib/player_skins.rb#L42-L46
train
jstumbaugh/copy_csv
lib/copy_csv.rb
CopyCsv.ClassMethods.write_to_csv
def write_to_csv(file_name, mode = "w") File.open(file_name, mode) do |file| all.copy_csv(file) end end
ruby
def write_to_csv(file_name, mode = "w") File.open(file_name, mode) do |file| all.copy_csv(file) end end
[ "def", "write_to_csv", "(", "file_name", ",", "mode", "=", "\"w\"", ")", "File", ".", "open", "(", "file_name", ",", "mode", ")", "do", "|", "file", "|", "all", ".", "copy_csv", "(", "file", ")", "end", "end" ]
Opens the file provided and writes the relation to it as a CSV. Example User.where(unsubscribed: false).write_to_csv("unsubscribed_users.csv") Returns nil
[ "Opens", "the", "file", "provided", "and", "writes", "the", "relation", "to", "it", "as", "a", "CSV", "." ]
3e3ec08715bd00784be3f0b17e88dd7a841de70c
https://github.com/jstumbaugh/copy_csv/blob/3e3ec08715bd00784be3f0b17e88dd7a841de70c/lib/copy_csv.rb#L41-L45
train
starpeak/gricer
app/controllers/gricer/base_controller.rb
Gricer.BaseController.process_stats
def process_stats @items = basic_collection handle_special_fields data = { alternatives: [ { type: 'spread', uri: url_for(action: "spread_stats", field: params[:field], filters: params[:filters], only_path: true) }, { type: 'process' } ], from: @stat_from.to_time.utc.to_i * 1000, thru: @stat_thru.to_time.utc.to_i * 1000, step: @stat_step.to_i * 1000, data: @items.stat(params[:field], @stat_from, @stat_thru, @stat_step) } if further_details.keys.include? params[:field] filters = (params[:filters] || {}) filters[params[:field]] = '%{self}' data[:detail_uri] = url_for(action: "process_stats", field: further_details[params[:field]], filters: filters, only_path: true) end render json: data end
ruby
def process_stats @items = basic_collection handle_special_fields data = { alternatives: [ { type: 'spread', uri: url_for(action: "spread_stats", field: params[:field], filters: params[:filters], only_path: true) }, { type: 'process' } ], from: @stat_from.to_time.utc.to_i * 1000, thru: @stat_thru.to_time.utc.to_i * 1000, step: @stat_step.to_i * 1000, data: @items.stat(params[:field], @stat_from, @stat_thru, @stat_step) } if further_details.keys.include? params[:field] filters = (params[:filters] || {}) filters[params[:field]] = '%{self}' data[:detail_uri] = url_for(action: "process_stats", field: further_details[params[:field]], filters: filters, only_path: true) end render json: data end
[ "def", "process_stats", "@items", "=", "basic_collection", "handle_special_fields", "data", "=", "{", "alternatives", ":", "[", "{", "type", ":", "'spread'", ",", "uri", ":", "url_for", "(", "action", ":", "\"spread_stats\"", ",", "field", ":", "params", "[", ":field", "]", ",", "filters", ":", "params", "[", ":filters", "]", ",", "only_path", ":", "true", ")", "}", ",", "{", "type", ":", "'process'", "}", "]", ",", "from", ":", "@stat_from", ".", "to_time", ".", "utc", ".", "to_i", "*", "1000", ",", "thru", ":", "@stat_thru", ".", "to_time", ".", "utc", ".", "to_i", "*", "1000", ",", "step", ":", "@stat_step", ".", "to_i", "*", "1000", ",", "data", ":", "@items", ".", "stat", "(", "params", "[", ":field", "]", ",", "@stat_from", ",", "@stat_thru", ",", "@stat_step", ")", "}", "if", "further_details", ".", "keys", ".", "include?", "params", "[", ":field", "]", "filters", "=", "(", "params", "[", ":filters", "]", "||", "{", "}", ")", "filters", "[", "params", "[", ":field", "]", "]", "=", "'%{self}'", "data", "[", ":detail_uri", "]", "=", "url_for", "(", "action", ":", "\"process_stats\"", ",", "field", ":", "further_details", "[", "params", "[", ":field", "]", "]", ",", "filters", ":", "filters", ",", "only_path", ":", "true", ")", "end", "render", "json", ":", "data", "end" ]
This action generates a JSON for a process statistics.
[ "This", "action", "generates", "a", "JSON", "for", "a", "process", "statistics", "." ]
46bb77bd4fc7074ce294d0310ad459fef068f507
https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/app/controllers/gricer/base_controller.rb#L12-L41
train
starpeak/gricer
app/controllers/gricer/base_controller.rb
Gricer.BaseController.spread_stats
def spread_stats @items = basic_collection.between_dates(@stat_from, @stat_thru) handle_special_fields data = { alternatives: [ { type: 'spread' }, { type: 'process', uri: url_for(action: "process_stats", field: params[:field], filters: params[:filters], only_path: true) } ], from: @stat_from.to_time.utc.to_i * 1000, thru: @stat_thru.to_time.utc.to_i * 1000, total: @items.count(:id), data: @items.count_by(params[:field]) } if further_details.keys.include? params[:field] filters = (params[:filters] || {}) filters[params[:field]] = '%{self}' data[:detail_uri] = url_for(action: "spread_stats", field: further_details[params[:field]], filters: filters, only_path: true) end render json: data end
ruby
def spread_stats @items = basic_collection.between_dates(@stat_from, @stat_thru) handle_special_fields data = { alternatives: [ { type: 'spread' }, { type: 'process', uri: url_for(action: "process_stats", field: params[:field], filters: params[:filters], only_path: true) } ], from: @stat_from.to_time.utc.to_i * 1000, thru: @stat_thru.to_time.utc.to_i * 1000, total: @items.count(:id), data: @items.count_by(params[:field]) } if further_details.keys.include? params[:field] filters = (params[:filters] || {}) filters[params[:field]] = '%{self}' data[:detail_uri] = url_for(action: "spread_stats", field: further_details[params[:field]], filters: filters, only_path: true) end render json: data end
[ "def", "spread_stats", "@items", "=", "basic_collection", ".", "between_dates", "(", "@stat_from", ",", "@stat_thru", ")", "handle_special_fields", "data", "=", "{", "alternatives", ":", "[", "{", "type", ":", "'spread'", "}", ",", "{", "type", ":", "'process'", ",", "uri", ":", "url_for", "(", "action", ":", "\"process_stats\"", ",", "field", ":", "params", "[", ":field", "]", ",", "filters", ":", "params", "[", ":filters", "]", ",", "only_path", ":", "true", ")", "}", "]", ",", "from", ":", "@stat_from", ".", "to_time", ".", "utc", ".", "to_i", "*", "1000", ",", "thru", ":", "@stat_thru", ".", "to_time", ".", "utc", ".", "to_i", "*", "1000", ",", "total", ":", "@items", ".", "count", "(", ":id", ")", ",", "data", ":", "@items", ".", "count_by", "(", "params", "[", ":field", "]", ")", "}", "if", "further_details", ".", "keys", ".", "include?", "params", "[", ":field", "]", "filters", "=", "(", "params", "[", ":filters", "]", "||", "{", "}", ")", "filters", "[", "params", "[", ":field", "]", "]", "=", "'%{self}'", "data", "[", ":detail_uri", "]", "=", "url_for", "(", "action", ":", "\"spread_stats\"", ",", "field", ":", "further_details", "[", "params", "[", ":field", "]", "]", ",", "filters", ":", "filters", ",", "only_path", ":", "true", ")", "end", "render", "json", ":", "data", "end" ]
This action generates a JSON for a spread statistics.
[ "This", "action", "generates", "a", "JSON", "for", "a", "spread", "statistics", "." ]
46bb77bd4fc7074ce294d0310ad459fef068f507
https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/app/controllers/gricer/base_controller.rb#L44-L73
train
starpeak/gricer
app/controllers/gricer/base_controller.rb
Gricer.BaseController.guess_from_thru
def guess_from_thru begin @stat_thru = Time.parse(params[:thru]).to_date rescue end begin @stat_from = Time.parse(params[:from]).to_date rescue end if @stat_from.nil? if @stat_thru.nil? @stat_thru = Time.now.localtime.to_date - 1.day end @stat_from = @stat_thru - 1.week + 1.day else if @stat_thru.nil? @stat_thru = @stat_from + 1.week - 1.day end end @stat_step = 1.day duration = @stat_thru - @stat_from if duration < 90 @stat_step = 12.hours end if duration < 30 @stat_step = 6.hour end if duration < 10 @stat_step = 1.hour end #if @stat_thru - @stat_from > 12.month # @stat_step = 4.week #end end
ruby
def guess_from_thru begin @stat_thru = Time.parse(params[:thru]).to_date rescue end begin @stat_from = Time.parse(params[:from]).to_date rescue end if @stat_from.nil? if @stat_thru.nil? @stat_thru = Time.now.localtime.to_date - 1.day end @stat_from = @stat_thru - 1.week + 1.day else if @stat_thru.nil? @stat_thru = @stat_from + 1.week - 1.day end end @stat_step = 1.day duration = @stat_thru - @stat_from if duration < 90 @stat_step = 12.hours end if duration < 30 @stat_step = 6.hour end if duration < 10 @stat_step = 1.hour end #if @stat_thru - @stat_from > 12.month # @stat_step = 4.week #end end
[ "def", "guess_from_thru", "begin", "@stat_thru", "=", "Time", ".", "parse", "(", "params", "[", ":thru", "]", ")", ".", "to_date", "rescue", "end", "begin", "@stat_from", "=", "Time", ".", "parse", "(", "params", "[", ":from", "]", ")", ".", "to_date", "rescue", "end", "if", "@stat_from", ".", "nil?", "if", "@stat_thru", ".", "nil?", "@stat_thru", "=", "Time", ".", "now", ".", "localtime", ".", "to_date", "-", "1", ".", "day", "end", "@stat_from", "=", "@stat_thru", "-", "1", ".", "week", "+", "1", ".", "day", "else", "if", "@stat_thru", ".", "nil?", "@stat_thru", "=", "@stat_from", "+", "1", ".", "week", "-", "1", ".", "day", "end", "end", "@stat_step", "=", "1", ".", "day", "duration", "=", "@stat_thru", "-", "@stat_from", "if", "duration", "<", "90", "@stat_step", "=", "12", ".", "hours", "end", "if", "duration", "<", "30", "@stat_step", "=", "6", ".", "hour", "end", "if", "duration", "<", "10", "@stat_step", "=", "1", ".", "hour", "end", "#if @stat_thru - @stat_from > 12.month", "# @stat_step = 4.week", "#end", "end" ]
Guess for which time range to display statistics
[ "Guess", "for", "which", "time", "range", "to", "display", "statistics" ]
46bb77bd4fc7074ce294d0310ad459fef068f507
https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/app/controllers/gricer/base_controller.rb#L98-L139
train
mntnorv/puttext
lib/puttext/po_file.rb
PutText.POFile.write_to
def write_to(io) deduplicate io.write(@header_entry.to_s) @entries.each do |entry| io.write("\n") io.write(entry.to_s) end end
ruby
def write_to(io) deduplicate io.write(@header_entry.to_s) @entries.each do |entry| io.write("\n") io.write(entry.to_s) end end
[ "def", "write_to", "(", "io", ")", "deduplicate", "io", ".", "write", "(", "@header_entry", ".", "to_s", ")", "@entries", ".", "each", "do", "|", "entry", "|", "io", ".", "write", "(", "\"\\n\"", ")", "io", ".", "write", "(", "entry", ".", "to_s", ")", "end", "end" ]
Write the contents of this file to the specified IO object. @param [IO] io the IO object to write the contents of the file to.
[ "Write", "the", "contents", "of", "this", "file", "to", "the", "specified", "IO", "object", "." ]
c5c210dff4e11f714418b6b426dc9e2739fe9876
https://github.com/mntnorv/puttext/blob/c5c210dff4e11f714418b6b426dc9e2739fe9876/lib/puttext/po_file.rb#L34-L43
train
caruby/core
lib/caruby/database/cache.rb
CaRuby.Cache.clear
def clear if @sticky.empty? then @ckh.clear else @ckh.each { |klass, ch| ch.clear unless @sticky.include?(klass) } end end
ruby
def clear if @sticky.empty? then @ckh.clear else @ckh.each { |klass, ch| ch.clear unless @sticky.include?(klass) } end end
[ "def", "clear", "if", "@sticky", ".", "empty?", "then", "@ckh", ".", "clear", "else", "@ckh", ".", "each", "{", "|", "klass", ",", "ch", "|", "ch", ".", "clear", "unless", "@sticky", ".", "include?", "(", "klass", ")", "}", "end", "end" ]
Clears the non-sticky class caches.
[ "Clears", "the", "non", "-", "sticky", "class", "caches", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/cache.rb#L63-L69
train
hackersrc/hs-cli
lib/hs/models/chapter.rb
HS.Chapter.find_module
def find_module(slug) modules.find { |m| m.slug.to_s == slug.to_s } end
ruby
def find_module(slug) modules.find { |m| m.slug.to_s == slug.to_s } end
[ "def", "find_module", "(", "slug", ")", "modules", ".", "find", "{", "|", "m", "|", "m", ".", "slug", ".", "to_s", "==", "slug", ".", "to_s", "}", "end" ]
Tries to find module in this chapter by module slug.
[ "Tries", "to", "find", "module", "in", "this", "chapter", "by", "module", "slug", "." ]
018367cab5e8d324f2097e79faaf71819390eccc
https://github.com/hackersrc/hs-cli/blob/018367cab5e8d324f2097e79faaf71819390eccc/lib/hs/models/chapter.rb#L37-L39
train
ithouse/lolita-paypal
app/controllers/lolita_paypal/transactions_controller.rb
LolitaPaypal.TransactionsController.answer
def answer if request.post? if ipn_notify.acknowledge LolitaPaypal::Transaction.create_transaction(ipn_notify, payment_from_ipn, request) end render nothing: true else if payment_from_ipn redirect_to payment_from_ipn.paypal_return_path else render text: I18n.t('lolita_paypal.wrong_request'), status: 400 end end ensure LolitaPaypal.logger.info("[#{session_id}][#{payment_from_ipn && payment_from_ipn.id}][answer] #{params}") end
ruby
def answer if request.post? if ipn_notify.acknowledge LolitaPaypal::Transaction.create_transaction(ipn_notify, payment_from_ipn, request) end render nothing: true else if payment_from_ipn redirect_to payment_from_ipn.paypal_return_path else render text: I18n.t('lolita_paypal.wrong_request'), status: 400 end end ensure LolitaPaypal.logger.info("[#{session_id}][#{payment_from_ipn && payment_from_ipn.id}][answer] #{params}") end
[ "def", "answer", "if", "request", ".", "post?", "if", "ipn_notify", ".", "acknowledge", "LolitaPaypal", "::", "Transaction", ".", "create_transaction", "(", "ipn_notify", ",", "payment_from_ipn", ",", "request", ")", "end", "render", "nothing", ":", "true", "else", "if", "payment_from_ipn", "redirect_to", "payment_from_ipn", ".", "paypal_return_path", "else", "render", "text", ":", "I18n", ".", "t", "(", "'lolita_paypal.wrong_request'", ")", ",", "status", ":", "400", "end", "end", "ensure", "LolitaPaypal", ".", "logger", ".", "info", "(", "\"[#{session_id}][#{payment_from_ipn && payment_from_ipn.id}][answer] #{params}\"", ")", "end" ]
process ipn request POST is sent from paypal and will create transaction GET is a redirect from paypal and will redirect back to return_path
[ "process", "ipn", "request", "POST", "is", "sent", "from", "paypal", "and", "will", "create", "transaction", "GET", "is", "a", "redirect", "from", "paypal", "and", "will", "redirect", "back", "to", "return_path" ]
f18d0995aaec58a144e39d073bf32bdd2c1cb4b1
https://github.com/ithouse/lolita-paypal/blob/f18d0995aaec58a144e39d073bf32bdd2c1cb4b1/app/controllers/lolita_paypal/transactions_controller.rb#L20-L35
train
ithouse/lolita-paypal
app/controllers/lolita_paypal/transactions_controller.rb
LolitaPaypal.TransactionsController.set_active_payment
def set_active_payment @payment ||= session[:payment_data][:billing_class].constantize.find(session[:payment_data][:billing_id]) rescue render text: I18n.t('lolita_paypal.wrong_request'), status: 400 end
ruby
def set_active_payment @payment ||= session[:payment_data][:billing_class].constantize.find(session[:payment_data][:billing_id]) rescue render text: I18n.t('lolita_paypal.wrong_request'), status: 400 end
[ "def", "set_active_payment", "@payment", "||=", "session", "[", ":payment_data", "]", "[", ":billing_class", "]", ".", "constantize", ".", "find", "(", "session", "[", ":payment_data", "]", "[", ":billing_id", "]", ")", "rescue", "render", "text", ":", "I18n", ".", "t", "(", "'lolita_paypal.wrong_request'", ")", ",", "status", ":", "400", "end" ]
returns current payment instance from session
[ "returns", "current", "payment", "instance", "from", "session" ]
f18d0995aaec58a144e39d073bf32bdd2c1cb4b1
https://github.com/ithouse/lolita-paypal/blob/f18d0995aaec58a144e39d073bf32bdd2c1cb4b1/app/controllers/lolita_paypal/transactions_controller.rb#L51-L55
train
loveablelobster/DwCR
lib/dwca_content_analyzer/file_contents.rb
DwCAContentAnalyzer.FileContents.headers
def headers(file) Array.new(CSV.open(file, &:readline).size) { |i| i.to_s } end
ruby
def headers(file) Array.new(CSV.open(file, &:readline).size) { |i| i.to_s } end
[ "def", "headers", "(", "file", ")", "Array", ".", "new", "(", "CSV", ".", "open", "(", "file", ",", ":readline", ")", ".", "size", ")", "{", "|", "i", "|", "i", ".", "to_s", "}", "end" ]
reads the first line of the CSV file returns the columns indices as an array
[ "reads", "the", "first", "line", "of", "the", "CSV", "file", "returns", "the", "columns", "indices", "as", "an", "array" ]
093e112337bfb664630a0f164c9d9d7552b1e54c
https://github.com/loveablelobster/DwCR/blob/093e112337bfb664630a0f164c9d9d7552b1e54c/lib/dwca_content_analyzer/file_contents.rb#L33-L35
train
petebrowne/machined
lib/machined/sprocket.rb
Machined.Sprocket.use_all_templates
def use_all_templates Utils.available_templates.each do |ext, template| next if engines(ext) register_engine ext, template end end
ruby
def use_all_templates Utils.available_templates.each do |ext, template| next if engines(ext) register_engine ext, template end end
[ "def", "use_all_templates", "Utils", ".", "available_templates", ".", "each", "do", "|", "ext", ",", "template", "|", "next", "if", "engines", "(", "ext", ")", "register_engine", "ext", ",", "template", "end", "end" ]
Loops through the available Tilt templates and registers them as processor engines for Sprockets. By default, Sprockets cherry picks templates that work for web assets. We need to allow use of Haml, Markdown, etc.
[ "Loops", "through", "the", "available", "Tilt", "templates", "and", "registers", "them", "as", "processor", "engines", "for", "Sprockets", ".", "By", "default", "Sprockets", "cherry", "picks", "templates", "that", "work", "for", "web", "assets", ".", "We", "need", "to", "allow", "use", "of", "Haml", "Markdown", "etc", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/sprocket.rb#L53-L58
train
bogrobotten/fetch
lib/fetch/callbacks.rb
Fetch.Callbacks.run_callbacks_for
def run_callbacks_for(name, args, reverse) callbacks_for(name, reverse).map do |block| run_callback(block, args) end end
ruby
def run_callbacks_for(name, args, reverse) callbacks_for(name, reverse).map do |block| run_callback(block, args) end end
[ "def", "run_callbacks_for", "(", "name", ",", "args", ",", "reverse", ")", "callbacks_for", "(", "name", ",", "reverse", ")", ".", "map", "do", "|", "block", "|", "run_callback", "(", "block", ",", "args", ")", "end", "end" ]
Run specific callbacks. run_callbacks_for(:before_fetch) run_callbacks_for(:progress, 12) # 12 percent done
[ "Run", "specific", "callbacks", "." ]
8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f
https://github.com/bogrobotten/fetch/blob/8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f/lib/fetch/callbacks.rb#L18-L22
train
payout/announcer
lib/announcer/subscription.rb
Announcer.Subscription._determine_path
def _determine_path path = File.expand_path('../..', __FILE__) # Will be something like: # "/path/to/file.rb:47:in `method_name'" non_announcer_caller = caller.find { |c| !c.start_with?(path) } unless non_announcer_caller # This is not expected to occur. raise Errors::SubscriptionError, "Could not find non-Announcer caller" end non_announcer_caller end
ruby
def _determine_path path = File.expand_path('../..', __FILE__) # Will be something like: # "/path/to/file.rb:47:in `method_name'" non_announcer_caller = caller.find { |c| !c.start_with?(path) } unless non_announcer_caller # This is not expected to occur. raise Errors::SubscriptionError, "Could not find non-Announcer caller" end non_announcer_caller end
[ "def", "_determine_path", "path", "=", "File", ".", "expand_path", "(", "'../..'", ",", "__FILE__", ")", "# Will be something like:", "# \"/path/to/file.rb:47:in `method_name'\"", "non_announcer_caller", "=", "caller", ".", "find", "{", "|", "c", "|", "!", "c", ".", "start_with?", "(", "path", ")", "}", "unless", "non_announcer_caller", "# This is not expected to occur.", "raise", "Errors", "::", "SubscriptionError", ",", "\"Could not find non-Announcer caller\"", "end", "non_announcer_caller", "end" ]
Determines the file path of the ruby code defining the subscription. It's important that this is called from within the initializer to get the desired effect.
[ "Determines", "the", "file", "path", "of", "the", "ruby", "code", "defining", "the", "subscription", ".", "It", "s", "important", "that", "this", "is", "called", "from", "within", "the", "initializer", "to", "get", "the", "desired", "effect", "." ]
2281360c368b5c024a00d447c0fc83af5f1b4ee1
https://github.com/payout/announcer/blob/2281360c368b5c024a00d447c0fc83af5f1b4ee1/lib/announcer/subscription.rb#L59-L72
train
payout/announcer
lib/announcer/subscription.rb
Announcer.Subscription._generate_identifier
def _generate_identifier # Cut off everything from the line number onward. That way, the identifier # does not change when the subscription block moves to a different line. index = _path.rindex(/:\d+:/) - 1 path = _path[0..index] raise Errors::SubscriptionError, "Invalid path: #{path}" unless File.exists?(path) Digest::MD5.hexdigest("#{path}:#{event_name}:#{name}").to_sym end
ruby
def _generate_identifier # Cut off everything from the line number onward. That way, the identifier # does not change when the subscription block moves to a different line. index = _path.rindex(/:\d+:/) - 1 path = _path[0..index] raise Errors::SubscriptionError, "Invalid path: #{path}" unless File.exists?(path) Digest::MD5.hexdigest("#{path}:#{event_name}:#{name}").to_sym end
[ "def", "_generate_identifier", "# Cut off everything from the line number onward. That way, the identifier", "# does not change when the subscription block moves to a different line.", "index", "=", "_path", ".", "rindex", "(", "/", "\\d", "/", ")", "-", "1", "path", "=", "_path", "[", "0", "..", "index", "]", "raise", "Errors", "::", "SubscriptionError", ",", "\"Invalid path: #{path}\"", "unless", "File", ".", "exists?", "(", "path", ")", "Digest", "::", "MD5", ".", "hexdigest", "(", "\"#{path}:#{event_name}:#{name}\"", ")", ".", "to_sym", "end" ]
Generates a unique identifier for this subscription which will be used to "serialize" it. The goal here is to generate a identifier that is the same across different processes and servers and that ideally changes infrequently between application versions, but when it does change, it should do so predictably.
[ "Generates", "a", "unique", "identifier", "for", "this", "subscription", "which", "will", "be", "used", "to", "serialize", "it", "." ]
2281360c368b5c024a00d447c0fc83af5f1b4ee1
https://github.com/payout/announcer/blob/2281360c368b5c024a00d447c0fc83af5f1b4ee1/lib/announcer/subscription.rb#L81-L90
train
payout/announcer
lib/announcer/subscription.rb
Announcer.Subscription._evaluate_priority_int
def _evaluate_priority_int(int) raise Errors::InvalidPriorityError, int unless int > 0 && int <= config.max_priority int end
ruby
def _evaluate_priority_int(int) raise Errors::InvalidPriorityError, int unless int > 0 && int <= config.max_priority int end
[ "def", "_evaluate_priority_int", "(", "int", ")", "raise", "Errors", "::", "InvalidPriorityError", ",", "int", "unless", "int", ">", "0", "&&", "int", "<=", "config", ".", "max_priority", "int", "end" ]
Evaluate an integer as a priority.
[ "Evaluate", "an", "integer", "as", "a", "priority", "." ]
2281360c368b5c024a00d447c0fc83af5f1b4ee1
https://github.com/payout/announcer/blob/2281360c368b5c024a00d447c0fc83af5f1b4ee1/lib/announcer/subscription.rb#L137-L140
train
payout/announcer
lib/announcer/subscription.rb
Announcer.Subscription._evaluate_priority_symbol
def _evaluate_priority_symbol(sym) if (priority = _symbol_to_priority(sym)) _evaluate_priority(priority) else raise Errors::InvalidPriorityError, sym.inspect end end
ruby
def _evaluate_priority_symbol(sym) if (priority = _symbol_to_priority(sym)) _evaluate_priority(priority) else raise Errors::InvalidPriorityError, sym.inspect end end
[ "def", "_evaluate_priority_symbol", "(", "sym", ")", "if", "(", "priority", "=", "_symbol_to_priority", "(", "sym", ")", ")", "_evaluate_priority", "(", "priority", ")", "else", "raise", "Errors", "::", "InvalidPriorityError", ",", "sym", ".", "inspect", "end", "end" ]
Evaluate a symbol as a priority.
[ "Evaluate", "a", "symbol", "as", "a", "priority", "." ]
2281360c368b5c024a00d447c0fc83af5f1b4ee1
https://github.com/payout/announcer/blob/2281360c368b5c024a00d447c0fc83af5f1b4ee1/lib/announcer/subscription.rb#L143-L149
train
payout/announcer
lib/announcer/subscription.rb
Announcer.Subscription._evaluate_priority_nil
def _evaluate_priority_nil # Need to specify value explicitly here, otherwise in the call to # _evaluate_priority, the case statement won't recognize it as a Symbol. # That's because when calls Symbol::=== to evaluate a match. priority = config.default_priority if priority _evaluate_priority(priority) else raise Errors::InvalidPriorityError, priority.inspect end end
ruby
def _evaluate_priority_nil # Need to specify value explicitly here, otherwise in the call to # _evaluate_priority, the case statement won't recognize it as a Symbol. # That's because when calls Symbol::=== to evaluate a match. priority = config.default_priority if priority _evaluate_priority(priority) else raise Errors::InvalidPriorityError, priority.inspect end end
[ "def", "_evaluate_priority_nil", "# Need to specify value explicitly here, otherwise in the call to", "# _evaluate_priority, the case statement won't recognize it as a Symbol.", "# That's because when calls Symbol::=== to evaluate a match.", "priority", "=", "config", ".", "default_priority", "if", "priority", "_evaluate_priority", "(", "priority", ")", "else", "raise", "Errors", "::", "InvalidPriorityError", ",", "priority", ".", "inspect", "end", "end" ]
Evaluate nil as a priority.
[ "Evaluate", "nil", "as", "a", "priority", "." ]
2281360c368b5c024a00d447c0fc83af5f1b4ee1
https://github.com/payout/announcer/blob/2281360c368b5c024a00d447c0fc83af5f1b4ee1/lib/announcer/subscription.rb#L152-L163
train
ithouse/lolita-paypal
app/helpers/lolita_paypal/application_helper.rb
LolitaPaypal.ApplicationHelper.encrypt_request
def encrypt_request(payment_request) variables = payment_request.request_variables.reverse_merge({ 'notify_url'=> answer_paypal_url(protocol: 'https') }) LolitaPaypal::Request.encrypt_for_paypal variables ensure LolitaPaypal.logger.info "[#{payment_request.payment_id}] #{variables}" end
ruby
def encrypt_request(payment_request) variables = payment_request.request_variables.reverse_merge({ 'notify_url'=> answer_paypal_url(protocol: 'https') }) LolitaPaypal::Request.encrypt_for_paypal variables ensure LolitaPaypal.logger.info "[#{payment_request.payment_id}] #{variables}" end
[ "def", "encrypt_request", "(", "payment_request", ")", "variables", "=", "payment_request", ".", "request_variables", ".", "reverse_merge", "(", "{", "'notify_url'", "=>", "answer_paypal_url", "(", "protocol", ":", "'https'", ")", "}", ")", "LolitaPaypal", "::", "Request", ".", "encrypt_for_paypal", "variables", "ensure", "LolitaPaypal", ".", "logger", ".", "info", "\"[#{payment_request.payment_id}] #{variables}\"", "end" ]
returns encrypted request variables
[ "returns", "encrypted", "request", "variables" ]
f18d0995aaec58a144e39d073bf32bdd2c1cb4b1
https://github.com/ithouse/lolita-paypal/blob/f18d0995aaec58a144e39d073bf32bdd2c1cb4b1/app/helpers/lolita_paypal/application_helper.rb#L6-L13
train
waka/musako
lib/musako/configuration.rb
Musako.Configuration.read_config_file
def read_config_file c = clone config = YAML.load_file(File.join(DEFAULTS[:source], "config.yml")) unless config.is_a? Hash raise ArgumentError.new("Configuration file: invalid #{file}") end c.merge(config) rescue SystemCallError raise LoadError, "Configuration file: not found #{file}" end
ruby
def read_config_file c = clone config = YAML.load_file(File.join(DEFAULTS[:source], "config.yml")) unless config.is_a? Hash raise ArgumentError.new("Configuration file: invalid #{file}") end c.merge(config) rescue SystemCallError raise LoadError, "Configuration file: not found #{file}" end
[ "def", "read_config_file", "c", "=", "clone", "config", "=", "YAML", ".", "load_file", "(", "File", ".", "join", "(", "DEFAULTS", "[", ":source", "]", ",", "\"config.yml\"", ")", ")", "unless", "config", ".", "is_a?", "Hash", "raise", "ArgumentError", ".", "new", "(", "\"Configuration file: invalid #{file}\"", ")", "end", "c", ".", "merge", "(", "config", ")", "rescue", "SystemCallError", "raise", "LoadError", ",", "\"Configuration file: not found #{file}\"", "end" ]
load YAML file.
[ "load", "YAML", "file", "." ]
895463ae3a24555f019637d3f6ef6763b7b96735
https://github.com/waka/musako/blob/895463ae3a24555f019637d3f6ef6763b7b96735/lib/musako/configuration.rb#L27-L37
train
jarrett/ichiban
lib/ichiban/helpers.rb
Ichiban.Helpers.path_with_slashes
def path_with_slashes(path) path = '/' + path unless path.start_with?('/') path << '/' unless path.end_with?('/') path end
ruby
def path_with_slashes(path) path = '/' + path unless path.start_with?('/') path << '/' unless path.end_with?('/') path end
[ "def", "path_with_slashes", "(", "path", ")", "path", "=", "'/'", "+", "path", "unless", "path", ".", "start_with?", "(", "'/'", ")", "path", "<<", "'/'", "unless", "path", ".", "end_with?", "(", "'/'", ")", "path", "end" ]
Adds leading and trailing slashes if none are present
[ "Adds", "leading", "and", "trailing", "slashes", "if", "none", "are", "present" ]
310f96b0981ea19bf01246995f3732c986915d5b
https://github.com/jarrett/ichiban/blob/310f96b0981ea19bf01246995f3732c986915d5b/lib/ichiban/helpers.rb#L78-L82
train
checkdin/checkdin-ruby
lib/checkdin/votes.rb
Checkdin.Votes.votes
def votes(options={}) response = connection.get do |req| req.url "votes", options end return_error_or_body(response) end
ruby
def votes(options={}) response = connection.get do |req| req.url "votes", options end return_error_or_body(response) end
[ "def", "votes", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"votes\"", ",", "options", "end", "return_error_or_body", "(", "response", ")", "end" ]
Get a list of all votes for the authenticating client. @param [Hash] options @option options Integer :user_id - Only return votes for this user. @option options Integer :limit - The maximum number of records to return.
[ "Get", "a", "list", "of", "all", "votes", "for", "the", "authenticating", "client", "." ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/votes.rb#L10-L15
train
fenton-project/fenton_shell
lib/fenton_shell/client.rb
FentonShell.Client.create
def create(global_options, options) status, body = client_create(global_options, options) if status == 201 save_message('Client': ['created!']) true else save_message(body) false end end
ruby
def create(global_options, options) status, body = client_create(global_options, options) if status == 201 save_message('Client': ['created!']) true else save_message(body) false end end
[ "def", "create", "(", "global_options", ",", "options", ")", "status", ",", "body", "=", "client_create", "(", "global_options", ",", "options", ")", "if", "status", "==", "201", "save_message", "(", "'Client'", ":", "[", "'created!'", "]", ")", "true", "else", "save_message", "(", "body", ")", "false", "end", "end" ]
Creates a new client on fenton server by sending a post request with json from the command line to create the client @param global_options [Hash] global command line options @param options [Hash] json fields to send to fenton server @return [String] success or failure message
[ "Creates", "a", "new", "client", "on", "fenton", "server", "by", "sending", "a", "post", "request", "with", "json", "from", "the", "command", "line", "to", "create", "the", "client" ]
6e1d76186fa7ee7a3be141afad9361e3a3e0ec91
https://github.com/fenton-project/fenton_shell/blob/6e1d76186fa7ee7a3be141afad9361e3a3e0ec91/lib/fenton_shell/client.rb#L15-L25
train
fenton-project/fenton_shell
lib/fenton_shell/client.rb
FentonShell.Client.create_with_organization
def create_with_organization(global_options, options) create(global_options, options) if Organization.new.create(global_options, name: options[:username], key: options[:username]) save_message('Organization': ['created!']) true else save_message('Organization': ['not created!']) false end end
ruby
def create_with_organization(global_options, options) create(global_options, options) if Organization.new.create(global_options, name: options[:username], key: options[:username]) save_message('Organization': ['created!']) true else save_message('Organization': ['not created!']) false end end
[ "def", "create_with_organization", "(", "global_options", ",", "options", ")", "create", "(", "global_options", ",", "options", ")", "if", "Organization", ".", "new", ".", "create", "(", "global_options", ",", "name", ":", "options", "[", ":username", "]", ",", "key", ":", "options", "[", ":username", "]", ")", "save_message", "(", "'Organization'", ":", "[", "'created!'", "]", ")", "true", "else", "save_message", "(", "'Organization'", ":", "[", "'not created!'", "]", ")", "false", "end", "end" ]
Calls create new client then creates an organization for that client via a post request with json from the command line @param global_options [Hash] global command line options @param options [Hash] json fields to send to fenton server @return [String] success or failure message
[ "Calls", "create", "new", "client", "then", "creates", "an", "organization", "for", "that", "client", "via", "a", "post", "request", "with", "json", "from", "the", "command", "line" ]
6e1d76186fa7ee7a3be141afad9361e3a3e0ec91
https://github.com/fenton-project/fenton_shell/blob/6e1d76186fa7ee7a3be141afad9361e3a3e0ec91/lib/fenton_shell/client.rb#L34-L45
train
fenton-project/fenton_shell
lib/fenton_shell/client.rb
FentonShell.Client.client_json
def client_json(options) { client: { username: options[:username], name: options[:name], email: options[:email], public_key: File.read(options[:public_key]) } }.to_json end
ruby
def client_json(options) { client: { username: options[:username], name: options[:name], email: options[:email], public_key: File.read(options[:public_key]) } }.to_json end
[ "def", "client_json", "(", "options", ")", "{", "client", ":", "{", "username", ":", "options", "[", ":username", "]", ",", "name", ":", "options", "[", ":name", "]", ",", "email", ":", "options", "[", ":email", "]", ",", "public_key", ":", "File", ".", "read", "(", "options", "[", ":public_key", "]", ")", "}", "}", ".", "to_json", "end" ]
Formulates the client json for the post request @param options [Hash] fields from fenton command line @return [String] json created from the options hash
[ "Formulates", "the", "client", "json", "for", "the", "post", "request" ]
6e1d76186fa7ee7a3be141afad9361e3a3e0ec91
https://github.com/fenton-project/fenton_shell/blob/6e1d76186fa7ee7a3be141afad9361e3a3e0ec91/lib/fenton_shell/client.rb#L69-L78
train
caruby/scat
lib/scat/authorization.rb
Scat.Authorization.perform!
def perform!(email, password, &block) login_required CaTissue::Database.current.open(email, password, &block) end
ruby
def perform!(email, password, &block) login_required CaTissue::Database.current.open(email, password, &block) end
[ "def", "perform!", "(", "email", ",", "password", ",", "&", "block", ")", "login_required", "CaTissue", "::", "Database", ".", "current", ".", "open", "(", "email", ",", "password", ",", "block", ")", "end" ]
Runs the given caTissue operation block with the given caTissue credentials. @yield (see #protect!) @return [String, nil] the status message
[ "Runs", "the", "given", "caTissue", "operation", "block", "with", "the", "given", "caTissue", "credentials", "." ]
90291b317eb6b8ef8b0a4497622eadc15d3d9028
https://github.com/caruby/scat/blob/90291b317eb6b8ef8b0a4497622eadc15d3d9028/lib/scat/authorization.rb#L70-L73
train
parrish/attention
lib/attention/publisher.rb
Attention.Publisher.publish
def publish(channel, value) redis = Attention.redis.call yield redis if block_given? redis.publish channel, payload_for(value) end
ruby
def publish(channel, value) redis = Attention.redis.call yield redis if block_given? redis.publish channel, payload_for(value) end
[ "def", "publish", "(", "channel", ",", "value", ")", "redis", "=", "Attention", ".", "redis", ".", "call", "yield", "redis", "if", "block_given?", "redis", ".", "publish", "channel", ",", "payload_for", "(", "value", ")", "end" ]
Publishes the value to the channel @param channel [String] The channel to publish to @param value [Object] The value to publish @yield Allows an optional block to use the Redis connection @yieldparam redis [Redis] The Redis connection
[ "Publishes", "the", "value", "to", "the", "channel" ]
ff5bd780b946636ba0e22f66bae3fb41b9c4353d
https://github.com/parrish/attention/blob/ff5bd780b946636ba0e22f66bae3fb41b9c4353d/lib/attention/publisher.rb#L9-L13
train
parrish/attention
lib/attention/publisher.rb
Attention.Publisher.payload_for
def payload_for(value) case value when Array, Hash JSON.dump value else value end rescue value end
ruby
def payload_for(value) case value when Array, Hash JSON.dump value else value end rescue value end
[ "def", "payload_for", "(", "value", ")", "case", "value", "when", "Array", ",", "Hash", "JSON", ".", "dump", "value", "else", "value", "end", "rescue", "value", "end" ]
Converts published values to JSON if possible @api private
[ "Converts", "published", "values", "to", "JSON", "if", "possible" ]
ff5bd780b946636ba0e22f66bae3fb41b9c4353d
https://github.com/parrish/attention/blob/ff5bd780b946636ba0e22f66bae3fb41b9c4353d/lib/attention/publisher.rb#L17-L26
train
nosolosoftware/azure_jwt_auth
lib/azure_jwt_auth/jwt_manager.rb
AzureJwtAuth.JwtManager.custom_valid?
def custom_valid? @provider.validations.each do |key, value| return false unless payload[key] == value end true end
ruby
def custom_valid? @provider.validations.each do |key, value| return false unless payload[key] == value end true end
[ "def", "custom_valid?", "@provider", ".", "validations", ".", "each", "do", "|", "key", ",", "value", "|", "return", "false", "unless", "payload", "[", "key", "]", "==", "value", "end", "true", "end" ]
Check custom validations defined into provider
[ "Check", "custom", "validations", "defined", "into", "provider" ]
1c7010ac29afb10b099393ec4648f919b17a2695
https://github.com/nosolosoftware/azure_jwt_auth/blob/1c7010ac29afb10b099393ec4648f919b17a2695/lib/azure_jwt_auth/jwt_manager.rb#L43-L49
train
nosolosoftware/azure_jwt_auth
lib/azure_jwt_auth/jwt_manager.rb
AzureJwtAuth.JwtManager.rsa_decode
def rsa_decode kid = header['kid'] try = false begin rsa = @provider.keys[kid] raise KidNotFound, 'kid not found into provider keys' unless rsa JWT.decode(@jwt, rsa.public_key, true, algorithm: 'RS256') rescue JWT::VerificationError, KidNotFound raise if try @provider.load_keys # maybe keys have been changed try = true retry end end
ruby
def rsa_decode kid = header['kid'] try = false begin rsa = @provider.keys[kid] raise KidNotFound, 'kid not found into provider keys' unless rsa JWT.decode(@jwt, rsa.public_key, true, algorithm: 'RS256') rescue JWT::VerificationError, KidNotFound raise if try @provider.load_keys # maybe keys have been changed try = true retry end end
[ "def", "rsa_decode", "kid", "=", "header", "[", "'kid'", "]", "try", "=", "false", "begin", "rsa", "=", "@provider", ".", "keys", "[", "kid", "]", "raise", "KidNotFound", ",", "'kid not found into provider keys'", "unless", "rsa", "JWT", ".", "decode", "(", "@jwt", ",", "rsa", ".", "public_key", ",", "true", ",", "algorithm", ":", "'RS256'", ")", "rescue", "JWT", "::", "VerificationError", ",", "KidNotFound", "raise", "if", "try", "@provider", ".", "load_keys", "# maybe keys have been changed", "try", "=", "true", "retry", "end", "end" ]
Decodes the JWT with the signed secret
[ "Decodes", "the", "JWT", "with", "the", "signed", "secret" ]
1c7010ac29afb10b099393ec4648f919b17a2695
https://github.com/nosolosoftware/azure_jwt_auth/blob/1c7010ac29afb10b099393ec4648f919b17a2695/lib/azure_jwt_auth/jwt_manager.rb#L59-L75
train
jtzero/vigilem-core
lib/vigilem/core/hooks.rb
Vigilem::Core.Hooks.run_hook
def run_hook(hook_name, *args, &block) hooks.find {|hook| hook.name == hook_name }.run(self, *args, &block) end
ruby
def run_hook(hook_name, *args, &block) hooks.find {|hook| hook.name == hook_name }.run(self, *args, &block) end
[ "def", "run_hook", "(", "hook_name", ",", "*", "args", ",", "&", "block", ")", "hooks", ".", "find", "{", "|", "hook", "|", "hook", ".", "name", "==", "hook_name", "}", ".", "run", "(", "self", ",", "args", ",", "block", ")", "end" ]
class level finds a hook by that name and runs it @param hook_name the hook to find @param [Array] args arguments to be passed to the hook @param [Proc] block Proc to be passed to the hook @return [Hook]
[ "class", "level", "finds", "a", "hook", "by", "that", "name", "and", "runs", "it" ]
a35864229ee76800f5197e3c3c6fb2bf34a68495
https://github.com/jtzero/vigilem-core/blob/a35864229ee76800f5197e3c3c6fb2bf34a68495/lib/vigilem/core/hooks.rb#L26-L28
train
johnwunder/stix_schema_spy
lib/stix_schema_spy/models/complex_type.rb
StixSchemaSpy.ComplexType.vocab_values
def vocab_values type = Schema.find(self.schema.prefix, stix_version).find_type(name.gsub("Vocab", "Enum")) if type type.enumeration_values else raise "Unable to find corresponding enumeration for vocabulary" end end
ruby
def vocab_values type = Schema.find(self.schema.prefix, stix_version).find_type(name.gsub("Vocab", "Enum")) if type type.enumeration_values else raise "Unable to find corresponding enumeration for vocabulary" end end
[ "def", "vocab_values", "type", "=", "Schema", ".", "find", "(", "self", ".", "schema", ".", "prefix", ",", "stix_version", ")", ".", "find_type", "(", "name", ".", "gsub", "(", "\"Vocab\"", ",", "\"Enum\"", ")", ")", "if", "type", "type", ".", "enumeration_values", "else", "raise", "\"Unable to find corresponding enumeration for vocabulary\"", "end", "end" ]
Only valid for vocabularies Returns a list of possible values for that vocabulary
[ "Only", "valid", "for", "vocabularies", "Returns", "a", "list", "of", "possible", "values", "for", "that", "vocabulary" ]
2d551c6854d749eb330340e69f73baee1c4b52d3
https://github.com/johnwunder/stix_schema_spy/blob/2d551c6854d749eb330340e69f73baee1c4b52d3/lib/stix_schema_spy/models/complex_type.rb#L40-L48
train
moose-secret-agents/coach_assist
lib/coach/entity.rb
Coach.Entity.fetch
def fetch assert_has_uri! response = client.get clean_uri, query: { start: 0, size: 10000 } update_attributes! filter_response_body(JSON.parse(response.body)) self end
ruby
def fetch assert_has_uri! response = client.get clean_uri, query: { start: 0, size: 10000 } update_attributes! filter_response_body(JSON.parse(response.body)) self end
[ "def", "fetch", "assert_has_uri!", "response", "=", "client", ".", "get", "clean_uri", ",", "query", ":", "{", "start", ":", "0", ",", "size", ":", "10000", "}", "update_attributes!", "filter_response_body", "(", "JSON", ".", "parse", "(", "response", ".", "body", ")", ")", "self", "end" ]
Fetch an entity based on its uri. Each entity containing a valid uri will be retrievable through this method
[ "Fetch", "an", "entity", "based", "on", "its", "uri", ".", "Each", "entity", "containing", "a", "valid", "uri", "will", "be", "retrievable", "through", "this", "method" ]
bc135cd3b54102993bb23c21db5723468bd77ce6
https://github.com/moose-secret-agents/coach_assist/blob/bc135cd3b54102993bb23c21db5723468bd77ce6/lib/coach/entity.rb#L13-L20
train
vjoel/funl
lib/funl/message.rb
Funl.Message.to_msgpack
def to_msgpack(pk = nil) case pk when MessagePack::Packer pk.write_array_header(6) pk.write @client_id pk.write @local_tick pk.write @global_tick pk.write @delta pk.write @tags pk.write @blob return pk else # nil or IO MessagePack.pack(self, pk) end end
ruby
def to_msgpack(pk = nil) case pk when MessagePack::Packer pk.write_array_header(6) pk.write @client_id pk.write @local_tick pk.write @global_tick pk.write @delta pk.write @tags pk.write @blob return pk else # nil or IO MessagePack.pack(self, pk) end end
[ "def", "to_msgpack", "(", "pk", "=", "nil", ")", "case", "pk", "when", "MessagePack", "::", "Packer", "pk", ".", "write_array_header", "(", "6", ")", "pk", ".", "write", "@client_id", "pk", ".", "write", "@local_tick", "pk", ".", "write", "@global_tick", "pk", ".", "write", "@delta", "pk", ".", "write", "@tags", "pk", ".", "write", "@blob", "return", "pk", "else", "# nil or IO", "MessagePack", ".", "pack", "(", "self", ",", "pk", ")", "end", "end" ]
Call with Packer, nil, or IO. If +pk+ is nil, returns string. If +pk+ is a Packer, returns the Packer, which will need to be flushed. If +pk+ is IO, returns nil.
[ "Call", "with", "Packer", "nil", "or", "IO", ".", "If", "+", "pk", "+", "is", "nil", "returns", "string", ".", "If", "+", "pk", "+", "is", "a", "Packer", "returns", "the", "Packer", "which", "will", "need", "to", "be", "flushed", ".", "If", "+", "pk", "+", "is", "IO", "returns", "nil", "." ]
3b05b89d0f9f029b31862e94311f52ff3491ab9c
https://github.com/vjoel/funl/blob/3b05b89d0f9f029b31862e94311f52ff3491ab9c/lib/funl/message.rb#L86-L101
train
christoph-buente/retentiongrid
lib/retentiongrid/resource.rb
Retentiongrid.Resource.attributes
def attributes self.class::ATTRIBUTES_NAMES.inject({}) do |attribs, attrib_name| value = self.send(attrib_name) attribs[attrib_name] = value unless value.nil? attribs end end
ruby
def attributes self.class::ATTRIBUTES_NAMES.inject({}) do |attribs, attrib_name| value = self.send(attrib_name) attribs[attrib_name] = value unless value.nil? attribs end end
[ "def", "attributes", "self", ".", "class", "::", "ATTRIBUTES_NAMES", ".", "inject", "(", "{", "}", ")", "do", "|", "attribs", ",", "attrib_name", "|", "value", "=", "self", ".", "send", "(", "attrib_name", ")", "attribs", "[", "attrib_name", "]", "=", "value", "unless", "value", ".", "nil?", "attribs", "end", "end" ]
Return all attributes as a hash @return [Hash]
[ "Return", "all", "attributes", "as", "a", "hash" ]
601d256786dd2e2c42f7374b999cd4e195e0e848
https://github.com/christoph-buente/retentiongrid/blob/601d256786dd2e2c42f7374b999cd4e195e0e848/lib/retentiongrid/resource.rb#L28-L34
train
zdavatz/odba
lib/odba/persistable.rb
ODBA.Persistable.odba_cut_connection
def odba_cut_connection(remove_object) odba_potentials.each { |name| var = instance_variable_get(name) if(var.eql?(remove_object)) instance_variable_set(name, nil) end } end
ruby
def odba_cut_connection(remove_object) odba_potentials.each { |name| var = instance_variable_get(name) if(var.eql?(remove_object)) instance_variable_set(name, nil) end } end
[ "def", "odba_cut_connection", "(", "remove_object", ")", "odba_potentials", ".", "each", "{", "|", "name", "|", "var", "=", "instance_variable_get", "(", "name", ")", "if", "(", "var", ".", "eql?", "(", "remove_object", ")", ")", "instance_variable_set", "(", "name", ",", "nil", ")", "end", "}", "end" ]
Removes all connections to another persistable. This method is called by the Cache server when _remove_object_ is deleted from the database
[ "Removes", "all", "connections", "to", "another", "persistable", ".", "This", "method", "is", "called", "by", "the", "Cache", "server", "when", "_remove_object_", "is", "deleted", "from", "the", "database" ]
40a4f3a07abdc6d41d627338848ca8cb1dd52294
https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/persistable.rb#L211-L218
train
zdavatz/odba
lib/odba/persistable.rb
ODBA.Persistable.odba_take_snapshot
def odba_take_snapshot @odba_snapshot_level ||= 0 snapshot_level = @odba_snapshot_level.next current_level = [self] tree_level = 0 while(!current_level.empty?) tree_level += 1 obj_count = 0 next_level = [] current_level.each { |item| if(item.odba_unsaved?(snapshot_level)) obj_count += 1 next_level += item.odba_unsaved_neighbors(snapshot_level) item.odba_snapshot(snapshot_level) end } current_level = next_level #.uniq end end
ruby
def odba_take_snapshot @odba_snapshot_level ||= 0 snapshot_level = @odba_snapshot_level.next current_level = [self] tree_level = 0 while(!current_level.empty?) tree_level += 1 obj_count = 0 next_level = [] current_level.each { |item| if(item.odba_unsaved?(snapshot_level)) obj_count += 1 next_level += item.odba_unsaved_neighbors(snapshot_level) item.odba_snapshot(snapshot_level) end } current_level = next_level #.uniq end end
[ "def", "odba_take_snapshot", "@odba_snapshot_level", "||=", "0", "snapshot_level", "=", "@odba_snapshot_level", ".", "next", "current_level", "=", "[", "self", "]", "tree_level", "=", "0", "while", "(", "!", "current_level", ".", "empty?", ")", "tree_level", "+=", "1", "obj_count", "=", "0", "next_level", "=", "[", "]", "current_level", ".", "each", "{", "|", "item", "|", "if", "(", "item", ".", "odba_unsaved?", "(", "snapshot_level", ")", ")", "obj_count", "+=", "1", "next_level", "+=", "item", ".", "odba_unsaved_neighbors", "(", "snapshot_level", ")", "item", ".", "odba_snapshot", "(", "snapshot_level", ")", "end", "}", "current_level", "=", "next_level", "#.uniq", "end", "end" ]
Recursively stores all connected Persistables.
[ "Recursively", "stores", "all", "connected", "Persistables", "." ]
40a4f3a07abdc6d41d627338848ca8cb1dd52294
https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/persistable.rb#L425-L443
train
noted/scholar
lib/scholar/citation.rb
Scholar.Citation.to_hash
def to_hash hash = {} instance_variables.each do |v| hash[v.to_s[1..-1].to_sym] = instance_variable_get(v) end hash end
ruby
def to_hash hash = {} instance_variables.each do |v| hash[v.to_s[1..-1].to_sym] = instance_variable_get(v) end hash end
[ "def", "to_hash", "hash", "=", "{", "}", "instance_variables", ".", "each", "do", "|", "v", "|", "hash", "[", "v", ".", "to_s", "[", "1", "..", "-", "1", "]", ".", "to_sym", "]", "=", "instance_variable_get", "(", "v", ")", "end", "hash", "end" ]
Creates a new Citation from the given attributes. ==== Attributes * +options+ - The attributes of the Citation. ==== Options * +:type+ - Not optional. The type of source you are citing. * +:contributors+ - An array of hashes of contributors. ==== Examples citation = Scholar::Citation.new({ :type => :book, :title => "Foobar", :contributors => [ { :role => :author, :first => "John", :last => "Sample" } ] }) Obviously, you'd include more than that, but you need to see the specific sources for more documentation. Returns the Citation object in Hash form.
[ "Creates", "a", "new", "Citation", "from", "the", "given", "attributes", "." ]
2bfface9d90307d7d3cecfa756f921087407d394
https://github.com/noted/scholar/blob/2bfface9d90307d7d3cecfa756f921087407d394/lib/scholar/citation.rb#L71-L79
train
aapis/notifaction
lib/notifaction/helpers.rb
Notifaction.Helpers.deprecation_notice
def deprecation_notice(version, config = {}) handler = Notifaction::Type::Terminal.new handler.warning( "Deprecated as of #{version}, current #{Notifaction::VERSION}", config ) handler.quit_soft end
ruby
def deprecation_notice(version, config = {}) handler = Notifaction::Type::Terminal.new handler.warning( "Deprecated as of #{version}, current #{Notifaction::VERSION}", config ) handler.quit_soft end
[ "def", "deprecation_notice", "(", "version", ",", "config", "=", "{", "}", ")", "handler", "=", "Notifaction", "::", "Type", "::", "Terminal", ".", "new", "handler", ".", "warning", "(", "\"Deprecated as of #{version}, current #{Notifaction::VERSION}\"", ",", "config", ")", "handler", ".", "quit_soft", "end" ]
Alert the user that the method they've called is not supported @since 0.4.1
[ "Alert", "the", "user", "that", "the", "method", "they", "ve", "called", "is", "not", "supported" ]
dbad4c2888a1a59f2a3745d1c1e55c923e0d2039
https://github.com/aapis/notifaction/blob/dbad4c2888a1a59f2a3745d1c1e55c923e0d2039/lib/notifaction/helpers.rb#L5-L12
train
donnoman/mysql2_model
lib/mysql2_model/composer.rb
Mysql2Model.Composer.compose_sql
def compose_sql(*statement) raise PreparedStatementInvalid, "Statement is blank!" if statement.blank? if statement.is_a?(Array) if statement.size == 1 #strip the outer array compose_sql_array(statement.first) else compose_sql_array(statement) end else statement end end
ruby
def compose_sql(*statement) raise PreparedStatementInvalid, "Statement is blank!" if statement.blank? if statement.is_a?(Array) if statement.size == 1 #strip the outer array compose_sql_array(statement.first) else compose_sql_array(statement) end else statement end end
[ "def", "compose_sql", "(", "*", "statement", ")", "raise", "PreparedStatementInvalid", ",", "\"Statement is blank!\"", "if", "statement", ".", "blank?", "if", "statement", ".", "is_a?", "(", "Array", ")", "if", "statement", ".", "size", "==", "1", "#strip the outer array", "compose_sql_array", "(", "statement", ".", "first", ")", "else", "compose_sql_array", "(", "statement", ")", "end", "else", "statement", "end", "end" ]
Accepts multiple arguments, an array, or string of SQL and composes them @example String "name='foo''bar' and group_id='4'" #=> "name='foo''bar' and group_id='4'" @example Array ["name='%s' and group_id='%s'", "foo'bar", 4] #=> "name='foo''bar' and group_id='4'" @param [Array,String]
[ "Accepts", "multiple", "arguments", "an", "array", "or", "string", "of", "SQL", "and", "composes", "them" ]
700a2c6a09b0eb1c0ea318d1c0b6652961e3d223
https://github.com/donnoman/mysql2_model/blob/700a2c6a09b0eb1c0ea318d1c0b6652961e3d223/lib/mysql2_model/composer.rb#L25-L36
train
donnoman/mysql2_model
lib/mysql2_model/composer.rb
Mysql2Model.Composer.compose_sql_array
def compose_sql_array(ary) statement, *values = ary if values.first.is_a?(Hash) and statement =~ /:\w+/ replace_named_bind_variables(statement, values.first) elsif statement.include?('?') replace_bind_variables(statement, values) else statement % values.collect { |value| client.escape(value.to_s) } end end
ruby
def compose_sql_array(ary) statement, *values = ary if values.first.is_a?(Hash) and statement =~ /:\w+/ replace_named_bind_variables(statement, values.first) elsif statement.include?('?') replace_bind_variables(statement, values) else statement % values.collect { |value| client.escape(value.to_s) } end end
[ "def", "compose_sql_array", "(", "ary", ")", "statement", ",", "*", "values", "=", "ary", "if", "values", ".", "first", ".", "is_a?", "(", "Hash", ")", "and", "statement", "=~", "/", "\\w", "/", "replace_named_bind_variables", "(", "statement", ",", "values", ".", "first", ")", "elsif", "statement", ".", "include?", "(", "'?'", ")", "replace_bind_variables", "(", "statement", ",", "values", ")", "else", "statement", "%", "values", ".", "collect", "{", "|", "value", "|", "client", ".", "escape", "(", "value", ".", "to_s", ")", "}", "end", "end" ]
Accepts an array of conditions. The array has each value sanitized and interpolated into the SQL statement. @param [Array] ary @example Array ["name='%s' and group_id='%s'", "foo'bar", 4] #=> "name='foo''bar' and group_id='4'" @private
[ "Accepts", "an", "array", "of", "conditions", ".", "The", "array", "has", "each", "value", "sanitized", "and", "interpolated", "into", "the", "SQL", "statement", "." ]
700a2c6a09b0eb1c0ea318d1c0b6652961e3d223
https://github.com/donnoman/mysql2_model/blob/700a2c6a09b0eb1c0ea318d1c0b6652961e3d223/lib/mysql2_model/composer.rb#L44-L53
train
ideonetwork/lato-blog
app/models/lato_blog/tag/serializer_helpers.rb
LatoBlog.Tag::SerializerHelpers.serialize
def serialize serialized = {} # set basic info serialized[:id] = id serialized[:title] = title serialized[:meta_language] = meta_language serialized[:meta_permalink] = meta_permalink # add tag parent informations serialized[:other_informations] = serialize_other_informations # return serialized post serialized end
ruby
def serialize serialized = {} # set basic info serialized[:id] = id serialized[:title] = title serialized[:meta_language] = meta_language serialized[:meta_permalink] = meta_permalink # add tag parent informations serialized[:other_informations] = serialize_other_informations # return serialized post serialized end
[ "def", "serialize", "serialized", "=", "{", "}", "# set basic info", "serialized", "[", ":id", "]", "=", "id", "serialized", "[", ":title", "]", "=", "title", "serialized", "[", ":meta_language", "]", "=", "meta_language", "serialized", "[", ":meta_permalink", "]", "=", "meta_permalink", "# add tag parent informations", "serialized", "[", ":other_informations", "]", "=", "serialize_other_informations", "# return serialized post", "serialized", "end" ]
This function serializes a complete version of the tag.
[ "This", "function", "serializes", "a", "complete", "version", "of", "the", "tag", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/tag/serializer_helpers.rb#L5-L19
train
jarrett/ichiban
lib/ichiban/deleter.rb
Ichiban.Deleter.delete_dest
def delete_dest(path) file = Ichiban::ProjectFile.from_abs(path) # file will be nil if the path doesn't map to a known subclass of IchibanFile. Furthermore, # even if file is not nil, it may be a kind of IchibanFile that does not have a destination. if file and file.has_dest? dest = file.dest else dest = nil end if dest and File.exist?(dest) FileUtils.rm(dest) end # Log the deletion(s) Ichiban.logger.deletion(path, dest) end
ruby
def delete_dest(path) file = Ichiban::ProjectFile.from_abs(path) # file will be nil if the path doesn't map to a known subclass of IchibanFile. Furthermore, # even if file is not nil, it may be a kind of IchibanFile that does not have a destination. if file and file.has_dest? dest = file.dest else dest = nil end if dest and File.exist?(dest) FileUtils.rm(dest) end # Log the deletion(s) Ichiban.logger.deletion(path, dest) end
[ "def", "delete_dest", "(", "path", ")", "file", "=", "Ichiban", "::", "ProjectFile", ".", "from_abs", "(", "path", ")", "# file will be nil if the path doesn't map to a known subclass of IchibanFile. Furthermore,", "# even if file is not nil, it may be a kind of IchibanFile that does not have a destination.", "if", "file", "and", "file", ".", "has_dest?", "dest", "=", "file", ".", "dest", "else", "dest", "=", "nil", "end", "if", "dest", "and", "File", ".", "exist?", "(", "dest", ")", "FileUtils", ".", "rm", "(", "dest", ")", "end", "# Log the deletion(s)", "Ichiban", ".", "logger", ".", "deletion", "(", "path", ",", "dest", ")", "end" ]
Deletes a file's associated destination file, if any.
[ "Deletes", "a", "file", "s", "associated", "destination", "file", "if", "any", "." ]
310f96b0981ea19bf01246995f3732c986915d5b
https://github.com/jarrett/ichiban/blob/310f96b0981ea19bf01246995f3732c986915d5b/lib/ichiban/deleter.rb#L4-L19
train
mje113/couchbase-jruby-model
lib/couchbase/model.rb
Couchbase.Model.delete
def delete(options = {}) raise Couchbase::Error::MissingId, 'missing id attribute' unless @id model.bucket.delete(@id, options) @id = nil @meta = nil self end
ruby
def delete(options = {}) raise Couchbase::Error::MissingId, 'missing id attribute' unless @id model.bucket.delete(@id, options) @id = nil @meta = nil self end
[ "def", "delete", "(", "options", "=", "{", "}", ")", "raise", "Couchbase", "::", "Error", "::", "MissingId", ",", "'missing id attribute'", "unless", "@id", "model", ".", "bucket", ".", "delete", "(", "@id", ",", "options", ")", "@id", "=", "nil", "@meta", "=", "nil", "self", "end" ]
Delete this object from the bucket @since 0.0.1 @note This method will reset +id+ attribute @param [Hash] options options for operation, see {{Couchbase::Bucket#delete}} @return [Couchbase::Model] Returns a reference of itself. @example Delete the Post model p = Post.find('hello-world') p.delete
[ "Delete", "this", "object", "from", "the", "bucket" ]
e801b73e6e394297e3a92ff51b92af628ae57a27
https://github.com/mje113/couchbase-jruby-model/blob/e801b73e6e394297e3a92ff51b92af628ae57a27/lib/couchbase/model.rb#L616-L622
train
mje113/couchbase-jruby-model
lib/couchbase/model.rb
Couchbase.Model.reload
def reload raise Couchbase::Error::MissingId, 'missing id attribute' unless @id pristine = model.find(@id) update_attributes(pristine.attributes) @meta[:cas] = pristine.meta[:cas] self end
ruby
def reload raise Couchbase::Error::MissingId, 'missing id attribute' unless @id pristine = model.find(@id) update_attributes(pristine.attributes) @meta[:cas] = pristine.meta[:cas] self end
[ "def", "reload", "raise", "Couchbase", "::", "Error", "::", "MissingId", ",", "'missing id attribute'", "unless", "@id", "pristine", "=", "model", ".", "find", "(", "@id", ")", "update_attributes", "(", "pristine", ".", "attributes", ")", "@meta", "[", ":cas", "]", "=", "pristine", ".", "meta", "[", ":cas", "]", "self", "end" ]
Reload all the model attributes from the bucket @since 0.0.1 @return [Model] the latest model state @raise [Error::MissingId] for records without +id+ attribute
[ "Reload", "all", "the", "model", "attributes", "from", "the", "bucket" ]
e801b73e6e394297e3a92ff51b92af628ae57a27
https://github.com/mje113/couchbase-jruby-model/blob/e801b73e6e394297e3a92ff51b92af628ae57a27/lib/couchbase/model.rb#L734-L740
train
jimcar/orchestrate-api
lib/orchestrate/api/request.rb
Orchestrate::API.Request.perform
def perform uri = URI(url) response = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https' ) { |http| Orchestrate.config.logger.debug "Performing #{method.to_s.upcase} request to \"#{url}\"" http.request(request(uri)) } Response.new(response) end
ruby
def perform uri = URI(url) response = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https' ) { |http| Orchestrate.config.logger.debug "Performing #{method.to_s.upcase} request to \"#{url}\"" http.request(request(uri)) } Response.new(response) end
[ "def", "perform", "uri", "=", "URI", "(", "url", ")", "response", "=", "Net", "::", "HTTP", ".", "start", "(", "uri", ".", "hostname", ",", "uri", ".", "port", ",", ":use_ssl", "=>", "uri", ".", "scheme", "==", "'https'", ")", "{", "|", "http", "|", "Orchestrate", ".", "config", ".", "logger", ".", "debug", "\"Performing #{method.to_s.upcase} request to \\\"#{url}\\\"\"", "http", ".", "request", "(", "request", "(", "uri", ")", ")", "}", "Response", ".", "new", "(", "response", ")", "end" ]
Sets the universal attributes from the params; any additional attributes are set from the block. Sends the HTTP request and returns a Response object.
[ "Sets", "the", "universal", "attributes", "from", "the", "params", ";", "any", "additional", "attributes", "are", "set", "from", "the", "block", "." ]
8931c41d69b9e32096db7615d0b252b971a5857d
https://github.com/jimcar/orchestrate-api/blob/8931c41d69b9e32096db7615d0b252b971a5857d/lib/orchestrate/api/request.rb#L32-L40
train
octoai/gem-octocore-mongo
lib/octocore-mongo/trendable.rb
Octo.Trendable.aggregate_sum
def aggregate_sum(aggr) sum = {} aggr.each do |ts, counterVals| sum[ts] = {} unless sum.has_key?ts counterVals.each do |obj, count| if obj.respond_to?(:enterprise_id) eid = obj.public_send(:enterprise_id).to_s sum[ts][eid] = sum[ts].fetch(eid, 0) + count end end end sum end
ruby
def aggregate_sum(aggr) sum = {} aggr.each do |ts, counterVals| sum[ts] = {} unless sum.has_key?ts counterVals.each do |obj, count| if obj.respond_to?(:enterprise_id) eid = obj.public_send(:enterprise_id).to_s sum[ts][eid] = sum[ts].fetch(eid, 0) + count end end end sum end
[ "def", "aggregate_sum", "(", "aggr", ")", "sum", "=", "{", "}", "aggr", ".", "each", "do", "|", "ts", ",", "counterVals", "|", "sum", "[", "ts", "]", "=", "{", "}", "unless", "sum", ".", "has_key?", "ts", "counterVals", ".", "each", "do", "|", "obj", ",", "count", "|", "if", "obj", ".", "respond_to?", "(", ":enterprise_id", ")", "eid", "=", "obj", ".", "public_send", "(", ":enterprise_id", ")", ".", "to_s", "sum", "[", "ts", "]", "[", "eid", "]", "=", "sum", "[", "ts", "]", ".", "fetch", "(", "eid", ",", "0", ")", "+", "count", "end", "end", "end", "sum", "end" ]
Aggregates to find the sum of all counters for an enterprise at a time @param [Hash] aggr The aggregated hash @return [Hash] The summed up hash
[ "Aggregates", "to", "find", "the", "sum", "of", "all", "counters", "for", "an", "enterprise", "at", "a", "time" ]
bf7fa833fd7e08947697d0341ab5e80e89c8d05a
https://github.com/octoai/gem-octocore-mongo/blob/bf7fa833fd7e08947697d0341ab5e80e89c8d05a/lib/octocore-mongo/trendable.rb#L62-L74
train
pixeltrix/sortifiable
lib/sortifiable.rb
Sortifiable.InstanceMethods.add_to_list
def add_to_list if in_list? move_to_bottom else list_class.transaction do ids = lock_list! last_position = ids.size if persisted? update_position last_position + 1 else set_position last_position + 1 end end end end
ruby
def add_to_list if in_list? move_to_bottom else list_class.transaction do ids = lock_list! last_position = ids.size if persisted? update_position last_position + 1 else set_position last_position + 1 end end end end
[ "def", "add_to_list", "if", "in_list?", "move_to_bottom", "else", "list_class", ".", "transaction", "do", "ids", "=", "lock_list!", "last_position", "=", "ids", ".", "size", "if", "persisted?", "update_position", "last_position", "+", "1", "else", "set_position", "last_position", "+", "1", "end", "end", "end", "end" ]
Add the item to the end of the list
[ "Add", "the", "item", "to", "the", "end", "of", "the", "list" ]
fa54c36e4e6a5500247e8823d77401acc8014ba7
https://github.com/pixeltrix/sortifiable/blob/fa54c36e4e6a5500247e8823d77401acc8014ba7/lib/sortifiable.rb#L104-L118
train
ideonetwork/lato-blog
app/helpers/lato_blog/fields_helper.rb
LatoBlog.FieldsHelper.render_post_fields
def render_post_fields(post) post_fields = post.post_fields.visibles.roots.order('position ASC') render 'lato_blog/back/posts/shared/fields', post_fields: post_fields end
ruby
def render_post_fields(post) post_fields = post.post_fields.visibles.roots.order('position ASC') render 'lato_blog/back/posts/shared/fields', post_fields: post_fields end
[ "def", "render_post_fields", "(", "post", ")", "post_fields", "=", "post", ".", "post_fields", ".", "visibles", ".", "roots", ".", "order", "(", "'position ASC'", ")", "render", "'lato_blog/back/posts/shared/fields'", ",", "post_fields", ":", "post_fields", "end" ]
This function render the partial used to render post fields for a specific post.
[ "This", "function", "render", "the", "partial", "used", "to", "render", "post", "fields", "for", "a", "specific", "post", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/helpers/lato_blog/fields_helper.rb#L6-L9
train
ideonetwork/lato-blog
app/helpers/lato_blog/fields_helper.rb
LatoBlog.FieldsHelper.render_post_field
def render_post_field(post_field, key_parent = 'fields') # define key key = "#{key_parent}[#{post_field.id}]" # render correct field case post_field.typology when 'text' render_post_field_text(post_field, key) when 'textarea' render_post_field_textarea(post_field, key) when 'datetime' render_post_field_datetime(post_field, key) when 'editor' render_post_field_editor(post_field, key) when 'geolocalization' render_post_field_geolocalization(post_field, key) when 'image' render_post_field_image(post_field, key) when 'gallery' render_post_field_gallery(post_field, key) when 'youtube' render_post_field_youtube(post_field, key) when 'composed' render_post_field_composed(post_field, key) when 'relay' render_post_field_relay(post_field, key) end end
ruby
def render_post_field(post_field, key_parent = 'fields') # define key key = "#{key_parent}[#{post_field.id}]" # render correct field case post_field.typology when 'text' render_post_field_text(post_field, key) when 'textarea' render_post_field_textarea(post_field, key) when 'datetime' render_post_field_datetime(post_field, key) when 'editor' render_post_field_editor(post_field, key) when 'geolocalization' render_post_field_geolocalization(post_field, key) when 'image' render_post_field_image(post_field, key) when 'gallery' render_post_field_gallery(post_field, key) when 'youtube' render_post_field_youtube(post_field, key) when 'composed' render_post_field_composed(post_field, key) when 'relay' render_post_field_relay(post_field, key) end end
[ "def", "render_post_field", "(", "post_field", ",", "key_parent", "=", "'fields'", ")", "# define key", "key", "=", "\"#{key_parent}[#{post_field.id}]\"", "# render correct field", "case", "post_field", ".", "typology", "when", "'text'", "render_post_field_text", "(", "post_field", ",", "key", ")", "when", "'textarea'", "render_post_field_textarea", "(", "post_field", ",", "key", ")", "when", "'datetime'", "render_post_field_datetime", "(", "post_field", ",", "key", ")", "when", "'editor'", "render_post_field_editor", "(", "post_field", ",", "key", ")", "when", "'geolocalization'", "render_post_field_geolocalization", "(", "post_field", ",", "key", ")", "when", "'image'", "render_post_field_image", "(", "post_field", ",", "key", ")", "when", "'gallery'", "render_post_field_gallery", "(", "post_field", ",", "key", ")", "when", "'youtube'", "render_post_field_youtube", "(", "post_field", ",", "key", ")", "when", "'composed'", "render_post_field_composed", "(", "post_field", ",", "key", ")", "when", "'relay'", "render_post_field_relay", "(", "post_field", ",", "key", ")", "end", "end" ]
This function render a single post field.
[ "This", "function", "render", "a", "single", "post", "field", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/helpers/lato_blog/fields_helper.rb#L12-L38
train
devrieda/stylesheet
spec/stubs/fake_request.rb
Stylesheet.FakeRequest.get
def get(url) begin uri = URI.parse(url.strip) rescue URI::InvalidURIError uri = URI.parse(URI.escape(url.strip)) end # simple hack to read in fixtures instead of url for tests fixture = "#{File.dirname(__FILE__)}/../fixtures#{uri.path}" File.read(fixture) if File.exist?(fixture) end
ruby
def get(url) begin uri = URI.parse(url.strip) rescue URI::InvalidURIError uri = URI.parse(URI.escape(url.strip)) end # simple hack to read in fixtures instead of url for tests fixture = "#{File.dirname(__FILE__)}/../fixtures#{uri.path}" File.read(fixture) if File.exist?(fixture) end
[ "def", "get", "(", "url", ")", "begin", "uri", "=", "URI", ".", "parse", "(", "url", ".", "strip", ")", "rescue", "URI", "::", "InvalidURIError", "uri", "=", "URI", ".", "parse", "(", "URI", ".", "escape", "(", "url", ".", "strip", ")", ")", "end", "# simple hack to read in fixtures instead of url for tests", "fixture", "=", "\"#{File.dirname(__FILE__)}/../fixtures#{uri.path}\"", "File", ".", "read", "(", "fixture", ")", "if", "File", ".", "exist?", "(", "fixture", ")", "end" ]
Read in fixture file instead of url
[ "Read", "in", "fixture", "file", "instead", "of", "url" ]
d1334eb734ac2023afc6ba4df07bf2627268de11
https://github.com/devrieda/stylesheet/blob/d1334eb734ac2023afc6ba4df07bf2627268de11/spec/stubs/fake_request.rb#L7-L17
train
sanichi/icu_tournament
lib/icu_tournament/player.rb
ICU.Player.renumber
def renumber(map) raise "player number #{@num} not found in renumbering hash" unless map[@num] self.num = map[@num] @results.each{ |r| r.renumber(map) } self end
ruby
def renumber(map) raise "player number #{@num} not found in renumbering hash" unless map[@num] self.num = map[@num] @results.each{ |r| r.renumber(map) } self end
[ "def", "renumber", "(", "map", ")", "raise", "\"player number #{@num} not found in renumbering hash\"", "unless", "map", "[", "@num", "]", "self", ".", "num", "=", "map", "[", "@num", "]", "@results", ".", "each", "{", "|", "r", "|", "r", ".", "renumber", "(", "map", ")", "}", "self", "end" ]
Renumber the player according to the supplied hash. Return self.
[ "Renumber", "the", "player", "according", "to", "the", "supplied", "hash", ".", "Return", "self", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/player.rb#L203-L208
train
sanichi/icu_tournament
lib/icu_tournament/player.rb
ICU.Player.merge
def merge(other) raise "cannot merge two players that are not equal" unless self == other [:id, :fide_id, :rating, :fide_rating, :title, :fed, :gender].each do |m| self.send("#{m}=", other.send(m)) unless self.send(m) end end
ruby
def merge(other) raise "cannot merge two players that are not equal" unless self == other [:id, :fide_id, :rating, :fide_rating, :title, :fed, :gender].each do |m| self.send("#{m}=", other.send(m)) unless self.send(m) end end
[ "def", "merge", "(", "other", ")", "raise", "\"cannot merge two players that are not equal\"", "unless", "self", "==", "other", "[", ":id", ",", ":fide_id", ",", ":rating", ",", ":fide_rating", ",", ":title", ",", ":fed", ",", ":gender", "]", ".", "each", "do", "|", "m", "|", "self", ".", "send", "(", "\"#{m}=\"", ",", "other", ".", "send", "(", "m", ")", ")", "unless", "self", ".", "send", "(", "m", ")", "end", "end" ]
Loose equality test. Passes if the names match and the federations are not different. Strict equality test. Passes if the playes are loosly equal and also if their IDs, rating, gender and title are not different. Merge in some of the details of another player.
[ "Loose", "equality", "test", ".", "Passes", "if", "the", "names", "match", "and", "the", "federations", "are", "not", "different", ".", "Strict", "equality", "test", ".", "Passes", "if", "the", "playes", "are", "loosly", "equal", "and", "also", "if", "their", "IDs", "rating", "gender", "and", "title", "are", "not", "different", ".", "Merge", "in", "some", "of", "the", "details", "of", "another", "player", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/player.rb#L231-L236
train
bilus/kawaii
lib/kawaii/server_methods.rb
Kawaii.ServerMethods.start!
def start!(port) # @todo Support other handlers http://www.rubydoc.info/github/rack/rack/Rack/Handler Rack::Handler.get(WEBRICK).run(self, Port: port) do |s| @server = s at_exit { stop! } [:INT, :TERM].each do |signal| old = trap(signal) do stop! old.call if old.respond_to?(:call) end end end end
ruby
def start!(port) # @todo Support other handlers http://www.rubydoc.info/github/rack/rack/Rack/Handler Rack::Handler.get(WEBRICK).run(self, Port: port) do |s| @server = s at_exit { stop! } [:INT, :TERM].each do |signal| old = trap(signal) do stop! old.call if old.respond_to?(:call) end end end end
[ "def", "start!", "(", "port", ")", "# @todo Support other handlers http://www.rubydoc.info/github/rack/rack/Rack/Handler", "Rack", "::", "Handler", ".", "get", "(", "WEBRICK", ")", ".", "run", "(", "self", ",", "Port", ":", "port", ")", "do", "|", "s", "|", "@server", "=", "s", "at_exit", "{", "stop!", "}", "[", ":INT", ",", ":TERM", "]", ".", "each", "do", "|", "signal", "|", "old", "=", "trap", "(", "signal", ")", "do", "stop!", "old", ".", "call", "if", "old", ".", "respond_to?", "(", ":call", ")", "end", "end", "end", "end" ]
Starts serving the app. @param port [Fixnum] port number to bind to
[ "Starts", "serving", "the", "app", "." ]
a72be28e713b0ed2b2cfc180a38bebe0c968b0b3
https://github.com/bilus/kawaii/blob/a72be28e713b0ed2b2cfc180a38bebe0c968b0b3/lib/kawaii/server_methods.rb#L10-L21
train
rgeyer/rs-mule
lib/rs-mule/run_executable.rb
RsMule.RunExecutable.run_executable
def run_executable(tags, executable, options={}) options = { :executable_type => "auto", :right_script_revision => "latest", :tag_match_strategy => "all", :inputs => {}, :update_inputs => [] }.merge(options) execute_params = {} tags = [tags] unless tags.is_a?(Array) options[:update_inputs] = [options[:update_inputs]] unless options[:update_inputs].is_a?(Array) case options[:executable_type] when "right_script_href" execute_params[:right_script_href] = executable when "right_script_name" scripts = find_right_script_lineage_by_name(executable) execute_params[:right_script_href] = right_script_revision_from_lineage(scripts, options[:right_script_revision]).href when "recipe_name" execute_params[:recipe_name] = executable when "auto" is_recipe = executable =~ /.*::.*/ is_href = executable =~ /^\/api\/right_scripts\/[a-zA-Z0-9]*/ if is_recipe execute_params[:recipe_name] = executable else if is_href execute_params[:right_script_href] = executable else scripts = find_right_script_lineage_by_name(executable) execute_params[:right_script_href] = right_script_revision_from_lineage(scripts, options[:right_script_revision]).href end end else raise ArgumentError.new("Unknown executable_type (#{options[:executable_type]})") end if options[:inputs].length > 0 execute_params[:inputs] = options[:inputs] end resources_by_tag = @right_api_client.tags.by_tag( :resource_type => "instances", :tags => tags, :match_all => options[:tag_match_strategy] == "all" ? "true" : "false" ) resources_by_tag.each do |res| instance = @right_api_client.resource(res.links.first["href"]) instance.run_executable(execute_params) options[:update_inputs].each do |update_type| update_inputs(instance, options[:inputs], update_type) end end end
ruby
def run_executable(tags, executable, options={}) options = { :executable_type => "auto", :right_script_revision => "latest", :tag_match_strategy => "all", :inputs => {}, :update_inputs => [] }.merge(options) execute_params = {} tags = [tags] unless tags.is_a?(Array) options[:update_inputs] = [options[:update_inputs]] unless options[:update_inputs].is_a?(Array) case options[:executable_type] when "right_script_href" execute_params[:right_script_href] = executable when "right_script_name" scripts = find_right_script_lineage_by_name(executable) execute_params[:right_script_href] = right_script_revision_from_lineage(scripts, options[:right_script_revision]).href when "recipe_name" execute_params[:recipe_name] = executable when "auto" is_recipe = executable =~ /.*::.*/ is_href = executable =~ /^\/api\/right_scripts\/[a-zA-Z0-9]*/ if is_recipe execute_params[:recipe_name] = executable else if is_href execute_params[:right_script_href] = executable else scripts = find_right_script_lineage_by_name(executable) execute_params[:right_script_href] = right_script_revision_from_lineage(scripts, options[:right_script_revision]).href end end else raise ArgumentError.new("Unknown executable_type (#{options[:executable_type]})") end if options[:inputs].length > 0 execute_params[:inputs] = options[:inputs] end resources_by_tag = @right_api_client.tags.by_tag( :resource_type => "instances", :tags => tags, :match_all => options[:tag_match_strategy] == "all" ? "true" : "false" ) resources_by_tag.each do |res| instance = @right_api_client.resource(res.links.first["href"]) instance.run_executable(execute_params) options[:update_inputs].each do |update_type| update_inputs(instance, options[:inputs], update_type) end end end
[ "def", "run_executable", "(", "tags", ",", "executable", ",", "options", "=", "{", "}", ")", "options", "=", "{", ":executable_type", "=>", "\"auto\"", ",", ":right_script_revision", "=>", "\"latest\"", ",", ":tag_match_strategy", "=>", "\"all\"", ",", ":inputs", "=>", "{", "}", ",", ":update_inputs", "=>", "[", "]", "}", ".", "merge", "(", "options", ")", "execute_params", "=", "{", "}", "tags", "=", "[", "tags", "]", "unless", "tags", ".", "is_a?", "(", "Array", ")", "options", "[", ":update_inputs", "]", "=", "[", "options", "[", ":update_inputs", "]", "]", "unless", "options", "[", ":update_inputs", "]", ".", "is_a?", "(", "Array", ")", "case", "options", "[", ":executable_type", "]", "when", "\"right_script_href\"", "execute_params", "[", ":right_script_href", "]", "=", "executable", "when", "\"right_script_name\"", "scripts", "=", "find_right_script_lineage_by_name", "(", "executable", ")", "execute_params", "[", ":right_script_href", "]", "=", "right_script_revision_from_lineage", "(", "scripts", ",", "options", "[", ":right_script_revision", "]", ")", ".", "href", "when", "\"recipe_name\"", "execute_params", "[", ":recipe_name", "]", "=", "executable", "when", "\"auto\"", "is_recipe", "=", "executable", "=~", "/", "/", "is_href", "=", "executable", "=~", "/", "\\/", "\\/", "\\/", "/", "if", "is_recipe", "execute_params", "[", ":recipe_name", "]", "=", "executable", "else", "if", "is_href", "execute_params", "[", ":right_script_href", "]", "=", "executable", "else", "scripts", "=", "find_right_script_lineage_by_name", "(", "executable", ")", "execute_params", "[", ":right_script_href", "]", "=", "right_script_revision_from_lineage", "(", "scripts", ",", "options", "[", ":right_script_revision", "]", ")", ".", "href", "end", "end", "else", "raise", "ArgumentError", ".", "new", "(", "\"Unknown executable_type (#{options[:executable_type]})\"", ")", "end", "if", "options", "[", ":inputs", "]", ".", "length", ">", "0", "execute_params", "[", ":inputs", "]", "=", "options", "[", ":inputs", "]", "end", "resources_by_tag", "=", "@right_api_client", ".", "tags", ".", "by_tag", "(", ":resource_type", "=>", "\"instances\"", ",", ":tags", "=>", "tags", ",", ":match_all", "=>", "options", "[", ":tag_match_strategy", "]", "==", "\"all\"", "?", "\"true\"", ":", "\"false\"", ")", "resources_by_tag", ".", "each", "do", "|", "res", "|", "instance", "=", "@right_api_client", ".", "resource", "(", "res", ".", "links", ".", "first", "[", "\"href\"", "]", ")", "instance", ".", "run_executable", "(", "execute_params", ")", "options", "[", ":update_inputs", "]", ".", "each", "do", "|", "update_type", "|", "update_inputs", "(", "instance", ",", "options", "[", ":inputs", "]", ",", "update_type", ")", "end", "end", "end" ]
Initializes a new RunExecutable @param [RightApi::Client] right_api_client An instantiated and authenticated RightApi::Client instance which will be used for making the request(s) Runs a RightScript or Chef Recipe on all instances which have all of the specified tags. @param [String|Array<String>] tags An array of tags. If a string is supplied it will be converted to an array of Strings. @param [String] executable RightScript name or href, or the name of a recipe. This method will attempt to auto detect which it is, or you can be friendly and provide a hint using the executable_type option. @param [Hash] options A list of options where the possible values are - executable_type [String] One of ["auto","right_script_name","right_script_href","recipe_name"]. When set to "auto" we will attempt to determine if an executable is a recipe, a RightScript name, or a RightScript href. Defaults to "auto" - right_script_revision [String] When a RightScript name or href is specified, this can be used to declare the revision to use. Can be a specific revision number or "latest". Defaults to "latest" - tag_match_strategy [String] If multiple tags are specified, this will determine how they are matched. When set to "all" instances with all tags will be matched. When set to "any" instances with any of the provided tags will be matched. Defaults to "all" - inputs [Hash] A hash where the keys are the name of an input and the value is the desired value for that input. Uses Inputs 2.0[http://reference.rightscale.com/api1.5/resources/ResourceInputs.html#multi_update] semantics. - update_inputs [Array<String>] An array of values indicating which objects should be updated with the inputs supplied. Can be empty in which case the inputs will be used only for this execution. Acceptable values are ["current_instance","next_instance","deployment"] @raise [RightScriptNotFound] If the specified RightScript lineage does not exist, or the specified revision is not available.
[ "Initializes", "a", "new", "RunExecutable" ]
f6396729679c7cf2525aeff9c52c26db75d87a43
https://github.com/rgeyer/rs-mule/blob/f6396729679c7cf2525aeff9c52c26db75d87a43/lib/rs-mule/run_executable.rb#L61-L115
train
rgeyer/rs-mule
lib/rs-mule/run_executable.rb
RsMule.RunExecutable.right_script_revision_from_lineage
def right_script_revision_from_lineage(lineage, revision="latest") right_script = nil if revision == "latest" latest_script = lineage.max_by{|rs| rs.revision} right_script = latest_script else desired_script = lineage.select{|rs| rs.revision == revision} if desired_script.length == 0 raise Exception::RightScriptNotFound.new("RightScript revision (#{revision}) was not found. Available revisions are (#{lineage.map{|rs| rs.revision}})") end right_script = desired_script.first end right_script end
ruby
def right_script_revision_from_lineage(lineage, revision="latest") right_script = nil if revision == "latest" latest_script = lineage.max_by{|rs| rs.revision} right_script = latest_script else desired_script = lineage.select{|rs| rs.revision == revision} if desired_script.length == 0 raise Exception::RightScriptNotFound.new("RightScript revision (#{revision}) was not found. Available revisions are (#{lineage.map{|rs| rs.revision}})") end right_script = desired_script.first end right_script end
[ "def", "right_script_revision_from_lineage", "(", "lineage", ",", "revision", "=", "\"latest\"", ")", "right_script", "=", "nil", "if", "revision", "==", "\"latest\"", "latest_script", "=", "lineage", ".", "max_by", "{", "|", "rs", "|", "rs", ".", "revision", "}", "right_script", "=", "latest_script", "else", "desired_script", "=", "lineage", ".", "select", "{", "|", "rs", "|", "rs", ".", "revision", "==", "revision", "}", "if", "desired_script", ".", "length", "==", "0", "raise", "Exception", "::", "RightScriptNotFound", ".", "new", "(", "\"RightScript revision (#{revision}) was not found. Available revisions are (#{lineage.map{|rs| rs.revision}})\"", ")", "end", "right_script", "=", "desired_script", ".", "first", "end", "right_script", "end" ]
Gets the specified revision of a RightScript from it's lineage @param [Array<RightApi::Resource>] An array of RightApi::Resource objects of media type RightScript[http://reference.rightscale.com/api1.5/media_types/MediaTypeRightScript.html] @param [String] An optional parameter for the desired lineage. When set to "latest" it will get the highest number committed revision. Specify 0 for the head revision. @raise [RightScriptNotFound] If the specified revision is not in the lineage
[ "Gets", "the", "specified", "revision", "of", "a", "RightScript", "from", "it", "s", "lineage" ]
f6396729679c7cf2525aeff9c52c26db75d87a43
https://github.com/rgeyer/rs-mule/blob/f6396729679c7cf2525aeff9c52c26db75d87a43/lib/rs-mule/run_executable.rb#L143-L156
train