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
jduckett/duck_map
lib/duck_map/attributes.rb
DuckMap.Attributes.sitemap_attributes
def sitemap_attributes(key = :default) key = key.blank? ? :default : key.to_sym # if the key exists and has a Hash value, cool. Otherwise, go back to :default. # self.class.sitemap_attributes should ALWAYS return a Hash, so, no need to test for that. # however, key may or may not be a Hash. should test for that. unless self.class.sitemap_attributes[key].kind_of?(Hash) key = :default end # the :default Hash SHOULD ALWAYS be there. If not, this might cause an exception!! return self.class.sitemap_attributes[key] end
ruby
def sitemap_attributes(key = :default) key = key.blank? ? :default : key.to_sym # if the key exists and has a Hash value, cool. Otherwise, go back to :default. # self.class.sitemap_attributes should ALWAYS return a Hash, so, no need to test for that. # however, key may or may not be a Hash. should test for that. unless self.class.sitemap_attributes[key].kind_of?(Hash) key = :default end # the :default Hash SHOULD ALWAYS be there. If not, this might cause an exception!! return self.class.sitemap_attributes[key] end
[ "def", "sitemap_attributes", "(", "key", "=", ":default", ")", "key", "=", "key", ".", "blank?", "?", ":default", ":", "key", ".", "to_sym", "unless", "self", ".", "class", ".", "sitemap_attributes", "[", "key", "]", ".", "kind_of?", "(", "Hash", ")", "key", "=", ":default", "end", "return", "self", ".", "class", ".", "sitemap_attributes", "[", "key", "]", "end" ]
Returns a Hash associated with a key. The Hash represents all of the attributes for a given action name on a controller. acts_as_sitemap :index, title: "my title" # index is the key sitemap_attributes("index") # index is the key @return [Hash]
[ "Returns", "a", "Hash", "associated", "with", "a", "key", ".", "The", "Hash", "represents", "all", "of", "the", "attributes", "for", "a", "given", "action", "name", "on", "a", "controller", "." ]
c510acfa95e8ad4afb1501366058ae88a73704df
https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/attributes.rb#L122-L134
train
mikiobraun/jblas-ruby
lib/jblas/mixin_general.rb
JBLAS.MatrixGeneralMixin.hcat
def hcat(y) unless self.dims[0] == y.dims[0] raise ArgumentError, "Matrices must have same number of rows" end DoubleMatrix.concat_horizontally(self, y) end
ruby
def hcat(y) unless self.dims[0] == y.dims[0] raise ArgumentError, "Matrices must have same number of rows" end DoubleMatrix.concat_horizontally(self, y) end
[ "def", "hcat", "(", "y", ")", "unless", "self", ".", "dims", "[", "0", "]", "==", "y", ".", "dims", "[", "0", "]", "raise", "ArgumentError", ",", "\"Matrices must have same number of rows\"", "end", "DoubleMatrix", ".", "concat_horizontally", "(", "self", ",", "y", ")", "end" ]
Return a new matrix which consists of the _self_ and _y_ side by side. In general the hcat method should be used sparingly as it creates a new matrix and copies everything on each use. You should always ask yourself if an array of vectors or matrices doesn't serve you better. That said, you _can_ do funny things with +inject+. For example, a = mat[1,2,3] [a, 2*a, 3*a].inject {|s,x| s = s.hcat(x)} => 1.0 2.0 3.0 2.0 4.0 6.0 3.0 6.0 9.0
[ "Return", "a", "new", "matrix", "which", "consists", "of", "the", "_self_", "and", "_y_", "side", "by", "side", ".", "In", "general", "the", "hcat", "method", "should", "be", "used", "sparingly", "as", "it", "creates", "a", "new", "matrix", "and", "copies", "everything", "on", "each", "use", ".", "You", "should", "always", "ask", "yourself", "if", "an", "array", "of", "vectors", "or", "matrices", "doesn", "t", "serve", "you", "better", ".", "That", "said", "you", "_can_", "do", "funny", "things", "with", "+", "inject", "+", ".", "For", "example" ]
7233976c9e3b210e30bc36ead2b1e05ab3383fec
https://github.com/mikiobraun/jblas-ruby/blob/7233976c9e3b210e30bc36ead2b1e05ab3383fec/lib/jblas/mixin_general.rb#L114-L119
train
mikiobraun/jblas-ruby
lib/jblas/mixin_general.rb
JBLAS.MatrixGeneralMixin.vcat
def vcat(y) unless self.dims[1] == y.dims[1] raise ArgumentError, "Matrices must have same number of columns" end DoubleMatrix.concat_vertically(self, y) end
ruby
def vcat(y) unless self.dims[1] == y.dims[1] raise ArgumentError, "Matrices must have same number of columns" end DoubleMatrix.concat_vertically(self, y) end
[ "def", "vcat", "(", "y", ")", "unless", "self", ".", "dims", "[", "1", "]", "==", "y", ".", "dims", "[", "1", "]", "raise", "ArgumentError", ",", "\"Matrices must have same number of columns\"", "end", "DoubleMatrix", ".", "concat_vertically", "(", "self", ",", "y", ")", "end" ]
Return a new matrix which consists of the _self_ on top of _y_. In general the hcat methods should be used sparingly. You should always ask yourself if an array of vectors or matrices doesn't serve you better. See also hcat.
[ "Return", "a", "new", "matrix", "which", "consists", "of", "the", "_self_", "on", "top", "of", "_y_", ".", "In", "general", "the", "hcat", "methods", "should", "be", "used", "sparingly", ".", "You", "should", "always", "ask", "yourself", "if", "an", "array", "of", "vectors", "or", "matrices", "doesn", "t", "serve", "you", "better", ".", "See", "also", "hcat", "." ]
7233976c9e3b210e30bc36ead2b1e05ab3383fec
https://github.com/mikiobraun/jblas-ruby/blob/7233976c9e3b210e30bc36ead2b1e05ab3383fec/lib/jblas/mixin_general.rb#L125-L130
train
postmodern/rprogram
lib/rprogram/option.rb
RProgram.Option.arguments
def arguments(value) case value when true [@flag] when false, nil [] else value = super(value) if @multiple args = [] value.each do |arg| args += Array(@formatter.call(self,[arg])) end return args else value = [value.join(@separator)] if @separator return Array(@formatter.call(self,value)) end end end
ruby
def arguments(value) case value when true [@flag] when false, nil [] else value = super(value) if @multiple args = [] value.each do |arg| args += Array(@formatter.call(self,[arg])) end return args else value = [value.join(@separator)] if @separator return Array(@formatter.call(self,value)) end end end
[ "def", "arguments", "(", "value", ")", "case", "value", "when", "true", "[", "@flag", "]", "when", "false", ",", "nil", "[", "]", "else", "value", "=", "super", "(", "value", ")", "if", "@multiple", "args", "=", "[", "]", "value", ".", "each", "do", "|", "arg", "|", "args", "+=", "Array", "(", "@formatter", ".", "call", "(", "self", ",", "[", "arg", "]", ")", ")", "end", "return", "args", "else", "value", "=", "[", "value", ".", "join", "(", "@separator", ")", "]", "if", "@separator", "return", "Array", "(", "@formatter", ".", "call", "(", "self", ",", "value", ")", ")", "end", "end", "end" ]
Creates a new Option object with. If a block is given it will be used for the custom formatting of the option. If a block is not given, the option will use the default_format when generating the arguments. @param [Hash] options Additional options. @option options [String] :flag The command-line flag to use. @option options [true, false] :equals (false) Implies the option maybe formated as `--flag=value`. @option options [true, false] :multiple (false) Specifies the option maybe given an Array of values. @option options [String] :separator The separator to use for formating multiple arguments into one `String`. Cannot be used with the `:multiple` option. @option options [true, false] :sub_options (false) Specifies that the option contains sub-options. @yield [option, value] If a block is given, it will be used to format each value of the option. @yieldparam [Option] option The option that is being formatted. @yieldparam [String, Array] value The value to format for the option. May be an Array, if multiple values are allowed with the option. Formats the arguments for the option. @param [Hash, Array, String] value The arguments to format. @return [Array] The formatted arguments of the option.
[ "Creates", "a", "new", "Option", "object", "with", ".", "If", "a", "block", "is", "given", "it", "will", "be", "used", "for", "the", "custom", "formatting", "of", "the", "option", ".", "If", "a", "block", "is", "not", "given", "the", "option", "will", "use", "the", "default_format", "when", "generating", "the", "arguments", "." ]
94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be
https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/option.rb#L88-L111
train
loveablelobster/specify_cli
lib/specify/database.rb
Specify.Database.close
def close return if sessions.empty? sessions.each do |session| session.close session.delete_observer self end # TODO: should close database connection end
ruby
def close return if sessions.empty? sessions.each do |session| session.close session.delete_observer self end # TODO: should close database connection end
[ "def", "close", "return", "if", "sessions", ".", "empty?", "sessions", ".", "each", "do", "|", "session", "|", "session", ".", "close", "session", ".", "delete_observer", "self", "end", "end" ]
Closes all sessions.
[ "Closes", "all", "sessions", "." ]
79c390307172f1cd8aa288fdde8fb0fc99ad2b91
https://github.com/loveablelobster/specify_cli/blob/79c390307172f1cd8aa288fdde8fb0fc99ad2b91/lib/specify/database.rb#L82-L89
train
boston-library/mei
lib/mei/web_service_base.rb
Mei.WebServiceBase.get_json
def get_json(url) r = Mei::WebServiceBase.fetch(url) JSON.parse(r.body) end
ruby
def get_json(url) r = Mei::WebServiceBase.fetch(url) JSON.parse(r.body) end
[ "def", "get_json", "(", "url", ")", "r", "=", "Mei", "::", "WebServiceBase", ".", "fetch", "(", "url", ")", "JSON", ".", "parse", "(", "r", ".", "body", ")", "end" ]
mix-in to retreive and parse JSON content from the web
[ "mix", "-", "in", "to", "retreive", "and", "parse", "JSON", "content", "from", "the", "web" ]
57279df72a2f45d0fb79fd31c22f495b3a0ae290
https://github.com/boston-library/mei/blob/57279df72a2f45d0fb79fd31c22f495b3a0ae290/lib/mei/web_service_base.rb#L34-L37
train
birarda/logan
lib/logan/comment.rb
Logan.Comment.creator=
def creator=(creator) @creator = creator.is_a?(Hash) ? Logan::Person.new(creator) : creator end
ruby
def creator=(creator) @creator = creator.is_a?(Hash) ? Logan::Person.new(creator) : creator end
[ "def", "creator", "=", "(", "creator", ")", "@creator", "=", "creator", ".", "is_a?", "(", "Hash", ")", "?", "Logan", "::", "Person", ".", "new", "(", "creator", ")", ":", "creator", "end" ]
sets the creator for this todo @param [Object] creator person hash from API or <Logan::Person> object
[ "sets", "the", "creator", "for", "this", "todo" ]
c007081c7dbb5b98ef5312db78f84867c6075ab0
https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/comment.rb#L28-L30
train
birarda/logan
lib/logan/todo.rb
Logan.Todo.assignee=
def assignee=(assignee) @assignee = assignee.is_a?(Hash) ? Logan::Person.new(assignee) : assignee end
ruby
def assignee=(assignee) @assignee = assignee.is_a?(Hash) ? Logan::Person.new(assignee) : assignee end
[ "def", "assignee", "=", "(", "assignee", ")", "@assignee", "=", "assignee", ".", "is_a?", "(", "Hash", ")", "?", "Logan", "::", "Person", ".", "new", "(", "assignee", ")", ":", "assignee", "end" ]
sets the assignee for this todo @param [Object] assignee person hash from API or <Logan::Person> object @return [Logan::Person] the assignee for this todo
[ "sets", "the", "assignee", "for", "this", "todo" ]
c007081c7dbb5b98ef5312db78f84867c6075ab0
https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/todo.rb#L86-L88
train
birarda/logan
lib/logan/todo.rb
Logan.Todo.create_comment
def create_comment(comment) post_params = { :body => comment.post_json, :headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'}) } response = Logan::Client.post "/projects/#{@project_id}/todos/#{@id}/comments.json", post_params Logan::Comment.new response end
ruby
def create_comment(comment) post_params = { :body => comment.post_json, :headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'}) } response = Logan::Client.post "/projects/#{@project_id}/todos/#{@id}/comments.json", post_params Logan::Comment.new response end
[ "def", "create_comment", "(", "comment", ")", "post_params", "=", "{", ":body", "=>", "comment", ".", "post_json", ",", ":headers", "=>", "Logan", "::", "Client", ".", "headers", ".", "merge", "(", "{", "'Content-Type'", "=>", "'application/json'", "}", ")", "}", "response", "=", "Logan", "::", "Client", ".", "post", "\"/projects/#{@project_id}/todos/#{@id}/comments.json\"", ",", "post_params", "Logan", "::", "Comment", ".", "new", "response", "end" ]
create a create in this todo list via the Basecamp API @param [Logan::Comment] todo the comment instance to create in this todo lost @return [Logan::Comment] the created comment returned from the Basecamp API
[ "create", "a", "create", "in", "this", "todo", "list", "via", "the", "Basecamp", "API" ]
c007081c7dbb5b98ef5312db78f84867c6075ab0
https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/todo.rb#L94-L102
train
EmmanuelOga/firering
lib/firering/data/room.rb
Firering.Room.today_transcript
def today_transcript(&callback) connection.http(:get, "/room/#{id}/transcript.json") do |data, http| callback.call(data[:messages].map { |msg| Firering::Message.instantiate(connection, msg) }) if callback end end
ruby
def today_transcript(&callback) connection.http(:get, "/room/#{id}/transcript.json") do |data, http| callback.call(data[:messages].map { |msg| Firering::Message.instantiate(connection, msg) }) if callback end end
[ "def", "today_transcript", "(", "&", "callback", ")", "connection", ".", "http", "(", ":get", ",", "\"/room/#{id}/transcript.json\"", ")", "do", "|", "data", ",", "http", "|", "callback", ".", "call", "(", "data", "[", ":messages", "]", ".", "map", "{", "|", "msg", "|", "Firering", "::", "Message", ".", "instantiate", "(", "connection", ",", "msg", ")", "}", ")", "if", "callback", "end", "end" ]
Returns all the messages sent today to a room.
[ "Returns", "all", "the", "messages", "sent", "today", "to", "a", "room", "." ]
9e13dc3399f7429713b5213c5ee77bedf01def31
https://github.com/EmmanuelOga/firering/blob/9e13dc3399f7429713b5213c5ee77bedf01def31/lib/firering/data/room.rb#L50-L54
train
EmmanuelOga/firering
lib/firering/data/room.rb
Firering.Room.transcript
def transcript(year, month, day, &callback) connection.http(:get, "/room/#{id}/transcript/#{year}/#{month}/#{day}.json") do |data, http| callback.call(data[:messages].map { |msg| Firering::Message.instantiate(connection, msg) }) if callback end end
ruby
def transcript(year, month, day, &callback) connection.http(:get, "/room/#{id}/transcript/#{year}/#{month}/#{day}.json") do |data, http| callback.call(data[:messages].map { |msg| Firering::Message.instantiate(connection, msg) }) if callback end end
[ "def", "transcript", "(", "year", ",", "month", ",", "day", ",", "&", "callback", ")", "connection", ".", "http", "(", ":get", ",", "\"/room/#{id}/transcript/#{year}/#{month}/#{day}.json\"", ")", "do", "|", "data", ",", "http", "|", "callback", ".", "call", "(", "data", "[", ":messages", "]", ".", "map", "{", "|", "msg", "|", "Firering", "::", "Message", ".", "instantiate", "(", "connection", ",", "msg", ")", "}", ")", "if", "callback", "end", "end" ]
Returns all the messages sent on a specific date to a room.
[ "Returns", "all", "the", "messages", "sent", "on", "a", "specific", "date", "to", "a", "room", "." ]
9e13dc3399f7429713b5213c5ee77bedf01def31
https://github.com/EmmanuelOga/firering/blob/9e13dc3399f7429713b5213c5ee77bedf01def31/lib/firering/data/room.rb#L57-L61
train
EmmanuelOga/firering
lib/firering/data/room.rb
Firering.Room.speak
def speak(data, &callback) connection.http(:post, "/room/#{id}/speak.json", "message" => data) do |data, http| # Response Status: 201 Created callback.call(Firering::Message.instantiate(connection, data, "message")) if callback end end
ruby
def speak(data, &callback) connection.http(:post, "/room/#{id}/speak.json", "message" => data) do |data, http| # Response Status: 201 Created callback.call(Firering::Message.instantiate(connection, data, "message")) if callback end end
[ "def", "speak", "(", "data", ",", "&", "callback", ")", "connection", ".", "http", "(", ":post", ",", "\"/room/#{id}/speak.json\"", ",", "\"message\"", "=>", "data", ")", "do", "|", "data", ",", "http", "|", "callback", ".", "call", "(", "Firering", "::", "Message", ".", "instantiate", "(", "connection", ",", "data", ",", "\"message\"", ")", ")", "if", "callback", "end", "end" ]
Sends a new message with the currently authenticated user as the sender. The XML for the new message is returned on a successful request. The valid types are: * TextMessage (regular chat message) * PasteMessage (pre-formatted message, rendered in a fixed-width font) * SoundMessage (plays a sound as determined by the message, which can be either “rimshot”, “crickets”, or “trombone”) * TweetMessage (a Twitter status URL to be fetched and inserted into the chat) If an explicit type is omitted, it will be inferred from the content (e.g., if the message contains new line characters, it will be considered a paste). :type => "TextMessage", :body => "Hello"
[ "Sends", "a", "new", "message", "with", "the", "currently", "authenticated", "user", "as", "the", "sender", ".", "The", "XML", "for", "the", "new", "message", "is", "returned", "on", "a", "successful", "request", "." ]
9e13dc3399f7429713b5213c5ee77bedf01def31
https://github.com/EmmanuelOga/firering/blob/9e13dc3399f7429713b5213c5ee77bedf01def31/lib/firering/data/room.rb#L97-L101
train
mirego/emotions
lib/emotions/emotion.rb
Emotions.Emotion.ensure_valid_emotion_name
def ensure_valid_emotion_name unless Emotions.emotions.include?(emotion.try(:to_sym)) errors.add :emotion, I18n.t(:invalid, scope: [:errors, :messages]) end end
ruby
def ensure_valid_emotion_name unless Emotions.emotions.include?(emotion.try(:to_sym)) errors.add :emotion, I18n.t(:invalid, scope: [:errors, :messages]) end end
[ "def", "ensure_valid_emotion_name", "unless", "Emotions", ".", "emotions", ".", "include?", "(", "emotion", ".", "try", "(", ":to_sym", ")", ")", "errors", ".", "add", ":emotion", ",", "I18n", ".", "t", "(", ":invalid", ",", "scope", ":", "[", ":errors", ",", ":messages", "]", ")", "end", "end" ]
Make sure we're using an allowed emotion name
[ "Make", "sure", "we", "re", "using", "an", "allowed", "emotion", "name" ]
f0adc687dbdac906d9fcebfb0f3bf6afb6fa5d56
https://github.com/mirego/emotions/blob/f0adc687dbdac906d9fcebfb0f3bf6afb6fa5d56/lib/emotions/emotion.rb#L33-L37
train
asaaki/sjekksum
lib/sjekksum/isbn10.rb
Sjekksum.ISBN10.of
def of number raise_on_type_mismatch number digits = convert_number_to_digits(number)[0..9] sum = digits.reverse_each.with_index.reduce(0) do |check, (digit, idx)| check += digit * (idx+2) end check = (11 - sum % 11) % 11 check == 10 ? "X" : check end
ruby
def of number raise_on_type_mismatch number digits = convert_number_to_digits(number)[0..9] sum = digits.reverse_each.with_index.reduce(0) do |check, (digit, idx)| check += digit * (idx+2) end check = (11 - sum % 11) % 11 check == 10 ? "X" : check end
[ "def", "of", "number", "raise_on_type_mismatch", "number", "digits", "=", "convert_number_to_digits", "(", "number", ")", "[", "0", "..", "9", "]", "sum", "=", "digits", ".", "reverse_each", ".", "with_index", ".", "reduce", "(", "0", ")", "do", "|", "check", ",", "(", "digit", ",", "idx", ")", "|", "check", "+=", "digit", "*", "(", "idx", "+", "2", ")", "end", "check", "=", "(", "11", "-", "sum", "%", "11", ")", "%", "11", "check", "==", "10", "?", "\"X\"", ":", "check", "end" ]
Calculates ISBN-10 checksum @example Sjekksum::ISBN10.of("147743025") #=> 3 Sjekksum::ISBN10.of("193435600") #=> "X" @param number [Integer, String] number for which the checksum should be calculated @return [Integer, String] calculated checksum
[ "Calculates", "ISBN", "-", "10", "checksum" ]
47a21c19dcffc67a3bef11d4f2de7c167fd20087
https://github.com/asaaki/sjekksum/blob/47a21c19dcffc67a3bef11d4f2de7c167fd20087/lib/sjekksum/isbn10.rb#L21-L31
train
asaaki/sjekksum
lib/sjekksum/isbn10.rb
Sjekksum.ISBN10.valid?
def valid? number raise_on_type_mismatch number num, check = split_isbn_number(number) convert_number_to_digits(num).length == 9 && self.of(num) == check end
ruby
def valid? number raise_on_type_mismatch number num, check = split_isbn_number(number) convert_number_to_digits(num).length == 9 && self.of(num) == check end
[ "def", "valid?", "number", "raise_on_type_mismatch", "number", "num", ",", "check", "=", "split_isbn_number", "(", "number", ")", "convert_number_to_digits", "(", "num", ")", ".", "length", "==", "9", "&&", "self", ".", "of", "(", "num", ")", "==", "check", "end" ]
ISBN-10 validation of provided number @example Sjekksum::ISBN10.valid?("1477430253") #=> true Sjekksum::ISBN10.valid?("193435600X") #=> true @param number [Integer, String] number with included checksum @return [Boolean]
[ "ISBN", "-", "10", "validation", "of", "provided", "number" ]
47a21c19dcffc67a3bef11d4f2de7c167fd20087
https://github.com/asaaki/sjekksum/blob/47a21c19dcffc67a3bef11d4f2de7c167fd20087/lib/sjekksum/isbn10.rb#L44-L48
train
asaaki/sjekksum
lib/sjekksum/isbn10.rb
Sjekksum.ISBN10.convert
def convert number raise_on_type_mismatch number check = self.of(number) if number.is_a?(String) or check.is_a?(String) number.to_s << self.of(number).to_s else convert_to_int(number) * 10 + self.of(number) end end
ruby
def convert number raise_on_type_mismatch number check = self.of(number) if number.is_a?(String) or check.is_a?(String) number.to_s << self.of(number).to_s else convert_to_int(number) * 10 + self.of(number) end end
[ "def", "convert", "number", "raise_on_type_mismatch", "number", "check", "=", "self", ".", "of", "(", "number", ")", "if", "number", ".", "is_a?", "(", "String", ")", "or", "check", ".", "is_a?", "(", "String", ")", "number", ".", "to_s", "<<", "self", ".", "of", "(", "number", ")", ".", "to_s", "else", "convert_to_int", "(", "number", ")", "*", "10", "+", "self", ".", "of", "(", "number", ")", "end", "end" ]
Transforms a number by appending the ISBN-10 checksum digit @example Sjekksum::ISBN10.convert("147743025") #=> "1477430253" Sjekksum::ISBN10.convert("193435600") #=> "193435600X" @param number [Integer, String] number without a checksum @return [Integer, String] final number including the checksum
[ "Transforms", "a", "number", "by", "appending", "the", "ISBN", "-", "10", "checksum", "digit" ]
47a21c19dcffc67a3bef11d4f2de7c167fd20087
https://github.com/asaaki/sjekksum/blob/47a21c19dcffc67a3bef11d4f2de7c167fd20087/lib/sjekksum/isbn10.rb#L61-L69
train
carboncalculated/calculated
lib/calculated/session.rb
Calculated.Session.api_call
def api_call(method, path, params ={}, &proc) if cache = caching? && (@cache[cache_key(path, params)]) return cache else if @logging Calculated::Logging.log_calculated_api(method, path, params) do api_call_without_logging(method, path, params, &proc) end else api_call_without_logging(method, path, params, &proc) end end end
ruby
def api_call(method, path, params ={}, &proc) if cache = caching? && (@cache[cache_key(path, params)]) return cache else if @logging Calculated::Logging.log_calculated_api(method, path, params) do api_call_without_logging(method, path, params, &proc) end else api_call_without_logging(method, path, params, &proc) end end end
[ "def", "api_call", "(", "method", ",", "path", ",", "params", "=", "{", "}", ",", "&", "proc", ")", "if", "cache", "=", "caching?", "&&", "(", "@cache", "[", "cache_key", "(", "path", ",", "params", ")", "]", ")", "return", "cache", "else", "if", "@logging", "Calculated", "::", "Logging", ".", "log_calculated_api", "(", "method", ",", "path", ",", "params", ")", "do", "api_call_without_logging", "(", "method", ",", "path", ",", "params", ",", "&", "proc", ")", "end", "else", "api_call_without_logging", "(", "method", ",", "path", ",", "params", ",", "&", "proc", ")", "end", "end", "end" ]
if we caching and we have the same cache lets try and get the  cache; otherwise we will make the request logging if need be
[ "if", "we", "caching", "and", "we", "have", "the", "same", "cache", "lets", "try", "and", "get", "the", "cache", ";", "otherwise", "we", "will", "make", "the", "request", "logging", "if", "need", "be" ]
0234d89b515db26add000f88c594f6d3fb5edd5e
https://github.com/carboncalculated/calculated/blob/0234d89b515db26add000f88c594f6d3fb5edd5e/lib/calculated/session.rb#L64-L76
train
mattnichols/ice_cube_cron
lib/ice_cube_cron/expression_parser.rb
IceCubeCron.ExpressionParser.split_parts_and_interval
def split_parts_and_interval(expression_str) interval = nil parts = expression_str.split(/ +/).map do |part| part, part_interval = part.split('/') interval = part_interval unless part_interval.blank? next nil if part.blank? || part == '*' part end [parts, interval] end
ruby
def split_parts_and_interval(expression_str) interval = nil parts = expression_str.split(/ +/).map do |part| part, part_interval = part.split('/') interval = part_interval unless part_interval.blank? next nil if part.blank? || part == '*' part end [parts, interval] end
[ "def", "split_parts_and_interval", "(", "expression_str", ")", "interval", "=", "nil", "parts", "=", "expression_str", ".", "split", "(", "/", "/", ")", ".", "map", "do", "|", "part", "|", "part", ",", "part_interval", "=", "part", ".", "split", "(", "'/'", ")", "interval", "=", "part_interval", "unless", "part_interval", ".", "blank?", "next", "nil", "if", "part", ".", "blank?", "||", "part", "==", "'*'", "part", "end", "[", "parts", ",", "interval", "]", "end" ]
Split a cron string and extract the LAST interval that appears
[ "Split", "a", "cron", "string", "and", "extract", "the", "LAST", "interval", "that", "appears" ]
9b406a40b5d15b03a3e58cb0ec64ca4a85a85cd0
https://github.com/mattnichols/ice_cube_cron/blob/9b406a40b5d15b03a3e58cb0ec64ca4a85a85cd0/lib/ice_cube_cron/expression_parser.rb#L158-L169
train
mattnichols/ice_cube_cron
lib/ice_cube_cron/expression_parser.rb
IceCubeCron.ExpressionParser.string_to_expression_parts
def string_to_expression_parts(expression_str) return {} if expression_str.nil? parts, interval = split_parts_and_interval(expression_str) expression_parts = ::Hash[EXPRESSION_PART_KEYS.zip(parts)] expression_parts.select! do |_key, value| !value.nil? end expression_parts[:interval] = interval unless interval.nil? expression_parts end
ruby
def string_to_expression_parts(expression_str) return {} if expression_str.nil? parts, interval = split_parts_and_interval(expression_str) expression_parts = ::Hash[EXPRESSION_PART_KEYS.zip(parts)] expression_parts.select! do |_key, value| !value.nil? end expression_parts[:interval] = interval unless interval.nil? expression_parts end
[ "def", "string_to_expression_parts", "(", "expression_str", ")", "return", "{", "}", "if", "expression_str", ".", "nil?", "parts", ",", "interval", "=", "split_parts_and_interval", "(", "expression_str", ")", "expression_parts", "=", "::", "Hash", "[", "EXPRESSION_PART_KEYS", ".", "zip", "(", "parts", ")", "]", "expression_parts", ".", "select!", "do", "|", "_key", ",", "value", "|", "!", "value", ".", "nil?", "end", "expression_parts", "[", ":interval", "]", "=", "interval", "unless", "interval", ".", "nil?", "expression_parts", "end" ]
Split string expression into parts
[ "Split", "string", "expression", "into", "parts" ]
9b406a40b5d15b03a3e58cb0ec64ca4a85a85cd0
https://github.com/mattnichols/ice_cube_cron/blob/9b406a40b5d15b03a3e58cb0ec64ca4a85a85cd0/lib/ice_cube_cron/expression_parser.rb#L174-L186
train
jarhart/rattler
lib/rattler/parsers/assert.rb
Rattler::Parsers.Assert.parse
def parse(scanner, rules, scope = ParserScope.empty) pos = scanner.pos result = (child.parse(scanner, rules, scope) && true) scanner.pos = pos result end
ruby
def parse(scanner, rules, scope = ParserScope.empty) pos = scanner.pos result = (child.parse(scanner, rules, scope) && true) scanner.pos = pos result end
[ "def", "parse", "(", "scanner", ",", "rules", ",", "scope", "=", "ParserScope", ".", "empty", ")", "pos", "=", "scanner", ".", "pos", "result", "=", "(", "child", ".", "parse", "(", "scanner", ",", "rules", ",", "scope", ")", "&&", "true", ")", "scanner", ".", "pos", "=", "pos", "result", "end" ]
Succeed or fail like the decorated parser but do not consume any input and return +true+ on success. @param (see Match#parse) @return [Boolean] +true+ if the decorated parser succeeds
[ "Succeed", "or", "fail", "like", "the", "decorated", "parser", "but", "do", "not", "consume", "any", "input", "and", "return", "+", "true", "+", "on", "success", "." ]
8b4efde2a05e9e790955bb635d4a1a9615893719
https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/parsers/assert.rb#L15-L20
train
marcmo/cxxproject
lib/cxxproject/buildingblocks/shared_libs_helper.rb
Cxxproject.OsxSharedLibs.post_link_hook
def post_link_hook(linker, bb) basic_name = get_basic_name(linker, bb) symlink_lib_to(basic_name, bb) end
ruby
def post_link_hook(linker, bb) basic_name = get_basic_name(linker, bb) symlink_lib_to(basic_name, bb) end
[ "def", "post_link_hook", "(", "linker", ",", "bb", ")", "basic_name", "=", "get_basic_name", "(", "linker", ",", "bb", ")", "symlink_lib_to", "(", "basic_name", ",", "bb", ")", "end" ]
Some symbolic links ln -s foo.dylib foo.A.dylib
[ "Some", "symbolic", "links", "ln", "-", "s", "foo", ".", "dylib", "foo", ".", "A", ".", "dylib" ]
3740a09d6a143acd96bde3d2ff79055a6b810da4
https://github.com/marcmo/cxxproject/blob/3740a09d6a143acd96bde3d2ff79055a6b810da4/lib/cxxproject/buildingblocks/shared_libs_helper.rb#L38-L41
train
matteolc/t2_airtime
lib/t2_airtime/api.rb
T2Airtime.API.transaction_list
def transaction_list(start = (Time.now - 24.hours), stop = Time.now, msisdn = nil, destination = nil, code = nil) @params = { stop_date: to_yyyymmdd(stop), start_date: to_yyyymmdd(start) } code && !code.empty? && @params[:code] = code msisdn && !msisdn.empty? && @params[:msisdn] = msisdn destination && !destination.empty? && @params[:destination_msisdn] = destination run_action :trans_list end
ruby
def transaction_list(start = (Time.now - 24.hours), stop = Time.now, msisdn = nil, destination = nil, code = nil) @params = { stop_date: to_yyyymmdd(stop), start_date: to_yyyymmdd(start) } code && !code.empty? && @params[:code] = code msisdn && !msisdn.empty? && @params[:msisdn] = msisdn destination && !destination.empty? && @params[:destination_msisdn] = destination run_action :trans_list end
[ "def", "transaction_list", "(", "start", "=", "(", "Time", ".", "now", "-", "24", ".", "hours", ")", ",", "stop", "=", "Time", ".", "now", ",", "msisdn", "=", "nil", ",", "destination", "=", "nil", ",", "code", "=", "nil", ")", "@params", "=", "{", "stop_date", ":", "to_yyyymmdd", "(", "stop", ")", ",", "start_date", ":", "to_yyyymmdd", "(", "start", ")", "}", "code", "&&", "!", "code", ".", "empty?", "&&", "@params", "[", ":code", "]", "=", "code", "msisdn", "&&", "!", "msisdn", ".", "empty?", "&&", "@params", "[", ":msisdn", "]", "=", "msisdn", "destination", "&&", "!", "destination", ".", "empty?", "&&", "@params", "[", ":destination_msisdn", "]", "=", "destination", "run_action", ":trans_list", "end" ]
This method is used to retrieve the list of transactions performed within the date range by the MSISDN if set. Note that both dates are included during the search. parameters ========== msisdn ------ The format must be international with or without the ‘+’ or ‘00’: “6012345678” or “+6012345678” or “006012345678” (Malaysia) destination_msisdn ------------------ The format must be international with or without the ‘+’ or ‘00’: “6012345678” or “+6012345678” or “006012345678” (Malaysia) code ---- The error_code of the transactions to search for. E.g “0” to search for only all successful transactions. If left empty, all transactions will be returned(Failed and successful). start_date ---------- Defines the start date of the search. Format must be YYYY-MM-DD. stop_date --------- Defines the end date of the search (included). Format must be YYYY-MM-DD.
[ "This", "method", "is", "used", "to", "retrieve", "the", "list", "of", "transactions", "performed", "within", "the", "date", "range", "by", "the", "MSISDN", "if", "set", ".", "Note", "that", "both", "dates", "are", "included", "during", "the", "search", "." ]
4aba93d9f92dfae280a59958cccdd04f3fa5e994
https://github.com/matteolc/t2_airtime/blob/4aba93d9f92dfae280a59958cccdd04f3fa5e994/lib/t2_airtime/api.rb#L178-L187
train
profitbricks/profitbricks-sdk-ruby
lib/profitbricks/server.rb
ProfitBricks.Server.detach_volume
def detach_volume(volume_id) volume = ProfitBricks::Volume.get(datacenterId, nil, volume_id) volume.detach(id) end
ruby
def detach_volume(volume_id) volume = ProfitBricks::Volume.get(datacenterId, nil, volume_id) volume.detach(id) end
[ "def", "detach_volume", "(", "volume_id", ")", "volume", "=", "ProfitBricks", "::", "Volume", ".", "get", "(", "datacenterId", ",", "nil", ",", "volume_id", ")", "volume", ".", "detach", "(", "id", ")", "end" ]
Detach volume from server.
[ "Detach", "volume", "from", "server", "." ]
03a379e412b0e6c0789ed14f2449f18bda622742
https://github.com/profitbricks/profitbricks-sdk-ruby/blob/03a379e412b0e6c0789ed14f2449f18bda622742/lib/profitbricks/server.rb#L62-L65
train
jduckett/duck_map
lib/duck_map/controller_helpers.rb
DuckMap.ControllerHelpers.sitemap_setup
def sitemap_setup(options = {}) rows = [] DuckMap.logger.debug "sitemap_setup: action_name => #{options[:action_name]} source => #{options[:source]} model => #{options[:model]}" attributes = self.sitemap_attributes(options[:action_name]) DuckMap.logger.debug "sitemap_setup: attributes => #{attributes}" if attributes.kind_of?(Hash) && attributes[:handler].kind_of?(Hash) && !attributes[:handler][:action_name].blank? config = {handler: attributes[:handler]}.merge(options) rows = self.send(attributes[:handler][:action_name], config) end return rows end
ruby
def sitemap_setup(options = {}) rows = [] DuckMap.logger.debug "sitemap_setup: action_name => #{options[:action_name]} source => #{options[:source]} model => #{options[:model]}" attributes = self.sitemap_attributes(options[:action_name]) DuckMap.logger.debug "sitemap_setup: attributes => #{attributes}" if attributes.kind_of?(Hash) && attributes[:handler].kind_of?(Hash) && !attributes[:handler][:action_name].blank? config = {handler: attributes[:handler]}.merge(options) rows = self.send(attributes[:handler][:action_name], config) end return rows end
[ "def", "sitemap_setup", "(", "options", "=", "{", "}", ")", "rows", "=", "[", "]", "DuckMap", ".", "logger", ".", "debug", "\"sitemap_setup: action_name => #{options[:action_name]} source => #{options[:source]} model => #{options[:model]}\"", "attributes", "=", "self", ".", "sitemap_attributes", "(", "options", "[", ":action_name", "]", ")", "DuckMap", ".", "logger", ".", "debug", "\"sitemap_setup: attributes => #{attributes}\"", "if", "attributes", ".", "kind_of?", "(", "Hash", ")", "&&", "attributes", "[", ":handler", "]", ".", "kind_of?", "(", "Hash", ")", "&&", "!", "attributes", "[", ":handler", "]", "[", ":action_name", "]", ".", "blank?", "config", "=", "{", "handler", ":", "attributes", "[", ":handler", "]", "}", ".", "merge", "(", "options", ")", "rows", "=", "self", ".", "send", "(", "attributes", "[", ":handler", "]", "[", ":action_name", "]", ",", "config", ")", "end", "return", "rows", "end" ]
Determines all of the attributes defined for a controller, then, calls the handler method on the controller to generate and return an Array of Hashes representing all of the url nodes to be included in the sitemap for the current route being processed. @return [Array] An Array of Hashes.
[ "Determines", "all", "of", "the", "attributes", "defined", "for", "a", "controller", "then", "calls", "the", "handler", "method", "on", "the", "controller", "to", "generate", "and", "return", "an", "Array", "of", "Hashes", "representing", "all", "of", "the", "url", "nodes", "to", "be", "included", "in", "the", "sitemap", "for", "the", "current", "route", "being", "processed", "." ]
c510acfa95e8ad4afb1501366058ae88a73704df
https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/controller_helpers.rb#L93-L108
train
jarhart/rattler
lib/rattler/util/parser_cli.rb
Rattler::Util.ParserCLI.run
def run show_result @parser_class.parse!(ARGF.read) rescue Rattler::Runtime::SyntaxError => e puts e end
ruby
def run show_result @parser_class.parse!(ARGF.read) rescue Rattler::Runtime::SyntaxError => e puts e end
[ "def", "run", "show_result", "@parser_class", ".", "parse!", "(", "ARGF", ".", "read", ")", "rescue", "Rattler", "::", "Runtime", "::", "SyntaxError", "=>", "e", "puts", "e", "end" ]
Create a new command line interface for the given parser class @param [Class] parser_class the parser class to run the command line interface for Run the command line interface
[ "Create", "a", "new", "command", "line", "interface", "for", "the", "given", "parser", "class" ]
8b4efde2a05e9e790955bb635d4a1a9615893719
https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/util/parser_cli.rb#L65-L69
train
jdee/pattern_patch
lib/pattern_patch.rb
PatternPatch.Methods.patch
def patch(name) raise ConfigurationError, "patch_dir has not been set" if patch_dir.nil? raise ConfigurationError, "patch_dir is not a directory" unless Dir.exist?(patch_dir) Patch.from_yaml File.join(patch_dir, "#{name}.yml") end
ruby
def patch(name) raise ConfigurationError, "patch_dir has not been set" if patch_dir.nil? raise ConfigurationError, "patch_dir is not a directory" unless Dir.exist?(patch_dir) Patch.from_yaml File.join(patch_dir, "#{name}.yml") end
[ "def", "patch", "(", "name", ")", "raise", "ConfigurationError", ",", "\"patch_dir has not been set\"", "if", "patch_dir", ".", "nil?", "raise", "ConfigurationError", ",", "\"patch_dir is not a directory\"", "unless", "Dir", ".", "exist?", "(", "patch_dir", ")", "Patch", ".", "from_yaml", "File", ".", "join", "(", "patch_dir", ",", "\"#{name}.yml\"", ")", "end" ]
Loads a patch from the patch_dir @param name [#to_s] Name of a patch to load from the patch_dir @return [Patch] A patch loaded from the patch_dir @raise [ConfigurationError] If patch_dir is nil or is not a valid directory path
[ "Loads", "a", "patch", "from", "the", "patch_dir" ]
0cd99d338fed2208f31239e511efa47d17099fc3
https://github.com/jdee/pattern_patch/blob/0cd99d338fed2208f31239e511efa47d17099fc3/lib/pattern_patch.rb#L47-L51
train
jarhart/rattler
lib/rattler/runner.rb
Rattler.Runner.run
def run if result = analyze synthesize(result) else puts parser.failure exit ERRNO_PARSE_ERROR end end
ruby
def run if result = analyze synthesize(result) else puts parser.failure exit ERRNO_PARSE_ERROR end end
[ "def", "run", "if", "result", "=", "analyze", "synthesize", "(", "result", ")", "else", "puts", "parser", ".", "failure", "exit", "ERRNO_PARSE_ERROR", "end", "end" ]
Create a new command-line parser. @param [Array<String>] args the command-line arguments Run the command-line parser.
[ "Create", "a", "new", "command", "-", "line", "parser", "." ]
8b4efde2a05e9e790955bb635d4a1a9615893719
https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/runner.rb#L48-L55
train
elifoster/weatheruby
lib/weather/planner.rb
Weather.Planner.get_dewpoints
def get_dewpoints(start_date, end_date, location) response = get_planner_response(start_date, end_date, location) return response['response']['error'] unless response['response']['error'].nil? highs = response['trip']['dewpoint_high'] lows = response['trip']['dewpoint_low'] { high: { imperial: { minimum: highs['min']['F'].to_i, maximum: highs['max']['F'].to_i, average: highs['avg']['F'].to_i }, metric: { minimum: highs['min']['C'].to_i, maximum: highs['max']['C'].to_i, average: highs['avg']['C'].to_i } }, low: { imperial: { minimum: lows['min']['F'].to_i, maximum: lows['max']['F'].to_i, average: lows['avg']['F'].to_i }, metric: { minimum: lows['min']['C'].to_i, maximum: lows['max']['C'].to_i, average: lows['avg']['C'].to_i } } } end
ruby
def get_dewpoints(start_date, end_date, location) response = get_planner_response(start_date, end_date, location) return response['response']['error'] unless response['response']['error'].nil? highs = response['trip']['dewpoint_high'] lows = response['trip']['dewpoint_low'] { high: { imperial: { minimum: highs['min']['F'].to_i, maximum: highs['max']['F'].to_i, average: highs['avg']['F'].to_i }, metric: { minimum: highs['min']['C'].to_i, maximum: highs['max']['C'].to_i, average: highs['avg']['C'].to_i } }, low: { imperial: { minimum: lows['min']['F'].to_i, maximum: lows['max']['F'].to_i, average: lows['avg']['F'].to_i }, metric: { minimum: lows['min']['C'].to_i, maximum: lows['max']['C'].to_i, average: lows['avg']['C'].to_i } } } end
[ "def", "get_dewpoints", "(", "start_date", ",", "end_date", ",", "location", ")", "response", "=", "get_planner_response", "(", "start_date", ",", "end_date", ",", "location", ")", "return", "response", "[", "'response'", "]", "[", "'error'", "]", "unless", "response", "[", "'response'", "]", "[", "'error'", "]", ".", "nil?", "highs", "=", "response", "[", "'trip'", "]", "[", "'dewpoint_high'", "]", "lows", "=", "response", "[", "'trip'", "]", "[", "'dewpoint_low'", "]", "{", "high", ":", "{", "imperial", ":", "{", "minimum", ":", "highs", "[", "'min'", "]", "[", "'F'", "]", ".", "to_i", ",", "maximum", ":", "highs", "[", "'max'", "]", "[", "'F'", "]", ".", "to_i", ",", "average", ":", "highs", "[", "'avg'", "]", "[", "'F'", "]", ".", "to_i", "}", ",", "metric", ":", "{", "minimum", ":", "highs", "[", "'min'", "]", "[", "'C'", "]", ".", "to_i", ",", "maximum", ":", "highs", "[", "'max'", "]", "[", "'C'", "]", ".", "to_i", ",", "average", ":", "highs", "[", "'avg'", "]", "[", "'C'", "]", ".", "to_i", "}", "}", ",", "low", ":", "{", "imperial", ":", "{", "minimum", ":", "lows", "[", "'min'", "]", "[", "'F'", "]", ".", "to_i", ",", "maximum", ":", "lows", "[", "'max'", "]", "[", "'F'", "]", ".", "to_i", ",", "average", ":", "lows", "[", "'avg'", "]", "[", "'F'", "]", ".", "to_i", "}", ",", "metric", ":", "{", "minimum", ":", "lows", "[", "'min'", "]", "[", "'C'", "]", ".", "to_i", ",", "maximum", ":", "lows", "[", "'max'", "]", "[", "'C'", "]", ".", "to_i", ",", "average", ":", "lows", "[", "'avg'", "]", "[", "'C'", "]", ".", "to_i", "}", "}", "}", "end" ]
Gets the dewpoint highs and lows for the date range. @param (see #get_planner_response) @return [Hash<Symbol, Hash<Symbol, Hash<Symbol, Integer>>>] Highs and lows minimum, average, and maximum for both metric and imperial systems. @return [String] The error if possible. @todo Raise an error instead of returning a String.
[ "Gets", "the", "dewpoint", "highs", "and", "lows", "for", "the", "date", "range", "." ]
4d97db082448765b67ef5112c89346e502a74858
https://github.com/elifoster/weatheruby/blob/4d97db082448765b67ef5112c89346e502a74858/lib/weather/planner.rb#L135-L167
train
elifoster/weatheruby
lib/weather/planner.rb
Weather.Planner.get_planner_response
def get_planner_response(start_date, end_date, location) start = start_date.strftime('%m%d') final = end_date.strftime('%m%d') get("planner_#{start}#{final}", location) end
ruby
def get_planner_response(start_date, end_date, location) start = start_date.strftime('%m%d') final = end_date.strftime('%m%d') get("planner_#{start}#{final}", location) end
[ "def", "get_planner_response", "(", "start_date", ",", "end_date", ",", "location", ")", "start", "=", "start_date", ".", "strftime", "(", "'%m%d'", ")", "final", "=", "end_date", ".", "strftime", "(", "'%m%d'", ")", "get", "(", "\"planner_#{start}#{final}\"", ",", "location", ")", "end" ]
Gets the full planner API response. @param start_date [DateTime] The date to start at. Only month and day actually matter. @param end_date [DateTime] The date to end at. Only month and day actually matter. @param location [String] The location to get the planner data for. @since 0.5.0 @return (see Weatheruby#get)
[ "Gets", "the", "full", "planner", "API", "response", "." ]
4d97db082448765b67ef5112c89346e502a74858
https://github.com/elifoster/weatheruby/blob/4d97db082448765b67ef5112c89346e502a74858/lib/weather/planner.rb#L244-L248
train
jrochkind/borrow_direct
lib/borrow_direct/util.rb
BorrowDirect.Util.hash_key_path
def hash_key_path(hash, *path) result = nil path.each do |key| return nil unless hash.respond_to? :"[]" result = hash = hash[key] end return result end
ruby
def hash_key_path(hash, *path) result = nil path.each do |key| return nil unless hash.respond_to? :"[]" result = hash = hash[key] end return result end
[ "def", "hash_key_path", "(", "hash", ",", "*", "path", ")", "result", "=", "nil", "path", ".", "each", "do", "|", "key", "|", "return", "nil", "unless", "hash", ".", "respond_to?", ":\"", "\"", "result", "=", "hash", "=", "hash", "[", "key", "]", "end", "return", "result", "end" ]
A utility method that lets you access a nested hash, returning nil if any intermediate hashes are unavailable.
[ "A", "utility", "method", "that", "lets", "you", "access", "a", "nested", "hash", "returning", "nil", "if", "any", "intermediate", "hashes", "are", "unavailable", "." ]
f2f53760e15d742a5c5584dd641f20dea315f99f
https://github.com/jrochkind/borrow_direct/blob/f2f53760e15d742a5c5584dd641f20dea315f99f/lib/borrow_direct/util.rb#L5-L14
train
anthonator/dirigible
lib/dirigible/configuration.rb
Dirigible.Configuration.options
def options VALID_OPTION_KEYS.inject({}) do |option, key| option.merge!(key => send(key)) end end
ruby
def options VALID_OPTION_KEYS.inject({}) do |option, key| option.merge!(key => send(key)) end end
[ "def", "options", "VALID_OPTION_KEYS", ".", "inject", "(", "{", "}", ")", "do", "|", "option", ",", "key", "|", "option", ".", "merge!", "(", "key", "=>", "send", "(", "key", ")", ")", "end", "end" ]
Create a hash of options and their values.
[ "Create", "a", "hash", "of", "options", "and", "their", "values", "." ]
829b265ae4e54e3d4b284900b2a51a707afb6105
https://github.com/anthonator/dirigible/blob/829b265ae4e54e3d4b284900b2a51a707afb6105/lib/dirigible/configuration.rb#L46-L50
train
birarda/logan
lib/logan/project_template.rb
Logan.ProjectTemplate.create_project
def create_project( name, description = nil) post_params = { :body => {name: name, description: description}.to_json, :headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'}) } response = Logan::Client.post "/project_templates/#{@id}/projects.json", post_params Logan::Project.new response end
ruby
def create_project( name, description = nil) post_params = { :body => {name: name, description: description}.to_json, :headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'}) } response = Logan::Client.post "/project_templates/#{@id}/projects.json", post_params Logan::Project.new response end
[ "def", "create_project", "(", "name", ",", "description", "=", "nil", ")", "post_params", "=", "{", ":body", "=>", "{", "name", ":", "name", ",", "description", ":", "description", "}", ".", "to_json", ",", ":headers", "=>", "Logan", "::", "Client", ".", "headers", ".", "merge", "(", "{", "'Content-Type'", "=>", "'application/json'", "}", ")", "}", "response", "=", "Logan", "::", "Client", ".", "post", "\"/project_templates/#{@id}/projects.json\"", ",", "post_params", "Logan", "::", "Project", ".", "new", "response", "end" ]
create a project based on this project template via Basecamp API @param [String] name name for the new project @param [String] description description for the new project @return [Logan::Project] project instance from Basecamp API response
[ "create", "a", "project", "based", "on", "this", "project", "template", "via", "Basecamp", "API" ]
c007081c7dbb5b98ef5312db78f84867c6075ab0
https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/project_template.rb#L16-L24
train
jduckett/duck_map
lib/duck_map/config.rb
DuckMap.ConfigHelpers.log_level
def log_level(value, options = {}) DuckMap::Logger.log_level = value if options.has_key?(:full) DuckMap.logger.full_exception = options[:full] end end
ruby
def log_level(value, options = {}) DuckMap::Logger.log_level = value if options.has_key?(:full) DuckMap.logger.full_exception = options[:full] end end
[ "def", "log_level", "(", "value", ",", "options", "=", "{", "}", ")", "DuckMap", "::", "Logger", ".", "log_level", "=", "value", "if", "options", ".", "has_key?", "(", ":full", ")", "DuckMap", ".", "logger", ".", "full_exception", "=", "options", "[", ":full", "]", "end", "end" ]
Sets the logging level. # sets the logging level to :debug and full stack traces for exceptions. MyApp::Application.routes.draw do log_level :debug, full: true end @param [Symbol] value The logger level to use. Valid values are: - :debug - :info - :warn - :error - :fatal - :unknown @param [Hash] options Options Hash. @option options [Symbol] :full Including full: true will include full stack traces for exceptions. Otherwise, stack traces are stripped and attempt to only include application traces.
[ "Sets", "the", "logging", "level", "." ]
c510acfa95e8ad4afb1501366058ae88a73704df
https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/config.rb#L242-L247
train
postmodern/rprogram
lib/rprogram/task.rb
RProgram.Task.leading_non_options
def leading_non_options args = [] # add the task leading non-options @options.each do |name,value| non_opt = get_non_option(name) if (non_opt && non_opt.leading?) args += non_opt.arguments(value) end end # add all leading subtask non-options @subtasks.each_value do |task| args += task.leading_non_options end return args end
ruby
def leading_non_options args = [] # add the task leading non-options @options.each do |name,value| non_opt = get_non_option(name) if (non_opt && non_opt.leading?) args += non_opt.arguments(value) end end # add all leading subtask non-options @subtasks.each_value do |task| args += task.leading_non_options end return args end
[ "def", "leading_non_options", "args", "=", "[", "]", "@options", ".", "each", "do", "|", "name", ",", "value", "|", "non_opt", "=", "get_non_option", "(", "name", ")", "if", "(", "non_opt", "&&", "non_opt", ".", "leading?", ")", "args", "+=", "non_opt", ".", "arguments", "(", "value", ")", "end", "end", "@subtasks", ".", "each_value", "do", "|", "task", "|", "args", "+=", "task", ".", "leading_non_options", "end", "return", "args", "end" ]
Generates the command-line arguments for all leading non-options. @return [Array] The command-line arguments generated from all the leading non-options of the task and it's sub-tasks.
[ "Generates", "the", "command", "-", "line", "arguments", "for", "all", "leading", "non", "-", "options", "." ]
94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be
https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/task.rb#L208-L226
train
postmodern/rprogram
lib/rprogram/task.rb
RProgram.Task.options
def options args = [] # add all subtask options @subtasks.each_value do |task| args += task.arguments end # add the task options @options.each do |name,value| opt = get_option(name) args += opt.arguments(value) if opt end return args end
ruby
def options args = [] # add all subtask options @subtasks.each_value do |task| args += task.arguments end # add the task options @options.each do |name,value| opt = get_option(name) args += opt.arguments(value) if opt end return args end
[ "def", "options", "args", "=", "[", "]", "@subtasks", ".", "each_value", "do", "|", "task", "|", "args", "+=", "task", ".", "arguments", "end", "@options", ".", "each", "do", "|", "name", ",", "value", "|", "opt", "=", "get_option", "(", "name", ")", "args", "+=", "opt", ".", "arguments", "(", "value", ")", "if", "opt", "end", "return", "args", "end" ]
Generates the command-line arguments from all options. @return [Array] The command-line arguments generated from all the options of the task and it's sub-tasks.
[ "Generates", "the", "command", "-", "line", "arguments", "from", "all", "options", "." ]
94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be
https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/task.rb#L235-L250
train
postmodern/rprogram
lib/rprogram/task.rb
RProgram.Task.tailing_non_options
def tailing_non_options args = [] # add all tailing subtask non-options @subtasks.each_value do |task| args += task.tailing_non_options end # add the task tailing non-options @options.each do |name,value| non_opt = get_non_option(name) if (non_opt && non_opt.tailing?) args += non_opt.arguments(value) end end return args end
ruby
def tailing_non_options args = [] # add all tailing subtask non-options @subtasks.each_value do |task| args += task.tailing_non_options end # add the task tailing non-options @options.each do |name,value| non_opt = get_non_option(name) if (non_opt && non_opt.tailing?) args += non_opt.arguments(value) end end return args end
[ "def", "tailing_non_options", "args", "=", "[", "]", "@subtasks", ".", "each_value", "do", "|", "task", "|", "args", "+=", "task", ".", "tailing_non_options", "end", "@options", ".", "each", "do", "|", "name", ",", "value", "|", "non_opt", "=", "get_non_option", "(", "name", ")", "if", "(", "non_opt", "&&", "non_opt", ".", "tailing?", ")", "args", "+=", "non_opt", ".", "arguments", "(", "value", ")", "end", "end", "return", "args", "end" ]
Generates the command-line arguments from all tailing non-options. @return [Array] The command-line arguments generated from all the tailing non-options of the task and it's sub-tasks.
[ "Generates", "the", "command", "-", "line", "arguments", "from", "all", "tailing", "non", "-", "options", "." ]
94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be
https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/task.rb#L259-L277
train
postmodern/rprogram
lib/rprogram/task.rb
RProgram.Task.arguments
def arguments tailing_args = tailing_non_options if tailing_args.any? { |arg| arg[0,1] == '-' } tailing_args.unshift('--') end return leading_non_options + options + tailing_args end
ruby
def arguments tailing_args = tailing_non_options if tailing_args.any? { |arg| arg[0,1] == '-' } tailing_args.unshift('--') end return leading_non_options + options + tailing_args end
[ "def", "arguments", "tailing_args", "=", "tailing_non_options", "if", "tailing_args", ".", "any?", "{", "|", "arg", "|", "arg", "[", "0", ",", "1", "]", "==", "'-'", "}", "tailing_args", ".", "unshift", "(", "'--'", ")", "end", "return", "leading_non_options", "+", "options", "+", "tailing_args", "end" ]
Generates the command-line arguments from the task. @return [Array] The command-line arguments compiled from the leading non-options, options and tailing non-options of the task and it's sub-tasks.
[ "Generates", "the", "command", "-", "line", "arguments", "from", "the", "task", "." ]
94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be
https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/task.rb#L286-L294
train
jarhart/rattler
lib/rattler/compiler/optimizer/optimization_sequence.rb
Rattler::Compiler::Optimizer.OptimizationSequence.deep_apply
def deep_apply(parser, context) parser = apply(parser, context) apply(parser.map_children { |child| deep_apply(child, child_context(parser, context)) }, context) end
ruby
def deep_apply(parser, context) parser = apply(parser, context) apply(parser.map_children { |child| deep_apply(child, child_context(parser, context)) }, context) end
[ "def", "deep_apply", "(", "parser", ",", "context", ")", "parser", "=", "apply", "(", "parser", ",", "context", ")", "apply", "(", "parser", ".", "map_children", "{", "|", "child", "|", "deep_apply", "(", "child", ",", "child_context", "(", "parser", ",", "context", ")", ")", "}", ",", "context", ")", "end" ]
Apply the optimzations to +parser+'s children, then to +parser+, in +context+. @param [Rattler::Parsers::Parser] parser the parser to be optimized @param [Rattler::Compiler::Optimizer::OptimizationContext] context @return [Rattler::Parsers::Parser] the optimized parser
[ "Apply", "the", "optimzations", "to", "+", "parser", "+", "s", "children", "then", "to", "+", "parser", "+", "in", "+", "context", "+", "." ]
8b4efde2a05e9e790955bb635d4a1a9615893719
https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/compiler/optimizer/optimization_sequence.rb#L25-L30
train
jarhart/rattler
lib/rattler/parsers/choice.rb
Rattler::Parsers.Choice.parse
def parse(scanner, rules, scope = ParserScope.empty) for child in children if r = child.parse(scanner, rules, scope) return r end end false end
ruby
def parse(scanner, rules, scope = ParserScope.empty) for child in children if r = child.parse(scanner, rules, scope) return r end end false end
[ "def", "parse", "(", "scanner", ",", "rules", ",", "scope", "=", "ParserScope", ".", "empty", ")", "for", "child", "in", "children", "if", "r", "=", "child", ".", "parse", "(", "scanner", ",", "rules", ",", "scope", ")", "return", "r", "end", "end", "false", "end" ]
Try each parser in order until one succeeds and return that result. @param (see Match#parse) @return the result of the first parser that matches, or +false+
[ "Try", "each", "parser", "in", "order", "until", "one", "succeeds", "and", "return", "that", "result", "." ]
8b4efde2a05e9e790955bb635d4a1a9615893719
https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/parsers/choice.rb#L21-L28
train
erikh/archive
lib/archive/compress.rb
Archive.Compress.compress
def compress(files, verbose=false) if files.any? { |f| !File.file?(f) } raise ArgumentError, "Files supplied must all be real, actual files -- not directories or symlinks." end configure_archive compress_files(files, verbose) free_archive end
ruby
def compress(files, verbose=false) if files.any? { |f| !File.file?(f) } raise ArgumentError, "Files supplied must all be real, actual files -- not directories or symlinks." end configure_archive compress_files(files, verbose) free_archive end
[ "def", "compress", "(", "files", ",", "verbose", "=", "false", ")", "if", "files", ".", "any?", "{", "|", "f", "|", "!", "File", ".", "file?", "(", "f", ")", "}", "raise", "ArgumentError", ",", "\"Files supplied must all be real, actual files -- not directories or symlinks.\"", "end", "configure_archive", "compress_files", "(", "files", ",", "verbose", ")", "free_archive", "end" ]
Create a new Compress object. Takes a filename as string, and args as hash. args is a hash that contains two values, :type and :compression. * :type may be :tar or :zip * :compression may be :gzip, :bzip2, or nil (no compression) If the type :zip is selected, no compression will be used. Additionally, files in the .zip will all be stored as binary files. The default set of arguments is { :type => :tar, :compression => :gzip } Run the compression. Files are an array of filenames. Optional flag for verbosity; if true, will print each file it adds to the archive to stdout. Files must be real files. No symlinks, directories, unix sockets, character devices, etc. This method will raise ArgumentError if you provide any.
[ "Create", "a", "new", "Compress", "object", ".", "Takes", "a", "filename", "as", "string", "and", "args", "as", "hash", "." ]
b120f120ce881d194b5418ec0e5c08fd1dd6d144
https://github.com/erikh/archive/blob/b120f120ce881d194b5418ec0e5c08fd1dd6d144/lib/archive/compress.rb#L53-L61
train
nyk/catflap
lib/catflap/http.rb
CfWebserver.CfApiServlet.do_POST
def do_POST(req, resp) # Split the path into piece path = req.path[1..-1].split('/') # We don't want to cache catflap login page so set response headers. # Chrome and FF respect the no-store, while IE respects no-cache. resp['Cache-Control'] = 'no-cache, no-store' resp['Pragma'] = 'no-cache' # Legacy resp['Expires'] = '-1' # Microsoft advises this for older IE browsers. response_class = CfRestService.const_get 'CfRestService' raise "#{response_class} not a Class" unless response_class.is_a?(Class) raise HTTPStatus::NotFound unless path[1] response_method = path[1].to_sym # Make sure the method exists in the class raise HTTPStatus::NotFound unless response_class .respond_to? response_method if :sync == response_method resp.body = response_class.send response_method, req, resp, @cf end if :knock == response_method resp.body = response_class.send response_method, req, resp, @cf end # Remaining path segments get passed in as arguments to the method if path.length > 2 resp.body = response_class.send response_method, req, resp, @cf, path[1..-1] else resp.body = response_class.send response_method, req, resp, @cf end raise HTTPStatus::OK end
ruby
def do_POST(req, resp) # Split the path into piece path = req.path[1..-1].split('/') # We don't want to cache catflap login page so set response headers. # Chrome and FF respect the no-store, while IE respects no-cache. resp['Cache-Control'] = 'no-cache, no-store' resp['Pragma'] = 'no-cache' # Legacy resp['Expires'] = '-1' # Microsoft advises this for older IE browsers. response_class = CfRestService.const_get 'CfRestService' raise "#{response_class} not a Class" unless response_class.is_a?(Class) raise HTTPStatus::NotFound unless path[1] response_method = path[1].to_sym # Make sure the method exists in the class raise HTTPStatus::NotFound unless response_class .respond_to? response_method if :sync == response_method resp.body = response_class.send response_method, req, resp, @cf end if :knock == response_method resp.body = response_class.send response_method, req, resp, @cf end # Remaining path segments get passed in as arguments to the method if path.length > 2 resp.body = response_class.send response_method, req, resp, @cf, path[1..-1] else resp.body = response_class.send response_method, req, resp, @cf end raise HTTPStatus::OK end
[ "def", "do_POST", "(", "req", ",", "resp", ")", "path", "=", "req", ".", "path", "[", "1", "..", "-", "1", "]", ".", "split", "(", "'/'", ")", "resp", "[", "'Cache-Control'", "]", "=", "'no-cache, no-store'", "resp", "[", "'Pragma'", "]", "=", "'no-cache'", "resp", "[", "'Expires'", "]", "=", "'-1'", "response_class", "=", "CfRestService", ".", "const_get", "'CfRestService'", "raise", "\"#{response_class} not a Class\"", "unless", "response_class", ".", "is_a?", "(", "Class", ")", "raise", "HTTPStatus", "::", "NotFound", "unless", "path", "[", "1", "]", "response_method", "=", "path", "[", "1", "]", ".", "to_sym", "raise", "HTTPStatus", "::", "NotFound", "unless", "response_class", ".", "respond_to?", "response_method", "if", ":sync", "==", "response_method", "resp", ".", "body", "=", "response_class", ".", "send", "response_method", ",", "req", ",", "resp", ",", "@cf", "end", "if", ":knock", "==", "response_method", "resp", ".", "body", "=", "response_class", ".", "send", "response_method", ",", "req", ",", "resp", ",", "@cf", "end", "if", "path", ".", "length", ">", "2", "resp", ".", "body", "=", "response_class", ".", "send", "response_method", ",", "req", ",", "resp", ",", "@cf", ",", "path", "[", "1", "..", "-", "1", "]", "else", "resp", ".", "body", "=", "response_class", ".", "send", "response_method", ",", "req", ",", "resp", ",", "@cf", "end", "raise", "HTTPStatus", "::", "OK", "end" ]
Initializer to construct a new CfApiServlet object. @param [HTTPServer] server a WEBrick HTTP server object. @param [Catflap] cf a fully instantiated Catflap object. @return void Implementation of HTTPServlet::AbstractServlet method to handle GET method requests. @param [HTTPRequest] req a WEBrick::HTTPRequest object. @param [HTTPResponse] resp a WEBrick::HTTPResponse object. @return void rubocop:disable Style/MethodName
[ "Initializer", "to", "construct", "a", "new", "CfApiServlet", "object", "." ]
e146e5df6d8d0085c127bf3ab77bfecfa9af78d9
https://github.com/nyk/catflap/blob/e146e5df6d8d0085c127bf3ab77bfecfa9af78d9/lib/catflap/http.rb#L161-L198
train
KDEJewellers/aptly-api
lib/aptly/snapshot.rb
Aptly.Snapshot.update!
def update!(**kwords) kwords = kwords.map { |k, v| [k.to_s.capitalize, v] }.to_h response = @connection.send(:put, "/snapshots/#{self.Name}", body: JSON.generate(kwords)) hash = JSON.parse(response.body, symbolize_names: true) return nil if hash == marshal_dump marshal_load(hash) self end
ruby
def update!(**kwords) kwords = kwords.map { |k, v| [k.to_s.capitalize, v] }.to_h response = @connection.send(:put, "/snapshots/#{self.Name}", body: JSON.generate(kwords)) hash = JSON.parse(response.body, symbolize_names: true) return nil if hash == marshal_dump marshal_load(hash) self end
[ "def", "update!", "(", "**", "kwords", ")", "kwords", "=", "kwords", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ".", "to_s", ".", "capitalize", ",", "v", "]", "}", ".", "to_h", "response", "=", "@connection", ".", "send", "(", ":put", ",", "\"/snapshots/#{self.Name}\"", ",", "body", ":", "JSON", ".", "generate", "(", "kwords", ")", ")", "hash", "=", "JSON", ".", "parse", "(", "response", ".", "body", ",", "symbolize_names", ":", "true", ")", "return", "nil", "if", "hash", "==", "marshal_dump", "marshal_load", "(", "hash", ")", "self", "end" ]
Updates this snapshot @return [self] if the instance data was mutated @return [nil] if the instance data was not mutated
[ "Updates", "this", "snapshot" ]
71a13417618d81ca0dcb7834559de1f31ec46e29
https://github.com/KDEJewellers/aptly-api/blob/71a13417618d81ca0dcb7834559de1f31ec46e29/lib/aptly/snapshot.rb#L13-L22
train
KDEJewellers/aptly-api
lib/aptly/snapshot.rb
Aptly.Snapshot.diff
def diff(other_snapshot) endpoint = "/snapshots/#{self.Name}/diff/#{other_snapshot.Name}" response = @connection.send(:get, endpoint) JSON.parse(response.body) end
ruby
def diff(other_snapshot) endpoint = "/snapshots/#{self.Name}/diff/#{other_snapshot.Name}" response = @connection.send(:get, endpoint) JSON.parse(response.body) end
[ "def", "diff", "(", "other_snapshot", ")", "endpoint", "=", "\"/snapshots/#{self.Name}/diff/#{other_snapshot.Name}\"", "response", "=", "@connection", ".", "send", "(", ":get", ",", "endpoint", ")", "JSON", ".", "parse", "(", "response", ".", "body", ")", "end" ]
Find differences between this and another snapshot @param other_snapshot [Snapshot] to diff against @return [Array<Hash>] diff between the two snashots
[ "Find", "differences", "between", "this", "and", "another", "snapshot" ]
71a13417618d81ca0dcb7834559de1f31ec46e29
https://github.com/KDEJewellers/aptly-api/blob/71a13417618d81ca0dcb7834559de1f31ec46e29/lib/aptly/snapshot.rb#L33-L37
train
experteer/codeqa
lib/codeqa/configuration.rb
Codeqa.Configuration.git_root_till_home
def git_root_till_home Pathname.new(Dir.pwd).ascend do |dir_pathname| return dir_pathname if File.directory?("#{dir_pathname}/.git") return nil if dir_pathname.to_s == home_dir end end
ruby
def git_root_till_home Pathname.new(Dir.pwd).ascend do |dir_pathname| return dir_pathname if File.directory?("#{dir_pathname}/.git") return nil if dir_pathname.to_s == home_dir end end
[ "def", "git_root_till_home", "Pathname", ".", "new", "(", "Dir", ".", "pwd", ")", ".", "ascend", "do", "|", "dir_pathname", "|", "return", "dir_pathname", "if", "File", ".", "directory?", "(", "\"#{dir_pathname}/.git\"", ")", "return", "nil", "if", "dir_pathname", ".", "to_s", "==", "home_dir", "end", "end" ]
ascend from the current dir till I find a .git folder or reach home_dir
[ "ascend", "from", "the", "current", "dir", "till", "I", "find", "a", ".", "git", "folder", "or", "reach", "home_dir" ]
199fa9b686737293a3c20148ad708a60e6fef667
https://github.com/experteer/codeqa/blob/199fa9b686737293a3c20148ad708a60e6fef667/lib/codeqa/configuration.rb#L61-L66
train
m-31/puppetdb_query
lib/puppetdb_query/mongodb.rb
PuppetDBQuery.MongoDB.node_properties
def node_properties collection = connection[node_properties_collection] result = {} collection.find.batch_size(999).each do |values| id = values.delete('_id') result[id] = values end result end
ruby
def node_properties collection = connection[node_properties_collection] result = {} collection.find.batch_size(999).each do |values| id = values.delete('_id') result[id] = values end result end
[ "def", "node_properties", "collection", "=", "connection", "[", "node_properties_collection", "]", "result", "=", "{", "}", "collection", ".", "find", ".", "batch_size", "(", "999", ")", ".", "each", "do", "|", "values", "|", "id", "=", "values", ".", "delete", "(", "'_id'", ")", "result", "[", "id", "]", "=", "values", "end", "result", "end" ]
initialize access to mongodb You might want to adjust the logging level, for example: ::Mongo::Logger.logger.level = logger.level @param connection mongodb connection, should already be switched to correct database @param nodes symbol for collection that contains nodes with their facts @param node_properties symbol for collection for nodes with their update timestamps @param meta symbol for collection with update metadata get all nodes and their update dates
[ "initialize", "access", "to", "mongodb" ]
58103c91f291de8ce28d679256e50ae391b93ecb
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L47-L55
train
m-31/puppetdb_query
lib/puppetdb_query/mongodb.rb
PuppetDBQuery.MongoDB.all_nodes
def all_nodes collection = connection[nodes_collection] collection.find.batch_size(999).projection(_id: 1).map { |k| k[:_id] } end
ruby
def all_nodes collection = connection[nodes_collection] collection.find.batch_size(999).projection(_id: 1).map { |k| k[:_id] } end
[ "def", "all_nodes", "collection", "=", "connection", "[", "nodes_collection", "]", "collection", ".", "find", ".", "batch_size", "(", "999", ")", ".", "projection", "(", "_id", ":", "1", ")", ".", "map", "{", "|", "k", "|", "k", "[", ":_id", "]", "}", "end" ]
get all node names
[ "get", "all", "node", "names" ]
58103c91f291de8ce28d679256e50ae391b93ecb
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L58-L61
train
m-31/puppetdb_query
lib/puppetdb_query/mongodb.rb
PuppetDBQuery.MongoDB.query_nodes
def query_nodes(query) collection = connection[nodes_collection] collection.find(query).batch_size(999).projection(_id: 1).map { |k| k[:_id] } end
ruby
def query_nodes(query) collection = connection[nodes_collection] collection.find(query).batch_size(999).projection(_id: 1).map { |k| k[:_id] } end
[ "def", "query_nodes", "(", "query", ")", "collection", "=", "connection", "[", "nodes_collection", "]", "collection", ".", "find", "(", "query", ")", ".", "batch_size", "(", "999", ")", ".", "projection", "(", "_id", ":", "1", ")", ".", "map", "{", "|", "k", "|", "k", "[", ":_id", "]", "}", "end" ]
get node names that fulfill given mongodb query @param query mongodb query
[ "get", "node", "names", "that", "fulfill", "given", "mongodb", "query" ]
58103c91f291de8ce28d679256e50ae391b93ecb
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L66-L69
train
m-31/puppetdb_query
lib/puppetdb_query/mongodb.rb
PuppetDBQuery.MongoDB.query_facts
def query_facts(query, facts = []) fields = Hash[facts.collect { |fact| [fact.to_sym, 1] }] collection = connection[nodes_collection] result = {} collection.find(query).batch_size(999).projection(fields).each do |values| id = values.delete('_id') result[id] = values end result end
ruby
def query_facts(query, facts = []) fields = Hash[facts.collect { |fact| [fact.to_sym, 1] }] collection = connection[nodes_collection] result = {} collection.find(query).batch_size(999).projection(fields).each do |values| id = values.delete('_id') result[id] = values end result end
[ "def", "query_facts", "(", "query", ",", "facts", "=", "[", "]", ")", "fields", "=", "Hash", "[", "facts", ".", "collect", "{", "|", "fact", "|", "[", "fact", ".", "to_sym", ",", "1", "]", "}", "]", "collection", "=", "connection", "[", "nodes_collection", "]", "result", "=", "{", "}", "collection", ".", "find", "(", "query", ")", ".", "batch_size", "(", "999", ")", ".", "projection", "(", "fields", ")", ".", "each", "do", "|", "values", "|", "id", "=", "values", ".", "delete", "(", "'_id'", ")", "result", "[", "id", "]", "=", "values", "end", "result", "end" ]
get nodes and their facts that fulfill given mongodb query @param query mongodb query @param facts [Array<String>] get these facts in the result, eg ['fqdn'], empty for all
[ "get", "nodes", "and", "their", "facts", "that", "fulfill", "given", "mongodb", "query" ]
58103c91f291de8ce28d679256e50ae391b93ecb
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L75-L84
train
m-31/puppetdb_query
lib/puppetdb_query/mongodb.rb
PuppetDBQuery.MongoDB.query_facts_exist
def query_facts_exist(query, facts = []) result = query_facts(query, facts) unless facts.empty? result.keep_if do |_k, v| facts.any? { |f| !v[f].nil? } end end result end
ruby
def query_facts_exist(query, facts = []) result = query_facts(query, facts) unless facts.empty? result.keep_if do |_k, v| facts.any? { |f| !v[f].nil? } end end result end
[ "def", "query_facts_exist", "(", "query", ",", "facts", "=", "[", "]", ")", "result", "=", "query_facts", "(", "query", ",", "facts", ")", "unless", "facts", ".", "empty?", "result", ".", "keep_if", "do", "|", "_k", ",", "v", "|", "facts", ".", "any?", "{", "|", "f", "|", "!", "v", "[", "f", "]", ".", "nil?", "}", "end", "end", "result", "end" ]
get nodes and their facts that fulfill given mongodb query and have at least one value for one the given fact names @param query mongodb query @param facts [Array<String>] get these facts in the result, eg ['fqdn'], empty for all
[ "get", "nodes", "and", "their", "facts", "that", "fulfill", "given", "mongodb", "query", "and", "have", "at", "least", "one", "value", "for", "one", "the", "given", "fact", "names" ]
58103c91f291de8ce28d679256e50ae391b93ecb
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L91-L99
train
m-31/puppetdb_query
lib/puppetdb_query/mongodb.rb
PuppetDBQuery.MongoDB.search_facts
def search_facts(query, pattern, facts = [], facts_found = [], check_names = false) collection = connection[nodes_collection] result = {} collection.find(query).batch_size(999).each do |values| id = values.delete('_id') found = {} values.each do |k, v| if v =~ pattern found[k] = v elsif check_names && k =~ pattern found[k] = v end end next if found.empty? facts_found.concat(found.keys).uniq! facts.each do |f| found[f] = values[f] end result[id] = found end result end
ruby
def search_facts(query, pattern, facts = [], facts_found = [], check_names = false) collection = connection[nodes_collection] result = {} collection.find(query).batch_size(999).each do |values| id = values.delete('_id') found = {} values.each do |k, v| if v =~ pattern found[k] = v elsif check_names && k =~ pattern found[k] = v end end next if found.empty? facts_found.concat(found.keys).uniq! facts.each do |f| found[f] = values[f] end result[id] = found end result end
[ "def", "search_facts", "(", "query", ",", "pattern", ",", "facts", "=", "[", "]", ",", "facts_found", "=", "[", "]", ",", "check_names", "=", "false", ")", "collection", "=", "connection", "[", "nodes_collection", "]", "result", "=", "{", "}", "collection", ".", "find", "(", "query", ")", ".", "batch_size", "(", "999", ")", ".", "each", "do", "|", "values", "|", "id", "=", "values", ".", "delete", "(", "'_id'", ")", "found", "=", "{", "}", "values", ".", "each", "do", "|", "k", ",", "v", "|", "if", "v", "=~", "pattern", "found", "[", "k", "]", "=", "v", "elsif", "check_names", "&&", "k", "=~", "pattern", "found", "[", "k", "]", "=", "v", "end", "end", "next", "if", "found", ".", "empty?", "facts_found", ".", "concat", "(", "found", ".", "keys", ")", ".", "uniq!", "facts", ".", "each", "do", "|", "f", "|", "found", "[", "f", "]", "=", "values", "[", "f", "]", "end", "result", "[", "id", "]", "=", "found", "end", "result", "end" ]
get nodes and their facts for a pattern @param query mongodb query @param pattern [RegExp] search for @param facts [Array<String>] get these facts in the result, eg ['fqdn'], empty for all @param facts_found [Array<String>] fact names are added to this array @param check_names [Boolean] also search fact names
[ "get", "nodes", "and", "their", "facts", "for", "a", "pattern" ]
58103c91f291de8ce28d679256e50ae391b93ecb
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L108-L129
train
m-31/puppetdb_query
lib/puppetdb_query/mongodb.rb
PuppetDBQuery.MongoDB.single_node_facts
def single_node_facts(node, facts) fields = Hash[facts.collect { |fact| [fact.to_sym, 1] }] collection = connection[nodes_collection] result = collection.find(_id: node).limit(1).batch_size(1).projection(fields).to_a.first result.delete("_id") if result result end
ruby
def single_node_facts(node, facts) fields = Hash[facts.collect { |fact| [fact.to_sym, 1] }] collection = connection[nodes_collection] result = collection.find(_id: node).limit(1).batch_size(1).projection(fields).to_a.first result.delete("_id") if result result end
[ "def", "single_node_facts", "(", "node", ",", "facts", ")", "fields", "=", "Hash", "[", "facts", ".", "collect", "{", "|", "fact", "|", "[", "fact", ".", "to_sym", ",", "1", "]", "}", "]", "collection", "=", "connection", "[", "nodes_collection", "]", "result", "=", "collection", ".", "find", "(", "_id", ":", "node", ")", ".", "limit", "(", "1", ")", ".", "batch_size", "(", "1", ")", ".", "projection", "(", "fields", ")", ".", "to_a", ".", "first", "result", ".", "delete", "(", "\"_id\"", ")", "if", "result", "result", "end" ]
get facts for given node name @param node [String] node name @param facts [Array<String>] get these facts in the result, eg ['fqdn'], empty for all
[ "get", "facts", "for", "given", "node", "name" ]
58103c91f291de8ce28d679256e50ae391b93ecb
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L135-L141
train
m-31/puppetdb_query
lib/puppetdb_query/mongodb.rb
PuppetDBQuery.MongoDB.meta
def meta collection = connection[meta_collection] result = collection.find.first result.delete(:_id) result end
ruby
def meta collection = connection[meta_collection] result = collection.find.first result.delete(:_id) result end
[ "def", "meta", "collection", "=", "connection", "[", "meta_collection", "]", "result", "=", "collection", ".", "find", ".", "first", "result", ".", "delete", "(", ":_id", ")", "result", "end" ]
get meta informations about updates
[ "get", "meta", "informations", "about", "updates" ]
58103c91f291de8ce28d679256e50ae391b93ecb
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L158-L163
train
m-31/puppetdb_query
lib/puppetdb_query/mongodb.rb
PuppetDBQuery.MongoDB.node_update
def node_update(node, facts) logger.debug " updating #{node}" connection[nodes_collection].find(_id: node).replace_one(facts, upsert: true, bypass_document_validation: true, check_keys: false, validating_keys: false) rescue ::Mongo::Error::OperationFailure => e logger.warn " updating #{node} failed with: #{e.message}" # mongodb doesn't support keys with a dot # see https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names # as a dirty workaround we delete the document and insert it ;-) # The dotted field .. in .. is not valid for storage. (57) # .. is an illegal key in MongoDB. Keys may not start with '$' or contain a '.'. # (BSON::String::IllegalKey) raise e unless e.message =~ /The dotted field / || e.message =~ /is an illegal key/ logger.warn " we transform the dots into underline characters" begin facts = Hash[facts.map { |k, v| [k.tr('.', '_'), v] }] connection[nodes_collection].find(_id: node).replace_one(facts, upsert: true, bypass_document_validation: true, check_keys: false, validating_keys: false) rescue logger.error " inserting node #{node} failed again with: #{e.message}" end end
ruby
def node_update(node, facts) logger.debug " updating #{node}" connection[nodes_collection].find(_id: node).replace_one(facts, upsert: true, bypass_document_validation: true, check_keys: false, validating_keys: false) rescue ::Mongo::Error::OperationFailure => e logger.warn " updating #{node} failed with: #{e.message}" # mongodb doesn't support keys with a dot # see https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names # as a dirty workaround we delete the document and insert it ;-) # The dotted field .. in .. is not valid for storage. (57) # .. is an illegal key in MongoDB. Keys may not start with '$' or contain a '.'. # (BSON::String::IllegalKey) raise e unless e.message =~ /The dotted field / || e.message =~ /is an illegal key/ logger.warn " we transform the dots into underline characters" begin facts = Hash[facts.map { |k, v| [k.tr('.', '_'), v] }] connection[nodes_collection].find(_id: node).replace_one(facts, upsert: true, bypass_document_validation: true, check_keys: false, validating_keys: false) rescue logger.error " inserting node #{node} failed again with: #{e.message}" end end
[ "def", "node_update", "(", "node", ",", "facts", ")", "logger", ".", "debug", "\" updating #{node}\"", "connection", "[", "nodes_collection", "]", ".", "find", "(", "_id", ":", "node", ")", ".", "replace_one", "(", "facts", ",", "upsert", ":", "true", ",", "bypass_document_validation", ":", "true", ",", "check_keys", ":", "false", ",", "validating_keys", ":", "false", ")", "rescue", "::", "Mongo", "::", "Error", "::", "OperationFailure", "=>", "e", "logger", ".", "warn", "\" updating #{node} failed with: #{e.message}\"", "raise", "e", "unless", "e", ".", "message", "=~", "/", "/", "||", "e", ".", "message", "=~", "/", "/", "logger", ".", "warn", "\" we transform the dots into underline characters\"", "begin", "facts", "=", "Hash", "[", "facts", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ".", "tr", "(", "'.'", ",", "'_'", ")", ",", "v", "]", "}", "]", "connection", "[", "nodes_collection", "]", ".", "find", "(", "_id", ":", "node", ")", ".", "replace_one", "(", "facts", ",", "upsert", ":", "true", ",", "bypass_document_validation", ":", "true", ",", "check_keys", ":", "false", ",", "validating_keys", ":", "false", ")", "rescue", "logger", ".", "error", "\" inserting node #{node} failed again with: #{e.message}\"", "end", "end" ]
update or insert facts for given node name @param node [String] node name @param facts [Hash] facts for the node
[ "update", "or", "insert", "facts", "for", "given", "node", "name" ]
58103c91f291de8ce28d679256e50ae391b93ecb
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L169-L196
train
m-31/puppetdb_query
lib/puppetdb_query/mongodb.rb
PuppetDBQuery.MongoDB.node_properties_update
def node_properties_update(new_node_properties) collection = connection[node_properties_collection] old_names = collection.find.batch_size(999).projection(_id: 1).map { |k| k[:_id] } delete = old_names - new_node_properties.keys data = new_node_properties.map do |k, v| { replace_one: { filter: { _id: k }, replacement: v, upsert: true } } end collection.bulk_write(data) collection.delete_many(_id: { '$in' => delete }) end
ruby
def node_properties_update(new_node_properties) collection = connection[node_properties_collection] old_names = collection.find.batch_size(999).projection(_id: 1).map { |k| k[:_id] } delete = old_names - new_node_properties.keys data = new_node_properties.map do |k, v| { replace_one: { filter: { _id: k }, replacement: v, upsert: true } } end collection.bulk_write(data) collection.delete_many(_id: { '$in' => delete }) end
[ "def", "node_properties_update", "(", "new_node_properties", ")", "collection", "=", "connection", "[", "node_properties_collection", "]", "old_names", "=", "collection", ".", "find", ".", "batch_size", "(", "999", ")", ".", "projection", "(", "_id", ":", "1", ")", ".", "map", "{", "|", "k", "|", "k", "[", ":_id", "]", "}", "delete", "=", "old_names", "-", "new_node_properties", ".", "keys", "data", "=", "new_node_properties", ".", "map", "do", "|", "k", ",", "v", "|", "{", "replace_one", ":", "{", "filter", ":", "{", "_id", ":", "k", "}", ",", "replacement", ":", "v", ",", "upsert", ":", "true", "}", "}", "end", "collection", ".", "bulk_write", "(", "data", ")", "collection", ".", "delete_many", "(", "_id", ":", "{", "'$in'", "=>", "delete", "}", ")", "end" ]
update node properties
[ "update", "node", "properties" ]
58103c91f291de8ce28d679256e50ae391b93ecb
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L206-L222
train
m-31/puppetdb_query
lib/puppetdb_query/mongodb.rb
PuppetDBQuery.MongoDB.meta_fact_update
def meta_fact_update(method, ts_begin, ts_end) connection[meta_collection].find_one_and_update( {}, { '$set' => { last_fact_update: { ts_begin: ts_begin.iso8601, ts_end: ts_end.iso8601, method: method }, method => { ts_begin: ts_begin.iso8601, ts_end: ts_end.iso8601 } } }, { upsert: true } ) end
ruby
def meta_fact_update(method, ts_begin, ts_end) connection[meta_collection].find_one_and_update( {}, { '$set' => { last_fact_update: { ts_begin: ts_begin.iso8601, ts_end: ts_end.iso8601, method: method }, method => { ts_begin: ts_begin.iso8601, ts_end: ts_end.iso8601 } } }, { upsert: true } ) end
[ "def", "meta_fact_update", "(", "method", ",", "ts_begin", ",", "ts_end", ")", "connection", "[", "meta_collection", "]", ".", "find_one_and_update", "(", "{", "}", ",", "{", "'$set'", "=>", "{", "last_fact_update", ":", "{", "ts_begin", ":", "ts_begin", ".", "iso8601", ",", "ts_end", ":", "ts_end", ".", "iso8601", ",", "method", ":", "method", "}", ",", "method", "=>", "{", "ts_begin", ":", "ts_begin", ".", "iso8601", ",", "ts_end", ":", "ts_end", ".", "iso8601", "}", "}", "}", ",", "{", "upsert", ":", "true", "}", ")", "end" ]
update or insert timestamps for given fact update method
[ "update", "or", "insert", "timestamps", "for", "given", "fact", "update", "method" ]
58103c91f291de8ce28d679256e50ae391b93ecb
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L225-L243
train
m-31/puppetdb_query
lib/puppetdb_query/mongodb.rb
PuppetDBQuery.MongoDB.meta_node_properties_update
def meta_node_properties_update(ts_begin, ts_end) connection[meta_collection].find_one_and_update( {}, { '$set' => { last_node_properties_update: { ts_begin: ts_begin.iso8601, ts_end: ts_end.iso8601 } } }, { upsert: true } ) @node_properties_update_timestamp = ts_begin end
ruby
def meta_node_properties_update(ts_begin, ts_end) connection[meta_collection].find_one_and_update( {}, { '$set' => { last_node_properties_update: { ts_begin: ts_begin.iso8601, ts_end: ts_end.iso8601 } } }, { upsert: true } ) @node_properties_update_timestamp = ts_begin end
[ "def", "meta_node_properties_update", "(", "ts_begin", ",", "ts_end", ")", "connection", "[", "meta_collection", "]", ".", "find_one_and_update", "(", "{", "}", ",", "{", "'$set'", "=>", "{", "last_node_properties_update", ":", "{", "ts_begin", ":", "ts_begin", ".", "iso8601", ",", "ts_end", ":", "ts_end", ".", "iso8601", "}", "}", "}", ",", "{", "upsert", ":", "true", "}", ")", "@node_properties_update_timestamp", "=", "ts_begin", "end" ]
update or insert timestamps for node_properties_update
[ "update", "or", "insert", "timestamps", "for", "node_properties_update" ]
58103c91f291de8ce28d679256e50ae391b93ecb
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L246-L260
train
minhnghivn/idata
lib/idata/detector.rb
Idata.Detector.find_same_occurence
def find_same_occurence selected = @candidates.select { |delim, count| begin CSV.parse(@sample, col_sep: delim).select{|e| !e.empty? }.map{|e| e.count}.uniq.count == 1 rescue Exception => ex false end }.keys return selected.first if selected.count == 1 return DEFAULT_DELIMITER if selected.include?(DEFAULT_DELIMITER) end
ruby
def find_same_occurence selected = @candidates.select { |delim, count| begin CSV.parse(@sample, col_sep: delim).select{|e| !e.empty? }.map{|e| e.count}.uniq.count == 1 rescue Exception => ex false end }.keys return selected.first if selected.count == 1 return DEFAULT_DELIMITER if selected.include?(DEFAULT_DELIMITER) end
[ "def", "find_same_occurence", "selected", "=", "@candidates", ".", "select", "{", "|", "delim", ",", "count", "|", "begin", "CSV", ".", "parse", "(", "@sample", ",", "col_sep", ":", "delim", ")", ".", "select", "{", "|", "e", "|", "!", "e", ".", "empty?", "}", ".", "map", "{", "|", "e", "|", "e", ".", "count", "}", ".", "uniq", ".", "count", "==", "1", "rescue", "Exception", "=>", "ex", "false", "end", "}", ".", "keys", "return", "selected", ".", "first", "if", "selected", ".", "count", "==", "1", "return", "DEFAULT_DELIMITER", "if", "selected", ".", "include?", "(", "DEFAULT_DELIMITER", ")", "end" ]
high confident level
[ "high", "confident", "level" ]
266bff364e8c98dd12eb4256dc7a3ee10a142fb3
https://github.com/minhnghivn/idata/blob/266bff364e8c98dd12eb4256dc7a3ee10a142fb3/lib/idata/detector.rb#L53-L64
train
jduckett/duck_map
lib/duck_map/route.rb
DuckMap.Route.keys_required?
def keys_required? keys = self.segment_keys.dup keys.delete(:format) return keys.length > 0 ? true : false end
ruby
def keys_required? keys = self.segment_keys.dup keys.delete(:format) return keys.length > 0 ? true : false end
[ "def", "keys_required?", "keys", "=", "self", ".", "segment_keys", ".", "dup", "keys", ".", "delete", "(", ":format", ")", "return", "keys", ".", "length", ">", "0", "?", "true", ":", "false", "end" ]
Indicates if the current route requirements segments keys to generate a url. @return [Boolean] True if keys are required to generate a url, otherwise, false.
[ "Indicates", "if", "the", "current", "route", "requirements", "segments", "keys", "to", "generate", "a", "url", "." ]
c510acfa95e8ad4afb1501366058ae88a73704df
https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/route.rb#L261-L265
train
emancu/ork
lib/ork/result_set.rb
Ork.ResultSet.next_page
def next_page raise Ork::NoNextPage.new 'There is no next page' unless has_next_page? self.class.new(@model, @index, @query, @options.merge(continuation: keys.continuation)) end
ruby
def next_page raise Ork::NoNextPage.new 'There is no next page' unless has_next_page? self.class.new(@model, @index, @query, @options.merge(continuation: keys.continuation)) end
[ "def", "next_page", "raise", "Ork", "::", "NoNextPage", ".", "new", "'There is no next page'", "unless", "has_next_page?", "self", ".", "class", ".", "new", "(", "@model", ",", "@index", ",", "@query", ",", "@options", ".", "merge", "(", "continuation", ":", "keys", ".", "continuation", ")", ")", "end" ]
Get a new ResultSet fetch for the next page
[ "Get", "a", "new", "ResultSet", "fetch", "for", "the", "next", "page" ]
83b2deaef0e790d90f98c031f254b5f438b19edf
https://github.com/emancu/ork/blob/83b2deaef0e790d90f98c031f254b5f438b19edf/lib/ork/result_set.rb#L55-L62
train
rlafranchi/statixite
lib/statixite/cloud_sync.rb
Statixite.CloudSync.threaded_run!
def threaded_run!(files, change) return if files.empty? file_number = 0 total_files = files.length mutex = Mutex.new threads = [] 5.times do |i| threads[i] = Thread.new { until files.empty? mutex.synchronize do file_number += 1 Thread.current["file_number"] = file_number end file = files.pop rescue nil next unless file Rails.logger.info "[#{Thread.current["file_number"]}/#{total_files}] to #{change}..." case change when 'destroy' when 'create' when 'update' end end } end threads.each { |t| t.join } end
ruby
def threaded_run!(files, change) return if files.empty? file_number = 0 total_files = files.length mutex = Mutex.new threads = [] 5.times do |i| threads[i] = Thread.new { until files.empty? mutex.synchronize do file_number += 1 Thread.current["file_number"] = file_number end file = files.pop rescue nil next unless file Rails.logger.info "[#{Thread.current["file_number"]}/#{total_files}] to #{change}..." case change when 'destroy' when 'create' when 'update' end end } end threads.each { |t| t.join } end
[ "def", "threaded_run!", "(", "files", ",", "change", ")", "return", "if", "files", ".", "empty?", "file_number", "=", "0", "total_files", "=", "files", ".", "length", "mutex", "=", "Mutex", ".", "new", "threads", "=", "[", "]", "5", ".", "times", "do", "|", "i", "|", "threads", "[", "i", "]", "=", "Thread", ".", "new", "{", "until", "files", ".", "empty?", "mutex", ".", "synchronize", "do", "file_number", "+=", "1", "Thread", ".", "current", "[", "\"file_number\"", "]", "=", "file_number", "end", "file", "=", "files", ".", "pop", "rescue", "nil", "next", "unless", "file", "Rails", ".", "logger", ".", "info", "\"[#{Thread.current[\"file_number\"]}/#{total_files}] to #{change}...\"", "case", "change", "when", "'destroy'", "when", "'create'", "when", "'update'", "end", "end", "}", "end", "threads", ".", "each", "{", "|", "t", "|", "t", ".", "join", "}", "end" ]
todo improve speed
[ "todo", "improve", "speed" ]
5322d40d4086edb89c8aa3b7cb563a35ffac0140
https://github.com/rlafranchi/statixite/blob/5322d40d4086edb89c8aa3b7cb563a35ffac0140/lib/statixite/cloud_sync.rb#L93-L119
train
jarhart/rattler
lib/rattler/compiler/ruby_generator.rb
Rattler::Compiler.RubyGenerator.intersperse
def intersperse(enum, opts={}) sep = opts[:sep] newlines = opts[:newlines] || (opts[:newline] ? 1 : 0) enum.each_with_index do |_, i| if i > 0 self << sep if sep newlines.times { newline } end yield _ end self end
ruby
def intersperse(enum, opts={}) sep = opts[:sep] newlines = opts[:newlines] || (opts[:newline] ? 1 : 0) enum.each_with_index do |_, i| if i > 0 self << sep if sep newlines.times { newline } end yield _ end self end
[ "def", "intersperse", "(", "enum", ",", "opts", "=", "{", "}", ")", "sep", "=", "opts", "[", ":sep", "]", "newlines", "=", "opts", "[", ":newlines", "]", "||", "(", "opts", "[", ":newline", "]", "?", "1", ":", "0", ")", "enum", ".", "each_with_index", "do", "|", "_", ",", "i", "|", "if", "i", ">", "0", "self", "<<", "sep", "if", "sep", "newlines", ".", "times", "{", "newline", "}", "end", "yield", "_", "end", "self", "end" ]
Add a separator or newlines or both in between code generated in the given block for each element in +enum+. Newlines, are always added after the separator. @param [Enumerable] enum an enumerable sequence of objects @option opts [String] :sep (nil) optional separator to use between elements @option opts [true, false] :newline (false) separate with a single newline if +true+ (and if :newlines is not specified) @option opts [Integer] :newlines (nil) optional number of newlines to use between elements (overrides :newline) @yield [element] each element in +enum+ @return [self]
[ "Add", "a", "separator", "or", "newlines", "or", "both", "in", "between", "code", "generated", "in", "the", "given", "block", "for", "each", "element", "in", "+", "enum", "+", ".", "Newlines", "are", "always", "added", "after", "the", "separator", "." ]
8b4efde2a05e9e790955bb635d4a1a9615893719
https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/compiler/ruby_generator.rb#L124-L135
train
rubyrider/clomp
lib/clomp/operation.rb
Clomp.Operation.get_status
def get_status @result['tracks'].collect {|track| track.name if track.failure?}.compact.count.zero? ? 'Success' : 'Failure' end
ruby
def get_status @result['tracks'].collect {|track| track.name if track.failure?}.compact.count.zero? ? 'Success' : 'Failure' end
[ "def", "get_status", "@result", "[", "'tracks'", "]", ".", "collect", "{", "|", "track", "|", "track", ".", "name", "if", "track", ".", "failure?", "}", ".", "compact", ".", "count", ".", "zero?", "?", "'Success'", ":", "'Failure'", "end" ]
collect track status
[ "collect", "track", "status" ]
da3cfa9c86773aad93c2bf7e59c51795f1d51c4d
https://github.com/rubyrider/clomp/blob/da3cfa9c86773aad93c2bf7e59c51795f1d51c4d/lib/clomp/operation.rb#L52-L54
train
sloppycoder/fixed_width_file_validator
lib/fixed_width_file_validator/record_formatter.rb
FixedWidthFileValidator.RecordFormatter.formatted_value
def formatted_value(value, format, width) value_str = value ? format(format, value) : ' ' * width # all space for nil value length = value_str.length if length > width value_str.slice(0..width - 1) elsif length < width ' ' * (width - length) + value_str else value_str end end
ruby
def formatted_value(value, format, width) value_str = value ? format(format, value) : ' ' * width # all space for nil value length = value_str.length if length > width value_str.slice(0..width - 1) elsif length < width ' ' * (width - length) + value_str else value_str end end
[ "def", "formatted_value", "(", "value", ",", "format", ",", "width", ")", "value_str", "=", "value", "?", "format", "(", "format", ",", "value", ")", ":", "' '", "*", "width", "length", "=", "value_str", ".", "length", "if", "length", ">", "width", "value_str", ".", "slice", "(", "0", "..", "width", "-", "1", ")", "elsif", "length", "<", "width", "' '", "*", "(", "width", "-", "length", ")", "+", "value_str", "else", "value_str", "end", "end" ]
format the string using given format if the result is shorter than width, pad space to the left if the result is longer than width, truncate the last characters
[ "format", "the", "string", "using", "given", "format", "if", "the", "result", "is", "shorter", "than", "width", "pad", "space", "to", "the", "left", "if", "the", "result", "is", "longer", "than", "width", "truncate", "the", "last", "characters" ]
0dce83b0b73f65bc80c7fc61d5117a6a3acc1828
https://github.com/sloppycoder/fixed_width_file_validator/blob/0dce83b0b73f65bc80c7fc61d5117a6a3acc1828/lib/fixed_width_file_validator/record_formatter.rb#L32-L42
train
mikiobraun/jblas-ruby
lib/jblas/mixin_enum.rb
JBLAS.MatrixEnumMixin.map!
def map!(&block) (0...length).each do |i| put(i, block.call(get(i))) end self end
ruby
def map!(&block) (0...length).each do |i| put(i, block.call(get(i))) end self end
[ "def", "map!", "(", "&", "block", ")", "(", "0", "...", "length", ")", ".", "each", "do", "|", "i", "|", "put", "(", "i", ",", "block", ".", "call", "(", "get", "(", "i", ")", ")", ")", "end", "self", "end" ]
Map each element and store the result in the matrix. Note that the result must be again something which can be stored in the matrix. Otherwise you should do an to_a first.
[ "Map", "each", "element", "and", "store", "the", "result", "in", "the", "matrix", "." ]
7233976c9e3b210e30bc36ead2b1e05ab3383fec
https://github.com/mikiobraun/jblas-ruby/blob/7233976c9e3b210e30bc36ead2b1e05ab3383fec/lib/jblas/mixin_enum.rb#L76-L81
train
stomar/lanyon
lib/lanyon/router.rb
Lanyon.Router.endpoint
def endpoint(path) normalized = normalize_path_info(path) fullpath = File.join(@root, normalized) endpoint = if FileTest.file?(fullpath) fullpath elsif needs_redirect_to_dir?(fullpath) :must_redirect elsif FileTest.file?(fullpath_html = "#{fullpath}.html") fullpath_html else :not_found end endpoint end
ruby
def endpoint(path) normalized = normalize_path_info(path) fullpath = File.join(@root, normalized) endpoint = if FileTest.file?(fullpath) fullpath elsif needs_redirect_to_dir?(fullpath) :must_redirect elsif FileTest.file?(fullpath_html = "#{fullpath}.html") fullpath_html else :not_found end endpoint end
[ "def", "endpoint", "(", "path", ")", "normalized", "=", "normalize_path_info", "(", "path", ")", "fullpath", "=", "File", ".", "join", "(", "@root", ",", "normalized", ")", "endpoint", "=", "if", "FileTest", ".", "file?", "(", "fullpath", ")", "fullpath", "elsif", "needs_redirect_to_dir?", "(", "fullpath", ")", ":must_redirect", "elsif", "FileTest", ".", "file?", "(", "fullpath_html", "=", "\"#{fullpath}.html\"", ")", "fullpath_html", "else", ":not_found", "end", "endpoint", "end" ]
Creates a Router for the given root directory. Returns the full file system path of the file corresponding to the given URL +path+, or - +:must_redirect+ if the request must be redirected to +path/+, - +:not_found+ if no corresponding file exists. The return value is found as follows: 1. a +path/+ with a trailing slash is changed to +path/index.html+, 2. then, the method checks for an exactly corresponding file, 3. when +path+ does not exist but +path/index.html+ does, a redirect will be indicated, 4. finally, when no exactly corresponding file or redirect can be found, +path.html+ is tried.
[ "Creates", "a", "Router", "for", "the", "given", "root", "directory", ".", "Returns", "the", "full", "file", "system", "path", "of", "the", "file", "corresponding", "to", "the", "given", "URL", "+", "path", "+", "or" ]
2b32ab991c45fdc68c4b0ac86297e6ceb528ba08
https://github.com/stomar/lanyon/blob/2b32ab991c45fdc68c4b0ac86297e6ceb528ba08/lib/lanyon/router.rb#L30-L45
train
stomar/lanyon
lib/lanyon/router.rb
Lanyon.Router.custom_404_body
def custom_404_body filename = File.join(root, "404.html") File.exist?(filename) ? File.binread(filename) : nil end
ruby
def custom_404_body filename = File.join(root, "404.html") File.exist?(filename) ? File.binread(filename) : nil end
[ "def", "custom_404_body", "filename", "=", "File", ".", "join", "(", "root", ",", "\"404.html\"", ")", "File", ".", "exist?", "(", "filename", ")", "?", "File", ".", "binread", "(", "filename", ")", ":", "nil", "end" ]
Returns the body of the custom 404 page or +nil+ if none exists.
[ "Returns", "the", "body", "of", "the", "custom", "404", "page", "or", "+", "nil", "+", "if", "none", "exists", "." ]
2b32ab991c45fdc68c4b0ac86297e6ceb528ba08
https://github.com/stomar/lanyon/blob/2b32ab991c45fdc68c4b0ac86297e6ceb528ba08/lib/lanyon/router.rb#L48-L52
train
games-directory/api-giantbomb
lib/giantbomb/search.rb
GiantBomb.Search.filter
def filter(conditions) if conditions conditions.each do |key, value| if self.respond_to?(key) self.send(key, value) end end end end
ruby
def filter(conditions) if conditions conditions.each do |key, value| if self.respond_to?(key) self.send(key, value) end end end end
[ "def", "filter", "(", "conditions", ")", "if", "conditions", "conditions", ".", "each", "do", "|", "key", ",", "value", "|", "if", "self", ".", "respond_to?", "(", "key", ")", "self", ".", "send", "(", "key", ",", "value", ")", "end", "end", "end", "end" ]
A convenience method that takes a hash where each key is the symbol of a method, and each value is the parameters passed to that method.
[ "A", "convenience", "method", "that", "takes", "a", "hash", "where", "each", "key", "is", "the", "symbol", "of", "a", "method", "and", "each", "value", "is", "the", "parameters", "passed", "to", "that", "method", "." ]
5dded4d69f8fd746e44a509bc66a67d963c54ad4
https://github.com/games-directory/api-giantbomb/blob/5dded4d69f8fd746e44a509bc66a67d963c54ad4/lib/giantbomb/search.rb#L72-L80
train
gjtorikian/nanoc-conref-fs
lib/nanoc-conref-fs/ancestry.rb
NanocConrefFS.Ancestry.find_array_parents
def find_array_parents(toc, title) parents = '' toc.each do |item| if item.is_a?(Hash) parents = find_hash_parents(item, title) break unless parents.empty? end end parents end
ruby
def find_array_parents(toc, title) parents = '' toc.each do |item| if item.is_a?(Hash) parents = find_hash_parents(item, title) break unless parents.empty? end end parents end
[ "def", "find_array_parents", "(", "toc", ",", "title", ")", "parents", "=", "''", "toc", ".", "each", "do", "|", "item", "|", "if", "item", ".", "is_a?", "(", "Hash", ")", "parents", "=", "find_hash_parents", "(", "item", ",", "title", ")", "break", "unless", "parents", ".", "empty?", "end", "end", "parents", "end" ]
Given a category file that's an array, this method finds the parent of an item
[ "Given", "a", "category", "file", "that", "s", "an", "array", "this", "method", "finds", "the", "parent", "of", "an", "item" ]
d1b423daadf8921bc27da553b299f7b7ff9bffa9
https://github.com/gjtorikian/nanoc-conref-fs/blob/d1b423daadf8921bc27da553b299f7b7ff9bffa9/lib/nanoc-conref-fs/ancestry.rb#L23-L32
train
gjtorikian/nanoc-conref-fs
lib/nanoc-conref-fs/ancestry.rb
NanocConrefFS.Ancestry.find_hash_parents
def find_hash_parents(toc, title) parents = '' toc.each_key do |key| next if toc[key].nil? toc[key].each do |item| if item.is_a?(Hash) if item.keys.include?(title) parents = key break else if item[item.keys.first].include?(title) parents = key break end end elsif title == item parents = key break end end break unless parents.empty? end parents end
ruby
def find_hash_parents(toc, title) parents = '' toc.each_key do |key| next if toc[key].nil? toc[key].each do |item| if item.is_a?(Hash) if item.keys.include?(title) parents = key break else if item[item.keys.first].include?(title) parents = key break end end elsif title == item parents = key break end end break unless parents.empty? end parents end
[ "def", "find_hash_parents", "(", "toc", ",", "title", ")", "parents", "=", "''", "toc", ".", "each_key", "do", "|", "key", "|", "next", "if", "toc", "[", "key", "]", ".", "nil?", "toc", "[", "key", "]", ".", "each", "do", "|", "item", "|", "if", "item", ".", "is_a?", "(", "Hash", ")", "if", "item", ".", "keys", ".", "include?", "(", "title", ")", "parents", "=", "key", "break", "else", "if", "item", "[", "item", ".", "keys", ".", "first", "]", ".", "include?", "(", "title", ")", "parents", "=", "key", "break", "end", "end", "elsif", "title", "==", "item", "parents", "=", "key", "break", "end", "end", "break", "unless", "parents", ".", "empty?", "end", "parents", "end" ]
Given a category file that's a hash, this method finds the parent of an item
[ "Given", "a", "category", "file", "that", "s", "a", "hash", "this", "method", "finds", "the", "parent", "of", "an", "item" ]
d1b423daadf8921bc27da553b299f7b7ff9bffa9
https://github.com/gjtorikian/nanoc-conref-fs/blob/d1b423daadf8921bc27da553b299f7b7ff9bffa9/lib/nanoc-conref-fs/ancestry.rb#L37-L60
train
gjtorikian/nanoc-conref-fs
lib/nanoc-conref-fs/ancestry.rb
NanocConrefFS.Ancestry.find_array_children
def find_array_children(toc, title) toc.each do |item| next unless item.is_a?(Hash) item.each_pair do |key, values| if key == title children = values.flatten return children end end end # Found no children Array.new end
ruby
def find_array_children(toc, title) toc.each do |item| next unless item.is_a?(Hash) item.each_pair do |key, values| if key == title children = values.flatten return children end end end # Found no children Array.new end
[ "def", "find_array_children", "(", "toc", ",", "title", ")", "toc", ".", "each", "do", "|", "item", "|", "next", "unless", "item", ".", "is_a?", "(", "Hash", ")", "item", ".", "each_pair", "do", "|", "key", ",", "values", "|", "if", "key", "==", "title", "children", "=", "values", ".", "flatten", "return", "children", "end", "end", "end", "Array", ".", "new", "end" ]
Given a category file that's an array, this method finds the children of an item, probably a map topic toc - the array containing the table of contents title - the text title to return the children of Returns a flattened array of all descendants which could be empty.
[ "Given", "a", "category", "file", "that", "s", "an", "array", "this", "method", "finds", "the", "children", "of", "an", "item", "probably", "a", "map", "topic" ]
d1b423daadf8921bc27da553b299f7b7ff9bffa9
https://github.com/gjtorikian/nanoc-conref-fs/blob/d1b423daadf8921bc27da553b299f7b7ff9bffa9/lib/nanoc-conref-fs/ancestry.rb#L70-L82
train
gjtorikian/nanoc-conref-fs
lib/nanoc-conref-fs/ancestry.rb
NanocConrefFS.Ancestry.find_hash_children
def find_hash_children(toc, title) toc.each_key do |key| next if toc[key].nil? toc[key].each do |item| next unless item.is_a?(Hash) if item[title] children = item.values.flatten return children end end end # Found no children Array.new end
ruby
def find_hash_children(toc, title) toc.each_key do |key| next if toc[key].nil? toc[key].each do |item| next unless item.is_a?(Hash) if item[title] children = item.values.flatten return children end end end # Found no children Array.new end
[ "def", "find_hash_children", "(", "toc", ",", "title", ")", "toc", ".", "each_key", "do", "|", "key", "|", "next", "if", "toc", "[", "key", "]", ".", "nil?", "toc", "[", "key", "]", ".", "each", "do", "|", "item", "|", "next", "unless", "item", ".", "is_a?", "(", "Hash", ")", "if", "item", "[", "title", "]", "children", "=", "item", ".", "values", ".", "flatten", "return", "children", "end", "end", "end", "Array", ".", "new", "end" ]
Given a category file that's a hash, this method finds the children of an item, probably a map topic toc - the hash containing the table of contents title - the text title to return the children of Returns a flattened array of all descendants which could be empty.
[ "Given", "a", "category", "file", "that", "s", "a", "hash", "this", "method", "finds", "the", "children", "of", "an", "item", "probably", "a", "map", "topic" ]
d1b423daadf8921bc27da553b299f7b7ff9bffa9
https://github.com/gjtorikian/nanoc-conref-fs/blob/d1b423daadf8921bc27da553b299f7b7ff9bffa9/lib/nanoc-conref-fs/ancestry.rb#L92-L105
train
rschultheis/hatt
lib/hatt/api_clients.rb
Hatt.ApiClients.hatt_add_service
def hatt_add_service(name, url_or_svc_cfg_hash) svc_cfg = case url_or_svc_cfg_hash when String { 'url' => url_or_svc_cfg_hash } when Hash url_or_svc_cfg_hash else raise ArgumentError, "'#{url_or_svc_cfg_hash}' is not a url string nor hash with url key" end init_config services_config = hatt_configuration['hatt_services'] services_config[name] = svc_cfg @hatt_configuration.tcfg_set 'hatt_services', services_config @hatt_http_clients ||= {} @hatt_http_clients[name] = Hatt::HTTP.new hatt_configuration['hatt_services'][name] define_singleton_method name.intern do @hatt_http_clients[name] end end
ruby
def hatt_add_service(name, url_or_svc_cfg_hash) svc_cfg = case url_or_svc_cfg_hash when String { 'url' => url_or_svc_cfg_hash } when Hash url_or_svc_cfg_hash else raise ArgumentError, "'#{url_or_svc_cfg_hash}' is not a url string nor hash with url key" end init_config services_config = hatt_configuration['hatt_services'] services_config[name] = svc_cfg @hatt_configuration.tcfg_set 'hatt_services', services_config @hatt_http_clients ||= {} @hatt_http_clients[name] = Hatt::HTTP.new hatt_configuration['hatt_services'][name] define_singleton_method name.intern do @hatt_http_clients[name] end end
[ "def", "hatt_add_service", "(", "name", ",", "url_or_svc_cfg_hash", ")", "svc_cfg", "=", "case", "url_or_svc_cfg_hash", "when", "String", "{", "'url'", "=>", "url_or_svc_cfg_hash", "}", "when", "Hash", "url_or_svc_cfg_hash", "else", "raise", "ArgumentError", ",", "\"'#{url_or_svc_cfg_hash}' is not a url string nor hash with url key\"", "end", "init_config", "services_config", "=", "hatt_configuration", "[", "'hatt_services'", "]", "services_config", "[", "name", "]", "=", "svc_cfg", "@hatt_configuration", ".", "tcfg_set", "'hatt_services'", ",", "services_config", "@hatt_http_clients", "||=", "{", "}", "@hatt_http_clients", "[", "name", "]", "=", "Hatt", "::", "HTTP", ".", "new", "hatt_configuration", "[", "'hatt_services'", "]", "[", "name", "]", "define_singleton_method", "name", ".", "intern", "do", "@hatt_http_clients", "[", "name", "]", "end", "end" ]
add a service to hatt @param name [String] the name of the service @param url [String] an absolute url to the api
[ "add", "a", "service", "to", "hatt" ]
b1b5cddf2b52d8952e5607a2987d2efb648babaf
https://github.com/rschultheis/hatt/blob/b1b5cddf2b52d8952e5607a2987d2efb648babaf/lib/hatt/api_clients.rb#L18-L38
train
etailer/parcel_api
lib/parcel_api/address.rb
ParcelApi.Address.details
def details(address_id) details_url = File.join(DOMESTIC_URL, address_id.to_s) response = @connection.get details_url OpenStruct.new(response.parsed['address']) end
ruby
def details(address_id) details_url = File.join(DOMESTIC_URL, address_id.to_s) response = @connection.get details_url OpenStruct.new(response.parsed['address']) end
[ "def", "details", "(", "address_id", ")", "details_url", "=", "File", ".", "join", "(", "DOMESTIC_URL", ",", "address_id", ".", "to_s", ")", "response", "=", "@connection", ".", "get", "details_url", "OpenStruct", ".", "new", "(", "response", ".", "parsed", "[", "'address'", "]", ")", "end" ]
Return domestic address details for a domestic address id @param address_id [String] @return address detail object
[ "Return", "domestic", "address", "details", "for", "a", "domestic", "address", "id" ]
fcb8d64e45f7ba72bab48f143ac5115b0441aced
https://github.com/etailer/parcel_api/blob/fcb8d64e45f7ba72bab48f143ac5115b0441aced/lib/parcel_api/address.rb#L36-L40
train
etailer/parcel_api
lib/parcel_api/address.rb
ParcelApi.Address.australian_details
def australian_details(address_id) details_url = File.join(AUSTRALIAN_URL, address_id.to_s) response = @connection.get details_url RecursiveOpenStruct.new(response.parsed['address'], recurse_over_arrays: true) end
ruby
def australian_details(address_id) details_url = File.join(AUSTRALIAN_URL, address_id.to_s) response = @connection.get details_url RecursiveOpenStruct.new(response.parsed['address'], recurse_over_arrays: true) end
[ "def", "australian_details", "(", "address_id", ")", "details_url", "=", "File", ".", "join", "(", "AUSTRALIAN_URL", ",", "address_id", ".", "to_s", ")", "response", "=", "@connection", ".", "get", "details_url", "RecursiveOpenStruct", ".", "new", "(", "response", ".", "parsed", "[", "'address'", "]", ",", "recurse_over_arrays", ":", "true", ")", "end" ]
Return australian address details for a specific international address id @param address_id [String] @return australian address detail
[ "Return", "australian", "address", "details", "for", "a", "specific", "international", "address", "id" ]
fcb8d64e45f7ba72bab48f143ac5115b0441aced
https://github.com/etailer/parcel_api/blob/fcb8d64e45f7ba72bab48f143ac5115b0441aced/lib/parcel_api/address.rb#L55-L59
train
etailer/parcel_api
lib/parcel_api/address.rb
ParcelApi.Address.international_search
def international_search(query, count=5, country_code=nil) return [] if query.length < 4 response = @connection.get INTERNATIONAL_URL, params: { q: query.to_ascii, count: count, country_code: country_code } response.parsed['addresses'].map {|address| OpenStruct.new(address)} end
ruby
def international_search(query, count=5, country_code=nil) return [] if query.length < 4 response = @connection.get INTERNATIONAL_URL, params: { q: query.to_ascii, count: count, country_code: country_code } response.parsed['addresses'].map {|address| OpenStruct.new(address)} end
[ "def", "international_search", "(", "query", ",", "count", "=", "5", ",", "country_code", "=", "nil", ")", "return", "[", "]", "if", "query", ".", "length", "<", "4", "response", "=", "@connection", ".", "get", "INTERNATIONAL_URL", ",", "params", ":", "{", "q", ":", "query", ".", "to_ascii", ",", "count", ":", "count", ",", "country_code", ":", "country_code", "}", "response", ".", "parsed", "[", "'addresses'", "]", ".", "map", "{", "|", "address", "|", "OpenStruct", ".", "new", "(", "address", ")", "}", "end" ]
Search for an International Address @param [String] characters to search for @param [Integer] number of search results to return (max 10) @param [String] country code for results - listed here: https://developers.google.com/public-data/docs/canonical/countries_csv/ @return [Array] array of international addresses
[ "Search", "for", "an", "International", "Address" ]
fcb8d64e45f7ba72bab48f143ac5115b0441aced
https://github.com/etailer/parcel_api/blob/fcb8d64e45f7ba72bab48f143ac5115b0441aced/lib/parcel_api/address.rb#L67-L72
train
etailer/parcel_api
lib/parcel_api/address.rb
ParcelApi.Address.international_details
def international_details(address_id) details_url = File.join(INTERNATIONAL_URL, address_id.to_s) response = @connection.get details_url RecursiveOpenStruct.new(response.parsed['result'], recurse_over_arrays: true) end
ruby
def international_details(address_id) details_url = File.join(INTERNATIONAL_URL, address_id.to_s) response = @connection.get details_url RecursiveOpenStruct.new(response.parsed['result'], recurse_over_arrays: true) end
[ "def", "international_details", "(", "address_id", ")", "details_url", "=", "File", ".", "join", "(", "INTERNATIONAL_URL", ",", "address_id", ".", "to_s", ")", "response", "=", "@connection", ".", "get", "details_url", "RecursiveOpenStruct", ".", "new", "(", "response", ".", "parsed", "[", "'result'", "]", ",", "recurse_over_arrays", ":", "true", ")", "end" ]
Return international address details for a specific international address id @param address_id [String] @return international address detail
[ "Return", "international", "address", "details", "for", "a", "specific", "international", "address", "id" ]
fcb8d64e45f7ba72bab48f143ac5115b0441aced
https://github.com/etailer/parcel_api/blob/fcb8d64e45f7ba72bab48f143ac5115b0441aced/lib/parcel_api/address.rb#L78-L82
train
EricBoersma/actionkit_connector
lib/actionkit_connector.rb
ActionKitConnector.Connector.find_petition_pages
def find_petition_pages(name, limit: 10, offset: 0) target = "#{self.base_url}/petitionpage/" options = { basic_auth: self.auth, query: { _limit: limit, _offset: offset, name: name } } self.class.get(target, options) end
ruby
def find_petition_pages(name, limit: 10, offset: 0) target = "#{self.base_url}/petitionpage/" options = { basic_auth: self.auth, query: { _limit: limit, _offset: offset, name: name } } self.class.get(target, options) end
[ "def", "find_petition_pages", "(", "name", ",", "limit", ":", "10", ",", "offset", ":", "0", ")", "target", "=", "\"#{self.base_url}/petitionpage/\"", "options", "=", "{", "basic_auth", ":", "self", ".", "auth", ",", "query", ":", "{", "_limit", ":", "limit", ",", "_offset", ":", "offset", ",", "name", ":", "name", "}", "}", "self", ".", "class", ".", "get", "(", "target", ",", "options", ")", "end" ]
Find petition pages matching a given name. @param [Int] offset The number of records to skip. @param [Int] limit The maximum number of results to return. @param [String] name The string to match against name.
[ "Find", "petition", "pages", "matching", "a", "given", "name", "." ]
909b3a0feba9da3205473e676e66a2eb7294dc9e
https://github.com/EricBoersma/actionkit_connector/blob/909b3a0feba9da3205473e676e66a2eb7294dc9e/lib/actionkit_connector.rb#L50-L63
train
EricBoersma/actionkit_connector
lib/actionkit_connector.rb
ActionKitConnector.Connector.create_petition_page
def create_petition_page(name, title, lang, canonical_url) target = "#{self.base_url}/petitionpage/" options = { basic_auth: self.auth, headers: { 'Content-type' => 'application/json; charset=UTF-8' }, :body => { :type => 'petitionpage', :hidden => false, :name => name, :title => title, :language => lang, :canonical_url => canonical_url }.to_json, format: :json } self.class.post(target, options) end
ruby
def create_petition_page(name, title, lang, canonical_url) target = "#{self.base_url}/petitionpage/" options = { basic_auth: self.auth, headers: { 'Content-type' => 'application/json; charset=UTF-8' }, :body => { :type => 'petitionpage', :hidden => false, :name => name, :title => title, :language => lang, :canonical_url => canonical_url }.to_json, format: :json } self.class.post(target, options) end
[ "def", "create_petition_page", "(", "name", ",", "title", ",", "lang", ",", "canonical_url", ")", "target", "=", "\"#{self.base_url}/petitionpage/\"", "options", "=", "{", "basic_auth", ":", "self", ".", "auth", ",", "headers", ":", "{", "'Content-type'", "=>", "'application/json; charset=UTF-8'", "}", ",", ":body", "=>", "{", ":type", "=>", "'petitionpage'", ",", ":hidden", "=>", "false", ",", ":name", "=>", "name", ",", ":title", "=>", "title", ",", ":language", "=>", "lang", ",", ":canonical_url", "=>", "canonical_url", "}", ".", "to_json", ",", "format", ":", ":json", "}", "self", ".", "class", ".", "post", "(", "target", ",", "options", ")", "end" ]
Create a petition page in your ActionKit instance. @param [String] name The name of the page. @param [String] title The title of the page. @param [URI] lang The URI string for the language of this page in the form of /rest/v1/language/{id} @param [URL] canonical_url The canonical URL for this page.
[ "Create", "a", "petition", "page", "in", "your", "ActionKit", "instance", "." ]
909b3a0feba9da3205473e676e66a2eb7294dc9e
https://github.com/EricBoersma/actionkit_connector/blob/909b3a0feba9da3205473e676e66a2eb7294dc9e/lib/actionkit_connector.rb#L79-L97
train
EricBoersma/actionkit_connector
lib/actionkit_connector.rb
ActionKitConnector.Connector.create_action
def create_action(page_name, email, options={}) target = "#{self.base_url}/action/" body = { page: page_name, email: email }.merge self.parse_action_options(options) options = { basic_auth: self.auth, body: body.to_json, format: :json, headers: {'Content-Type' => 'application/json; charset=UTF-8'} } self.class.post(target, options) end
ruby
def create_action(page_name, email, options={}) target = "#{self.base_url}/action/" body = { page: page_name, email: email }.merge self.parse_action_options(options) options = { basic_auth: self.auth, body: body.to_json, format: :json, headers: {'Content-Type' => 'application/json; charset=UTF-8'} } self.class.post(target, options) end
[ "def", "create_action", "(", "page_name", ",", "email", ",", "options", "=", "{", "}", ")", "target", "=", "\"#{self.base_url}/action/\"", "body", "=", "{", "page", ":", "page_name", ",", "email", ":", "email", "}", ".", "merge", "self", ".", "parse_action_options", "(", "options", ")", "options", "=", "{", "basic_auth", ":", "self", ".", "auth", ",", "body", ":", "body", ".", "to_json", ",", "format", ":", ":json", ",", "headers", ":", "{", "'Content-Type'", "=>", "'application/json; charset=UTF-8'", "}", "}", "self", ".", "class", ".", "post", "(", "target", ",", "options", ")", "end" ]
Creates an action which associates a user with a page. @param [String] page_name The ActionKit name of the page on which the action is being taken. @param [String] email The email address of the person taking action.
[ "Creates", "an", "action", "which", "associates", "a", "user", "with", "a", "page", "." ]
909b3a0feba9da3205473e676e66a2eb7294dc9e
https://github.com/EricBoersma/actionkit_connector/blob/909b3a0feba9da3205473e676e66a2eb7294dc9e/lib/actionkit_connector.rb#L129-L139
train
EricBoersma/actionkit_connector
lib/actionkit_connector.rb
ActionKitConnector.Connector.create_donation_action
def create_donation_action(options={}) target = "#{self.base_url}/donationpush/" options = self.validate_donation_options(options) page_opts = { basic_auth: self.auth, body: options.to_json, headers: { 'Content-Type' => 'application/json; charset=UTF-8' } } self.class.post(target, page_opts) end
ruby
def create_donation_action(options={}) target = "#{self.base_url}/donationpush/" options = self.validate_donation_options(options) page_opts = { basic_auth: self.auth, body: options.to_json, headers: { 'Content-Type' => 'application/json; charset=UTF-8' } } self.class.post(target, page_opts) end
[ "def", "create_donation_action", "(", "options", "=", "{", "}", ")", "target", "=", "\"#{self.base_url}/donationpush/\"", "options", "=", "self", ".", "validate_donation_options", "(", "options", ")", "page_opts", "=", "{", "basic_auth", ":", "self", ".", "auth", ",", "body", ":", "options", ".", "to_json", ",", "headers", ":", "{", "'Content-Type'", "=>", "'application/json; charset=UTF-8'", "}", "}", "self", ".", "class", ".", "post", "(", "target", ",", "page_opts", ")", "end" ]
Creates an action which registers a donation with a user account. @param [Hash] options The hash of values sent to ActionKit which contain information about this transaction.
[ "Creates", "an", "action", "which", "registers", "a", "donation", "with", "a", "user", "account", "." ]
909b3a0feba9da3205473e676e66a2eb7294dc9e
https://github.com/EricBoersma/actionkit_connector/blob/909b3a0feba9da3205473e676e66a2eb7294dc9e/lib/actionkit_connector.rb#L144-L155
train
EricBoersma/actionkit_connector
lib/actionkit_connector.rb
ActionKitConnector.Connector.list_users
def list_users(offset=0, limit=20) target = "#{self.base_url}/user/" options = { basic_auth: self.auth, query: { _limit: limit, _offset: offset } } self.class.get(target, options) end
ruby
def list_users(offset=0, limit=20) target = "#{self.base_url}/user/" options = { basic_auth: self.auth, query: { _limit: limit, _offset: offset } } self.class.get(target, options) end
[ "def", "list_users", "(", "offset", "=", "0", ",", "limit", "=", "20", ")", "target", "=", "\"#{self.base_url}/user/\"", "options", "=", "{", "basic_auth", ":", "self", ".", "auth", ",", "query", ":", "{", "_limit", ":", "limit", ",", "_offset", ":", "offset", "}", "}", "self", ".", "class", ".", "get", "(", "target", ",", "options", ")", "end" ]
Lists users in your instance. @param [Int] offset The number of records to skip. @param [Int] limit The maximum number of results to return.
[ "Lists", "users", "in", "your", "instance", "." ]
909b3a0feba9da3205473e676e66a2eb7294dc9e
https://github.com/EricBoersma/actionkit_connector/blob/909b3a0feba9da3205473e676e66a2eb7294dc9e/lib/actionkit_connector.rb#L169-L179
train
nwops/retrospec
lib/retrospec/config.rb
Retrospec.Config.setup_config_file
def setup_config_file(file=nil) if file.nil? or ! File.exists?(file) # config does not exist setup_config_dir dst_file = File.join(default_retrospec_dir, 'config.yaml') src_file = File.join(gem_dir,'config.yaml.sample') safe_copy_file(src_file, dst_file) file = dst_file end @config_file = file end
ruby
def setup_config_file(file=nil) if file.nil? or ! File.exists?(file) # config does not exist setup_config_dir dst_file = File.join(default_retrospec_dir, 'config.yaml') src_file = File.join(gem_dir,'config.yaml.sample') safe_copy_file(src_file, dst_file) file = dst_file end @config_file = file end
[ "def", "setup_config_file", "(", "file", "=", "nil", ")", "if", "file", ".", "nil?", "or", "!", "File", ".", "exists?", "(", "file", ")", "setup_config_dir", "dst_file", "=", "File", ".", "join", "(", "default_retrospec_dir", ",", "'config.yaml'", ")", "src_file", "=", "File", ".", "join", "(", "gem_dir", ",", "'config.yaml.sample'", ")", "safe_copy_file", "(", "src_file", ",", "dst_file", ")", "file", "=", "dst_file", "end", "@config_file", "=", "file", "end" ]
we should be able to lookup where the user stores the config map so the user doesn't have to pass this info each time create a blank yaml config file it file does not exist
[ "we", "should", "be", "able", "to", "lookup", "where", "the", "user", "stores", "the", "config", "map", "so", "the", "user", "doesn", "t", "have", "to", "pass", "this", "info", "each", "time", "create", "a", "blank", "yaml", "config", "file", "it", "file", "does", "not", "exist" ]
e61a8e8b86384c64a3ce9340d1342fa416740522
https://github.com/nwops/retrospec/blob/e61a8e8b86384c64a3ce9340d1342fa416740522/lib/retrospec/config.rb#L18-L28
train
ajh/speaky_csv
lib/speaky_csv/config_builder.rb
SpeakyCsv.ConfigBuilder.field
def field(*fields, export_only: false) @config.fields += fields.map(&:to_sym) @config.fields.uniq! if export_only @config.export_only_fields += fields.map(&:to_sym) @config.export_only_fields.uniq! end nil end
ruby
def field(*fields, export_only: false) @config.fields += fields.map(&:to_sym) @config.fields.uniq! if export_only @config.export_only_fields += fields.map(&:to_sym) @config.export_only_fields.uniq! end nil end
[ "def", "field", "(", "*", "fields", ",", "export_only", ":", "false", ")", "@config", ".", "fields", "+=", "fields", ".", "map", "(", "&", ":to_sym", ")", "@config", ".", "fields", ".", "uniq!", "if", "export_only", "@config", ".", "export_only_fields", "+=", "fields", ".", "map", "(", "&", ":to_sym", ")", "@config", ".", "export_only_fields", ".", "uniq!", "end", "nil", "end" ]
Add one or many fields to the csv format. If options are passed, they apply to all given fields.
[ "Add", "one", "or", "many", "fields", "to", "the", "csv", "format", "." ]
aa16dd8e7dbe2202523b1a7d35a610c174c3fc21
https://github.com/ajh/speaky_csv/blob/aa16dd8e7dbe2202523b1a7d35a610c174c3fc21/lib/speaky_csv/config_builder.rb#L15-L25
train
ajh/speaky_csv
lib/speaky_csv/config_builder.rb
SpeakyCsv.ConfigBuilder.has_one
def has_one(name) @config.root or raise NotImplementedError, "nested associations are not supported" @config.has_ones[name.to_sym] ||= Config.new yield self.class.new config: @config.has_ones[name.to_sym], root: false nil end
ruby
def has_one(name) @config.root or raise NotImplementedError, "nested associations are not supported" @config.has_ones[name.to_sym] ||= Config.new yield self.class.new config: @config.has_ones[name.to_sym], root: false nil end
[ "def", "has_one", "(", "name", ")", "@config", ".", "root", "or", "raise", "NotImplementedError", ",", "\"nested associations are not supported\"", "@config", ".", "has_ones", "[", "name", ".", "to_sym", "]", "||=", "Config", ".", "new", "yield", "self", ".", "class", ".", "new", "config", ":", "@config", ".", "has_ones", "[", "name", ".", "to_sym", "]", ",", "root", ":", "false", "nil", "end" ]
Define a one to one association. This is also aliased as `belongs_to`. Expects a name and a block to define the fields on associated record. For example: define_csv_fields do |c| has_many 'publisher' do |p| p.field :id, :name, :_destroy end end
[ "Define", "a", "one", "to", "one", "association", ".", "This", "is", "also", "aliased", "as", "belongs_to", ".", "Expects", "a", "name", "and", "a", "block", "to", "define", "the", "fields", "on", "associated", "record", "." ]
aa16dd8e7dbe2202523b1a7d35a610c174c3fc21
https://github.com/ajh/speaky_csv/blob/aa16dd8e7dbe2202523b1a7d35a610c174c3fc21/lib/speaky_csv/config_builder.rb#L46-L52
train
ajh/speaky_csv
lib/speaky_csv/config_builder.rb
SpeakyCsv.ConfigBuilder.has_many
def has_many(name) @config.root or raise NotImplementedError, "nested associations are not supported" @config.has_manys[name.to_sym] ||= Config.new yield self.class.new config: @config.has_manys[name.to_sym], root: false nil end
ruby
def has_many(name) @config.root or raise NotImplementedError, "nested associations are not supported" @config.has_manys[name.to_sym] ||= Config.new yield self.class.new config: @config.has_manys[name.to_sym], root: false nil end
[ "def", "has_many", "(", "name", ")", "@config", ".", "root", "or", "raise", "NotImplementedError", ",", "\"nested associations are not supported\"", "@config", ".", "has_manys", "[", "name", ".", "to_sym", "]", "||=", "Config", ".", "new", "yield", "self", ".", "class", ".", "new", "config", ":", "@config", ".", "has_manys", "[", "name", ".", "to_sym", "]", ",", "root", ":", "false", "nil", "end" ]
Define a one to many association. Expect a name and a block to define the fields on associated records. For example: define_csv_fields do |c| has_many 'reviews' do |r| r.field :id, :name, :_destroy end end
[ "Define", "a", "one", "to", "many", "association", ".", "Expect", "a", "name", "and", "a", "block", "to", "define", "the", "fields", "on", "associated", "records", "." ]
aa16dd8e7dbe2202523b1a7d35a610c174c3fc21
https://github.com/ajh/speaky_csv/blob/aa16dd8e7dbe2202523b1a7d35a610c174c3fc21/lib/speaky_csv/config_builder.rb#L66-L72
train
mattnichols/ice_cube_cron
lib/ice_cube_cron/rule_builder.rb
IceCubeCron.RuleBuilder.build_rule
def build_rule(expression) rule = build_root_recurrence_rule(expression) rule = build_year_rules(rule, expression) rule = build_weekday_rule(rule, expression) rule = build_day_rules(rule, expression) rule = build_time_rules(rule, expression) rule = rule.until(expression.until) unless expression.until.blank? rule end
ruby
def build_rule(expression) rule = build_root_recurrence_rule(expression) rule = build_year_rules(rule, expression) rule = build_weekday_rule(rule, expression) rule = build_day_rules(rule, expression) rule = build_time_rules(rule, expression) rule = rule.until(expression.until) unless expression.until.blank? rule end
[ "def", "build_rule", "(", "expression", ")", "rule", "=", "build_root_recurrence_rule", "(", "expression", ")", "rule", "=", "build_year_rules", "(", "rule", ",", "expression", ")", "rule", "=", "build_weekday_rule", "(", "rule", ",", "expression", ")", "rule", "=", "build_day_rules", "(", "rule", ",", "expression", ")", "rule", "=", "build_time_rules", "(", "rule", ",", "expression", ")", "rule", "=", "rule", ".", "until", "(", "expression", ".", "until", ")", "unless", "expression", ".", "until", ".", "blank?", "rule", "end" ]
Generates a rule based on a parsed expression
[ "Generates", "a", "rule", "based", "on", "a", "parsed", "expression" ]
9b406a40b5d15b03a3e58cb0ec64ca4a85a85cd0
https://github.com/mattnichols/ice_cube_cron/blob/9b406a40b5d15b03a3e58cb0ec64ca4a85a85cd0/lib/ice_cube_cron/rule_builder.rb#L9-L18
train
rschultheis/hatt
lib/hatt/json_helpers.rb
Hatt.JsonHelpers.jsonify
def jsonify(obj) case obj when String JSON.pretty_generate(JSON.parse(obj)) when Hash, Array JSON.pretty_generate(obj) else obj.to_s end rescue Exception obj.to_s end
ruby
def jsonify(obj) case obj when String JSON.pretty_generate(JSON.parse(obj)) when Hash, Array JSON.pretty_generate(obj) else obj.to_s end rescue Exception obj.to_s end
[ "def", "jsonify", "(", "obj", ")", "case", "obj", "when", "String", "JSON", ".", "pretty_generate", "(", "JSON", ".", "parse", "(", "obj", ")", ")", "when", "Hash", ",", "Array", "JSON", ".", "pretty_generate", "(", "obj", ")", "else", "obj", ".", "to_s", "end", "rescue", "Exception", "obj", ".", "to_s", "end" ]
always returns a string, intended for request bodies every attempt is made to ensure string is valid json but if that is not possible, then its returned as is
[ "always", "returns", "a", "string", "intended", "for", "request", "bodies", "every", "attempt", "is", "made", "to", "ensure", "string", "is", "valid", "json", "but", "if", "that", "is", "not", "possible", "then", "its", "returned", "as", "is" ]
b1b5cddf2b52d8952e5607a2987d2efb648babaf
https://github.com/rschultheis/hatt/blob/b1b5cddf2b52d8952e5607a2987d2efb648babaf/lib/hatt/json_helpers.rb#L8-L19
train
rschultheis/hatt
lib/hatt/json_helpers.rb
Hatt.JsonHelpers.objectify
def objectify(json_string) return nil if json_string.nil? || json_string == '' case json_string when Hash, Array return json_string else JSON.parse(json_string.to_s) end rescue Exception json_string end
ruby
def objectify(json_string) return nil if json_string.nil? || json_string == '' case json_string when Hash, Array return json_string else JSON.parse(json_string.to_s) end rescue Exception json_string end
[ "def", "objectify", "(", "json_string", ")", "return", "nil", "if", "json_string", ".", "nil?", "||", "json_string", "==", "''", "case", "json_string", "when", "Hash", ",", "Array", "return", "json_string", "else", "JSON", ".", "parse", "(", "json_string", ".", "to_s", ")", "end", "rescue", "Exception", "json_string", "end" ]
attempts to parse json strings into native ruby objects
[ "attempts", "to", "parse", "json", "strings", "into", "native", "ruby", "objects" ]
b1b5cddf2b52d8952e5607a2987d2efb648babaf
https://github.com/rschultheis/hatt/blob/b1b5cddf2b52d8952e5607a2987d2efb648babaf/lib/hatt/json_helpers.rb#L22-L32
train
payout/podbay
lib/podbay/utils.rb
Podbay.Utils.count_values
def count_values(*values) values.inject(Hash.new(0)) { |h, v| h[v] += 1; h } end
ruby
def count_values(*values) values.inject(Hash.new(0)) { |h, v| h[v] += 1; h } end
[ "def", "count_values", "(", "*", "values", ")", "values", ".", "inject", "(", "Hash", ".", "new", "(", "0", ")", ")", "{", "|", "h", ",", "v", "|", "h", "[", "v", "]", "+=", "1", ";", "h", "}", "end" ]
Returns a hash where the keys are the values in the passed array and the values are the number of times that value appears in the list.
[ "Returns", "a", "hash", "where", "the", "keys", "are", "the", "values", "in", "the", "passed", "array", "and", "the", "values", "are", "the", "number", "of", "times", "that", "value", "appears", "in", "the", "list", "." ]
a17cc1db6a1f032d9d7005136e4176dbe7f3a73d
https://github.com/payout/podbay/blob/a17cc1db6a1f032d9d7005136e4176dbe7f3a73d/lib/podbay/utils.rb#L124-L126
train
payout/podbay
lib/podbay/utils.rb
Podbay.Utils.get_uid
def get_uid(username) Etc.passwd { |u| return u.uid if u.name == username } end
ruby
def get_uid(username) Etc.passwd { |u| return u.uid if u.name == username } end
[ "def", "get_uid", "(", "username", ")", "Etc", ".", "passwd", "{", "|", "u", "|", "return", "u", ".", "uid", "if", "u", ".", "name", "==", "username", "}", "end" ]
Returns the UID for the username on the host.
[ "Returns", "the", "UID", "for", "the", "username", "on", "the", "host", "." ]
a17cc1db6a1f032d9d7005136e4176dbe7f3a73d
https://github.com/payout/podbay/blob/a17cc1db6a1f032d9d7005136e4176dbe7f3a73d/lib/podbay/utils.rb#L130-L132
train
payout/podbay
lib/podbay/utils.rb
Podbay.Utils.get_gid
def get_gid(group_name) Etc.group { |g| return g.gid if g.name == group_name } end
ruby
def get_gid(group_name) Etc.group { |g| return g.gid if g.name == group_name } end
[ "def", "get_gid", "(", "group_name", ")", "Etc", ".", "group", "{", "|", "g", "|", "return", "g", ".", "gid", "if", "g", ".", "name", "==", "group_name", "}", "end" ]
Returns GID for the group on the host.
[ "Returns", "GID", "for", "the", "group", "on", "the", "host", "." ]
a17cc1db6a1f032d9d7005136e4176dbe7f3a73d
https://github.com/payout/podbay/blob/a17cc1db6a1f032d9d7005136e4176dbe7f3a73d/lib/podbay/utils.rb#L136-L138
train
payout/podbay
lib/podbay/utils.rb
Podbay.Utils.podbay_info
def podbay_info(ip_address, path, timeout = 5) JSON.parse( get_request( "http://#{ip_address}:#{Podbay::SERVER_INFO_PORT}/#{path}", timeout: timeout ).body, symbolize_names: true ) end
ruby
def podbay_info(ip_address, path, timeout = 5) JSON.parse( get_request( "http://#{ip_address}:#{Podbay::SERVER_INFO_PORT}/#{path}", timeout: timeout ).body, symbolize_names: true ) end
[ "def", "podbay_info", "(", "ip_address", ",", "path", ",", "timeout", "=", "5", ")", "JSON", ".", "parse", "(", "get_request", "(", "\"http://#{ip_address}:#{Podbay::SERVER_INFO_PORT}/#{path}\"", ",", "timeout", ":", "timeout", ")", ".", "body", ",", "symbolize_names", ":", "true", ")", "end" ]
Makes a GET request to the Podbay servers that are listening for Podbay data requests
[ "Makes", "a", "GET", "request", "to", "the", "Podbay", "servers", "that", "are", "listening", "for", "Podbay", "data", "requests" ]
a17cc1db6a1f032d9d7005136e4176dbe7f3a73d
https://github.com/payout/podbay/blob/a17cc1db6a1f032d9d7005136e4176dbe7f3a73d/lib/podbay/utils.rb#L156-L164
train
m-31/puppetdb_query
lib/puppetdb_query/updater.rb
PuppetDBQuery.Updater.update2
def update2 update_node_properties logger.info "update2 started (full update)" tsb = Time.now source_nodes = source_node_properties.keys destination_nodes = destination.all_nodes delete_missing(destination_nodes, source_nodes) errors = false complete = source.facts complete.each do |node, facts| begin destination.node_update(node, facts) rescue errors = true logger.error $! end end tse = Time.now logger.info "update2 updated #{source_nodes.size} nodes in #{tse - tsb}" destination.meta_fact_update("update2", tsb, tse) unless errors end
ruby
def update2 update_node_properties logger.info "update2 started (full update)" tsb = Time.now source_nodes = source_node_properties.keys destination_nodes = destination.all_nodes delete_missing(destination_nodes, source_nodes) errors = false complete = source.facts complete.each do |node, facts| begin destination.node_update(node, facts) rescue errors = true logger.error $! end end tse = Time.now logger.info "update2 updated #{source_nodes.size} nodes in #{tse - tsb}" destination.meta_fact_update("update2", tsb, tse) unless errors end
[ "def", "update2", "update_node_properties", "logger", ".", "info", "\"update2 started (full update)\"", "tsb", "=", "Time", ".", "now", "source_nodes", "=", "source_node_properties", ".", "keys", "destination_nodes", "=", "destination", ".", "all_nodes", "delete_missing", "(", "destination_nodes", ",", "source_nodes", ")", "errors", "=", "false", "complete", "=", "source", ".", "facts", "complete", ".", "each", "do", "|", "node", ",", "facts", "|", "begin", "destination", ".", "node_update", "(", "node", ",", "facts", ")", "rescue", "errors", "=", "true", "logger", ".", "error", "$!", "end", "end", "tse", "=", "Time", ".", "now", "logger", ".", "info", "\"update2 updated #{source_nodes.size} nodes in #{tse - tsb}\"", "destination", ".", "meta_fact_update", "(", "\"update2\"", ",", "tsb", ",", "tse", ")", "unless", "errors", "end" ]
update by deleting missing nodes and get a complete map of nodes with facts and update or insert facts for each one mongo: 1597 nodes in 35.31 seconds
[ "update", "by", "deleting", "missing", "nodes", "and", "get", "a", "complete", "map", "of", "nodes", "with", "facts", "and", "update", "or", "insert", "facts", "for", "each", "one" ]
58103c91f291de8ce28d679256e50ae391b93ecb
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/updater.rb#L47-L67
train
m-31/puppetdb_query
lib/puppetdb_query/updater.rb
PuppetDBQuery.Updater.update_node_properties
def update_node_properties logger.info "update_node_properties started" tsb = Time.now @source_node_properties = source.node_properties destination.node_properties_update(source_node_properties) tse = Time.now logger.info "update_node_properties got #{source_node_properties.size} nodes " \ "in #{tse - tsb}" destination.meta_node_properties_update(tsb, tse) end
ruby
def update_node_properties logger.info "update_node_properties started" tsb = Time.now @source_node_properties = source.node_properties destination.node_properties_update(source_node_properties) tse = Time.now logger.info "update_node_properties got #{source_node_properties.size} nodes " \ "in #{tse - tsb}" destination.meta_node_properties_update(tsb, tse) end
[ "def", "update_node_properties", "logger", ".", "info", "\"update_node_properties started\"", "tsb", "=", "Time", ".", "now", "@source_node_properties", "=", "source", ".", "node_properties", "destination", ".", "node_properties_update", "(", "source_node_properties", ")", "tse", "=", "Time", ".", "now", "logger", ".", "info", "\"update_node_properties got #{source_node_properties.size} nodes \"", "\"in #{tse - tsb}\"", "destination", ".", "meta_node_properties_update", "(", "tsb", ",", "tse", ")", "end" ]
update node update information mongo: 1602 nodes in 0.42 seconds
[ "update", "node", "update", "information" ]
58103c91f291de8ce28d679256e50ae391b93ecb
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/updater.rb#L98-L107
train
kamui/rack-accept_headers
lib/rack/accept_headers/encoding.rb
Rack::AcceptHeaders.Encoding.matches
def matches(encoding) values.select {|v| v == encoding || v == '*' }.sort {|a, b| # "*" gets least precedence, any others should be equal. a == '*' ? 1 : (b == '*' ? -1 : 0) } end
ruby
def matches(encoding) values.select {|v| v == encoding || v == '*' }.sort {|a, b| # "*" gets least precedence, any others should be equal. a == '*' ? 1 : (b == '*' ? -1 : 0) } end
[ "def", "matches", "(", "encoding", ")", "values", ".", "select", "{", "|", "v", "|", "v", "==", "encoding", "||", "v", "==", "'*'", "}", ".", "sort", "{", "|", "a", ",", "b", "|", "a", "==", "'*'", "?", "1", ":", "(", "b", "==", "'*'", "?", "-", "1", ":", "0", ")", "}", "end" ]
Returns an array of encodings from this header that match the given +encoding+, ordered by precedence.
[ "Returns", "an", "array", "of", "encodings", "from", "this", "header", "that", "match", "the", "given", "+", "encoding", "+", "ordered", "by", "precedence", "." ]
099bfbb919de86b5842c8e14be42b8b784e53f03
https://github.com/kamui/rack-accept_headers/blob/099bfbb919de86b5842c8e14be42b8b784e53f03/lib/rack/accept_headers/encoding.rb#L27-L34
train
nigelr/selections
lib/selections/belongs_to_selection.rb
Selections.BelongsToSelection.belongs_to_selection
def belongs_to_selection(target, options={}) belongs_to target, options.merge(:class_name => "Selection") # The "selections" table may not exist during certain rake scenarios such as db:migrate or db:reset. if ActiveRecord::Base.connection.table_exists? Selection.table_name prefix = self.name.downcase parent = Selection.where(system_code: "#{prefix}_#{target}").first if parent target_id = "#{target}_id".to_sym parent.children.each do |s| method_name = "#{s.system_code.sub("#{prefix}_", '')}?".to_sym class_eval do define_method method_name do send(target_id) == s.id end end end end end end
ruby
def belongs_to_selection(target, options={}) belongs_to target, options.merge(:class_name => "Selection") # The "selections" table may not exist during certain rake scenarios such as db:migrate or db:reset. if ActiveRecord::Base.connection.table_exists? Selection.table_name prefix = self.name.downcase parent = Selection.where(system_code: "#{prefix}_#{target}").first if parent target_id = "#{target}_id".to_sym parent.children.each do |s| method_name = "#{s.system_code.sub("#{prefix}_", '')}?".to_sym class_eval do define_method method_name do send(target_id) == s.id end end end end end end
[ "def", "belongs_to_selection", "(", "target", ",", "options", "=", "{", "}", ")", "belongs_to", "target", ",", "options", ".", "merge", "(", ":class_name", "=>", "\"Selection\"", ")", "if", "ActiveRecord", "::", "Base", ".", "connection", ".", "table_exists?", "Selection", ".", "table_name", "prefix", "=", "self", ".", "name", ".", "downcase", "parent", "=", "Selection", ".", "where", "(", "system_code", ":", "\"#{prefix}_#{target}\"", ")", ".", "first", "if", "parent", "target_id", "=", "\"#{target}_id\"", ".", "to_sym", "parent", ".", "children", ".", "each", "do", "|", "s", "|", "method_name", "=", "\"#{s.system_code.sub(\"#{prefix}_\", '')}?\"", ".", "to_sym", "class_eval", "do", "define_method", "method_name", "do", "send", "(", "target_id", ")", "==", "s", ".", "id", "end", "end", "end", "end", "end", "end" ]
Helper for belongs_to and accepts all the standard rails options Example class Thing < ActiveRecord::Base belongs_to_selection :priority by default adds - class_name: "Selection" This macro also adds a number of methods onto the class if there is a selection named as the class underscore name (eg: "thing_priority"), then methods are created for all of the selection values under that parent. For example: thing = Thing.find(x) thing.priority = Selection.thing_priority_high thing.priority_high? #=> true thing.priority_low? #=> false thing.priority_high? is equivalent to thing.priority == Selection.thing_priority_high except that the id of the selection is cached at the time the class is loaded. Note that this is only appropriate to use for system selection values that are known at development time, and not to values that the users can edit in the live system.
[ "Helper", "for", "belongs_to", "and", "accepts", "all", "the", "standard", "rails", "options" ]
f4702869ffaf11fbcdc8fdad4c0e91b3d0a1ce45
https://github.com/nigelr/selections/blob/f4702869ffaf11fbcdc8fdad4c0e91b3d0a1ce45/lib/selections/belongs_to_selection.rb#L26-L45
train
zdavatz/htmlgrid
lib/htmlgrid/composite.rb
HtmlGrid.Composite.full_colspan
def full_colspan raw_span = components.keys.collect{ |key| key.at(0) }.max.to_i (raw_span > 0) ? raw_span + 1 : nil end
ruby
def full_colspan raw_span = components.keys.collect{ |key| key.at(0) }.max.to_i (raw_span > 0) ? raw_span + 1 : nil end
[ "def", "full_colspan", "raw_span", "=", "components", ".", "keys", ".", "collect", "{", "|", "key", "|", "key", ".", "at", "(", "0", ")", "}", ".", "max", ".", "to_i", "(", "raw_span", ">", "0", ")", "?", "raw_span", "+", "1", ":", "nil", "end" ]
=begin def explode! @grid.explode! super end =end
[ "=", "begin", "def", "explode!" ]
88a0440466e422328b4553685d0efe7c9bbb4d72
https://github.com/zdavatz/htmlgrid/blob/88a0440466e422328b4553685d0efe7c9bbb4d72/lib/htmlgrid/composite.rb#L254-L259
train
crapooze/em-xmpp
lib/em-xmpp/entity.rb
EM::Xmpp.Entity.subscribe
def subscribe(&blk) pres = connection.presence_stanza('to'=>jid.bare, 'type' => 'subscribe') connection.send_stanza pres, &blk end
ruby
def subscribe(&blk) pres = connection.presence_stanza('to'=>jid.bare, 'type' => 'subscribe') connection.send_stanza pres, &blk end
[ "def", "subscribe", "(", "&", "blk", ")", "pres", "=", "connection", ".", "presence_stanza", "(", "'to'", "=>", "jid", ".", "bare", ",", "'type'", "=>", "'subscribe'", ")", "connection", ".", "send_stanza", "pres", ",", "&", "blk", "end" ]
sends a subscription request to the bare entity
[ "sends", "a", "subscription", "request", "to", "the", "bare", "entity" ]
804e139944c88bc317b359754d5ad69b75f42319
https://github.com/crapooze/em-xmpp/blob/804e139944c88bc317b359754d5ad69b75f42319/lib/em-xmpp/entity.rb#L42-L45
train
crapooze/em-xmpp
lib/em-xmpp/entity.rb
EM::Xmpp.Entity.accept_subscription
def accept_subscription(&blk) pres = connection.presence_stanza('to'=>jid.bare, 'type' => 'subscribed') connection.send_stanza pres, &blk end
ruby
def accept_subscription(&blk) pres = connection.presence_stanza('to'=>jid.bare, 'type' => 'subscribed') connection.send_stanza pres, &blk end
[ "def", "accept_subscription", "(", "&", "blk", ")", "pres", "=", "connection", ".", "presence_stanza", "(", "'to'", "=>", "jid", ".", "bare", ",", "'type'", "=>", "'subscribed'", ")", "connection", ".", "send_stanza", "pres", ",", "&", "blk", "end" ]
send a subscription stanza to accept an incoming subscription request
[ "send", "a", "subscription", "stanza", "to", "accept", "an", "incoming", "subscription", "request" ]
804e139944c88bc317b359754d5ad69b75f42319
https://github.com/crapooze/em-xmpp/blob/804e139944c88bc317b359754d5ad69b75f42319/lib/em-xmpp/entity.rb#L48-L51
train
crapooze/em-xmpp
lib/em-xmpp/entity.rb
EM::Xmpp.Entity.unsubscribe
def unsubscribe(&blk) pres = connection.presence_stanza('to'=>jid.bare, 'type' => 'unsubscribe') connection.send_stanza pres, &blk end
ruby
def unsubscribe(&blk) pres = connection.presence_stanza('to'=>jid.bare, 'type' => 'unsubscribe') connection.send_stanza pres, &blk end
[ "def", "unsubscribe", "(", "&", "blk", ")", "pres", "=", "connection", ".", "presence_stanza", "(", "'to'", "=>", "jid", ".", "bare", ",", "'type'", "=>", "'unsubscribe'", ")", "connection", ".", "send_stanza", "pres", ",", "&", "blk", "end" ]
unsubscribes from from the bare entity
[ "unsubscribes", "from", "from", "the", "bare", "entity" ]
804e139944c88bc317b359754d5ad69b75f42319
https://github.com/crapooze/em-xmpp/blob/804e139944c88bc317b359754d5ad69b75f42319/lib/em-xmpp/entity.rb#L54-L57
train