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
bjoernalbers/aruba-doubles
lib/aruba-doubles/double.rb
ArubaDoubles.Double.delete
def delete deregister fullpath = File.join(self.class.bindir, filename) FileUtils.rm(fullpath) if File.exists?(fullpath) end
ruby
def delete deregister fullpath = File.join(self.class.bindir, filename) FileUtils.rm(fullpath) if File.exists?(fullpath) end
[ "def", "delete", "deregister", "fullpath", "=", "File", ".", "join", "(", "self", ".", "class", ".", "bindir", ",", "filename", ")", "FileUtils", ".", "rm", "(", "fullpath", ")", "if", "File", ".", "exists?", "(", "fullpath", ")", "end" ]
Delete the executable double.
[ "Delete", "the", "executable", "double", "." ]
5e835bf60fef4bdf903c225a7c29968d17899516
https://github.com/bjoernalbers/aruba-doubles/blob/5e835bf60fef4bdf903c225a7c29968d17899516/lib/aruba-doubles/double.rb#L151-L155
train
meineerde/rackstash
lib/rackstash/filter_chain.rb
Rackstash.FilterChain.[]=
def []=(index, filter) raise TypeError, 'must provide a filter' unless filter.respond_to?(:call) synchronize do id = index_at(index) unless id && ([email protected]).cover?(id) raise ArgumentError, "Cannot insert at index #{index.inspect}" end @filters[id] = filter end end
ruby
def []=(index, filter) raise TypeError, 'must provide a filter' unless filter.respond_to?(:call) synchronize do id = index_at(index) unless id && ([email protected]).cover?(id) raise ArgumentError, "Cannot insert at index #{index.inspect}" end @filters[id] = filter end end
[ "def", "[]=", "(", "index", ",", "filter", ")", "raise", "TypeError", ",", "'must provide a filter'", "unless", "filter", ".", "respond_to?", "(", ":call", ")", "synchronize", "do", "id", "=", "index_at", "(", "index", ")", "unless", "id", "&&", "(", "0", "..", "@filters", ".", "size", ")", ".", "cover?", "(", "id", ")", "raise", "ArgumentError", ",", "\"Cannot insert at index #{index.inspect}\"", "end", "@filters", "[", "id", "]", "=", "filter", "end", "end" ]
Set the new filter at the given `index`. You can specify any existing filter or an index one above the highest index. @param index [Integer, Class, String, Object] The existing filter which should be overwritten with `filter`. It can be described in different ways: When given an `Integer`, we expect it to be the index number; when given a `Class`, we try to find the first filter being of that type; when given a `String`, we try to find the first filter being of a type named like that; when given any other object, we assume it is a filter and search for that. @param filter [#call, nil] the filter to set at `index` @raise [ArgumentError] if no existing filter could be found at `index` @raise [TypeError] if the given filter is not callable @return [#call] the given `filter`
[ "Set", "the", "new", "filter", "at", "the", "given", "index", ".", "You", "can", "specify", "any", "existing", "filter", "or", "an", "index", "one", "above", "the", "highest", "index", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/filter_chain.rb#L67-L78
train
meineerde/rackstash
lib/rackstash/filter_chain.rb
Rackstash.FilterChain.call
def call(event) each do |filter| result = filter.call(event) return false if result == false end event end
ruby
def call(event) each do |filter| result = filter.call(event) return false if result == false end event end
[ "def", "call", "(", "event", ")", "each", "do", "|", "filter", "|", "result", "=", "filter", ".", "call", "(", "event", ")", "return", "false", "if", "result", "==", "false", "end", "event", "end" ]
Filter the given event by calling each defined filter with it. Each filter will be called with the current event and can manipulate it in any way. If any of the filters returns `false`, no further filter will be applied and we also return `false`. This behavior can be used by filters to cancel the writing of an individual event. Any other return value of filters is ignored. @param event [Hash] an event hash, see {Buffer#event} for details @return [Hash, false] the filtered event or `false` if any of the filters returned `false`
[ "Filter", "the", "given", "event", "by", "calling", "each", "defined", "filter", "with", "it", ".", "Each", "filter", "will", "be", "called", "with", "the", "current", "event", "and", "can", "manipulate", "it", "in", "any", "way", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/filter_chain.rb#L110-L116
train
meineerde/rackstash
lib/rackstash/filter_chain.rb
Rackstash.FilterChain.insert_before
def insert_before(index, *filter_spec, &block) filter = build_filter(filter_spec, &block) synchronize do id = index_at(index) unless id && ([email protected]).cover?(id) raise ArgumentError, "No such filter to insert before: #{index.inspect}" end @filters.insert(id, filter) end self end
ruby
def insert_before(index, *filter_spec, &block) filter = build_filter(filter_spec, &block) synchronize do id = index_at(index) unless id && ([email protected]).cover?(id) raise ArgumentError, "No such filter to insert before: #{index.inspect}" end @filters.insert(id, filter) end self end
[ "def", "insert_before", "(", "index", ",", "*", "filter_spec", ",", "&", "block", ")", "filter", "=", "build_filter", "(", "filter_spec", ",", "&", "block", ")", "synchronize", "do", "id", "=", "index_at", "(", "index", ")", "unless", "id", "&&", "(", "0", "...", "@filters", ".", "size", ")", ".", "cover?", "(", "id", ")", "raise", "ArgumentError", ",", "\"No such filter to insert before: #{index.inspect}\"", "end", "@filters", ".", "insert", "(", "id", ",", "filter", ")", "end", "self", "end" ]
Insert a new filter before an existing filter in the filter chain. @param index [Integer, Class, String, Object] The existing filter before which the new one should be inserted. It can be described in different ways: When given an `Integer`, we expect it to be the index number; when given a `Class`, we try to find the first filter being of that type; when given a `String`, we try to find the first filter being of a type named like that; when given any other object, we assume it is a filter and search for that. @param filter_spec (see #build_filter) @raise [ArgumentError] if no existing filter could be found at `index` @raise [TypeError] if we could not build a filter from the given `filter_spec` @return [self]
[ "Insert", "a", "new", "filter", "before", "an", "existing", "filter", "in", "the", "filter", "chain", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/filter_chain.rb#L209-L221
train
meineerde/rackstash
lib/rackstash/filter_chain.rb
Rackstash.FilterChain.build_filter
def build_filter(filter_spec, &block) if filter_spec.empty? return Rackstash::Filter.build(block) if block_given? raise ArgumentError, 'Need to specify a filter' else Rackstash::Filter.build(*filter_spec, &block) end end
ruby
def build_filter(filter_spec, &block) if filter_spec.empty? return Rackstash::Filter.build(block) if block_given? raise ArgumentError, 'Need to specify a filter' else Rackstash::Filter.build(*filter_spec, &block) end end
[ "def", "build_filter", "(", "filter_spec", ",", "&", "block", ")", "if", "filter_spec", ".", "empty?", "return", "Rackstash", "::", "Filter", ".", "build", "(", "block", ")", "if", "block_given?", "raise", "ArgumentError", ",", "'Need to specify a filter'", "else", "Rackstash", "::", "Filter", ".", "build", "(", "*", "filter_spec", ",", "&", "block", ")", "end", "end" ]
Build a new filter instance from the given specification. @param filter_spec [Array] the description of a filter to create. If you give a single `Proc` (or any other object which responds to `#call`) or simply a proc, we will directly return it. If you give a `Class` plus any optional initializer arguments, we will return a new instance of that class. When giving a `String` or `Symbol`, we first use the {Filter.registry} to find the matching filter class. With that class, we then create a filter object as before using the additional arguments given to `initialize`. @return [#call] a filter instance
[ "Build", "a", "new", "filter", "instance", "from", "the", "given", "specification", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/filter_chain.rb#L306-L313
train
rapid7/daemon_runner
lib/daemon_runner/client.rb
DaemonRunner.Client.start!
def start! wait logger.warn 'Tasks list is empty' if tasks.empty? tasks.each do |task| run_task(task) sleep post_task_sleep_time end scheduler.join rescue SystemExit, Interrupt logger.info 'Shutting down' scheduler.shutdown end
ruby
def start! wait logger.warn 'Tasks list is empty' if tasks.empty? tasks.each do |task| run_task(task) sleep post_task_sleep_time end scheduler.join rescue SystemExit, Interrupt logger.info 'Shutting down' scheduler.shutdown end
[ "def", "start!", "wait", "logger", ".", "warn", "'Tasks list is empty'", "if", "tasks", ".", "empty?", "tasks", ".", "each", "do", "|", "task", "|", "run_task", "(", "task", ")", "sleep", "post_task_sleep_time", "end", "scheduler", ".", "join", "rescue", "SystemExit", ",", "Interrupt", "logger", ".", "info", "'Shutting down'", "scheduler", ".", "shutdown", "end" ]
Start the service @return [nil]
[ "Start", "the", "service" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/client.rb#L110-L123
train
meineerde/rackstash
lib/rackstash/class_registry.rb
Rackstash.ClassRegistry.fetch
def fetch(spec, default = UNDEFINED) case spec when Class spec when String, Symbol, ->(s) { s.respond_to?(:to_sym) } @registry.fetch(spec.to_sym) do |key| next yield(key) if block_given? next default unless UNDEFINED.equal? default raise KeyError, "No #{@object_type} was registered for #{spec.inspect}" end else raise TypeError, "#{spec.inspect} can not be used to describe " \ "#{@object_type} classes" end end
ruby
def fetch(spec, default = UNDEFINED) case spec when Class spec when String, Symbol, ->(s) { s.respond_to?(:to_sym) } @registry.fetch(spec.to_sym) do |key| next yield(key) if block_given? next default unless UNDEFINED.equal? default raise KeyError, "No #{@object_type} was registered for #{spec.inspect}" end else raise TypeError, "#{spec.inspect} can not be used to describe " \ "#{@object_type} classes" end end
[ "def", "fetch", "(", "spec", ",", "default", "=", "UNDEFINED", ")", "case", "spec", "when", "Class", "spec", "when", "String", ",", "Symbol", ",", "->", "(", "s", ")", "{", "s", ".", "respond_to?", "(", ":to_sym", ")", "}", "@registry", ".", "fetch", "(", "spec", ".", "to_sym", ")", "do", "|", "key", "|", "next", "yield", "(", "key", ")", "if", "block_given?", "next", "default", "unless", "UNDEFINED", ".", "equal?", "default", "raise", "KeyError", ",", "\"No #{@object_type} was registered for #{spec.inspect}\"", "end", "else", "raise", "TypeError", ",", "\"#{spec.inspect} can not be used to describe \"", "\"#{@object_type} classes\"", "end", "end" ]
Retrieve the registered class for a given name. If the argument is already a class, we return it unchanged. @param spec [Class,String,Symbol] either a class (in which case it is returned directly) or the name of a registered class @param default [Object] the default value that is returned if no registered class could be found for the given `spec` and no block was given. @yield if no registered class could be found for the given `spec`, we will run the optional block and return its result @yieldparam spec [Symbol] the requested class specification as a `Symbol` @raise [KeyError] when giving a `String` or `Symbol` but no registered class was found for it and no default was specified @raise [TypeError] when giving an invalid `spec` object @return [Class] the registered class (when giving a `String` or `Symbol`) or the given class (when giving a `Class`)
[ "Retrieve", "the", "registered", "class", "for", "a", "given", "name", ".", "If", "the", "argument", "is", "already", "a", "class", "we", "return", "it", "unchanged", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/class_registry.rb#L53-L68
train
meineerde/rackstash
lib/rackstash/class_registry.rb
Rackstash.ClassRegistry.[]=
def []=(name, registered_class) unless registered_class.is_a?(Class) raise TypeError, 'Can only register class objects' end case name when String, Symbol @registry[name.to_sym] = registered_class else raise TypeError, "Can not use #{name.inspect} to register a #{@object_type} class" end registered_class end
ruby
def []=(name, registered_class) unless registered_class.is_a?(Class) raise TypeError, 'Can only register class objects' end case name when String, Symbol @registry[name.to_sym] = registered_class else raise TypeError, "Can not use #{name.inspect} to register a #{@object_type} class" end registered_class end
[ "def", "[]=", "(", "name", ",", "registered_class", ")", "unless", "registered_class", ".", "is_a?", "(", "Class", ")", "raise", "TypeError", ",", "'Can only register class objects'", "end", "case", "name", "when", "String", ",", "Symbol", "@registry", "[", "name", ".", "to_sym", "]", "=", "registered_class", "else", "raise", "TypeError", ",", "\"Can not use #{name.inspect} to register a #{@object_type} class\"", "end", "registered_class", "end" ]
Register a class for the given name. @param name [String, Symbol] the name at which the class should be registered @param registered_class [Class] the class to register at `name` @raise [TypeError] if `name` is not a `String` or `Symbol`, or if `registered_class` is not a `Class` @return [Class] the `registered_class`
[ "Register", "a", "class", "for", "the", "given", "name", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/class_registry.rb#L78-L90
train
mkroman/blur
library/blur/callbacks.rb
Blur.Callbacks.emit
def emit name, *args # Trigger callbacks in scripts before triggering events in the client. EM.defer { notify_scripts name, *args } matching_callbacks = callbacks[name] return false unless matching_callbacks&.any? EM.defer do matching_callbacks.each { |callback| callback.call *args } end end
ruby
def emit name, *args # Trigger callbacks in scripts before triggering events in the client. EM.defer { notify_scripts name, *args } matching_callbacks = callbacks[name] return false unless matching_callbacks&.any? EM.defer do matching_callbacks.each { |callback| callback.call *args } end end
[ "def", "emit", "name", ",", "*", "args", "EM", ".", "defer", "{", "notify_scripts", "name", ",", "*", "args", "}", "matching_callbacks", "=", "callbacks", "[", "name", "]", "return", "false", "unless", "matching_callbacks", "&.", "any?", "EM", ".", "defer", "do", "matching_callbacks", ".", "each", "{", "|", "callback", "|", "callback", ".", "call", "*", "args", "}", "end", "end" ]
Emit a new event with given arguments. @param name [Symbol] The event name. @param args [optional, Array] The list of arguments to pass. @return [true, false] True if any callbacks were invoked, nil otherwise
[ "Emit", "a", "new", "event", "with", "given", "arguments", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/callbacks.rb#L17-L27
train
derek-schaefer/virtus_model
lib/virtus_model/base.rb
VirtusModel.Base.export
def export(options = nil) self.class.attributes.reduce({}) do |result, name| value = attributes[name] if self.class.association?(name, :many) result[name] = export_values(value, options) elsif self.class.association?(name, :one) result[name] = export_value(value, options) else result[name] = value end result end end
ruby
def export(options = nil) self.class.attributes.reduce({}) do |result, name| value = attributes[name] if self.class.association?(name, :many) result[name] = export_values(value, options) elsif self.class.association?(name, :one) result[name] = export_value(value, options) else result[name] = value end result end end
[ "def", "export", "(", "options", "=", "nil", ")", "self", ".", "class", ".", "attributes", ".", "reduce", "(", "{", "}", ")", "do", "|", "result", ",", "name", "|", "value", "=", "attributes", "[", "name", "]", "if", "self", ".", "class", ".", "association?", "(", "name", ",", ":many", ")", "result", "[", "name", "]", "=", "export_values", "(", "value", ",", "options", ")", "elsif", "self", ".", "class", ".", "association?", "(", "name", ",", ":one", ")", "result", "[", "name", "]", "=", "export_value", "(", "value", ",", "options", ")", "else", "result", "[", "name", "]", "=", "value", "end", "result", "end", "end" ]
Two models are equal if their attributes are equal. Recursively convert all attributes to hash pairs.
[ "Two", "models", "are", "equal", "if", "their", "attributes", "are", "equal", ".", "Recursively", "convert", "all", "attributes", "to", "hash", "pairs", "." ]
97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb
https://github.com/derek-schaefer/virtus_model/blob/97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb/lib/virtus_model/base.rb#L70-L82
train
derek-schaefer/virtus_model
lib/virtus_model/base.rb
VirtusModel.Base.extract_attributes
def extract_attributes(model) self.class.attributes.reduce({}) do |result, name| if model.respond_to?(name) result[name] = model.public_send(name) elsif model.respond_to?(:[]) && model.respond_to?(:key?) && model.key?(name) result[name] = model[name] end result end end
ruby
def extract_attributes(model) self.class.attributes.reduce({}) do |result, name| if model.respond_to?(name) result[name] = model.public_send(name) elsif model.respond_to?(:[]) && model.respond_to?(:key?) && model.key?(name) result[name] = model[name] end result end end
[ "def", "extract_attributes", "(", "model", ")", "self", ".", "class", ".", "attributes", ".", "reduce", "(", "{", "}", ")", "do", "|", "result", ",", "name", "|", "if", "model", ".", "respond_to?", "(", "name", ")", "result", "[", "name", "]", "=", "model", ".", "public_send", "(", "name", ")", "elsif", "model", ".", "respond_to?", "(", ":[]", ")", "&&", "model", ".", "respond_to?", "(", ":key?", ")", "&&", "model", ".", "key?", "(", "name", ")", "result", "[", "name", "]", "=", "model", "[", "name", "]", "end", "result", "end", "end" ]
Extract model attributes into a hash.
[ "Extract", "model", "attributes", "into", "a", "hash", "." ]
97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb
https://github.com/derek-schaefer/virtus_model/blob/97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb/lib/virtus_model/base.rb#L107-L116
train
derek-schaefer/virtus_model
lib/virtus_model/base.rb
VirtusModel.Base.validate_associations_many
def validate_associations_many self.class.associations(:many).each do |name| values = attributes[name] || [] values.each.with_index do |value, index| import_errors("#{name}[#{index}]", value) end end end
ruby
def validate_associations_many self.class.associations(:many).each do |name| values = attributes[name] || [] values.each.with_index do |value, index| import_errors("#{name}[#{index}]", value) end end end
[ "def", "validate_associations_many", "self", ".", "class", ".", "associations", "(", ":many", ")", ".", "each", "do", "|", "name", "|", "values", "=", "attributes", "[", "name", "]", "||", "[", "]", "values", ".", "each", ".", "with_index", "do", "|", "value", ",", "index", "|", "import_errors", "(", "\"#{name}[#{index}]\"", ",", "value", ")", "end", "end", "end" ]
Validate "many" associations and import errors.
[ "Validate", "many", "associations", "and", "import", "errors", "." ]
97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb
https://github.com/derek-schaefer/virtus_model/blob/97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb/lib/virtus_model/base.rb#L132-L139
train
derek-schaefer/virtus_model
lib/virtus_model/base.rb
VirtusModel.Base.import_errors
def import_errors(name, model) return unless model.respond_to?(:validate) return if model.validate(validation_context) model.errors.each do |field, error| errors.add("#{name}[#{field}]", error) end end
ruby
def import_errors(name, model) return unless model.respond_to?(:validate) return if model.validate(validation_context) model.errors.each do |field, error| errors.add("#{name}[#{field}]", error) end end
[ "def", "import_errors", "(", "name", ",", "model", ")", "return", "unless", "model", ".", "respond_to?", "(", ":validate", ")", "return", "if", "model", ".", "validate", "(", "validation_context", ")", "model", ".", "errors", ".", "each", "do", "|", "field", ",", "error", "|", "errors", ".", "add", "(", "\"#{name}[#{field}]\"", ",", "error", ")", "end", "end" ]
Merge associated errors using the current validation context.
[ "Merge", "associated", "errors", "using", "the", "current", "validation", "context", "." ]
97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb
https://github.com/derek-schaefer/virtus_model/blob/97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb/lib/virtus_model/base.rb#L142-L148
train
derek-schaefer/virtus_model
lib/virtus_model/base.rb
VirtusModel.Base.export_values
def export_values(values, options = nil) return if values.nil? values.map { |v| export_value(v, options) } end
ruby
def export_values(values, options = nil) return if values.nil? values.map { |v| export_value(v, options) } end
[ "def", "export_values", "(", "values", ",", "options", "=", "nil", ")", "return", "if", "values", ".", "nil?", "values", ".", "map", "{", "|", "v", "|", "export_value", "(", "v", ",", "options", ")", "}", "end" ]
Export each value with the provided options.
[ "Export", "each", "value", "with", "the", "provided", "options", "." ]
97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb
https://github.com/derek-schaefer/virtus_model/blob/97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb/lib/virtus_model/base.rb#L151-L154
train
derek-schaefer/virtus_model
lib/virtus_model/base.rb
VirtusModel.Base.export_value
def export_value(value, options = nil) return if value.nil? value.respond_to?(:export) ? value.export(options) : value end
ruby
def export_value(value, options = nil) return if value.nil? value.respond_to?(:export) ? value.export(options) : value end
[ "def", "export_value", "(", "value", ",", "options", "=", "nil", ")", "return", "if", "value", ".", "nil?", "value", ".", "respond_to?", "(", ":export", ")", "?", "value", ".", "export", "(", "options", ")", ":", "value", "end" ]
Export the value with the provided options.
[ "Export", "the", "value", "with", "the", "provided", "options", "." ]
97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb
https://github.com/derek-schaefer/virtus_model/blob/97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb/lib/virtus_model/base.rb#L157-L160
train
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.contender_key
def contender_key(value = 'none') if value.nil? || value.empty? raise ArgumentError, 'Value cannot be empty or nil' end key = "#{prefix}/#{session.id}" ::DaemonRunner::RetryErrors.retry do @contender_key = Diplomat::Lock.acquire(key, session.id, value) end @contender_key end
ruby
def contender_key(value = 'none') if value.nil? || value.empty? raise ArgumentError, 'Value cannot be empty or nil' end key = "#{prefix}/#{session.id}" ::DaemonRunner::RetryErrors.retry do @contender_key = Diplomat::Lock.acquire(key, session.id, value) end @contender_key end
[ "def", "contender_key", "(", "value", "=", "'none'", ")", "if", "value", ".", "nil?", "||", "value", ".", "empty?", "raise", "ArgumentError", ",", "'Value cannot be empty or nil'", "end", "key", "=", "\"#{prefix}/#{session.id}\"", "::", "DaemonRunner", "::", "RetryErrors", ".", "retry", "do", "@contender_key", "=", "Diplomat", "::", "Lock", ".", "acquire", "(", "key", ",", "session", ".", "id", ",", "value", ")", "end", "@contender_key", "end" ]
Create a contender key
[ "Create", "a", "contender", "key" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L139-L148
train
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.semaphore_state
def semaphore_state options = { decode_values: true, recurse: true } @state = Diplomat::Kv.get(prefix, options, :return) decode_semaphore_state unless state.empty? state end
ruby
def semaphore_state options = { decode_values: true, recurse: true } @state = Diplomat::Kv.get(prefix, options, :return) decode_semaphore_state unless state.empty? state end
[ "def", "semaphore_state", "options", "=", "{", "decode_values", ":", "true", ",", "recurse", ":", "true", "}", "@state", "=", "Diplomat", "::", "Kv", ".", "get", "(", "prefix", ",", "options", ",", ":return", ")", "decode_semaphore_state", "unless", "state", ".", "empty?", "state", "end" ]
Get the current semaphore state by fetching all conterder keys and the lock key
[ "Get", "the", "current", "semaphore", "state", "by", "fetching", "all", "conterder", "keys", "and", "the", "lock", "key" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L152-L157
train
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.write_lock
def write_lock index = lock_modify_index.nil? ? 0 : lock_modify_index value = generate_lockfile return true if value == true Diplomat::Kv.put(@lock, value, cas: index) end
ruby
def write_lock index = lock_modify_index.nil? ? 0 : lock_modify_index value = generate_lockfile return true if value == true Diplomat::Kv.put(@lock, value, cas: index) end
[ "def", "write_lock", "index", "=", "lock_modify_index", ".", "nil?", "?", "0", ":", "lock_modify_index", "value", "=", "generate_lockfile", "return", "true", "if", "value", "==", "true", "Diplomat", "::", "Kv", ".", "put", "(", "@lock", ",", "value", ",", "cas", ":", "index", ")", "end" ]
Write a new lock file if the number of contenders is less than `limit` @return [Boolean] `true` if the lock was written succesfully
[ "Write", "a", "new", "lock", "file", "if", "the", "number", "of", "contenders", "is", "less", "than", "limit" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L183-L188
train
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.renew?
def renew? logger.debug("Watching Consul #{prefix} for changes") options = { recurse: true } changes = Diplomat::Kv.get(prefix, options, :wait, :wait) logger.info("Changes on #{prefix} detected") if changes changes rescue StandardError => e logger.error(e) end
ruby
def renew? logger.debug("Watching Consul #{prefix} for changes") options = { recurse: true } changes = Diplomat::Kv.get(prefix, options, :wait, :wait) logger.info("Changes on #{prefix} detected") if changes changes rescue StandardError => e logger.error(e) end
[ "def", "renew?", "logger", ".", "debug", "(", "\"Watching Consul #{prefix} for changes\"", ")", "options", "=", "{", "recurse", ":", "true", "}", "changes", "=", "Diplomat", "::", "Kv", ".", "get", "(", "prefix", ",", "options", ",", ":wait", ",", ":wait", ")", "logger", ".", "info", "(", "\"Changes on #{prefix} detected\"", ")", "if", "changes", "changes", "rescue", "StandardError", "=>", "e", "logger", ".", "error", "(", "e", ")", "end" ]
Start a blocking query on the prefix, if there are changes we need to try to obtain the lock again. @return [Boolean] `true` if there are changes, `false` if the request has timed out
[ "Start", "a", "blocking", "query", "on", "the", "prefix", "if", "there", "are", "changes", "we", "need", "to", "try", "to", "obtain", "the", "lock", "again", "." ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L195-L203
train
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.decode_semaphore_state
def decode_semaphore_state lock_key = state.find { |k| k['Key'] == @lock } member_keys = state.delete_if { |k| k['Key'] == @lock } member_keys.map! { |k| k['Key'] } unless lock_key.nil? @lock_modify_index = lock_key['ModifyIndex'] @lock_content = JSON.parse(lock_key['Value']) end @members = member_keys.map { |k| k.split('/')[-1] } end
ruby
def decode_semaphore_state lock_key = state.find { |k| k['Key'] == @lock } member_keys = state.delete_if { |k| k['Key'] == @lock } member_keys.map! { |k| k['Key'] } unless lock_key.nil? @lock_modify_index = lock_key['ModifyIndex'] @lock_content = JSON.parse(lock_key['Value']) end @members = member_keys.map { |k| k.split('/')[-1] } end
[ "def", "decode_semaphore_state", "lock_key", "=", "state", ".", "find", "{", "|", "k", "|", "k", "[", "'Key'", "]", "==", "@lock", "}", "member_keys", "=", "state", ".", "delete_if", "{", "|", "k", "|", "k", "[", "'Key'", "]", "==", "@lock", "}", "member_keys", ".", "map!", "{", "|", "k", "|", "k", "[", "'Key'", "]", "}", "unless", "lock_key", ".", "nil?", "@lock_modify_index", "=", "lock_key", "[", "'ModifyIndex'", "]", "@lock_content", "=", "JSON", ".", "parse", "(", "lock_key", "[", "'Value'", "]", ")", "end", "@members", "=", "member_keys", ".", "map", "{", "|", "k", "|", "k", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "}", "end" ]
Decode raw response from Consul Set `@lock_modify_index`, `@lock_content`, and `@members` @returns [Array] List of members
[ "Decode", "raw", "response", "from", "Consul", "Set" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L210-L220
train
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.prune_members
def prune_members @holders = if lock_exists? holders = lock_content['Holders'] return @holders = [] if holders.nil? holders = holders.keys holders & members else [] end end
ruby
def prune_members @holders = if lock_exists? holders = lock_content['Holders'] return @holders = [] if holders.nil? holders = holders.keys holders & members else [] end end
[ "def", "prune_members", "@holders", "=", "if", "lock_exists?", "holders", "=", "lock_content", "[", "'Holders'", "]", "return", "@holders", "=", "[", "]", "if", "holders", ".", "nil?", "holders", "=", "holders", ".", "keys", "holders", "&", "members", "else", "[", "]", "end", "end" ]
Get the active members from the lock file, removing any _dead_ members. This is accomplished by using the contenders keys(`@members`) to get the list of all alive members. So we can easily remove any nodes that don't appear in that list.
[ "Get", "the", "active", "members", "from", "the", "lock", "file", "removing", "any", "_dead_", "members", ".", "This", "is", "accomplished", "by", "using", "the", "contenders", "keys", "(" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L231-L240
train
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.add_self_to_holders
def add_self_to_holders @holders.uniq! @reset = true if @holders.length == 0 return true if @holders.include? session.id if @holders.length < limit @holders << session.id end end
ruby
def add_self_to_holders @holders.uniq! @reset = true if @holders.length == 0 return true if @holders.include? session.id if @holders.length < limit @holders << session.id end end
[ "def", "add_self_to_holders", "@holders", ".", "uniq!", "@reset", "=", "true", "if", "@holders", ".", "length", "==", "0", "return", "true", "if", "@holders", ".", "include?", "session", ".", "id", "if", "@holders", ".", "length", "<", "limit", "@holders", "<<", "session", ".", "id", "end", "end" ]
Add our session.id to the holders list if holders is less than limit
[ "Add", "our", "session", ".", "id", "to", "the", "holders", "list", "if", "holders", "is", "less", "than", "limit" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L243-L250
train
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.format_holders
def format_holders @holders.uniq! @holders.sort! holders = {} logger.debug "Holders are: #{@holders.join(',')}" @holders.map { |m| holders[m] = true } @holders = holders end
ruby
def format_holders @holders.uniq! @holders.sort! holders = {} logger.debug "Holders are: #{@holders.join(',')}" @holders.map { |m| holders[m] = true } @holders = holders end
[ "def", "format_holders", "@holders", ".", "uniq!", "@holders", ".", "sort!", "holders", "=", "{", "}", "logger", ".", "debug", "\"Holders are: #{@holders.join(',')}\"", "@holders", ".", "map", "{", "|", "m", "|", "holders", "[", "m", "]", "=", "true", "}", "@holders", "=", "holders", "end" ]
Format the list of holders for the lock file
[ "Format", "the", "list", "of", "holders", "for", "the", "lock", "file" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L262-L269
train
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.generate_lockfile
def generate_lockfile if lock_exists? && lock_content['Holders'] == @holders logger.info 'Holders are unchanged, not updating' return true end lockfile_format = { 'Limit' => limit, 'Holders' => @holders } JSON.generate(lockfile_format) end
ruby
def generate_lockfile if lock_exists? && lock_content['Holders'] == @holders logger.info 'Holders are unchanged, not updating' return true end lockfile_format = { 'Limit' => limit, 'Holders' => @holders } JSON.generate(lockfile_format) end
[ "def", "generate_lockfile", "if", "lock_exists?", "&&", "lock_content", "[", "'Holders'", "]", "==", "@holders", "logger", ".", "info", "'Holders are unchanged, not updating'", "return", "true", "end", "lockfile_format", "=", "{", "'Limit'", "=>", "limit", ",", "'Holders'", "=>", "@holders", "}", "JSON", ".", "generate", "(", "lockfile_format", ")", "end" ]
Generate JSON formatted lockfile content, only if the content has changed
[ "Generate", "JSON", "formatted", "lockfile", "content", "only", "if", "the", "content", "has", "changed" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L272-L282
train
richo/juici
lib/juici/build_queue.rb
Juici.BuildQueue.bump!
def bump! return unless @started update_children candidate_children.each do |child| next if @child_pids.any? do |pid| get_build_by_pid(pid).parent == child.parent end # We're good to launch this build Juici.dbgp "Starting another child process" return child.tap do |cld| if pid = cld.build! Juici.dbgp "Started child: #{pid}" @child_pids << pid @builds_by_pid[pid] = cld else Juici.dbgp "Child #{cld} failed to start" bump! # Ruby's recursion isn't great, but re{try,do} may as well be # undefined behaviour here. end end end Juici.dbgp "I have quite enough to do" end
ruby
def bump! return unless @started update_children candidate_children.each do |child| next if @child_pids.any? do |pid| get_build_by_pid(pid).parent == child.parent end # We're good to launch this build Juici.dbgp "Starting another child process" return child.tap do |cld| if pid = cld.build! Juici.dbgp "Started child: #{pid}" @child_pids << pid @builds_by_pid[pid] = cld else Juici.dbgp "Child #{cld} failed to start" bump! # Ruby's recursion isn't great, but re{try,do} may as well be # undefined behaviour here. end end end Juici.dbgp "I have quite enough to do" end
[ "def", "bump!", "return", "unless", "@started", "update_children", "candidate_children", ".", "each", "do", "|", "child", "|", "next", "if", "@child_pids", ".", "any?", "do", "|", "pid", "|", "get_build_by_pid", "(", "pid", ")", ".", "parent", "==", "child", ".", "parent", "end", "Juici", ".", "dbgp", "\"Starting another child process\"", "return", "child", ".", "tap", "do", "|", "cld", "|", "if", "pid", "=", "cld", ".", "build!", "Juici", ".", "dbgp", "\"Started child: #{pid}\"", "@child_pids", "<<", "pid", "@builds_by_pid", "[", "pid", "]", "=", "cld", "else", "Juici", ".", "dbgp", "\"Child #{cld} failed to start\"", "bump!", "end", "end", "end", "Juici", ".", "dbgp", "\"I have quite enough to do\"", "end" ]
Magic hook that starts a process if there's a good reason to. Stopgap measure that means you can knock on this if there's a chance we should start a process
[ "Magic", "hook", "that", "starts", "a", "process", "if", "there", "s", "a", "good", "reason", "to", ".", "Stopgap", "measure", "that", "means", "you", "can", "knock", "on", "this", "if", "there", "s", "a", "chance", "we", "should", "start", "a", "process" ]
5649b251a9c8f8c29623fba2fd9fd0b1fc2dbffa
https://github.com/richo/juici/blob/5649b251a9c8f8c29623fba2fd9fd0b1fc2dbffa/lib/juici/build_queue.rb#L56-L80
train
mkroman/blur
library/blur/network.rb
Blur.Network.got_message
def got_message message @client.got_message self, message rescue StandardError => exception puts "#{exception.class}: #{exception.message}" puts puts '---' puts exception.backtrace end
ruby
def got_message message @client.got_message self, message rescue StandardError => exception puts "#{exception.class}: #{exception.message}" puts puts '---' puts exception.backtrace end
[ "def", "got_message", "message", "@client", ".", "got_message", "self", ",", "message", "rescue", "StandardError", "=>", "exception", "puts", "\"#{exception.class}: #{exception.message}\"", "puts", "puts", "'---'", "puts", "exception", ".", "backtrace", "end" ]
Forwards the received message to the client instance. Called when the network connection has enough data to form a command.
[ "Forwards", "the", "received", "message", "to", "the", "client", "instance", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/network.rb#L114-L121
train
mkroman/blur
library/blur/network.rb
Blur.Network.disconnected!
def disconnected! @channels.each { |_name, channel| channel.users.clear } @channels.clear @users.clear @client.network_connection_closed self end
ruby
def disconnected! @channels.each { |_name, channel| channel.users.clear } @channels.clear @users.clear @client.network_connection_closed self end
[ "def", "disconnected!", "@channels", ".", "each", "{", "|", "_name", ",", "channel", "|", "channel", ".", "users", ".", "clear", "}", "@channels", ".", "clear", "@users", ".", "clear", "@client", ".", "network_connection_closed", "self", "end" ]
Called when the connection was closed.
[ "Called", "when", "the", "connection", "was", "closed", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/network.rb#L176-L182
train
mkroman/blur
library/blur/network.rb
Blur.Network.transmit
def transmit name, *arguments message = IRCParser::Message.new command: name.to_s, parameters: arguments if @client.verbose formatted_command = message.command.to_s.ljust 8, ' ' formatted_params = message.parameters.map(&:inspect).join ' ' log "#{'→' ^ :red} #{formatted_command} #{formatted_params}" end @connection.send_data "#{message}\r\n" end
ruby
def transmit name, *arguments message = IRCParser::Message.new command: name.to_s, parameters: arguments if @client.verbose formatted_command = message.command.to_s.ljust 8, ' ' formatted_params = message.parameters.map(&:inspect).join ' ' log "#{'→' ^ :red} #{formatted_command} #{formatted_params}" end @connection.send_data "#{message}\r\n" end
[ "def", "transmit", "name", ",", "*", "arguments", "message", "=", "IRCParser", "::", "Message", ".", "new", "command", ":", "name", ".", "to_s", ",", "parameters", ":", "arguments", "if", "@client", ".", "verbose", "formatted_command", "=", "message", ".", "command", ".", "to_s", ".", "ljust", "8", ",", "' '", "formatted_params", "=", "message", ".", "parameters", ".", "map", "(", "&", ":inspect", ")", ".", "join", "' '", "log", "\"#{'→' ^ :red} #{formatted_command} #{formatted_params}\"", "end", "@connection", ".", "send_data", "\"#{message}\\r\\n\"", "end" ]
Transmit a command to the server. @param [Symbol, String] name the command name. @param [...] arguments all the prepended parameters.
[ "Transmit", "a", "command", "to", "the", "server", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/network.rb#L193-L203
train
fiverr/switch_board
lib/switch_board/datasets/redis_dataset.rb
SwitchBoard.RedisDataset.lock_id
def lock_id(locker_uid, id_to_lock, expire_in_sec = 5) now = redis_time @con.multi do @con.zadd("#{LOCK_MAP_KEY}_z", (now + expire_in_sec), id_to_lock) @con.hset("#{LOCK_MAP_KEY}_h", id_to_lock, locker_uid) end end
ruby
def lock_id(locker_uid, id_to_lock, expire_in_sec = 5) now = redis_time @con.multi do @con.zadd("#{LOCK_MAP_KEY}_z", (now + expire_in_sec), id_to_lock) @con.hset("#{LOCK_MAP_KEY}_h", id_to_lock, locker_uid) end end
[ "def", "lock_id", "(", "locker_uid", ",", "id_to_lock", ",", "expire_in_sec", "=", "5", ")", "now", "=", "redis_time", "@con", ".", "multi", "do", "@con", ".", "zadd", "(", "\"#{LOCK_MAP_KEY}_z\"", ",", "(", "now", "+", "expire_in_sec", ")", ",", "id_to_lock", ")", "@con", ".", "hset", "(", "\"#{LOCK_MAP_KEY}_h\"", ",", "id_to_lock", ",", "locker_uid", ")", "end", "end" ]
Locking mechanisem is based on sorted set, sorted set is used to allow a simulation of expiration time on the keys in the map
[ "Locking", "mechanisem", "is", "based", "on", "sorted", "set", "sorted", "set", "is", "used", "to", "allow", "a", "simulation", "of", "expiration", "time", "on", "the", "keys", "in", "the", "map" ]
429a095a39e28257f99ea7125b26b509dd80037c
https://github.com/fiverr/switch_board/blob/429a095a39e28257f99ea7125b26b509dd80037c/lib/switch_board/datasets/redis_dataset.rb#L50-L56
train
mkroman/blur
library/blur/client.rb
Blur.Client.connect
def connect networks = @networks.reject &:connected? EventMachine.run do load_scripts! networks.each &:connect EventMachine.error_handler do |exception| log.error "#{exception.message ^ :bold} on line #{exception.line.to_s ^ :bold}" puts exception.backtrace.join "\n" end end end
ruby
def connect networks = @networks.reject &:connected? EventMachine.run do load_scripts! networks.each &:connect EventMachine.error_handler do |exception| log.error "#{exception.message ^ :bold} on line #{exception.line.to_s ^ :bold}" puts exception.backtrace.join "\n" end end end
[ "def", "connect", "networks", "=", "@networks", ".", "reject", "&", ":connected?", "EventMachine", ".", "run", "do", "load_scripts!", "networks", ".", "each", "&", ":connect", "EventMachine", ".", "error_handler", "do", "|", "exception", "|", "log", ".", "error", "\"#{exception.message ^ :bold} on line #{exception.line.to_s ^ :bold}\"", "puts", "exception", ".", "backtrace", ".", "join", "\"\\n\"", "end", "end", "end" ]
Instantiates the client, stores the options, instantiates the networks and then loads available scripts. @param [Hash] options the options for the client. @option options [String] :config_path path to a configuration file. @option options [String] :environment the client environment. Connect to each network available that is not already connected, then proceed to start the run-loop.
[ "Instantiates", "the", "client", "stores", "the", "options", "instantiates", "the", "networks", "and", "then", "loads", "available", "scripts", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/client.rb#L74-L86
train
mkroman/blur
library/blur/client.rb
Blur.Client.quit
def quit signal = :SIGINT @networks.each do |network| network.transmit :QUIT, 'Got SIGINT?' network.disconnect end EventMachine.stop end
ruby
def quit signal = :SIGINT @networks.each do |network| network.transmit :QUIT, 'Got SIGINT?' network.disconnect end EventMachine.stop end
[ "def", "quit", "signal", "=", ":SIGINT", "@networks", ".", "each", "do", "|", "network", "|", "network", ".", "transmit", ":QUIT", ",", "'Got SIGINT?'", "network", ".", "disconnect", "end", "EventMachine", ".", "stop", "end" ]
Try to gracefully disconnect from each network, unload all scripts and exit properly. @param [optional, Symbol] signal The signal received by the system, if any.
[ "Try", "to", "gracefully", "disconnect", "from", "each", "network", "unload", "all", "scripts", "and", "exit", "properly", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/client.rb#L114-L121
train
mkroman/blur
library/blur/client.rb
Blur.Client.load_scripts!
def load_scripts! scripts_dir = File.expand_path @config['blur']['scripts_dir'] script_file_paths = Dir.glob File.join scripts_dir, '*.rb' # Sort the script file paths by file name so they load by alphabetical # order. # # This will make it possible to create a script called '10_database.rb' # which will be loaded before '20_settings.rb' and non-numeric prefixes # will be loaded after that. script_file_paths = script_file_paths.sort do |a, b| File.basename(a) <=> File.basename(b) end script_file_paths.each { |script_path| load_script_file script_path } initialize_superscripts emit :scripts_loaded end
ruby
def load_scripts! scripts_dir = File.expand_path @config['blur']['scripts_dir'] script_file_paths = Dir.glob File.join scripts_dir, '*.rb' # Sort the script file paths by file name so they load by alphabetical # order. # # This will make it possible to create a script called '10_database.rb' # which will be loaded before '20_settings.rb' and non-numeric prefixes # will be loaded after that. script_file_paths = script_file_paths.sort do |a, b| File.basename(a) <=> File.basename(b) end script_file_paths.each { |script_path| load_script_file script_path } initialize_superscripts emit :scripts_loaded end
[ "def", "load_scripts!", "scripts_dir", "=", "File", ".", "expand_path", "@config", "[", "'blur'", "]", "[", "'scripts_dir'", "]", "script_file_paths", "=", "Dir", ".", "glob", "File", ".", "join", "scripts_dir", ",", "'*.rb'", "script_file_paths", "=", "script_file_paths", ".", "sort", "do", "|", "a", ",", "b", "|", "File", ".", "basename", "(", "a", ")", "<=>", "File", ".", "basename", "(", "b", ")", "end", "script_file_paths", ".", "each", "{", "|", "script_path", "|", "load_script_file", "script_path", "}", "initialize_superscripts", "emit", ":scripts_loaded", "end" ]
Loads all scripts in the script directory.
[ "Loads", "all", "scripts", "in", "the", "script", "directory", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/client.rb#L135-L154
train
mkroman/blur
library/blur/client.rb
Blur.Client.load_script_file
def load_script_file file_path load file_path, true rescue Exception => exception warn "The script `#{file_path}' failed to load" warn "#{exception.class}: #{exception.message}" warn '' warn 'Backtrace:', '---', exception.backtrace end
ruby
def load_script_file file_path load file_path, true rescue Exception => exception warn "The script `#{file_path}' failed to load" warn "#{exception.class}: #{exception.message}" warn '' warn 'Backtrace:', '---', exception.backtrace end
[ "def", "load_script_file", "file_path", "load", "file_path", ",", "true", "rescue", "Exception", "=>", "exception", "warn", "\"The script `#{file_path}' failed to load\"", "warn", "\"#{exception.class}: #{exception.message}\"", "warn", "''", "warn", "'Backtrace:'", ",", "'---'", ",", "exception", ".", "backtrace", "end" ]
Loads the given +file_path+ as a Ruby script, wrapping it in an anonymous module to protect our global namespace. @param [String] file_path the path to the ruby script. @raise [Exception] if there was any problems loading the file
[ "Loads", "the", "given", "+", "file_path", "+", "as", "a", "Ruby", "script", "wrapping", "it", "in", "an", "anonymous", "module", "to", "protect", "our", "global", "namespace", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/client.rb#L162-L169
train
mkroman/blur
library/blur/client.rb
Blur.Client.unload_scripts!
def unload_scripts! @scripts.each do |name, script| script.__send__ :unloaded if script.respond_to? :unloaded end.clear Blur.reset_scripts! end
ruby
def unload_scripts! @scripts.each do |name, script| script.__send__ :unloaded if script.respond_to? :unloaded end.clear Blur.reset_scripts! end
[ "def", "unload_scripts!", "@scripts", ".", "each", "do", "|", "name", ",", "script", "|", "script", ".", "__send__", ":unloaded", "if", "script", ".", "respond_to?", ":unloaded", "end", ".", "clear", "Blur", ".", "reset_scripts!", "end" ]
Unloads initialized scripts and superscripts. This method will call #unloaded on the instance of each loaded script to give it a chance to clean up any resources.
[ "Unloads", "initialized", "scripts", "and", "superscripts", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/client.rb#L196-L202
train
mkroman/blur
library/blur/client.rb
Blur.Client.load_config!
def load_config! config = YAML.load_file @config_path if config.key? @environment @config = config[@environment] @config.deeper_merge! DEFAULT_CONFIG emit :config_load else raise Error, "No configuration found for specified environment `#{@environment}'" end end
ruby
def load_config! config = YAML.load_file @config_path if config.key? @environment @config = config[@environment] @config.deeper_merge! DEFAULT_CONFIG emit :config_load else raise Error, "No configuration found for specified environment `#{@environment}'" end end
[ "def", "load_config!", "config", "=", "YAML", ".", "load_file", "@config_path", "if", "config", ".", "key?", "@environment", "@config", "=", "config", "[", "@environment", "]", "@config", ".", "deeper_merge!", "DEFAULT_CONFIG", "emit", ":config_load", "else", "raise", "Error", ",", "\"No configuration found for specified environment `#{@environment}'\"", "end", "end" ]
Load the user-specified configuration file. @returns true on success, false otherwise.
[ "Load", "the", "user", "-", "specified", "configuration", "file", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/client.rb#L209-L220
train
jphager2/mangdown
lib/mangdown/page.rb
Mangdown.Page.setup_path
def setup_path(dir = nil) dir ||= chapter.path dir = Tools.valid_path_name(dir) name = self.name.tr('/', '') file = Dir.entries(dir).find { |f| f[name] } if Dir.exist?(dir) path = Tools.file_join(dir, file || name) @path = Tools.relative_or_absolute_path(path) end
ruby
def setup_path(dir = nil) dir ||= chapter.path dir = Tools.valid_path_name(dir) name = self.name.tr('/', '') file = Dir.entries(dir).find { |f| f[name] } if Dir.exist?(dir) path = Tools.file_join(dir, file || name) @path = Tools.relative_or_absolute_path(path) end
[ "def", "setup_path", "(", "dir", "=", "nil", ")", "dir", "||=", "chapter", ".", "path", "dir", "=", "Tools", ".", "valid_path_name", "(", "dir", ")", "name", "=", "self", ".", "name", ".", "tr", "(", "'/'", ",", "''", ")", "file", "=", "Dir", ".", "entries", "(", "dir", ")", ".", "find", "{", "|", "f", "|", "f", "[", "name", "]", "}", "if", "Dir", ".", "exist?", "(", "dir", ")", "path", "=", "Tools", ".", "file_join", "(", "dir", ",", "file", "||", "name", ")", "@path", "=", "Tools", ".", "relative_or_absolute_path", "(", "path", ")", "end" ]
Set path of page to file path if a file exists or to path without file extension if file is not found. File extensions are appended only after the file has been downloaded.
[ "Set", "path", "of", "page", "to", "file", "path", "if", "a", "file", "exists", "or", "to", "path", "without", "file", "extension", "if", "file", "is", "not", "found", ".", "File", "extensions", "are", "appended", "only", "after", "the", "file", "has", "been", "downloaded", "." ]
d57050f486b92873ca96a15cd20cbc1f468f2a61
https://github.com/jphager2/mangdown/blob/d57050f486b92873ca96a15cd20cbc1f468f2a61/lib/mangdown/page.rb#L33-L40
train
DocsWebApps/page_right
lib/page_right/text_helper.rb
PageRight.TextHelper.is_text_in_page?
def is_text_in_page?(content, flag=true) if flag assert page.has_content?("#{content}"), "Error: #{content} not found page !" else assert !page.has_content?("#{content}"), "Error: #{content} found in page !" end end
ruby
def is_text_in_page?(content, flag=true) if flag assert page.has_content?("#{content}"), "Error: #{content} not found page !" else assert !page.has_content?("#{content}"), "Error: #{content} found in page !" end end
[ "def", "is_text_in_page?", "(", "content", ",", "flag", "=", "true", ")", "if", "flag", "assert", "page", ".", "has_content?", "(", "\"#{content}\"", ")", ",", "\"Error: #{content} not found page !\"", "else", "assert", "!", "page", ".", "has_content?", "(", "\"#{content}\"", ")", ",", "\"Error: #{content} found in page !\"", "end", "end" ]
Check that the text 'content' is on the page, set flag to check that it isn't
[ "Check", "that", "the", "text", "content", "is", "on", "the", "page", "set", "flag", "to", "check", "that", "it", "isn", "t" ]
54dacbb7197c0d4371c64ef18f7588843dcc0940
https://github.com/DocsWebApps/page_right/blob/54dacbb7197c0d4371c64ef18f7588843dcc0940/lib/page_right/text_helper.rb#L4-L10
train
DocsWebApps/page_right
lib/page_right/text_helper.rb
PageRight.TextHelper.is_text_in_section?
def is_text_in_section?(section, content, flag=true) within("#{section}") do if flag assert page.has_content?("#{content}"), "Error: #{content} not found in #{section} !" else assert !page.has_content?("#{content}"), "Error: #{content} found in #{section} !" end end end
ruby
def is_text_in_section?(section, content, flag=true) within("#{section}") do if flag assert page.has_content?("#{content}"), "Error: #{content} not found in #{section} !" else assert !page.has_content?("#{content}"), "Error: #{content} found in #{section} !" end end end
[ "def", "is_text_in_section?", "(", "section", ",", "content", ",", "flag", "=", "true", ")", "within", "(", "\"#{section}\"", ")", "do", "if", "flag", "assert", "page", ".", "has_content?", "(", "\"#{content}\"", ")", ",", "\"Error: #{content} not found in #{section} !\"", "else", "assert", "!", "page", ".", "has_content?", "(", "\"#{content}\"", ")", ",", "\"Error: #{content} found in #{section} !\"", "end", "end", "end" ]
Check that the text 'content' is within a particular css section, set flag to check that it isn't
[ "Check", "that", "the", "text", "content", "is", "within", "a", "particular", "css", "section", "set", "flag", "to", "check", "that", "it", "isn", "t" ]
54dacbb7197c0d4371c64ef18f7588843dcc0940
https://github.com/DocsWebApps/page_right/blob/54dacbb7197c0d4371c64ef18f7588843dcc0940/lib/page_right/text_helper.rb#L13-L21
train
richo/juici
lib/juici/build_environment.rb
Juici.BuildEnvironment.load_json!
def load_json!(json) return true if json == "" loaded_json = JSON.load(json) if loaded_json.is_a? Hash env.merge!(loaded_json) return true end false rescue JSON::ParserError return false end
ruby
def load_json!(json) return true if json == "" loaded_json = JSON.load(json) if loaded_json.is_a? Hash env.merge!(loaded_json) return true end false rescue JSON::ParserError return false end
[ "def", "load_json!", "(", "json", ")", "return", "true", "if", "json", "==", "\"\"", "loaded_json", "=", "JSON", ".", "load", "(", "json", ")", "if", "loaded_json", ".", "is_a?", "Hash", "env", ".", "merge!", "(", "loaded_json", ")", "return", "true", "end", "false", "rescue", "JSON", "::", "ParserError", "return", "false", "end" ]
XXX This is spectacular. Not in the good way
[ "XXX", "This", "is", "spectacular", ".", "Not", "in", "the", "good", "way" ]
5649b251a9c8f8c29623fba2fd9fd0b1fc2dbffa
https://github.com/richo/juici/blob/5649b251a9c8f8c29623fba2fd9fd0b1fc2dbffa/lib/juici/build_environment.rb#L21-L31
train
meineerde/rackstash
lib/rackstash/buffer.rb
Rackstash.Buffer.timestamp
def timestamp(time = nil) @timestamp ||= begin time ||= Time.now.utc.freeze time = time.getutc.freeze unless time.utc? && time.frozen? time end end
ruby
def timestamp(time = nil) @timestamp ||= begin time ||= Time.now.utc.freeze time = time.getutc.freeze unless time.utc? && time.frozen? time end end
[ "def", "timestamp", "(", "time", "=", "nil", ")", "@timestamp", "||=", "begin", "time", "||=", "Time", ".", "now", ".", "utc", ".", "freeze", "time", "=", "time", ".", "getutc", ".", "freeze", "unless", "time", ".", "utc?", "&&", "time", ".", "frozen?", "time", "end", "end" ]
Returns the time of the current buffer as an ISO 8601 formatted string. If the timestamp was not yet set on the buffer, it is is set to the the passed `time` or the current time. @example buffer.timestamp # => "2016-10-17T13:37:00.234Z" @param time [Time] an optional time object. If no timestamp was set yet, this time is used @return [String] an ISO 8601 formatted UTC timestamp.
[ "Returns", "the", "time", "of", "the", "current", "buffer", "as", "an", "ISO", "8601", "formatted", "string", ".", "If", "the", "timestamp", "was", "not", "yet", "set", "on", "the", "buffer", "it", "is", "is", "set", "to", "the", "the", "passed", "time", "or", "the", "current", "time", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/buffer.rb#L293-L299
train
meineerde/rackstash
lib/rackstash/buffer.rb
Rackstash.Buffer.event
def event event = fields.to_h event[FIELD_TAGS] = tags.to_a event[FIELD_MESSAGE] = messages event[FIELD_TIMESTAMP] = timestamp event end
ruby
def event event = fields.to_h event[FIELD_TAGS] = tags.to_a event[FIELD_MESSAGE] = messages event[FIELD_TIMESTAMP] = timestamp event end
[ "def", "event", "event", "=", "fields", ".", "to_h", "event", "[", "FIELD_TAGS", "]", "=", "tags", ".", "to_a", "event", "[", "FIELD_MESSAGE", "]", "=", "messages", "event", "[", "FIELD_TIMESTAMP", "]", "=", "timestamp", "event", "end" ]
Create an event hash from `self`. * It contains the all of the current buffer's logged fields * We add the buffer's tags and add them as an array of strings to the `event['tags']` field. * We add the buffer's list of messages to `event['message']`. This field thus contains an array of {Message} objects. * We add the buffer's timestamp to the `event['@timestamp]` as a `Time` object in UTC. The typical event emitted here looks like this: { "beep" => "boop", "foo" => ["bar", "baz"], "tags" => ["request", "controller#action"], "message" => [ #<Rackstash::Message:0x007f908b4414c0 ...>, #<Rackstash::Message:0x007f908d14aee0 ...> ], "@timestamp" => 2016-10-17 13:37:42 UTC } Note that the resulting hash still contains an Array of {Message}s in the `"message"` field and a `Time` object in the '@timestamp' field. This allows the {Flow}'s components (usually a {Filter} or the {Flow#encoder}) to reject or adapt some messages based on their original attributes, e.g., their severity or timestamp. It is the responsibility of the {Flow#encoder} to correctly format the `"@timestamp"` field. All other fields in the event Hash besides `"message"` and `@timestamp"` are either `Hash`, `Array`, frozen `String`, `Integer` or `Float` objects. All hashes (including nested hashes) use `String` keys. @return [Hash] the event expected by the event {Filter}s.
[ "Create", "an", "event", "hash", "from", "self", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/buffer.rb#L336-L343
train
williambarry007/caboose-rets
lib/rets/http.rb
RETS.HTTP.url_encode
def url_encode(str) encoded_string = "" str.each_char do |char| case char when "+" encoded_string << "%2b" when "=" encoded_string << "%3d" when "?" encoded_string << "%3f" when "&" encoded_string << "%26" when "%" encoded_string << "%25" when "," encoded_string << "%2C" else encoded_string << char end end encoded_string end
ruby
def url_encode(str) encoded_string = "" str.each_char do |char| case char when "+" encoded_string << "%2b" when "=" encoded_string << "%3d" when "?" encoded_string << "%3f" when "&" encoded_string << "%26" when "%" encoded_string << "%25" when "," encoded_string << "%2C" else encoded_string << char end end encoded_string end
[ "def", "url_encode", "(", "str", ")", "encoded_string", "=", "\"\"", "str", ".", "each_char", "do", "|", "char", "|", "case", "char", "when", "\"+\"", "encoded_string", "<<", "\"%2b\"", "when", "\"=\"", "encoded_string", "<<", "\"%3d\"", "when", "\"?\"", "encoded_string", "<<", "\"%3f\"", "when", "\"&\"", "encoded_string", "<<", "\"%26\"", "when", "\"%\"", "encoded_string", "<<", "\"%25\"", "when", "\",\"", "encoded_string", "<<", "\"%2C\"", "else", "encoded_string", "<<", "char", "end", "end", "encoded_string", "end" ]
Creates a new HTTP instance which will automatically handle authenting to the RETS server.
[ "Creates", "a", "new", "HTTP", "instance", "which", "will", "automatically", "handle", "authenting", "to", "the", "RETS", "server", "." ]
1e7a5a3a1d51558229aeb2aa2c2f573e18727d27
https://github.com/williambarry007/caboose-rets/blob/1e7a5a3a1d51558229aeb2aa2c2f573e18727d27/lib/rets/http.rb#L30-L51
train
williambarry007/caboose-rets
lib/rets/http.rb
RETS.HTTP.save_digest
def save_digest(header) @request_count = 0 @digest = {} header.split(",").each do |line| k, v = line.strip.split("=", 2) @digest[k] = (k != "algorithm" and k != "stale") && v[1..-2] || v end @digest_type = @digest["qop"] ? @digest["qop"].split(",") : [] end
ruby
def save_digest(header) @request_count = 0 @digest = {} header.split(",").each do |line| k, v = line.strip.split("=", 2) @digest[k] = (k != "algorithm" and k != "stale") && v[1..-2] || v end @digest_type = @digest["qop"] ? @digest["qop"].split(",") : [] end
[ "def", "save_digest", "(", "header", ")", "@request_count", "=", "0", "@digest", "=", "{", "}", "header", ".", "split", "(", "\",\"", ")", ".", "each", "do", "|", "line", "|", "k", ",", "v", "=", "line", ".", "strip", ".", "split", "(", "\"=\"", ",", "2", ")", "@digest", "[", "k", "]", "=", "(", "k", "!=", "\"algorithm\"", "and", "k", "!=", "\"stale\"", ")", "&&", "v", "[", "1", "..", "-", "2", "]", "||", "v", "end", "@digest_type", "=", "@digest", "[", "\"qop\"", "]", "?", "@digest", "[", "\"qop\"", "]", ".", "split", "(", "\",\"", ")", ":", "[", "]", "end" ]
Creates and manages the HTTP digest auth if the WWW-Authorization header is passed, then it will overwrite what it knows about the auth data.
[ "Creates", "and", "manages", "the", "HTTP", "digest", "auth", "if", "the", "WWW", "-", "Authorization", "header", "is", "passed", "then", "it", "will", "overwrite", "what", "it", "knows", "about", "the", "auth", "data", "." ]
1e7a5a3a1d51558229aeb2aa2c2f573e18727d27
https://github.com/williambarry007/caboose-rets/blob/1e7a5a3a1d51558229aeb2aa2c2f573e18727d27/lib/rets/http.rb#L67-L77
train
williambarry007/caboose-rets
lib/rets/http.rb
RETS.HTTP.create_digest
def create_digest(method, request_uri) # http://en.wikipedia.org/wiki/Digest_access_authentication first = Digest::MD5.hexdigest("#{@config[:username]}:#{@digest["realm"]}:#{@config[:password]}") second = Digest::MD5.hexdigest("#{method}:#{request_uri}") # Using the "newer" authentication QOP if @digest_type.include?("auth") cnonce = Digest::MD5.hexdigest("#{@headers["User-Agent"]}:#{@config[:password]}:#{@request_count}:#{@digest["nonce"]}") hash = Digest::MD5.hexdigest("#{first}:#{@digest["nonce"]}:#{"%08X" % @request_count}:#{cnonce}:#{@digest["qop"]}:#{second}") # Nothing specified, so default to the old one elsif @digest_type.empty? hash = Digest::MD5.hexdigest("#{first}:#{@digest["nonce"]}:#{second}") else raise RETS::HTTPError, "Cannot determine auth type for server (#{@digest_type.join(",")})" end http_digest = "Digest username=\"#{@config[:username]}\", " http_digest << "realm=\"#{@digest["realm"]}\", " http_digest << "nonce=\"#{@digest["nonce"]}\", " http_digest << "uri=\"#{request_uri}\", " http_digest << "algorithm=MD5, " unless @digest_type.empty? http_digest << "response=\"#{hash}\", " http_digest << "opaque=\"#{@digest["opaque"]}\"" unless @digest_type.empty? http_digest << ", " http_digest << "qop=\"#{@digest["qop"]}\", " http_digest << "nc=#{"%08X" % @request_count}, " http_digest << "cnonce=\"#{cnonce}\"" end http_digest end
ruby
def create_digest(method, request_uri) # http://en.wikipedia.org/wiki/Digest_access_authentication first = Digest::MD5.hexdigest("#{@config[:username]}:#{@digest["realm"]}:#{@config[:password]}") second = Digest::MD5.hexdigest("#{method}:#{request_uri}") # Using the "newer" authentication QOP if @digest_type.include?("auth") cnonce = Digest::MD5.hexdigest("#{@headers["User-Agent"]}:#{@config[:password]}:#{@request_count}:#{@digest["nonce"]}") hash = Digest::MD5.hexdigest("#{first}:#{@digest["nonce"]}:#{"%08X" % @request_count}:#{cnonce}:#{@digest["qop"]}:#{second}") # Nothing specified, so default to the old one elsif @digest_type.empty? hash = Digest::MD5.hexdigest("#{first}:#{@digest["nonce"]}:#{second}") else raise RETS::HTTPError, "Cannot determine auth type for server (#{@digest_type.join(",")})" end http_digest = "Digest username=\"#{@config[:username]}\", " http_digest << "realm=\"#{@digest["realm"]}\", " http_digest << "nonce=\"#{@digest["nonce"]}\", " http_digest << "uri=\"#{request_uri}\", " http_digest << "algorithm=MD5, " unless @digest_type.empty? http_digest << "response=\"#{hash}\", " http_digest << "opaque=\"#{@digest["opaque"]}\"" unless @digest_type.empty? http_digest << ", " http_digest << "qop=\"#{@digest["qop"]}\", " http_digest << "nc=#{"%08X" % @request_count}, " http_digest << "cnonce=\"#{cnonce}\"" end http_digest end
[ "def", "create_digest", "(", "method", ",", "request_uri", ")", "first", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "\"#{@config[:username]}:#{@digest[\"realm\"]}:#{@config[:password]}\"", ")", "second", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "\"#{method}:#{request_uri}\"", ")", "if", "@digest_type", ".", "include?", "(", "\"auth\"", ")", "cnonce", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "\"#{@headers[\"User-Agent\"]}:#{@config[:password]}:#{@request_count}:#{@digest[\"nonce\"]}\"", ")", "hash", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "\"#{first}:#{@digest[\"nonce\"]}:#{\"%08X\" % @request_count}:#{cnonce}:#{@digest[\"qop\"]}:#{second}\"", ")", "elsif", "@digest_type", ".", "empty?", "hash", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "\"#{first}:#{@digest[\"nonce\"]}:#{second}\"", ")", "else", "raise", "RETS", "::", "HTTPError", ",", "\"Cannot determine auth type for server (#{@digest_type.join(\",\")})\"", "end", "http_digest", "=", "\"Digest username=\\\"#{@config[:username]}\\\", \"", "http_digest", "<<", "\"realm=\\\"#{@digest[\"realm\"]}\\\", \"", "http_digest", "<<", "\"nonce=\\\"#{@digest[\"nonce\"]}\\\", \"", "http_digest", "<<", "\"uri=\\\"#{request_uri}\\\", \"", "http_digest", "<<", "\"algorithm=MD5, \"", "unless", "@digest_type", ".", "empty?", "http_digest", "<<", "\"response=\\\"#{hash}\\\", \"", "http_digest", "<<", "\"opaque=\\\"#{@digest[\"opaque\"]}\\\"\"", "unless", "@digest_type", ".", "empty?", "http_digest", "<<", "\", \"", "http_digest", "<<", "\"qop=\\\"#{@digest[\"qop\"]}\\\", \"", "http_digest", "<<", "\"nc=#{\"%08X\" % @request_count}, \"", "http_digest", "<<", "\"cnonce=\\\"#{cnonce}\\\"\"", "end", "http_digest", "end" ]
Creates a HTTP digest header.
[ "Creates", "a", "HTTP", "digest", "header", "." ]
1e7a5a3a1d51558229aeb2aa2c2f573e18727d27
https://github.com/williambarry007/caboose-rets/blob/1e7a5a3a1d51558229aeb2aa2c2f573e18727d27/lib/rets/http.rb#L81-L113
train
williambarry007/caboose-rets
lib/rets/http.rb
RETS.HTTP.get_rets_response
def get_rets_response(rets) code, text = nil, nil rets.attributes.each do |attr| key = attr.first.downcase if key == "replycode" code = attr.last.value elsif key == "replytext" text = attr.last.value end end # puts "replycode: #{code}" return code, text end
ruby
def get_rets_response(rets) code, text = nil, nil rets.attributes.each do |attr| key = attr.first.downcase if key == "replycode" code = attr.last.value elsif key == "replytext" text = attr.last.value end end # puts "replycode: #{code}" return code, text end
[ "def", "get_rets_response", "(", "rets", ")", "code", ",", "text", "=", "nil", ",", "nil", "rets", ".", "attributes", ".", "each", "do", "|", "attr", "|", "key", "=", "attr", ".", "first", ".", "downcase", "if", "key", "==", "\"replycode\"", "code", "=", "attr", ".", "last", ".", "value", "elsif", "key", "==", "\"replytext\"", "text", "=", "attr", ".", "last", ".", "value", "end", "end", "return", "code", ",", "text", "end" ]
Finds the ReplyText and ReplyCode attributes in the response @param [Nokogiri::XML::NodeSet] rets <RETS> attributes found @return [String] RETS ReplyCode @return [String] RETS ReplyText
[ "Finds", "the", "ReplyText", "and", "ReplyCode", "attributes", "in", "the", "response" ]
1e7a5a3a1d51558229aeb2aa2c2f573e18727d27
https://github.com/williambarry007/caboose-rets/blob/1e7a5a3a1d51558229aeb2aa2c2f573e18727d27/lib/rets/http.rb#L128-L140
train
igor-starostenko/tune_spec
lib/tune_spec/instances.rb
TuneSpec.Instances.groups
def groups(name, opts = {}, *args, &block) instance_handler(name, Groups, opts, *args, block) end
ruby
def groups(name, opts = {}, *args, &block) instance_handler(name, Groups, opts, *args, block) end
[ "def", "groups", "(", "name", ",", "opts", "=", "{", "}", ",", "*", "args", ",", "&", "block", ")", "instance_handler", "(", "name", ",", "Groups", ",", "opts", ",", "*", "args", ",", "block", ")", "end" ]
Creates an instance of Group or calls an existing @param name [Symbol, String] the prefix of the Groups object class @param opts [Hash] optional arguments @param args [Any] extra arguments @param block [Block] that yields to self @return [GroupObject] @example groups(:login, {}, 'Main').complete
[ "Creates", "an", "instance", "of", "Group", "or", "calls", "an", "existing" ]
385e078bf618b9409d823ecbbf90334f5173e3a1
https://github.com/igor-starostenko/tune_spec/blob/385e078bf618b9409d823ecbbf90334f5173e3a1/lib/tune_spec/instances.rb#L20-L22
train
igor-starostenko/tune_spec
lib/tune_spec/instances.rb
TuneSpec.Instances.steps
def steps(name, opts = {}, *args, &block) opts[:page] && opts[:page] = pages(opts.fetch(:page)) instance_handler(name, Steps, opts, *args, block) end
ruby
def steps(name, opts = {}, *args, &block) opts[:page] && opts[:page] = pages(opts.fetch(:page)) instance_handler(name, Steps, opts, *args, block) end
[ "def", "steps", "(", "name", ",", "opts", "=", "{", "}", ",", "*", "args", ",", "&", "block", ")", "opts", "[", ":page", "]", "&&", "opts", "[", ":page", "]", "=", "pages", "(", "opts", ".", "fetch", "(", ":page", ")", ")", "instance_handler", "(", "name", ",", "Steps", ",", "opts", ",", "*", "args", ",", "block", ")", "end" ]
Creates an instance of Step or calls an existing @param name [Symbol, String] the prefix of the Step object class @param opts [Hash] optional arguments @param args [Any] extra arguments @param block [Block] that yields to self @return [StepObject] @example steps(:calculator, page: :demo).verify_result
[ "Creates", "an", "instance", "of", "Step", "or", "calls", "an", "existing" ]
385e078bf618b9409d823ecbbf90334f5173e3a1
https://github.com/igor-starostenko/tune_spec/blob/385e078bf618b9409d823ecbbf90334f5173e3a1/lib/tune_spec/instances.rb#L33-L36
train
igor-starostenko/tune_spec
lib/tune_spec/instances.rb
TuneSpec.Instances.pages
def pages(name, opts = {}, *args, &block) instance_handler(name, Page, opts, *args, block) end
ruby
def pages(name, opts = {}, *args, &block) instance_handler(name, Page, opts, *args, block) end
[ "def", "pages", "(", "name", ",", "opts", "=", "{", "}", ",", "*", "args", ",", "&", "block", ")", "instance_handler", "(", "name", ",", "Page", ",", "opts", ",", "*", "args", ",", "block", ")", "end" ]
Creates an instance of Page or calls an existing @param name [Symbol, String] the prefix of the Page object class @param opts [Hash] optional arguments @param args [Any] extra arguments @param block [Block] that yields to self @return [PageObject] @example pages(:home).click_element
[ "Creates", "an", "instance", "of", "Page", "or", "calls", "an", "existing" ]
385e078bf618b9409d823ecbbf90334f5173e3a1
https://github.com/igor-starostenko/tune_spec/blob/385e078bf618b9409d823ecbbf90334f5173e3a1/lib/tune_spec/instances.rb#L47-L49
train
fixrb/matchi
lib/matchi/matchers_base.rb
Matchi.MatchersBase.to_s
def to_s s = matcher_name .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .downcase defined?(@expected) ? [s, @expected.inspect].join(' ') : s end
ruby
def to_s s = matcher_name .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .downcase defined?(@expected) ? [s, @expected.inspect].join(' ') : s end
[ "def", "to_s", "s", "=", "matcher_name", ".", "gsub", "(", "/", "/", ",", "'\\1_\\2'", ")", ".", "gsub", "(", "/", "\\d", "/", ",", "'\\1_\\2'", ")", ".", "downcase", "defined?", "(", "@expected", ")", "?", "[", "s", ",", "@expected", ".", "inspect", "]", ".", "join", "(", "' '", ")", ":", "s", "end" ]
Returns a string representing the matcher. @example The readable definition of a FooBar matcher. matcher = Matchi::Matchers::FooBar::Matcher.new(42) matcher.to_s # => "foo_bar 42" @return [String] A string representing the matcher.
[ "Returns", "a", "string", "representing", "the", "matcher", "." ]
4ea2eaf339cbc048fffd104ac392c1d2d98c9c16
https://github.com/fixrb/matchi/blob/4ea2eaf339cbc048fffd104ac392c1d2d98c9c16/lib/matchi/matchers_base.rb#L20-L27
train
benton/fog_tracker
lib/fog_tracker/tracker.rb
FogTracker.Tracker.query
def query(query_string) results = FogTracker::Query::QueryProcessor.new( @trackers, :logger => @log ).execute(query_string) (results.each {|r| yield r}) if block_given? results end
ruby
def query(query_string) results = FogTracker::Query::QueryProcessor.new( @trackers, :logger => @log ).execute(query_string) (results.each {|r| yield r}) if block_given? results end
[ "def", "query", "(", "query_string", ")", "results", "=", "FogTracker", "::", "Query", "::", "QueryProcessor", ".", "new", "(", "@trackers", ",", ":logger", "=>", "@log", ")", ".", "execute", "(", "query_string", ")", "(", "results", ".", "each", "{", "|", "r", "|", "yield", "r", "}", ")", "if", "block_given?", "results", "end" ]
Returns an array of Resources matching the query_string. Calls any block passed for each resulting resource. @param [String] query_string a string used to filter for matching resources it might look like: "Account Name::Compute::AWS::servers" @return [Array <Fog::Model>] an Array of Resources, filtered by query
[ "Returns", "an", "array", "of", "Resources", "matching", "the", "query_string", ".", "Calls", "any", "block", "passed", "for", "each", "resulting", "resource", "." ]
73fdf35dd76ff1b1fc448698f2761ebfbea52e0e
https://github.com/benton/fog_tracker/blob/73fdf35dd76ff1b1fc448698f2761ebfbea52e0e/lib/fog_tracker/tracker.rb#L78-L84
train
benton/fog_tracker
lib/fog_tracker/tracker.rb
FogTracker.Tracker.accounts=
def accounts=(new_accounts) old_accounts = @accounts @accounts = FogTracker.validate_accounts(new_accounts) if (@accounts != old_accounts) stop if (was_running = running?) create_trackers start if was_running end @accounts end
ruby
def accounts=(new_accounts) old_accounts = @accounts @accounts = FogTracker.validate_accounts(new_accounts) if (@accounts != old_accounts) stop if (was_running = running?) create_trackers start if was_running end @accounts end
[ "def", "accounts", "=", "(", "new_accounts", ")", "old_accounts", "=", "@accounts", "@accounts", "=", "FogTracker", ".", "validate_accounts", "(", "new_accounts", ")", "if", "(", "@accounts", "!=", "old_accounts", ")", "stop", "if", "(", "was_running", "=", "running?", ")", "create_trackers", "start", "if", "was_running", "end", "@accounts", "end" ]
Sets the account information. If any account info has changed, all trackers are restarted. @param [Hash] accounts a Hash of account information (see accounts.example.yml)
[ "Sets", "the", "account", "information", ".", "If", "any", "account", "info", "has", "changed", "all", "trackers", "are", "restarted", "." ]
73fdf35dd76ff1b1fc448698f2761ebfbea52e0e
https://github.com/benton/fog_tracker/blob/73fdf35dd76ff1b1fc448698f2761ebfbea52e0e/lib/fog_tracker/tracker.rb#L109-L118
train
benton/fog_tracker
lib/fog_tracker/tracker.rb
FogTracker.Tracker.create_trackers
def create_trackers @trackers = Hash.new @accounts.each do |name, account| @log.debug "Setting up tracker for account #{name}" @trackers[name] = AccountTracker.new(name, account, { :delay => @delay, :error_callback => @error_proc, :logger => @log, :callback => Proc.new do |resources| # attach a QueryProcessor to all returned resources qp = FogTracker::Query::QueryProcessor.new(@trackers, :logger => @log) resources.each {|resource| resource._query_processor = qp} # now relay the resources back to the client software @callback.call(resources) if @callback end } ) end end
ruby
def create_trackers @trackers = Hash.new @accounts.each do |name, account| @log.debug "Setting up tracker for account #{name}" @trackers[name] = AccountTracker.new(name, account, { :delay => @delay, :error_callback => @error_proc, :logger => @log, :callback => Proc.new do |resources| # attach a QueryProcessor to all returned resources qp = FogTracker::Query::QueryProcessor.new(@trackers, :logger => @log) resources.each {|resource| resource._query_processor = qp} # now relay the resources back to the client software @callback.call(resources) if @callback end } ) end end
[ "def", "create_trackers", "@trackers", "=", "Hash", ".", "new", "@accounts", ".", "each", "do", "|", "name", ",", "account", "|", "@log", ".", "debug", "\"Setting up tracker for account #{name}\"", "@trackers", "[", "name", "]", "=", "AccountTracker", ".", "new", "(", "name", ",", "account", ",", "{", ":delay", "=>", "@delay", ",", ":error_callback", "=>", "@error_proc", ",", ":logger", "=>", "@log", ",", ":callback", "=>", "Proc", ".", "new", "do", "|", "resources", "|", "qp", "=", "FogTracker", "::", "Query", "::", "QueryProcessor", ".", "new", "(", "@trackers", ",", ":logger", "=>", "@log", ")", "resources", ".", "each", "{", "|", "resource", "|", "resource", ".", "_query_processor", "=", "qp", "}", "@callback", ".", "call", "(", "resources", ")", "if", "@callback", "end", "}", ")", "end", "end" ]
Creates a Hash of AccountTracker objects, indexed by account name
[ "Creates", "a", "Hash", "of", "AccountTracker", "objects", "indexed", "by", "account", "name" ]
73fdf35dd76ff1b1fc448698f2761ebfbea52e0e
https://github.com/benton/fog_tracker/blob/73fdf35dd76ff1b1fc448698f2761ebfbea52e0e/lib/fog_tracker/tracker.rb#L123-L139
train
meineerde/rackstash
lib/rackstash/logger.rb
Rackstash.Logger.<<
def <<(msg) buffer.add_message Message.new( msg, time: Time.now.utc.freeze, progname: @progname, severity: UNKNOWN ) msg end
ruby
def <<(msg) buffer.add_message Message.new( msg, time: Time.now.utc.freeze, progname: @progname, severity: UNKNOWN ) msg end
[ "def", "<<", "(", "msg", ")", "buffer", ".", "add_message", "Message", ".", "new", "(", "msg", ",", "time", ":", "Time", ".", "now", ".", "utc", ".", "freeze", ",", "progname", ":", "@progname", ",", "severity", ":", "UNKNOWN", ")", "msg", "end" ]
Create a new Logger instance. We mostly follow the common interface of Ruby's core Logger class with the exception that you can give one or more flows to write logs to. Each {Flow} is responsible to write a log event (e.g. to a file, STDOUT, a TCP socket, ...). Each log event is written to all defined {#flows}. When giving the flows here, you can given them in one of varous representations, all of which we will transform into an actual {Flow}: * A {Rackstash::Flow} object. For the most control over the flow, you can create the {Flow} object on your own and pass it here * A {Rackstash::Adapter::Adapter}. When passing an adapter, we will create a new {Flow} from this adapter, using its default encoder and without any defined filters. * An log device from which we can create an adapter. In this case, we first attempt to build an adapter from it using {Rackstash::Adapter.[]}. After that, we use it to create a {Flow} as above. When passing a block to this initializer, we will yield the last created flow object to it. If you pass multiple log devices / adapters / flows, only the last one will be yielded. If the block doesn't expect an argument, we run the block in the instance scope of the flow. The following three example to create a custom Logger are thus equivalent: logger = Rackstash::Logger.new(STDOUT) do encoder Rackstash::Encoder::Message.new end logger = Rackstash::Logger.new(Rackstash::Adapter::IO.new(STDOUT)) do encoder Rackstash::Encoder::Message.new end adapter = Rackstash::Adapter::IO.new(STDOUT) flow = Rackstash::Flows.new(adapter) do encoder Rackstash::Encoder::Message.new end logger = Rackstash::Logger.new(flow) To create a simple Logger which logs to `STDOUT` using the default JSON format, you can just use logger = Rackstash::Logger.new(STDOUT) @param flows [Array<Flow, Object>, Flow, Adapter::Adapter, Object] an array of {Flow}s or a single {Flow}, respectivly object which can be used as a {Flow}'s adapter. See {Flow#initialize}. @param level [Integer] a numeric log level. Normally you'd use one of the {SEVERITIES} constants, i.e., an integer between 0 and 5. We will only log messages with a severity above the configured level. @param progname [String] the logger's progname, used as the default for log messages if none is passed to {#add} and passed to the {#formatter}. By default we use {PROGNAME}. @param formatter [#call] the log formatter for each individual buffered line. See {#formatter} for details. @yieldparam flow [Rackstash::Flow] if the given block accepts an argument, we yield the last {Flow} as a parameter. Without an expected argument, the block is directly executed in the context of the last {Flow}. Add a message to the current {Buffer} without any further formatting. If the current buffer is bufering, the message will just be added. Else, it will be flushed to the configured {#flows} directly. @param msg [Object] @return [String] the passed `msg`
[ "Create", "a", "new", "Logger", "instance", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/logger.rb#L132-L140
train
meineerde/rackstash
lib/rackstash/logger.rb
Rackstash.Logger.capture
def capture(buffer_args = {}) raise ArgumentError, 'block required' unless block_given? buffer_stack.push(buffer_args) begin yield ensure buffer_stack.flush_and_pop end end
ruby
def capture(buffer_args = {}) raise ArgumentError, 'block required' unless block_given? buffer_stack.push(buffer_args) begin yield ensure buffer_stack.flush_and_pop end end
[ "def", "capture", "(", "buffer_args", "=", "{", "}", ")", "raise", "ArgumentError", ",", "'block required'", "unless", "block_given?", "buffer_stack", ".", "push", "(", "buffer_args", ")", "begin", "yield", "ensure", "buffer_stack", ".", "flush_and_pop", "end", "end" ]
Capture all messages and fields logged for the duration of the provided block in the current thread. Create a new {Buffer} and put in on the {BufferStack} for the current thread. For the duration of the block, all new logged messages and any access to fields and tags will be sent to this new buffer. Previous buffers created in the same thread will only be visible after the execution left the block. Note that the created {Buffer} is only valid for the current thread. In other threads, it not visible and will thus not be used. @param buffer_args [Hash<Symbol => Object>] optional arguments for the new {Buffer}. See {Buffer#initialize} for allowed values. @yield During the duration of the block, all logged messages, fields and tags are set on the new buffer. After the block returns, the {Buffer} is removed from the {BufferStack} again and is always flushed automatically. @return [Object] the return value of the block
[ "Capture", "all", "messages", "and", "fields", "logged", "for", "the", "duration", "of", "the", "provided", "block", "in", "the", "current", "thread", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/logger.rb#L454-L463
train
seapagan/confoog
lib/confoog.rb
Confoog.Settings.load
def load @config = YAML.load_file(config_path) @status.set(errors: Status::INFO_FILE_LOADED) if @config == false @status.set(errors: Status::ERR_NOT_LOADING_EMPTY_FILE) end rescue @status.set(errors: Status::ERR_CANT_LOAD) end
ruby
def load @config = YAML.load_file(config_path) @status.set(errors: Status::INFO_FILE_LOADED) if @config == false @status.set(errors: Status::ERR_NOT_LOADING_EMPTY_FILE) end rescue @status.set(errors: Status::ERR_CANT_LOAD) end
[ "def", "load", "@config", "=", "YAML", ".", "load_file", "(", "config_path", ")", "@status", ".", "set", "(", "errors", ":", "Status", "::", "INFO_FILE_LOADED", ")", "if", "@config", "==", "false", "@status", ".", "set", "(", "errors", ":", "Status", "::", "ERR_NOT_LOADING_EMPTY_FILE", ")", "end", "rescue", "@status", ".", "set", "(", "errors", ":", "Status", "::", "ERR_CANT_LOAD", ")", "end" ]
Populate the configuration (@config) from the YAML file. @param [None] @example settings.load @return Unspecified
[ "Populate", "the", "configuration", "(" ]
f5a00ff6db132a3f6d7ce880f360e9e5b74bf5b7
https://github.com/seapagan/confoog/blob/f5a00ff6db132a3f6d7ce880f360e9e5b74bf5b7/lib/confoog.rb#L137-L145
train
DocsWebApps/page_right
lib/page_right/css_helper.rb
PageRight.CssHelper.is_css_in_page?
def is_css_in_page?(css, flag=true) if flag assert page.has_css?("#{css}"), "Error: #{css} not found on page !" else assert !page.has_css?("#{css}"), "Error: #{css} found on page !" end end
ruby
def is_css_in_page?(css, flag=true) if flag assert page.has_css?("#{css}"), "Error: #{css} not found on page !" else assert !page.has_css?("#{css}"), "Error: #{css} found on page !" end end
[ "def", "is_css_in_page?", "(", "css", ",", "flag", "=", "true", ")", "if", "flag", "assert", "page", ".", "has_css?", "(", "\"#{css}\"", ")", ",", "\"Error: #{css} not found on page !\"", "else", "assert", "!", "page", ".", "has_css?", "(", "\"#{css}\"", ")", ",", "\"Error: #{css} found on page !\"", "end", "end" ]
Check that a css element is on the page, set flag to check that it isn't
[ "Check", "that", "a", "css", "element", "is", "on", "the", "page", "set", "flag", "to", "check", "that", "it", "isn", "t" ]
54dacbb7197c0d4371c64ef18f7588843dcc0940
https://github.com/DocsWebApps/page_right/blob/54dacbb7197c0d4371c64ef18f7588843dcc0940/lib/page_right/css_helper.rb#L4-L10
train
DocsWebApps/page_right
lib/page_right/css_helper.rb
PageRight.CssHelper.is_css_in_section?
def is_css_in_section?(css1, css2, flag=true) within("#{css1}") do if flag assert page.has_css?("#{css2}"), "Error: #{css2} not found in #{css1} !" else assert !page.has_css?("#{css2}"), "Error: #{css2} found in #{css1} !" end end end
ruby
def is_css_in_section?(css1, css2, flag=true) within("#{css1}") do if flag assert page.has_css?("#{css2}"), "Error: #{css2} not found in #{css1} !" else assert !page.has_css?("#{css2}"), "Error: #{css2} found in #{css1} !" end end end
[ "def", "is_css_in_section?", "(", "css1", ",", "css2", ",", "flag", "=", "true", ")", "within", "(", "\"#{css1}\"", ")", "do", "if", "flag", "assert", "page", ".", "has_css?", "(", "\"#{css2}\"", ")", ",", "\"Error: #{css2} not found in #{css1} !\"", "else", "assert", "!", "page", ".", "has_css?", "(", "\"#{css2}\"", ")", ",", "\"Error: #{css2} found in #{css1} !\"", "end", "end", "end" ]
Check that a css element is nested within another css element, set flag to check that it isn't
[ "Check", "that", "a", "css", "element", "is", "nested", "within", "another", "css", "element", "set", "flag", "to", "check", "that", "it", "isn", "t" ]
54dacbb7197c0d4371c64ef18f7588843dcc0940
https://github.com/DocsWebApps/page_right/blob/54dacbb7197c0d4371c64ef18f7588843dcc0940/lib/page_right/css_helper.rb#L13-L21
train
fixrb/fix-its
lib/fix/its.rb
Fix.On.its
def its(method, &spec) i = It.new(described, (challenges + [Defi.send(method)]), helpers.dup) result = i.verify(&spec) if configuration.fetch(:verbose, true) print result.to_char(configuration.fetch(:color, false)) end results << result end
ruby
def its(method, &spec) i = It.new(described, (challenges + [Defi.send(method)]), helpers.dup) result = i.verify(&spec) if configuration.fetch(:verbose, true) print result.to_char(configuration.fetch(:color, false)) end results << result end
[ "def", "its", "(", "method", ",", "&", "spec", ")", "i", "=", "It", ".", "new", "(", "described", ",", "(", "challenges", "+", "[", "Defi", ".", "send", "(", "method", ")", "]", ")", ",", "helpers", ".", "dup", ")", "result", "=", "i", ".", "verify", "(", "&", "spec", ")", "if", "configuration", ".", "fetch", "(", ":verbose", ",", "true", ")", "print", "result", ".", "to_char", "(", "configuration", ".", "fetch", "(", ":color", ",", "false", ")", ")", "end", "results", "<<", "result", "end" ]
Add its method to the DSL. @api public @example Its absolute value must equal 42 its(:abs) { MUST equal 42 } @param method [Symbol] The identifier of a method. @param spec [Proc] A spec to compare against the computed value. @return [Array] List of results. rubocop:disable AbcSize
[ "Add", "its", "method", "to", "the", "DSL", "." ]
9baf121b610b33ee48b63a7e378f419d4214a2d7
https://github.com/fixrb/fix-its/blob/9baf121b610b33ee48b63a7e378f419d4214a2d7/lib/fix/its.rb#L28-L38
train
bys-control/active_model_serializers_binary
lib/active_model_serializers_binary/base_type.rb
DataTypes.BaseType.before_dump
def before_dump(value) self.value = value if !value.nil? if [email protected]? value = @parent.instance_exec( self, :dump, &@block ) end self.value = value if !value.nil? end
ruby
def before_dump(value) self.value = value if !value.nil? if [email protected]? value = @parent.instance_exec( self, :dump, &@block ) end self.value = value if !value.nil? end
[ "def", "before_dump", "(", "value", ")", "self", ".", "value", "=", "value", "if", "!", "value", ".", "nil?", "if", "!", "@block", ".", "nil?", "value", "=", "@parent", ".", "instance_exec", "(", "self", ",", ":dump", ",", "&", "@block", ")", "end", "self", ".", "value", "=", "value", "if", "!", "value", ".", "nil?", "end" ]
Se ejecuta antes de serializar los datos @param [Object] value valor del objeto a serializar original @return [Array] nuevo valor del objeto a serializar
[ "Se", "ejecuta", "antes", "de", "serializar", "los", "datos" ]
f5c77dcc57530a5dfa7b2e6bbe48e951e30412d1
https://github.com/bys-control/active_model_serializers_binary/blob/f5c77dcc57530a5dfa7b2e6bbe48e951e30412d1/lib/active_model_serializers_binary/base_type.rb#L117-L123
train
rapid7/daemon_runner
lib/daemon_runner/shell_out.rb
DaemonRunner.ShellOut.run_and_detach
def run_and_detach log_r, log_w = IO.pipe @pid = Process.spawn(command, pgroup: true, err: :out, out: log_w) log_r.close log_w.close @pid end
ruby
def run_and_detach log_r, log_w = IO.pipe @pid = Process.spawn(command, pgroup: true, err: :out, out: log_w) log_r.close log_w.close @pid end
[ "def", "run_and_detach", "log_r", ",", "log_w", "=", "IO", ".", "pipe", "@pid", "=", "Process", ".", "spawn", "(", "command", ",", "pgroup", ":", "true", ",", "err", ":", ":out", ",", "out", ":", "log_w", ")", "log_r", ".", "close", "log_w", ".", "close", "@pid", "end" ]
Run a command in a new process group, thus ignoring any furthur updates about the status of the process @return [Fixnum] process id
[ "Run", "a", "command", "in", "a", "new", "process", "group", "thus", "ignoring", "any", "furthur", "updates", "about", "the", "status", "of", "the", "process" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/shell_out.rb#L66-L72
train
meineerde/rackstash
lib/rackstash/message.rb
Rackstash.Message.gsub
def gsub(pattern, replacement = UNDEFINED, &block) if UNDEFINED.equal? replacement if block_given? copy_with @message.gsub(pattern, &block).freeze else enum_for(__method__) end else copy_with @message.gsub(pattern, replacement, &block).freeze end end
ruby
def gsub(pattern, replacement = UNDEFINED, &block) if UNDEFINED.equal? replacement if block_given? copy_with @message.gsub(pattern, &block).freeze else enum_for(__method__) end else copy_with @message.gsub(pattern, replacement, &block).freeze end end
[ "def", "gsub", "(", "pattern", ",", "replacement", "=", "UNDEFINED", ",", "&", "block", ")", "if", "UNDEFINED", ".", "equal?", "replacement", "if", "block_given?", "copy_with", "@message", ".", "gsub", "(", "pattern", ",", "&", "block", ")", ".", "freeze", "else", "enum_for", "(", "__method__", ")", "end", "else", "copy_with", "@message", ".", "gsub", "(", "pattern", ",", "replacement", ",", "&", "block", ")", ".", "freeze", "end", "end" ]
Returns a copy of the Message with all occurances of `pattern` in the `message` attribute substituted for the second argument. This works very similar to [`String#gsub`](https://ruby-doc.org/core/String.html#method-i-gsub). We are returning a new Message object herre with the `message` attribute being updated. Please see the documentation of the String method for how to use this. Note that when supplying a block for replacement, the current match string is passed in as a parameter. Differing from `String#gsub`, the special variables `$1`, `$2`, `$``, `$&`, and `$'` will *not* be set here. @param pattern [String, Regexp] the search pattern @param replacement [String, Hash] the replacement definition @yield match If `replacement` is not given, we yield each match to the supplied block and use its return value for the replacement @return [Message, Enumerator] a new frozen Message object or an Enumerator if neither a block nor a `replacement` were given.
[ "Returns", "a", "copy", "of", "the", "Message", "with", "all", "occurances", "of", "pattern", "in", "the", "message", "attribute", "substituted", "for", "the", "second", "argument", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/message.rb#L94-L104
train
meineerde/rackstash
lib/rackstash/message.rb
Rackstash.Message.sub
def sub(pattern, replacement = UNDEFINED, &block) message = if UNDEFINED.equal? replacement @message.sub(pattern, &block) else @message.sub(pattern, replacement, &block) end copy_with(message.freeze) end
ruby
def sub(pattern, replacement = UNDEFINED, &block) message = if UNDEFINED.equal? replacement @message.sub(pattern, &block) else @message.sub(pattern, replacement, &block) end copy_with(message.freeze) end
[ "def", "sub", "(", "pattern", ",", "replacement", "=", "UNDEFINED", ",", "&", "block", ")", "message", "=", "if", "UNDEFINED", ".", "equal?", "replacement", "@message", ".", "sub", "(", "pattern", ",", "&", "block", ")", "else", "@message", ".", "sub", "(", "pattern", ",", "replacement", ",", "&", "block", ")", "end", "copy_with", "(", "message", ".", "freeze", ")", "end" ]
Returns a copy of the Message with the first occurance of `pattern` in the `message` attribute substituted for the second argument. This works very similar to [`String#sub`](https://ruby-doc.org/core/String.html#method-i-sub). We are returning a new Message object herre with the `message` attribute being updated. Please see the documentation of the String method for how to use this. Note that when supplying a block for replacement, the current match string is passed in as a parameter. Differing from `String#gsub`, the special variables `$1`, `$2`, `$``, `$&`, and `$'` will *not* be set here. @param pattern [String, Regexp] the search pattern @param replacement [String, Hash] the replacement definition @yield match If `replacement` is not given, we yield the match (if any) to the supplied block and use its return value for the replacement. @return [Message, Enumerator] a new frozen Message object or an Enumerator if neither a block nor a `replacement` were given.
[ "Returns", "a", "copy", "of", "the", "Message", "with", "the", "first", "occurance", "of", "pattern", "in", "the", "message", "attribute", "substituted", "for", "the", "second", "argument", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/message.rb#L125-L133
train
erichmenge/signed_form
lib/signed_form/hmac.rb
SignedForm.HMAC.secure_compare
def secure_compare(a, b) return false unless a.bytesize == b.bytesize l = a.unpack("C*") r, i = 0, -1 b.each_byte { |v| r |= v ^ l[i+=1] } r == 0 end
ruby
def secure_compare(a, b) return false unless a.bytesize == b.bytesize l = a.unpack("C*") r, i = 0, -1 b.each_byte { |v| r |= v ^ l[i+=1] } r == 0 end
[ "def", "secure_compare", "(", "a", ",", "b", ")", "return", "false", "unless", "a", ".", "bytesize", "==", "b", ".", "bytesize", "l", "=", "a", ".", "unpack", "(", "\"C*\"", ")", "r", ",", "i", "=", "0", ",", "-", "1", "b", ".", "each_byte", "{", "|", "v", "|", "r", "|=", "v", "^", "l", "[", "i", "+=", "1", "]", "}", "r", "==", "0", "end" ]
After the Rack implementation
[ "After", "the", "Rack", "implementation" ]
ea3842888e78035b7da3fc28f7eaa220d4fc8640
https://github.com/erichmenge/signed_form/blob/ea3842888e78035b7da3fc28f7eaa220d4fc8640/lib/signed_form/hmac.rb#L32-L40
train
duck8823/danger-slack
lib/slack/plugin.rb
Danger.DangerSlack.notify
def notify(channel: '#general', text: nil, **opts) attachments = text.nil? ? report : [] text ||= '<http://danger.systems/|Danger> reports' @conn.post do |req| req.url 'chat.postMessage' req.params = { token: @api_token, channel: channel, text: text, attachments: attachments.to_json, link_names: 1, **opts } end end
ruby
def notify(channel: '#general', text: nil, **opts) attachments = text.nil? ? report : [] text ||= '<http://danger.systems/|Danger> reports' @conn.post do |req| req.url 'chat.postMessage' req.params = { token: @api_token, channel: channel, text: text, attachments: attachments.to_json, link_names: 1, **opts } end end
[ "def", "notify", "(", "channel", ":", "'#general'", ",", "text", ":", "nil", ",", "**", "opts", ")", "attachments", "=", "text", ".", "nil?", "?", "report", ":", "[", "]", "text", "||=", "'<http://danger.systems/|Danger> reports'", "@conn", ".", "post", "do", "|", "req", "|", "req", ".", "url", "'chat.postMessage'", "req", ".", "params", "=", "{", "token", ":", "@api_token", ",", "channel", ":", "channel", ",", "text", ":", "text", ",", "attachments", ":", "attachments", ".", "to_json", ",", "link_names", ":", "1", ",", "**", "opts", "}", "end", "end" ]
notify to Slack @param [String] channel It is channel to be notified, defaults to '#general' @param [String] text text message posted to slack, defaults to nil. if nil, this method post danger reports to slack. @param [Hash] **opts @return [void]
[ "notify", "to", "Slack" ]
a5e7b7fa50fe4d7ee4d1e9f2e4d3afc9befafa18
https://github.com/duck8823/danger-slack/blob/a5e7b7fa50fe4d7ee4d1e9f2e4d3afc9befafa18/lib/slack/plugin.rb#L78-L92
train
duck8823/danger-slack
lib/slack/plugin.rb
Danger.DangerSlack.report
def report attachment = status_report .reject { |_, v| v.empty? } .map do |k, v| case k.to_s when 'errors' then { text: v.join("\n"), color: 'danger' } when 'warnings' then { text: v.join("\n"), color: 'warning' } when 'messages' then { text: v.join("\n"), color: 'good' } when 'markdowns' then v.map do |val| { text: val.message, fields: fields(val) } end end end attachment.flatten end
ruby
def report attachment = status_report .reject { |_, v| v.empty? } .map do |k, v| case k.to_s when 'errors' then { text: v.join("\n"), color: 'danger' } when 'warnings' then { text: v.join("\n"), color: 'warning' } when 'messages' then { text: v.join("\n"), color: 'good' } when 'markdowns' then v.map do |val| { text: val.message, fields: fields(val) } end end end attachment.flatten end
[ "def", "report", "attachment", "=", "status_report", ".", "reject", "{", "|", "_", ",", "v", "|", "v", ".", "empty?", "}", ".", "map", "do", "|", "k", ",", "v", "|", "case", "k", ".", "to_s", "when", "'errors'", "then", "{", "text", ":", "v", ".", "join", "(", "\"\\n\"", ")", ",", "color", ":", "'danger'", "}", "when", "'warnings'", "then", "{", "text", ":", "v", ".", "join", "(", "\"\\n\"", ")", ",", "color", ":", "'warning'", "}", "when", "'messages'", "then", "{", "text", ":", "v", ".", "join", "(", "\"\\n\"", ")", ",", "color", ":", "'good'", "}", "when", "'markdowns'", "then", "v", ".", "map", "do", "|", "val", "|", "{", "text", ":", "val", ".", "message", ",", "fields", ":", "fields", "(", "val", ")", "}", "end", "end", "end", "attachment", ".", "flatten", "end" ]
get status_report text @return [[Hash]]
[ "get", "status_report", "text" ]
a5e7b7fa50fe4d7ee4d1e9f2e4d3afc9befafa18
https://github.com/duck8823/danger-slack/blob/a5e7b7fa50fe4d7ee4d1e9f2e4d3afc9befafa18/lib/slack/plugin.rb#L98-L128
train
duck8823/danger-slack
lib/slack/plugin.rb
Danger.DangerSlack.fields
def fields(markdown) fields = [] if markdown.file fields.push(title: 'file', value: markdown.file, short: true) end if markdown.line fields.push(title: 'line', value: markdown.line, short: true) end fields end
ruby
def fields(markdown) fields = [] if markdown.file fields.push(title: 'file', value: markdown.file, short: true) end if markdown.line fields.push(title: 'line', value: markdown.line, short: true) end fields end
[ "def", "fields", "(", "markdown", ")", "fields", "=", "[", "]", "if", "markdown", ".", "file", "fields", ".", "push", "(", "title", ":", "'file'", ",", "value", ":", "markdown", ".", "file", ",", "short", ":", "true", ")", "end", "if", "markdown", ".", "line", "fields", ".", "push", "(", "title", ":", "'line'", ",", "value", ":", "markdown", ".", "line", ",", "short", ":", "true", ")", "end", "fields", "end" ]
get markdown fields @return [[Hash]]
[ "get", "markdown", "fields" ]
a5e7b7fa50fe4d7ee4d1e9f2e4d3afc9befafa18
https://github.com/duck8823/danger-slack/blob/a5e7b7fa50fe4d7ee4d1e9f2e4d3afc9befafa18/lib/slack/plugin.rb#L132-L145
train
erichmenge/signed_form
lib/signed_form/form_builder.rb
SignedForm.FormBuilder.fields_for
def fields_for(record_name, record_object = nil, fields_options = {}, &block) hash = {} array = [] if nested_attributes_association?(record_name) hash["#{record_name}_attributes"] = fields_options[:signed_attributes_context] = array else hash[record_name] = fields_options[:signed_attributes_context] = array end add_signed_fields hash content = super array.uniq! content end
ruby
def fields_for(record_name, record_object = nil, fields_options = {}, &block) hash = {} array = [] if nested_attributes_association?(record_name) hash["#{record_name}_attributes"] = fields_options[:signed_attributes_context] = array else hash[record_name] = fields_options[:signed_attributes_context] = array end add_signed_fields hash content = super array.uniq! content end
[ "def", "fields_for", "(", "record_name", ",", "record_object", "=", "nil", ",", "fields_options", "=", "{", "}", ",", "&", "block", ")", "hash", "=", "{", "}", "array", "=", "[", "]", "if", "nested_attributes_association?", "(", "record_name", ")", "hash", "[", "\"#{record_name}_attributes\"", "]", "=", "fields_options", "[", ":signed_attributes_context", "]", "=", "array", "else", "hash", "[", "record_name", "]", "=", "fields_options", "[", ":signed_attributes_context", "]", "=", "array", "end", "add_signed_fields", "hash", "content", "=", "super", "array", ".", "uniq!", "content", "end" ]
Wrapper for Rails fields_for @see http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-fields_for
[ "Wrapper", "for", "Rails", "fields_for" ]
ea3842888e78035b7da3fc28f7eaa220d4fc8640
https://github.com/erichmenge/signed_form/blob/ea3842888e78035b7da3fc28f7eaa220d4fc8640/lib/signed_form/form_builder.rb#L65-L80
train
datamapper/dm-migrations
lib/dm-migrations/migration.rb
DataMapper.Migration.say_with_time
def say_with_time(message, indent = 2) say(message, indent) result = nil time = Benchmark.measure { result = yield } say("-> %.4fs" % time.real, indent) result end
ruby
def say_with_time(message, indent = 2) say(message, indent) result = nil time = Benchmark.measure { result = yield } say("-> %.4fs" % time.real, indent) result end
[ "def", "say_with_time", "(", "message", ",", "indent", "=", "2", ")", "say", "(", "message", ",", "indent", ")", "result", "=", "nil", "time", "=", "Benchmark", ".", "measure", "{", "result", "=", "yield", "}", "say", "(", "\"-> %.4fs\"", "%", "time", ".", "real", ",", "indent", ")", "result", "end" ]
Time how long the block takes to run, and output it with the message.
[ "Time", "how", "long", "the", "block", "takes", "to", "run", "and", "output", "it", "with", "the", "message", "." ]
ca96baac4072b7a4bf442c11da099c7f1461346d
https://github.com/datamapper/dm-migrations/blob/ca96baac4072b7a4bf442c11da099c7f1461346d/lib/dm-migrations/migration.rb#L207-L213
train
datamapper/dm-migrations
lib/dm-migrations/migration.rb
DataMapper.Migration.update_migration_info
def update_migration_info(direction) save, @verbose = @verbose, false create_migration_info_table_if_needed if direction.to_sym == :up execute("INSERT INTO #{migration_info_table} (#{migration_name_column}) VALUES (#{quoted_name})") elsif direction.to_sym == :down execute("DELETE FROM #{migration_info_table} WHERE #{migration_name_column} = #{quoted_name}") end @verbose = save end
ruby
def update_migration_info(direction) save, @verbose = @verbose, false create_migration_info_table_if_needed if direction.to_sym == :up execute("INSERT INTO #{migration_info_table} (#{migration_name_column}) VALUES (#{quoted_name})") elsif direction.to_sym == :down execute("DELETE FROM #{migration_info_table} WHERE #{migration_name_column} = #{quoted_name}") end @verbose = save end
[ "def", "update_migration_info", "(", "direction", ")", "save", ",", "@verbose", "=", "@verbose", ",", "false", "create_migration_info_table_if_needed", "if", "direction", ".", "to_sym", "==", ":up", "execute", "(", "\"INSERT INTO #{migration_info_table} (#{migration_name_column}) VALUES (#{quoted_name})\"", ")", "elsif", "direction", ".", "to_sym", "==", ":down", "execute", "(", "\"DELETE FROM #{migration_info_table} WHERE #{migration_name_column} = #{quoted_name}\"", ")", "end", "@verbose", "=", "save", "end" ]
Inserts or removes a row into the `migration_info` table, so we can mark this migration as run, or un-done
[ "Inserts", "or", "removes", "a", "row", "into", "the", "migration_info", "table", "so", "we", "can", "mark", "this", "migration", "as", "run", "or", "un", "-", "done" ]
ca96baac4072b7a4bf442c11da099c7f1461346d
https://github.com/datamapper/dm-migrations/blob/ca96baac4072b7a4bf442c11da099c7f1461346d/lib/dm-migrations/migration.rb#L221-L232
train
datamapper/dm-migrations
lib/dm-migrations/migration.rb
DataMapper.Migration.setup!
def setup! @adapter = DataMapper.repository(@repository).adapter case @adapter.class.name when /Sqlite/ then @adapter.extend(SQL::Sqlite) when /Mysql/ then @adapter.extend(SQL::Mysql) when /Postgres/ then @adapter.extend(SQL::Postgres) when /Sqlserver/ then @adapter.extend(SQL::Sqlserver) when /Oracle/ then @adapter.extend(SQL::Oracle) else raise(RuntimeError,"Unsupported Migration Adapter #{@adapter.class}",caller) end end
ruby
def setup! @adapter = DataMapper.repository(@repository).adapter case @adapter.class.name when /Sqlite/ then @adapter.extend(SQL::Sqlite) when /Mysql/ then @adapter.extend(SQL::Mysql) when /Postgres/ then @adapter.extend(SQL::Postgres) when /Sqlserver/ then @adapter.extend(SQL::Sqlserver) when /Oracle/ then @adapter.extend(SQL::Oracle) else raise(RuntimeError,"Unsupported Migration Adapter #{@adapter.class}",caller) end end
[ "def", "setup!", "@adapter", "=", "DataMapper", ".", "repository", "(", "@repository", ")", ".", "adapter", "case", "@adapter", ".", "class", ".", "name", "when", "/", "/", "then", "@adapter", ".", "extend", "(", "SQL", "::", "Sqlite", ")", "when", "/", "/", "then", "@adapter", ".", "extend", "(", "SQL", "::", "Mysql", ")", "when", "/", "/", "then", "@adapter", ".", "extend", "(", "SQL", "::", "Postgres", ")", "when", "/", "/", "then", "@adapter", ".", "extend", "(", "SQL", "::", "Sqlserver", ")", "when", "/", "/", "then", "@adapter", ".", "extend", "(", "SQL", "::", "Oracle", ")", "else", "raise", "(", "RuntimeError", ",", "\"Unsupported Migration Adapter #{@adapter.class}\"", ",", "caller", ")", "end", "end" ]
Sets up the migration. @since 1.0.1
[ "Sets", "up", "the", "migration", "." ]
ca96baac4072b7a4bf442c11da099c7f1461346d
https://github.com/datamapper/dm-migrations/blob/ca96baac4072b7a4bf442c11da099c7f1461346d/lib/dm-migrations/migration.rb#L308-L320
train
datamapper/dm-migrations
lib/dm-migrations/migration_runner.rb
DataMapper.MigrationRunner.migration
def migration( number, name, opts = {}, &block ) raise "Migration name conflict: '#{name}'" if migrations.map { |m| m.name }.include?(name.to_s) migrations << DataMapper::Migration.new( number, name.to_s, opts, &block ) end
ruby
def migration( number, name, opts = {}, &block ) raise "Migration name conflict: '#{name}'" if migrations.map { |m| m.name }.include?(name.to_s) migrations << DataMapper::Migration.new( number, name.to_s, opts, &block ) end
[ "def", "migration", "(", "number", ",", "name", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "raise", "\"Migration name conflict: '#{name}'\"", "if", "migrations", ".", "map", "{", "|", "m", "|", "m", ".", "name", "}", ".", "include?", "(", "name", ".", "to_s", ")", "migrations", "<<", "DataMapper", "::", "Migration", ".", "new", "(", "number", ",", "name", ".", "to_s", ",", "opts", ",", "&", "block", ")", "end" ]
Creates a new migration, and adds it to the list of migrations to be run. Migrations can be defined in any order, they will be sorted and run in the correct order. The order that migrations are run in is set by the first argument. It is not neccessary that this be unique; migrations with the same version number are expected to be able to be run in any order. The second argument is the name of the migration. This name is used internally to track if the migration has been run. It is required that this name be unique across all migrations. Addtionally, it accepts a number of options: * <tt>:database</tt> If you defined several DataMapper::database instances use this to choose which one to run the migration gagainst. Defaults to <tt>:default</tt>. Migrations are tracked individually per database. * <tt>:verbose</tt> true/false, defaults to true. Determines if the migration should output its status messages when it runs. Example of a simple migration: migration( 1, :create_people_table ) do up do create_table :people do column :id, Integer, :serial => true column :name, String, :size => 50 column :age, Integer end end down do drop_table :people end end Its recommended that you stick with raw SQL for migrations that manipulate data. If you write a migration using a model, then later change the model, there's a possibility the migration will no longer work. Using SQL will always work.
[ "Creates", "a", "new", "migration", "and", "adds", "it", "to", "the", "list", "of", "migrations", "to", "be", "run", ".", "Migrations", "can", "be", "defined", "in", "any", "order", "they", "will", "be", "sorted", "and", "run", "in", "the", "correct", "order", "." ]
ca96baac4072b7a4bf442c11da099c7f1461346d
https://github.com/datamapper/dm-migrations/blob/ca96baac4072b7a4bf442c11da099c7f1461346d/lib/dm-migrations/migration_runner.rb#L42-L46
train
datamapper/dm-migrations
lib/dm-migrations/migration_runner.rb
DataMapper.MigrationRunner.migrate_up!
def migrate_up!(level = nil) migrations.sort.each do |migration| if level.nil? migration.perform_up() else migration.perform_up() if migration.position <= level.to_i end end end
ruby
def migrate_up!(level = nil) migrations.sort.each do |migration| if level.nil? migration.perform_up() else migration.perform_up() if migration.position <= level.to_i end end end
[ "def", "migrate_up!", "(", "level", "=", "nil", ")", "migrations", ".", "sort", ".", "each", "do", "|", "migration", "|", "if", "level", ".", "nil?", "migration", ".", "perform_up", "(", ")", "else", "migration", ".", "perform_up", "(", ")", "if", "migration", ".", "position", "<=", "level", ".", "to_i", "end", "end", "end" ]
Run all migrations that need to be run. In most cases, this would be called by a rake task as part of a larger project, but this provides the ability to run them in a script or test. has an optional argument 'level' which if supplied, only performs the migrations with a position less than or equal to the level.
[ "Run", "all", "migrations", "that", "need", "to", "be", "run", ".", "In", "most", "cases", "this", "would", "be", "called", "by", "a", "rake", "task", "as", "part", "of", "a", "larger", "project", "but", "this", "provides", "the", "ability", "to", "run", "them", "in", "a", "script", "or", "test", "." ]
ca96baac4072b7a4bf442c11da099c7f1461346d
https://github.com/datamapper/dm-migrations/blob/ca96baac4072b7a4bf442c11da099c7f1461346d/lib/dm-migrations/migration_runner.rb#L54-L62
train
datamapper/dm-migrations
lib/dm-migrations/migration_runner.rb
DataMapper.MigrationRunner.migrate_down!
def migrate_down!(level = nil) migrations.sort.reverse.each do |migration| if level.nil? migration.perform_down() else migration.perform_down() if migration.position > level.to_i end end end
ruby
def migrate_down!(level = nil) migrations.sort.reverse.each do |migration| if level.nil? migration.perform_down() else migration.perform_down() if migration.position > level.to_i end end end
[ "def", "migrate_down!", "(", "level", "=", "nil", ")", "migrations", ".", "sort", ".", "reverse", ".", "each", "do", "|", "migration", "|", "if", "level", ".", "nil?", "migration", ".", "perform_down", "(", ")", "else", "migration", ".", "perform_down", "(", ")", "if", "migration", ".", "position", ">", "level", ".", "to_i", "end", "end", "end" ]
Run all the down steps for the migrations that have already been run. has an optional argument 'level' which, if supplied, only performs the down migrations with a postion greater than the level.
[ "Run", "all", "the", "down", "steps", "for", "the", "migrations", "that", "have", "already", "been", "run", "." ]
ca96baac4072b7a4bf442c11da099c7f1461346d
https://github.com/datamapper/dm-migrations/blob/ca96baac4072b7a4bf442c11da099c7f1461346d/lib/dm-migrations/migration_runner.rb#L68-L76
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.copy
def copy(from_path, to_path) resp = request('/files/copy', from_path: from_path, to_path: to_path) parse_tagged_response(resp) end
ruby
def copy(from_path, to_path) resp = request('/files/copy', from_path: from_path, to_path: to_path) parse_tagged_response(resp) end
[ "def", "copy", "(", "from_path", ",", "to_path", ")", "resp", "=", "request", "(", "'/files/copy'", ",", "from_path", ":", "from_path", ",", "to_path", ":", "to_path", ")", "parse_tagged_response", "(", "resp", ")", "end" ]
Copy a file or folder to a different location in the user's Dropbox. @param [String] from_path @param [String] to_path @return [Dropbox::Metadata]
[ "Copy", "a", "file", "or", "folder", "to", "a", "different", "location", "in", "the", "user", "s", "Dropbox", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L30-L33
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.get_copy_reference
def get_copy_reference(path) resp = request('/files/copy_reference/get', path: path) metadata = parse_tagged_response(resp['metadata']) return metadata, resp['copy_reference'] end
ruby
def get_copy_reference(path) resp = request('/files/copy_reference/get', path: path) metadata = parse_tagged_response(resp['metadata']) return metadata, resp['copy_reference'] end
[ "def", "get_copy_reference", "(", "path", ")", "resp", "=", "request", "(", "'/files/copy_reference/get'", ",", "path", ":", "path", ")", "metadata", "=", "parse_tagged_response", "(", "resp", "[", "'metadata'", "]", ")", "return", "metadata", ",", "resp", "[", "'copy_reference'", "]", "end" ]
Get a copy reference to a file or folder. @param [String] path @return [Dropbox::Metadata] metadata @return [String] copy_reference
[ "Get", "a", "copy", "reference", "to", "a", "file", "or", "folder", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L40-L44
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.save_copy_reference
def save_copy_reference(copy_reference, path) resp = request('/files/copy_reference/save', copy_reference: copy_reference, path: path) parse_tagged_response(resp['metadata']) end
ruby
def save_copy_reference(copy_reference, path) resp = request('/files/copy_reference/save', copy_reference: copy_reference, path: path) parse_tagged_response(resp['metadata']) end
[ "def", "save_copy_reference", "(", "copy_reference", ",", "path", ")", "resp", "=", "request", "(", "'/files/copy_reference/save'", ",", "copy_reference", ":", "copy_reference", ",", "path", ":", "path", ")", "parse_tagged_response", "(", "resp", "[", "'metadata'", "]", ")", "end" ]
Save a copy reference to the user's Dropbox. @param [String] copy_reference @param [String] path @return [Dropbox::Metadata] metadata
[ "Save", "a", "copy", "reference", "to", "the", "user", "s", "Dropbox", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L51-L54
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.download
def download(path) resp, body = content_request('/files/download', path: path) return FileMetadata.new(resp), body end
ruby
def download(path) resp, body = content_request('/files/download', path: path) return FileMetadata.new(resp), body end
[ "def", "download", "(", "path", ")", "resp", ",", "body", "=", "content_request", "(", "'/files/download'", ",", "path", ":", "path", ")", "return", "FileMetadata", ".", "new", "(", "resp", ")", ",", "body", "end" ]
Download a file from a user's Dropbox. @param [String] path @return [Dropbox::FileMetadata] metadata @return [HTTP::Response::Body] body
[ "Download", "a", "file", "from", "a", "user", "s", "Dropbox", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L79-L82
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.get_preview
def get_preview(path) resp, body = content_request('/files/get_preview', path: path) return FileMetadata.new(resp), body end
ruby
def get_preview(path) resp, body = content_request('/files/get_preview', path: path) return FileMetadata.new(resp), body end
[ "def", "get_preview", "(", "path", ")", "resp", ",", "body", "=", "content_request", "(", "'/files/get_preview'", ",", "path", ":", "path", ")", "return", "FileMetadata", ".", "new", "(", "resp", ")", ",", "body", "end" ]
Get a preview for a file. @param [String] path @return [Dropbox::FileMetadata] metadata @return [HTTP::Response::Body] body
[ "Get", "a", "preview", "for", "a", "file", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L98-L101
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.get_temporary_link
def get_temporary_link(path) resp = request('/files/get_temporary_link', path: path) return FileMetadata.new(resp['metadata']), resp['link'] end
ruby
def get_temporary_link(path) resp = request('/files/get_temporary_link', path: path) return FileMetadata.new(resp['metadata']), resp['link'] end
[ "def", "get_temporary_link", "(", "path", ")", "resp", "=", "request", "(", "'/files/get_temporary_link'", ",", "path", ":", "path", ")", "return", "FileMetadata", ".", "new", "(", "resp", "[", "'metadata'", "]", ")", ",", "resp", "[", "'link'", "]", "end" ]
Get a temporary link to stream content of a file. @param [String] path @return [Dropbox::FileMetadata] metadata @return [String] link
[ "Get", "a", "temporary", "link", "to", "stream", "content", "of", "a", "file", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L108-L111
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.get_thumbnail
def get_thumbnail(path, format='jpeg', size='w64h64') resp, body = content_request('/files/get_thumbnail', path: path, format: format, size: size) return FileMetadata.new(resp), body end
ruby
def get_thumbnail(path, format='jpeg', size='w64h64') resp, body = content_request('/files/get_thumbnail', path: path, format: format, size: size) return FileMetadata.new(resp), body end
[ "def", "get_thumbnail", "(", "path", ",", "format", "=", "'jpeg'", ",", "size", "=", "'w64h64'", ")", "resp", ",", "body", "=", "content_request", "(", "'/files/get_thumbnail'", ",", "path", ":", "path", ",", "format", ":", "format", ",", "size", ":", "size", ")", "return", "FileMetadata", ".", "new", "(", "resp", ")", ",", "body", "end" ]
Get a thumbnail for an image. @param [String] path @param [String] format @param [String] size @return [Dropbox::FileMetadata] metadata @return [HTTP::Response::Body] body
[ "Get", "a", "thumbnail", "for", "an", "image", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L120-L123
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.list_folder
def list_folder(path) resp = request('/files/list_folder', path: path) resp['entries'].map { |e| parse_tagged_response(e) } end
ruby
def list_folder(path) resp = request('/files/list_folder', path: path) resp['entries'].map { |e| parse_tagged_response(e) } end
[ "def", "list_folder", "(", "path", ")", "resp", "=", "request", "(", "'/files/list_folder'", ",", "path", ":", "path", ")", "resp", "[", "'entries'", "]", ".", "map", "{", "|", "e", "|", "parse_tagged_response", "(", "e", ")", "}", "end" ]
Get the contents of a folder. @param [String] path @return [Array<Dropbox::Metadata>]
[ "Get", "the", "contents", "of", "a", "folder", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L129-L132
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.continue_list_folder
def continue_list_folder(cursor) resp = request('/files/list_folder/continue', cursor: cursor) resp['entries'].map { |e| parse_tagged_response(e) } end
ruby
def continue_list_folder(cursor) resp = request('/files/list_folder/continue', cursor: cursor) resp['entries'].map { |e| parse_tagged_response(e) } end
[ "def", "continue_list_folder", "(", "cursor", ")", "resp", "=", "request", "(", "'/files/list_folder/continue'", ",", "cursor", ":", "cursor", ")", "resp", "[", "'entries'", "]", ".", "map", "{", "|", "e", "|", "parse_tagged_response", "(", "e", ")", "}", "end" ]
Get the contents of a folder that are after a cursor. @param [String] cursor @return [Array<Dropbox::Metadata>]
[ "Get", "the", "contents", "of", "a", "folder", "that", "are", "after", "a", "cursor", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L138-L141
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.list_revisions
def list_revisions(path) resp = request('/files/list_revisions', path: path) entries = resp['entries'].map { |e| FileMetadata.new(e) } return entries, resp['is_deleted'] end
ruby
def list_revisions(path) resp = request('/files/list_revisions', path: path) entries = resp['entries'].map { |e| FileMetadata.new(e) } return entries, resp['is_deleted'] end
[ "def", "list_revisions", "(", "path", ")", "resp", "=", "request", "(", "'/files/list_revisions'", ",", "path", ":", "path", ")", "entries", "=", "resp", "[", "'entries'", "]", ".", "map", "{", "|", "e", "|", "FileMetadata", ".", "new", "(", "e", ")", "}", "return", "entries", ",", "resp", "[", "'is_deleted'", "]", "end" ]
Get the revisions of a file. @param [String] path @return [Array<Dropbox::FileMetadata>] entries @return [Boolean] is_deleted
[ "Get", "the", "revisions", "of", "a", "file", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L157-L161
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.move
def move(from_path, to_path) resp = request('/files/move', from_path: from_path, to_path: to_path) parse_tagged_response(resp) end
ruby
def move(from_path, to_path) resp = request('/files/move', from_path: from_path, to_path: to_path) parse_tagged_response(resp) end
[ "def", "move", "(", "from_path", ",", "to_path", ")", "resp", "=", "request", "(", "'/files/move'", ",", "from_path", ":", "from_path", ",", "to_path", ":", "to_path", ")", "parse_tagged_response", "(", "resp", ")", "end" ]
Move a file or folder to a different location in the user's Dropbox. @param [String] from_path @param [String] to_path @return [Dropbox::Metadata]
[ "Move", "a", "file", "or", "folder", "to", "a", "different", "location", "in", "the", "user", "s", "Dropbox", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L168-L171
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.restore
def restore(path, rev) resp = request('/files/restore', path: path, rev: rev) FileMetadata.new(resp) end
ruby
def restore(path, rev) resp = request('/files/restore', path: path, rev: rev) FileMetadata.new(resp) end
[ "def", "restore", "(", "path", ",", "rev", ")", "resp", "=", "request", "(", "'/files/restore'", ",", "path", ":", "path", ",", "rev", ":", "rev", ")", "FileMetadata", ".", "new", "(", "resp", ")", "end" ]
Restore a file to a specific revision. @param [String] path @param [String] rev @return [Dropbox::FileMetadata]
[ "Restore", "a", "file", "to", "a", "specific", "revision", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L187-L190
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.save_url
def save_url(path, url) resp = request('/files/save_url', path: path, url: url) parse_tagged_response(resp) end
ruby
def save_url(path, url) resp = request('/files/save_url', path: path, url: url) parse_tagged_response(resp) end
[ "def", "save_url", "(", "path", ",", "url", ")", "resp", "=", "request", "(", "'/files/save_url'", ",", "path", ":", "path", ",", "url", ":", "url", ")", "parse_tagged_response", "(", "resp", ")", "end" ]
Save a specified URL into a file in user's Dropbox. @param [String] path @param [String] url @return [String] the job id, if the processing is asynchronous. @return [Dropbox::FileMetadata] if the processing is synchronous.
[ "Save", "a", "specified", "URL", "into", "a", "file", "in", "user", "s", "Dropbox", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L198-L201
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.search
def search(path, query, start=0, max_results=100, mode='filename') resp = request('/files/search', path: path, query: query, start: start, max_results: max_results, mode: mode) matches = resp['matches'].map { |m| parse_tagged_response(m['metadata']) } return matches end
ruby
def search(path, query, start=0, max_results=100, mode='filename') resp = request('/files/search', path: path, query: query, start: start, max_results: max_results, mode: mode) matches = resp['matches'].map { |m| parse_tagged_response(m['metadata']) } return matches end
[ "def", "search", "(", "path", ",", "query", ",", "start", "=", "0", ",", "max_results", "=", "100", ",", "mode", "=", "'filename'", ")", "resp", "=", "request", "(", "'/files/search'", ",", "path", ":", "path", ",", "query", ":", "query", ",", "start", ":", "start", ",", "max_results", ":", "max_results", ",", "mode", ":", "mode", ")", "matches", "=", "resp", "[", "'matches'", "]", ".", "map", "{", "|", "m", "|", "parse_tagged_response", "(", "m", "[", "'metadata'", "]", ")", "}", "return", "matches", "end" ]
Search for files and folders. @param [String] path @param [String] query @param [Integer] start @param [Integer] max_results @param [String] mode @return [Array<Dropbox::Metadata>] matches
[ "Search", "for", "files", "and", "folders", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L222-L227
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.upload
def upload(path, body, options={}) options[:client_modified] = Time.now.utc.iso8601 options[:path] = path resp = upload_request('/files/upload', body, options.merge(path: path)) FileMetadata.new(resp) end
ruby
def upload(path, body, options={}) options[:client_modified] = Time.now.utc.iso8601 options[:path] = path resp = upload_request('/files/upload', body, options.merge(path: path)) FileMetadata.new(resp) end
[ "def", "upload", "(", "path", ",", "body", ",", "options", "=", "{", "}", ")", "options", "[", ":client_modified", "]", "=", "Time", ".", "now", ".", "utc", ".", "iso8601", "options", "[", ":path", "]", "=", "path", "resp", "=", "upload_request", "(", "'/files/upload'", ",", "body", ",", "options", ".", "merge", "(", "path", ":", "path", ")", ")", "FileMetadata", ".", "new", "(", "resp", ")", "end" ]
Create a new file. @param [String] path @param [String, Enumerable] body @option options [String] :mode @option options [Boolean] :autorename @option options [Boolean] :mute @return [Dropbox::FileMetadata]
[ "Create", "a", "new", "file", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L237-L242
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.start_upload_session
def start_upload_session(body, close=false) resp = upload_request('/files/upload_session/start', body, close: close) UploadSessionCursor.new(resp['session_id'], body.length) end
ruby
def start_upload_session(body, close=false) resp = upload_request('/files/upload_session/start', body, close: close) UploadSessionCursor.new(resp['session_id'], body.length) end
[ "def", "start_upload_session", "(", "body", ",", "close", "=", "false", ")", "resp", "=", "upload_request", "(", "'/files/upload_session/start'", ",", "body", ",", "close", ":", "close", ")", "UploadSessionCursor", ".", "new", "(", "resp", "[", "'session_id'", "]", ",", "body", ".", "length", ")", "end" ]
Start an upload session to upload a file using multiple requests. @param [String, Enumerable] body @param [Boolean] close @return [Dropbox::UploadSessionCursor] cursor
[ "Start", "an", "upload", "session", "to", "upload", "a", "file", "using", "multiple", "requests", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L249-L252
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.append_upload_session
def append_upload_session(cursor, body, close=false) args = {cursor: cursor.to_h, close: close} resp = upload_request('/files/upload_session/append_v2', body, args) cursor.offset += body.length cursor end
ruby
def append_upload_session(cursor, body, close=false) args = {cursor: cursor.to_h, close: close} resp = upload_request('/files/upload_session/append_v2', body, args) cursor.offset += body.length cursor end
[ "def", "append_upload_session", "(", "cursor", ",", "body", ",", "close", "=", "false", ")", "args", "=", "{", "cursor", ":", "cursor", ".", "to_h", ",", "close", ":", "close", "}", "resp", "=", "upload_request", "(", "'/files/upload_session/append_v2'", ",", "body", ",", "args", ")", "cursor", ".", "offset", "+=", "body", ".", "length", "cursor", "end" ]
Append more data to an upload session. @param [Dropbox::UploadSessionCursor] cursor @param [String, Enumerable] body @param [Boolean] close @return [Dropbox::UploadSessionCursor] cursor
[ "Append", "more", "data", "to", "an", "upload", "session", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L260-L265
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.finish_upload_session
def finish_upload_session(cursor, path, body, options={}) options[:client_modified] = Time.now.utc.iso8601 options[:path] = path args = {cursor: cursor.to_h, commit: options} resp = upload_request('/files/upload_session/finish', body, args) FileMetadata.new(resp) end
ruby
def finish_upload_session(cursor, path, body, options={}) options[:client_modified] = Time.now.utc.iso8601 options[:path] = path args = {cursor: cursor.to_h, commit: options} resp = upload_request('/files/upload_session/finish', body, args) FileMetadata.new(resp) end
[ "def", "finish_upload_session", "(", "cursor", ",", "path", ",", "body", ",", "options", "=", "{", "}", ")", "options", "[", ":client_modified", "]", "=", "Time", ".", "now", ".", "utc", ".", "iso8601", "options", "[", ":path", "]", "=", "path", "args", "=", "{", "cursor", ":", "cursor", ".", "to_h", ",", "commit", ":", "options", "}", "resp", "=", "upload_request", "(", "'/files/upload_session/finish'", ",", "body", ",", "args", ")", "FileMetadata", ".", "new", "(", "resp", ")", "end" ]
Finish an upload session and save the uploaded data to the given file path. @param [Dropbox::UploadSessionCursor] cursor @param [String] path @param [String, Enumerable] body @param [Hash] options @option (see #upload) @return [Dropbox::FileMetadata]
[ "Finish", "an", "upload", "session", "and", "save", "the", "uploaded", "data", "to", "the", "given", "file", "path", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L275-L281
train
waits/dropbox-sdk-ruby
lib/dropbox/client.rb
Dropbox.Client.get_account_batch
def get_account_batch(account_ids) resp = request('/users/get_account_batch', account_ids: account_ids) resp.map { |a| BasicAccount.new(a) } end
ruby
def get_account_batch(account_ids) resp = request('/users/get_account_batch', account_ids: account_ids) resp.map { |a| BasicAccount.new(a) } end
[ "def", "get_account_batch", "(", "account_ids", ")", "resp", "=", "request", "(", "'/users/get_account_batch'", ",", "account_ids", ":", "account_ids", ")", "resp", ".", "map", "{", "|", "a", "|", "BasicAccount", ".", "new", "(", "a", ")", "}", "end" ]
Get information about multiple user accounts. @param [Array<String>] account_ids @return [Array<Dropbox::BasicAccount>]
[ "Get", "information", "about", "multiple", "user", "accounts", "." ]
fb99660f8c2fdfcd6818f605a3cf3061bc21c189
https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L296-L299
train
piotrmurach/tty-editor
lib/tty/editor.rb
TTY.Editor.tempfile_path
def tempfile_path(content) tempfile = Tempfile.new('tty-editor') tempfile << content tempfile.flush unless tempfile.nil? tempfile.close end tempfile.path end
ruby
def tempfile_path(content) tempfile = Tempfile.new('tty-editor') tempfile << content tempfile.flush unless tempfile.nil? tempfile.close end tempfile.path end
[ "def", "tempfile_path", "(", "content", ")", "tempfile", "=", "Tempfile", ".", "new", "(", "'tty-editor'", ")", "tempfile", "<<", "content", "tempfile", ".", "flush", "unless", "tempfile", ".", "nil?", "tempfile", ".", "close", "end", "tempfile", ".", "path", "end" ]
Create tempfile with content @param [String] content @return [String] @api private
[ "Create", "tempfile", "with", "content" ]
e8a2082cbe5f160248c35a1baf6e891a017614e3
https://github.com/piotrmurach/tty-editor/blob/e8a2082cbe5f160248c35a1baf6e891a017614e3/lib/tty/editor.rb#L187-L195
train
piotrmurach/tty-editor
lib/tty/editor.rb
TTY.Editor.open
def open status = system(env, *Shellwords.split(command_path)) return status if status fail CommandInvocationError, "`#{command_path}` failed with status: #{$? ? $?.exitstatus : nil}" end
ruby
def open status = system(env, *Shellwords.split(command_path)) return status if status fail CommandInvocationError, "`#{command_path}` failed with status: #{$? ? $?.exitstatus : nil}" end
[ "def", "open", "status", "=", "system", "(", "env", ",", "*", "Shellwords", ".", "split", "(", "command_path", ")", ")", "return", "status", "if", "status", "fail", "CommandInvocationError", ",", "\"`#{command_path}` failed with status: #{$? ? $?.exitstatus : nil}\"", "end" ]
Inovke editor command in a shell @raise [TTY::CommandInvocationError] @api private
[ "Inovke", "editor", "command", "in", "a", "shell" ]
e8a2082cbe5f160248c35a1baf6e891a017614e3
https://github.com/piotrmurach/tty-editor/blob/e8a2082cbe5f160248c35a1baf6e891a017614e3/lib/tty/editor.rb#L202-L207
train
rvm/rvm-gem
lib/rvm/environment/gemset.rb
RVM.Environment.gemset_globalcache
def gemset_globalcache(enable = true) case enable when "enabled", :enabled run(:__rvm_using_gemset_globalcache).successful? when true, "enable", :enable rvm(:gemset, :globalcache, :enable).successful? when false, "disable", :disable rvm(:gemset, :globalcache, :disable).successful? else false end end
ruby
def gemset_globalcache(enable = true) case enable when "enabled", :enabled run(:__rvm_using_gemset_globalcache).successful? when true, "enable", :enable rvm(:gemset, :globalcache, :enable).successful? when false, "disable", :disable rvm(:gemset, :globalcache, :disable).successful? else false end end
[ "def", "gemset_globalcache", "(", "enable", "=", "true", ")", "case", "enable", "when", "\"enabled\"", ",", ":enabled", "run", "(", ":__rvm_using_gemset_globalcache", ")", ".", "successful?", "when", "true", ",", "\"enable\"", ",", ":enable", "rvm", "(", ":gemset", ",", ":globalcache", ",", ":enable", ")", ".", "successful?", "when", "false", ",", "\"disable\"", ",", ":disable", "rvm", "(", ":gemset", ",", ":globalcache", ",", ":disable", ")", ".", "successful?", "else", "false", "end", "end" ]
Enable or disable the rvm gem global cache.
[ "Enable", "or", "disable", "the", "rvm", "gem", "global", "cache", "." ]
7ef58904108a1abf1dbabafc605ece1fc9c53668
https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/gemset.rb#L66-L77
train
take-five/acts_as_ordered_tree
lib/acts_as_ordered_tree/node.rb
ActsAsOrderedTree.Node.scope
def scope if tree.columns.scope? tree.base_class.where Hash[tree.columns.scope.map { |column| [column, record[column]] }] else tree.base_class.where(nil) end end
ruby
def scope if tree.columns.scope? tree.base_class.where Hash[tree.columns.scope.map { |column| [column, record[column]] }] else tree.base_class.where(nil) end end
[ "def", "scope", "if", "tree", ".", "columns", ".", "scope?", "tree", ".", "base_class", ".", "where", "Hash", "[", "tree", ".", "columns", ".", "scope", ".", "map", "{", "|", "column", "|", "[", "column", ",", "record", "[", "column", "]", "]", "}", "]", "else", "tree", ".", "base_class", ".", "where", "(", "nil", ")", "end", "end" ]
Returns scope to which record should be applied
[ "Returns", "scope", "to", "which", "record", "should", "be", "applied" ]
082b08d7e5560256d09987bfb015d684f93b56ed
https://github.com/take-five/acts_as_ordered_tree/blob/082b08d7e5560256d09987bfb015d684f93b56ed/lib/acts_as_ordered_tree/node.rb#L31-L37
train
take-five/acts_as_ordered_tree
lib/acts_as_ordered_tree/position.rb
ActsAsOrderedTree.Position.lower
def lower position? ? siblings.where(klass.arel_table[klass.ordered_tree.columns.position].gteq(position)) : siblings end
ruby
def lower position? ? siblings.where(klass.arel_table[klass.ordered_tree.columns.position].gteq(position)) : siblings end
[ "def", "lower", "position?", "?", "siblings", ".", "where", "(", "klass", ".", "arel_table", "[", "klass", ".", "ordered_tree", ".", "columns", ".", "position", "]", ".", "gteq", "(", "position", ")", ")", ":", "siblings", "end" ]
Returns all nodes that are lower than current position
[ "Returns", "all", "nodes", "that", "are", "lower", "than", "current", "position" ]
082b08d7e5560256d09987bfb015d684f93b56ed
https://github.com/take-five/acts_as_ordered_tree/blob/082b08d7e5560256d09987bfb015d684f93b56ed/lib/acts_as_ordered_tree/position.rb#L108-L112
train
alloy/lowdown
lib/lowdown/client.rb
Lowdown.Client.disconnect
def disconnect if @connection.respond_to?(:actors) @connection.actors.each do |connection| connection.async.disconnect if connection.alive? end else @connection.async.disconnect if @connection.alive? end end
ruby
def disconnect if @connection.respond_to?(:actors) @connection.actors.each do |connection| connection.async.disconnect if connection.alive? end else @connection.async.disconnect if @connection.alive? end end
[ "def", "disconnect", "if", "@connection", ".", "respond_to?", "(", ":actors", ")", "@connection", ".", "actors", ".", "each", "do", "|", "connection", "|", "connection", ".", "async", ".", "disconnect", "if", "connection", ".", "alive?", "end", "else", "@connection", ".", "async", ".", "disconnect", "if", "@connection", ".", "alive?", "end", "end" ]
Closes the connection to the service. @see Connection#disconnect @return [void]
[ "Closes", "the", "connection", "to", "the", "service", "." ]
7a75185d2b93015c18b6093f6784938d42c021f7
https://github.com/alloy/lowdown/blob/7a75185d2b93015c18b6093f6784938d42c021f7/lib/lowdown/client.rb#L183-L191
train
alloy/lowdown
lib/lowdown/client.rb
Lowdown.Client.group
def group(timeout: nil) group = nil monitor do |condition| group = RequestGroup.new(self, condition) yield group if !group.empty? && exception = condition.wait(timeout || DEFAULT_GROUP_TIMEOUT) raise exception end end ensure group.terminate end
ruby
def group(timeout: nil) group = nil monitor do |condition| group = RequestGroup.new(self, condition) yield group if !group.empty? && exception = condition.wait(timeout || DEFAULT_GROUP_TIMEOUT) raise exception end end ensure group.terminate end
[ "def", "group", "(", "timeout", ":", "nil", ")", "group", "=", "nil", "monitor", "do", "|", "condition", "|", "group", "=", "RequestGroup", ".", "new", "(", "self", ",", "condition", ")", "yield", "group", "if", "!", "group", ".", "empty?", "&&", "exception", "=", "condition", ".", "wait", "(", "timeout", "||", "DEFAULT_GROUP_TIMEOUT", ")", "raise", "exception", "end", "end", "ensure", "group", ".", "terminate", "end" ]
Use this to group a batch of requests and halt the caller thread until all of the requests in the group have been performed. It proxies {RequestGroup#send_notification} to {Client#send_notification}, but, unlike the latter, the request callbacks are provided in the form of a block. @note Do **not** share the yielded group across threads. @see RequestGroup#send_notification @see Connection::Monitor @param [Numeric] timeout the maximum amount of time to wait for a request group to halt the caller thread. Defaults to 1 hour. @yieldparam [RequestGroup] group the request group object. @raise [Exception] if a connection in the pool has died during the execution of this group, the reason for its death will be raised. @return [void]
[ "Use", "this", "to", "group", "a", "batch", "of", "requests", "and", "halt", "the", "caller", "thread", "until", "all", "of", "the", "requests", "in", "the", "group", "have", "been", "performed", "." ]
7a75185d2b93015c18b6093f6784938d42c021f7
https://github.com/alloy/lowdown/blob/7a75185d2b93015c18b6093f6784938d42c021f7/lib/lowdown/client.rb#L216-L227
train
alloy/lowdown
lib/lowdown/client.rb
Lowdown.Client.monitor
def monitor condition = Connection::Monitor::Condition.new if defined?(Mock::Connection) && @connection.class == Mock::Connection yield condition else begin @connection.__register_lowdown_crash_condition__(condition) yield condition ensure @connection.__deregister_lowdown_crash_condition__(condition) end end end
ruby
def monitor condition = Connection::Monitor::Condition.new if defined?(Mock::Connection) && @connection.class == Mock::Connection yield condition else begin @connection.__register_lowdown_crash_condition__(condition) yield condition ensure @connection.__deregister_lowdown_crash_condition__(condition) end end end
[ "def", "monitor", "condition", "=", "Connection", "::", "Monitor", "::", "Condition", ".", "new", "if", "defined?", "(", "Mock", "::", "Connection", ")", "&&", "@connection", ".", "class", "==", "Mock", "::", "Connection", "yield", "condition", "else", "begin", "@connection", ".", "__register_lowdown_crash_condition__", "(", "condition", ")", "yield", "condition", "ensure", "@connection", ".", "__deregister_lowdown_crash_condition__", "(", "condition", ")", "end", "end", "end" ]
Registers a condition object with the connection pool, for the duration of the given block. It either returns an exception that caused a connection to die, or whatever value you signal to it. This is automatically used by {#group}. @yieldparam [Connection::Monitor::Condition] condition the monitor condition object. @return [void]
[ "Registers", "a", "condition", "object", "with", "the", "connection", "pool", "for", "the", "duration", "of", "the", "given", "block", ".", "It", "either", "returns", "an", "exception", "that", "caused", "a", "connection", "to", "die", "or", "whatever", "value", "you", "signal", "to", "it", "." ]
7a75185d2b93015c18b6093f6784938d42c021f7
https://github.com/alloy/lowdown/blob/7a75185d2b93015c18b6093f6784938d42c021f7/lib/lowdown/client.rb#L239-L251
train