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
jinx/migrate
lib/jinx/migration/migrator.rb
Jinx.Migrator.migrate_valid_references
def migrate_valid_references(row, migrated) # Split the valid and invalid objects. The iteration is in reverse dependency order, # since invalidating a dependent can invalidate the owner. ordered = migrated.transitive_closure(:dependents) ordered.keep_if { |obj| migrated.include?(obj) }.reverse! valid, invalid = ordered.partition do |obj| if migration_valid?(obj) then obj.migrate_references(row, migrated, @target_class, @attr_flt_hash[obj.class]) true else obj.class.owner_attributes.each { |pa| obj.clear_attribute(pa) } false end end # Go back through the valid objects in dependency order to invalidate dependents # whose owner is invalid. valid.reverse.each do |obj| unless owner_valid?(obj, valid, invalid) then invalid << valid.delete(obj) logger.debug { "The migrator invalidated #{obj} since it does not have a valid owner." } end end # Go back through the valid objects in reverse dependency order to invalidate owners # created only to hold a dependent which was subsequently invalidated. valid.reject do |obj| if @owners.include?(obj.class) and obj.dependents.all? { |dep| invalid.include?(dep) } then # clear all references from the invalidated owner obj.class.domain_attributes.each { |pa| obj.clear_attribute(pa) } invalid << obj logger.debug { "The migrator invalidated #{obj.qp} since it was created solely to hold subsequently invalidated dependents." } true end end end
ruby
def migrate_valid_references(row, migrated) # Split the valid and invalid objects. The iteration is in reverse dependency order, # since invalidating a dependent can invalidate the owner. ordered = migrated.transitive_closure(:dependents) ordered.keep_if { |obj| migrated.include?(obj) }.reverse! valid, invalid = ordered.partition do |obj| if migration_valid?(obj) then obj.migrate_references(row, migrated, @target_class, @attr_flt_hash[obj.class]) true else obj.class.owner_attributes.each { |pa| obj.clear_attribute(pa) } false end end # Go back through the valid objects in dependency order to invalidate dependents # whose owner is invalid. valid.reverse.each do |obj| unless owner_valid?(obj, valid, invalid) then invalid << valid.delete(obj) logger.debug { "The migrator invalidated #{obj} since it does not have a valid owner." } end end # Go back through the valid objects in reverse dependency order to invalidate owners # created only to hold a dependent which was subsequently invalidated. valid.reject do |obj| if @owners.include?(obj.class) and obj.dependents.all? { |dep| invalid.include?(dep) } then # clear all references from the invalidated owner obj.class.domain_attributes.each { |pa| obj.clear_attribute(pa) } invalid << obj logger.debug { "The migrator invalidated #{obj.qp} since it was created solely to hold subsequently invalidated dependents." } true end end end
[ "def", "migrate_valid_references", "(", "row", ",", "migrated", ")", "ordered", "=", "migrated", ".", "transitive_closure", "(", ":dependents", ")", "ordered", ".", "keep_if", "{", "|", "obj", "|", "migrated", ".", "include?", "(", "obj", ")", "}", ".", "reverse!", "valid", ",", "invalid", "=", "ordered", ".", "partition", "do", "|", "obj", "|", "if", "migration_valid?", "(", "obj", ")", "then", "obj", ".", "migrate_references", "(", "row", ",", "migrated", ",", "@target_class", ",", "@attr_flt_hash", "[", "obj", ".", "class", "]", ")", "true", "else", "obj", ".", "class", ".", "owner_attributes", ".", "each", "{", "|", "pa", "|", "obj", ".", "clear_attribute", "(", "pa", ")", "}", "false", "end", "end", "valid", ".", "reverse", ".", "each", "do", "|", "obj", "|", "unless", "owner_valid?", "(", "obj", ",", "valid", ",", "invalid", ")", "then", "invalid", "<<", "valid", ".", "delete", "(", "obj", ")", "logger", ".", "debug", "{", "\"The migrator invalidated #{obj} since it does not have a valid owner.\"", "}", "end", "end", "valid", ".", "reject", "do", "|", "obj", "|", "if", "@owners", ".", "include?", "(", "obj", ".", "class", ")", "and", "obj", ".", "dependents", ".", "all?", "{", "|", "dep", "|", "invalid", ".", "include?", "(", "dep", ")", "}", "then", "obj", ".", "class", ".", "domain_attributes", ".", "each", "{", "|", "pa", "|", "obj", ".", "clear_attribute", "(", "pa", ")", "}", "invalid", "<<", "obj", "logger", ".", "debug", "{", "\"The migrator invalidated #{obj.qp} since it was created solely to hold subsequently invalidated dependents.\"", "}", "true", "end", "end", "end" ]
Sets the migration references for each valid migrated object. @param row (see #migrate_row) @param [Array] migrated the migrated objects @return [Array] the valid migrated objects
[ "Sets", "the", "migration", "references", "for", "each", "valid", "migrated", "object", "." ]
309957a470d72da3bd074f8173dbbe2f12449883
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L567-L602
train
jinx/migrate
lib/jinx/migration/migrator.rb
Jinx.Migrator.create_instance
def create_instance(klass, row, created) # the new object logger.debug { "The migrator is building #{klass.qp}..." } created << obj = klass.new migrate_properties(obj, row, created) add_defaults(obj, row, created) logger.debug { "The migrator built #{obj}." } obj end
ruby
def create_instance(klass, row, created) # the new object logger.debug { "The migrator is building #{klass.qp}..." } created << obj = klass.new migrate_properties(obj, row, created) add_defaults(obj, row, created) logger.debug { "The migrator built #{obj}." } obj end
[ "def", "create_instance", "(", "klass", ",", "row", ",", "created", ")", "logger", ".", "debug", "{", "\"The migrator is building #{klass.qp}...\"", "}", "created", "<<", "obj", "=", "klass", ".", "new", "migrate_properties", "(", "obj", ",", "row", ",", "created", ")", "add_defaults", "(", "obj", ",", "row", ",", "created", ")", "logger", ".", "debug", "{", "\"The migrator built #{obj}.\"", "}", "obj", "end" ]
Creates an instance of the given klass from the given row. The new klass instance and all intermediate migrated instances are added to the created set. @param [Class] klass @param [{Symbol => Object}] row the input row @param [<Resource>] created the migrated instances for this row @return [Resource] the new instance
[ "Creates", "an", "instance", "of", "the", "given", "klass", "from", "the", "given", "row", ".", "The", "new", "klass", "instance", "and", "all", "intermediate", "migrated", "instances", "are", "added", "to", "the", "created", "set", "." ]
309957a470d72da3bd074f8173dbbe2f12449883
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L637-L645
train
jinx/migrate
lib/jinx/migration/migrator.rb
Jinx.Migrator.migrate_properties
def migrate_properties(obj, row, created) # for each input header which maps to a migratable target attribute metadata path, # set the target attribute, creating intermediate objects as needed. @cls_paths_hash[obj.class].each do |path| header = @header_map[path][obj.class] # the input value value = row[header] value.strip! if String === value next if value.nil? # fill the reference path ref = fill_path(obj, path[0...-1], row, created) # set the attribute migrate_property(ref, path.last, value, row) end end
ruby
def migrate_properties(obj, row, created) # for each input header which maps to a migratable target attribute metadata path, # set the target attribute, creating intermediate objects as needed. @cls_paths_hash[obj.class].each do |path| header = @header_map[path][obj.class] # the input value value = row[header] value.strip! if String === value next if value.nil? # fill the reference path ref = fill_path(obj, path[0...-1], row, created) # set the attribute migrate_property(ref, path.last, value, row) end end
[ "def", "migrate_properties", "(", "obj", ",", "row", ",", "created", ")", "@cls_paths_hash", "[", "obj", ".", "class", "]", ".", "each", "do", "|", "path", "|", "header", "=", "@header_map", "[", "path", "]", "[", "obj", ".", "class", "]", "value", "=", "row", "[", "header", "]", "value", ".", "strip!", "if", "String", "===", "value", "next", "if", "value", ".", "nil?", "ref", "=", "fill_path", "(", "obj", ",", "path", "[", "0", "...", "-", "1", "]", ",", "row", ",", "created", ")", "migrate_property", "(", "ref", ",", "path", ".", "last", ",", "value", ",", "row", ")", "end", "end" ]
Migrates each input field to the associated domain object attribute. String input values are stripped. Missing input values are ignored. @param [Resource] the migration object @param row (see #create) @param [<Resource>] created (see #create)
[ "Migrates", "each", "input", "field", "to", "the", "associated", "domain", "object", "attribute", ".", "String", "input", "values", "are", "stripped", ".", "Missing", "input", "values", "are", "ignored", "." ]
309957a470d72da3bd074f8173dbbe2f12449883
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L653-L667
train
jinx/migrate
lib/jinx/migration/migrator.rb
Jinx.Migrator.fill_path
def fill_path(obj, path, row, created) # create the intermediate objects as needed (or return obj if path is empty) path.inject(obj) do |parent, prop| # the referenced object parent.send(prop.reader) or create_reference(parent, prop, row, created) end end
ruby
def fill_path(obj, path, row, created) # create the intermediate objects as needed (or return obj if path is empty) path.inject(obj) do |parent, prop| # the referenced object parent.send(prop.reader) or create_reference(parent, prop, row, created) end end
[ "def", "fill_path", "(", "obj", ",", "path", ",", "row", ",", "created", ")", "path", ".", "inject", "(", "obj", ")", "do", "|", "parent", ",", "prop", "|", "parent", ".", "send", "(", "prop", ".", "reader", ")", "or", "create_reference", "(", "parent", ",", "prop", ",", "row", ",", "created", ")", "end", "end" ]
Fills the given reference Property path starting at obj. @param row (see #create) @param created (see #create) @return the last domain object in the path
[ "Fills", "the", "given", "reference", "Property", "path", "starting", "at", "obj", "." ]
309957a470d72da3bd074f8173dbbe2f12449883
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L687-L693
train
jinx/migrate
lib/jinx/migration/migrator.rb
Jinx.Migrator.create_reference
def create_reference(obj, property, row, created) if property.type.abstract? then raise MigrationError.new("Cannot create #{obj.qp} #{property} with abstract type #{property.type}") end ref = property.type.new ref.migrate(row, Array::EMPTY_ARRAY) obj.send(property.writer, ref) created << ref logger.debug { "The migrator created #{obj.qp} #{property} #{ref}." } ref end
ruby
def create_reference(obj, property, row, created) if property.type.abstract? then raise MigrationError.new("Cannot create #{obj.qp} #{property} with abstract type #{property.type}") end ref = property.type.new ref.migrate(row, Array::EMPTY_ARRAY) obj.send(property.writer, ref) created << ref logger.debug { "The migrator created #{obj.qp} #{property} #{ref}." } ref end
[ "def", "create_reference", "(", "obj", ",", "property", ",", "row", ",", "created", ")", "if", "property", ".", "type", ".", "abstract?", "then", "raise", "MigrationError", ".", "new", "(", "\"Cannot create #{obj.qp} #{property} with abstract type #{property.type}\"", ")", "end", "ref", "=", "property", ".", "type", ".", "new", "ref", ".", "migrate", "(", "row", ",", "Array", "::", "EMPTY_ARRAY", ")", "obj", ".", "send", "(", "property", ".", "writer", ",", "ref", ")", "created", "<<", "ref", "logger", ".", "debug", "{", "\"The migrator created #{obj.qp} #{property} #{ref}.\"", "}", "ref", "end" ]
Sets the given migrated object's reference attribute to a new referenced domain object. @param [Resource] obj the domain object being migrated @param [Property] property the property being migrated @param row (see #create) @param created (see #create) @return the new object
[ "Sets", "the", "given", "migrated", "object", "s", "reference", "attribute", "to", "a", "new", "referenced", "domain", "object", "." ]
309957a470d72da3bd074f8173dbbe2f12449883
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L702-L712
train
jinx/migrate
lib/jinx/migration/migrator.rb
Jinx.Migrator.load_defaults_files
def load_defaults_files(files) # collect the class => path => value entries from each defaults file hash = LazyHash.new { Hash.new } files.enumerate { |file| load_defaults_file(file, hash) } hash end
ruby
def load_defaults_files(files) # collect the class => path => value entries from each defaults file hash = LazyHash.new { Hash.new } files.enumerate { |file| load_defaults_file(file, hash) } hash end
[ "def", "load_defaults_files", "(", "files", ")", "hash", "=", "LazyHash", ".", "new", "{", "Hash", ".", "new", "}", "files", ".", "enumerate", "{", "|", "file", "|", "load_defaults_file", "(", "file", ",", "hash", ")", "}", "hash", "end" ]
Loads the defaults configuration files. @param [<String>, String] files the file or file array to load @return [<Class => <String => Object>>] the class => path => default value entries
[ "Loads", "the", "defaults", "configuration", "files", "." ]
309957a470d72da3bd074f8173dbbe2f12449883
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L838-L843
train
jinx/migrate
lib/jinx/migration/migrator.rb
Jinx.Migrator.load_defaults_file
def load_defaults_file(file, hash) begin config = YAML::load_file(file) rescue raise MigrationError.new("Could not read defaults file #{file}: " + $!) end # collect the class => path => value entries config.each do |path_s, value| next if value.nil_or_empty? klass, path = create_attribute_path(path_s) hash[klass][path] = value end end
ruby
def load_defaults_file(file, hash) begin config = YAML::load_file(file) rescue raise MigrationError.new("Could not read defaults file #{file}: " + $!) end # collect the class => path => value entries config.each do |path_s, value| next if value.nil_or_empty? klass, path = create_attribute_path(path_s) hash[klass][path] = value end end
[ "def", "load_defaults_file", "(", "file", ",", "hash", ")", "begin", "config", "=", "YAML", "::", "load_file", "(", "file", ")", "rescue", "raise", "MigrationError", ".", "new", "(", "\"Could not read defaults file #{file}: \"", "+", "$!", ")", "end", "config", ".", "each", "do", "|", "path_s", ",", "value", "|", "next", "if", "value", ".", "nil_or_empty?", "klass", ",", "path", "=", "create_attribute_path", "(", "path_s", ")", "hash", "[", "klass", "]", "[", "path", "]", "=", "value", "end", "end" ]
Loads the defaults config file into the given hash. @param [String] file the file to load @param [<Class => <String => Object>>] hash the class => path => default value entries
[ "Loads", "the", "defaults", "config", "file", "into", "the", "given", "hash", "." ]
309957a470d72da3bd074f8173dbbe2f12449883
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L849-L861
train
jinx/migrate
lib/jinx/migration/migrator.rb
Jinx.Migrator.load_filter_files
def load_filter_files(files) # collect the class => path => value entries from each defaults file hash = {} files.enumerate { |file| load_filter_file(file, hash) } logger.debug { "The migrator loaded the filters #{hash.qp}." } hash end
ruby
def load_filter_files(files) # collect the class => path => value entries from each defaults file hash = {} files.enumerate { |file| load_filter_file(file, hash) } logger.debug { "The migrator loaded the filters #{hash.qp}." } hash end
[ "def", "load_filter_files", "(", "files", ")", "hash", "=", "{", "}", "files", ".", "enumerate", "{", "|", "file", "|", "load_filter_file", "(", "file", ",", "hash", ")", "}", "logger", ".", "debug", "{", "\"The migrator loaded the filters #{hash.qp}.\"", "}", "hash", "end" ]
Loads the filter config files. @param [<String>, String] files the file or file array to load @return [<Class => <String => Object>>] the class => path => default value entries
[ "Loads", "the", "filter", "config", "files", "." ]
309957a470d72da3bd074f8173dbbe2f12449883
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L866-L872
train
jinx/migrate
lib/jinx/migration/migrator.rb
Jinx.Migrator.load_filter_file
def load_filter_file(file, hash) # collect the class => attribute => filter entries logger.debug { "Loading the migration filter configuration #{file}..." } begin config = YAML::load_file(file) rescue raise MigrationError.new("Could not read filter file #{file}: " + $!) end config.each do |path_s, flt| next if flt.nil_or_empty? klass, path = create_attribute_path(path_s) if path.empty? then raise MigrationError.new("Migration filter configuration path does not include a property: #{path_s}") elsif path.size > 1 then raise MigrationError.new("Migration filter configuration path with more than one property is not supported: #{path_s}") end pa = klass.standard_attribute(path.first.to_sym) flt_hash = hash[klass] ||= {} flt_hash[pa] = flt end end
ruby
def load_filter_file(file, hash) # collect the class => attribute => filter entries logger.debug { "Loading the migration filter configuration #{file}..." } begin config = YAML::load_file(file) rescue raise MigrationError.new("Could not read filter file #{file}: " + $!) end config.each do |path_s, flt| next if flt.nil_or_empty? klass, path = create_attribute_path(path_s) if path.empty? then raise MigrationError.new("Migration filter configuration path does not include a property: #{path_s}") elsif path.size > 1 then raise MigrationError.new("Migration filter configuration path with more than one property is not supported: #{path_s}") end pa = klass.standard_attribute(path.first.to_sym) flt_hash = hash[klass] ||= {} flt_hash[pa] = flt end end
[ "def", "load_filter_file", "(", "file", ",", "hash", ")", "logger", ".", "debug", "{", "\"Loading the migration filter configuration #{file}...\"", "}", "begin", "config", "=", "YAML", "::", "load_file", "(", "file", ")", "rescue", "raise", "MigrationError", ".", "new", "(", "\"Could not read filter file #{file}: \"", "+", "$!", ")", "end", "config", ".", "each", "do", "|", "path_s", ",", "flt", "|", "next", "if", "flt", ".", "nil_or_empty?", "klass", ",", "path", "=", "create_attribute_path", "(", "path_s", ")", "if", "path", ".", "empty?", "then", "raise", "MigrationError", ".", "new", "(", "\"Migration filter configuration path does not include a property: #{path_s}\"", ")", "elsif", "path", ".", "size", ">", "1", "then", "raise", "MigrationError", ".", "new", "(", "\"Migration filter configuration path with more than one property is not supported: #{path_s}\"", ")", "end", "pa", "=", "klass", ".", "standard_attribute", "(", "path", ".", "first", ".", "to_sym", ")", "flt_hash", "=", "hash", "[", "klass", "]", "||=", "{", "}", "flt_hash", "[", "pa", "]", "=", "flt", "end", "end" ]
Loads the filter config file into the given hash. @param [String] file the file to load @param [<Class => <String => <Object => Object>>>] hash the class => path => input value => caTissue value entries
[ "Loads", "the", "filter", "config", "file", "into", "the", "given", "hash", "." ]
309957a470d72da3bd074f8173dbbe2f12449883
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L878-L898
train
mitukiii/cha
lib/cha/api.rb
Cha.API.create_room
def create_room(name, members_admin_ids, params = {}) members_admin_ids = array_to_string(members_admin_ids) if value = params[:members_member_ids] params[:members_member_ids] = array_to_string(value) end if value = params[:members_readonly_ids] params[:members_readonly_ids] = array_to_string(value) end params = params.merge(name: name, members_admin_ids: members_admin_ids) post('rooms', params) end
ruby
def create_room(name, members_admin_ids, params = {}) members_admin_ids = array_to_string(members_admin_ids) if value = params[:members_member_ids] params[:members_member_ids] = array_to_string(value) end if value = params[:members_readonly_ids] params[:members_readonly_ids] = array_to_string(value) end params = params.merge(name: name, members_admin_ids: members_admin_ids) post('rooms', params) end
[ "def", "create_room", "(", "name", ",", "members_admin_ids", ",", "params", "=", "{", "}", ")", "members_admin_ids", "=", "array_to_string", "(", "members_admin_ids", ")", "if", "value", "=", "params", "[", ":members_member_ids", "]", "params", "[", ":members_member_ids", "]", "=", "array_to_string", "(", "value", ")", "end", "if", "value", "=", "params", "[", ":members_readonly_ids", "]", "params", "[", ":members_readonly_ids", "]", "=", "array_to_string", "(", "value", ")", "end", "params", "=", "params", ".", "merge", "(", "name", ":", "name", ",", "members_admin_ids", ":", "members_admin_ids", ")", "post", "(", "'rooms'", ",", "params", ")", "end" ]
Create new chat room @param name [String] Name of chat room @param members_admin_ids [Array<Integer>] Array of member ID that want to admin authority @param params [Hash] Hash of optional parameter @option params [String] :description (nil) Summary of chat room @option params [Symbol] :icon_preset (nil) Kind of Icon of chat room (group, check, document, meeting, event, project, business, study, security, star, idea, heart, magcup, beer, music, sports, travel) @option params [Array<Integer>] :members_member_ids (nil) Array of member ID that want to member authority @option params [Array<Integer>] :members_readonly_ids (nil) Array of member ID that want to read only @return [Hashie::Mash]
[ "Create", "new", "chat", "room" ]
1e4d708a95cbeab270c701f0c77d4546194c297d
https://github.com/mitukiii/cha/blob/1e4d708a95cbeab270c701f0c77d4546194c297d/lib/cha/api.rb#L60-L70
train
mitukiii/cha
lib/cha/api.rb
Cha.API.update_room_members
def update_room_members(room_id, members_admin_ids, params = {}) members_admin_ids = array_to_string(members_admin_ids) if value = params[:members_member_ids] params[:members_member_ids] = array_to_string(value) end if value = params[:members_readonly_ids] params[:members_readonly_ids] = array_to_string(value) end params = params.merge(members_admin_ids: members_admin_ids) put("rooms/#{room_id}/members", params) end
ruby
def update_room_members(room_id, members_admin_ids, params = {}) members_admin_ids = array_to_string(members_admin_ids) if value = params[:members_member_ids] params[:members_member_ids] = array_to_string(value) end if value = params[:members_readonly_ids] params[:members_readonly_ids] = array_to_string(value) end params = params.merge(members_admin_ids: members_admin_ids) put("rooms/#{room_id}/members", params) end
[ "def", "update_room_members", "(", "room_id", ",", "members_admin_ids", ",", "params", "=", "{", "}", ")", "members_admin_ids", "=", "array_to_string", "(", "members_admin_ids", ")", "if", "value", "=", "params", "[", ":members_member_ids", "]", "params", "[", ":members_member_ids", "]", "=", "array_to_string", "(", "value", ")", "end", "if", "value", "=", "params", "[", ":members_readonly_ids", "]", "params", "[", ":members_readonly_ids", "]", "=", "array_to_string", "(", "value", ")", "end", "params", "=", "params", ".", "merge", "(", "members_admin_ids", ":", "members_admin_ids", ")", "put", "(", "\"rooms/#{room_id}/members\"", ",", "params", ")", "end" ]
Update chat room members @param room_id [Integer] ID of chat room @param members_admin_ids [Array<Integer>] Array of member ID that want to admin authority @param params [Hash] Hash of optional parameter @option params [Array<Integer>] :members_member_ids (nil) Array of member ID that want to member authority @option params [Array<Integer>] :members_readonly_ids (nil) Array of member ID that want to read only @return [Hahsie::Mash]
[ "Update", "chat", "room", "members" ]
1e4d708a95cbeab270c701f0c77d4546194c297d
https://github.com/mitukiii/cha/blob/1e4d708a95cbeab270c701f0c77d4546194c297d/lib/cha/api.rb#L122-L132
train
mitukiii/cha
lib/cha/api.rb
Cha.API.create_room_task
def create_room_task(room_id, body, to_ids, params = {}) to_ids = array_to_string(to_ids) if value = params[:limit] params[:limit] = time_to_integer(value) end post("rooms/#{room_id}/tasks", params.merge(body: body, to_ids: to_ids)) end
ruby
def create_room_task(room_id, body, to_ids, params = {}) to_ids = array_to_string(to_ids) if value = params[:limit] params[:limit] = time_to_integer(value) end post("rooms/#{room_id}/tasks", params.merge(body: body, to_ids: to_ids)) end
[ "def", "create_room_task", "(", "room_id", ",", "body", ",", "to_ids", ",", "params", "=", "{", "}", ")", "to_ids", "=", "array_to_string", "(", "to_ids", ")", "if", "value", "=", "params", "[", ":limit", "]", "params", "[", ":limit", "]", "=", "time_to_integer", "(", "value", ")", "end", "post", "(", "\"rooms/#{room_id}/tasks\"", ",", "params", ".", "merge", "(", "body", ":", "body", ",", "to_ids", ":", "to_ids", ")", ")", "end" ]
Create new task of chat room @param room_id [Integer] ID of chat room @param body [String] Contents of task @param to_ids [Array<Integer>] Array of account ID of person in charge @param params [Hash] Hash of optional parameter @option params [Integer, Time] :limit (nil) Deadline of task (unix time) @return [Hashie::Mash]
[ "Create", "new", "task", "of", "chat", "room" ]
1e4d708a95cbeab270c701f0c77d4546194c297d
https://github.com/mitukiii/cha/blob/1e4d708a95cbeab270c701f0c77d4546194c297d/lib/cha/api.rb#L186-L192
train
mitukiii/cha
lib/cha/api.rb
Cha.API.room_file
def room_file(room_id, file_id, params = {}) unless (value = params[:create_download_url]).nil? params[:create_download_url] = boolean_to_integer(value) end get("rooms/#{room_id}/files/#{file_id}", params) end
ruby
def room_file(room_id, file_id, params = {}) unless (value = params[:create_download_url]).nil? params[:create_download_url] = boolean_to_integer(value) end get("rooms/#{room_id}/files/#{file_id}", params) end
[ "def", "room_file", "(", "room_id", ",", "file_id", ",", "params", "=", "{", "}", ")", "unless", "(", "value", "=", "params", "[", ":create_download_url", "]", ")", ".", "nil?", "params", "[", ":create_download_url", "]", "=", "boolean_to_integer", "(", "value", ")", "end", "get", "(", "\"rooms/#{room_id}/files/#{file_id}\"", ",", "params", ")", "end" ]
Get file information @param room_id [Integer] ID of chat room @param file_id [Integer] ID of file @param params [Hash] Hash of optional parameter @option params [Boolean] :create_download_url (false) Create URL for download
[ "Get", "file", "information" ]
1e4d708a95cbeab270c701f0c77d4546194c297d
https://github.com/mitukiii/cha/blob/1e4d708a95cbeab270c701f0c77d4546194c297d/lib/cha/api.rb#L220-L225
train
knaveofdiamonds/uk_working_days
lib/uk_working_days/easter.rb
UkWorkingDays.Easter.easter
def easter(year) golden_number = (year % 19) + 1 if year <= 1752 then # Julian calendar dominical_number = (year + (year / 4) + 5) % 7 paschal_full_moon = (3 - (11 * golden_number) - 7) % 30 else # Gregorian calendar dominical_number = (year + (year / 4) - (year / 100) + (year / 400)) % 7 solar_correction = (year - 1600) / 100 - (year - 1600) / 400 lunar_correction = (((year - 1400) / 100) * 8) / 25 paschal_full_moon = (3 - 11 * golden_number + solar_correction - lunar_correction) % 30 end dominical_number += 7 until dominical_number > 0 paschal_full_moon += 30 until paschal_full_moon > 0 paschal_full_moon -= 1 if paschal_full_moon == 29 or (paschal_full_moon == 28 and golden_number > 11) difference = (4 - paschal_full_moon - dominical_number) % 7 difference += 7 if difference < 0 day_easter = paschal_full_moon + difference + 1 day_easter < 11 ? new(year, 3, day_easter + 21) : new(year, 4, day_easter - 10) end
ruby
def easter(year) golden_number = (year % 19) + 1 if year <= 1752 then # Julian calendar dominical_number = (year + (year / 4) + 5) % 7 paschal_full_moon = (3 - (11 * golden_number) - 7) % 30 else # Gregorian calendar dominical_number = (year + (year / 4) - (year / 100) + (year / 400)) % 7 solar_correction = (year - 1600) / 100 - (year - 1600) / 400 lunar_correction = (((year - 1400) / 100) * 8) / 25 paschal_full_moon = (3 - 11 * golden_number + solar_correction - lunar_correction) % 30 end dominical_number += 7 until dominical_number > 0 paschal_full_moon += 30 until paschal_full_moon > 0 paschal_full_moon -= 1 if paschal_full_moon == 29 or (paschal_full_moon == 28 and golden_number > 11) difference = (4 - paschal_full_moon - dominical_number) % 7 difference += 7 if difference < 0 day_easter = paschal_full_moon + difference + 1 day_easter < 11 ? new(year, 3, day_easter + 21) : new(year, 4, day_easter - 10) end
[ "def", "easter", "(", "year", ")", "golden_number", "=", "(", "year", "%", "19", ")", "+", "1", "if", "year", "<=", "1752", "then", "dominical_number", "=", "(", "year", "+", "(", "year", "/", "4", ")", "+", "5", ")", "%", "7", "paschal_full_moon", "=", "(", "3", "-", "(", "11", "*", "golden_number", ")", "-", "7", ")", "%", "30", "else", "dominical_number", "=", "(", "year", "+", "(", "year", "/", "4", ")", "-", "(", "year", "/", "100", ")", "+", "(", "year", "/", "400", ")", ")", "%", "7", "solar_correction", "=", "(", "year", "-", "1600", ")", "/", "100", "-", "(", "year", "-", "1600", ")", "/", "400", "lunar_correction", "=", "(", "(", "(", "year", "-", "1400", ")", "/", "100", ")", "*", "8", ")", "/", "25", "paschal_full_moon", "=", "(", "3", "-", "11", "*", "golden_number", "+", "solar_correction", "-", "lunar_correction", ")", "%", "30", "end", "dominical_number", "+=", "7", "until", "dominical_number", ">", "0", "paschal_full_moon", "+=", "30", "until", "paschal_full_moon", ">", "0", "paschal_full_moon", "-=", "1", "if", "paschal_full_moon", "==", "29", "or", "(", "paschal_full_moon", "==", "28", "and", "golden_number", ">", "11", ")", "difference", "=", "(", "4", "-", "paschal_full_moon", "-", "dominical_number", ")", "%", "7", "difference", "+=", "7", "if", "difference", "<", "0", "day_easter", "=", "paschal_full_moon", "+", "difference", "+", "1", "day_easter", "<", "11", "?", "new", "(", "year", ",", "3", ",", "day_easter", "+", "21", ")", ":", "new", "(", "year", ",", "4", ",", "day_easter", "-", "10", ")", "end" ]
Calculate easter sunday for the given year
[ "Calculate", "easter", "sunday", "for", "the", "given", "year" ]
cd97bec608019418a877ee2b348871b701e0751b
https://github.com/knaveofdiamonds/uk_working_days/blob/cd97bec608019418a877ee2b348871b701e0751b/lib/uk_working_days/easter.rb#L15-L41
train
starrhorne/konfig
lib/konfig/evaluator.rb
Konfig.Evaluator.names_by_value
def names_by_value(a) a = @data[a] if a.is_a?(String) || a.is_a?(Symbol) Hash[ a.map { |i| i.reverse } ] end
ruby
def names_by_value(a) a = @data[a] if a.is_a?(String) || a.is_a?(Symbol) Hash[ a.map { |i| i.reverse } ] end
[ "def", "names_by_value", "(", "a", ")", "a", "=", "@data", "[", "a", "]", "if", "a", ".", "is_a?", "(", "String", ")", "||", "a", ".", "is_a?", "(", "Symbol", ")", "Hash", "[", "a", ".", "map", "{", "|", "i", "|", "i", ".", "reverse", "}", "]", "end" ]
Converts an options-style nested array into a hash for easy name lookup @param [Array] a an array like [['name', 'val']] @return [Hash] a hash like { val => name }
[ "Converts", "an", "options", "-", "style", "nested", "array", "into", "a", "hash", "for", "easy", "name", "lookup" ]
5d655945586a489868bb868243d9c0da18c90228
https://github.com/starrhorne/konfig/blob/5d655945586a489868bb868243d9c0da18c90228/lib/konfig/evaluator.rb#L26-L29
train
rndstr/halffare
lib/halffare/stats.rb
Halffare.Stats.read
def read(filename, months=nil) @orders = [] start = months ? (Date.today << months.to_i).strftime('%Y-%m-%d') : nil file = File.open(filename, "r:UTF-8") do |f| while line = f.gets order = Halffare::Model::Order.new(line) if (start.nil? || line[0,10] >= start) && (order.note != Fetch::ORDER_NOTE_FILE_CREATED) @orders.push(order) end end end log_info "read #{@orders.length} orders from #{filename}" if @orders.length == 0 if start.nil? log_notice "no orders found" else log_notice "no orders found after #{start}, maybe tweak the --months param" end end end
ruby
def read(filename, months=nil) @orders = [] start = months ? (Date.today << months.to_i).strftime('%Y-%m-%d') : nil file = File.open(filename, "r:UTF-8") do |f| while line = f.gets order = Halffare::Model::Order.new(line) if (start.nil? || line[0,10] >= start) && (order.note != Fetch::ORDER_NOTE_FILE_CREATED) @orders.push(order) end end end log_info "read #{@orders.length} orders from #{filename}" if @orders.length == 0 if start.nil? log_notice "no orders found" else log_notice "no orders found after #{start}, maybe tweak the --months param" end end end
[ "def", "read", "(", "filename", ",", "months", "=", "nil", ")", "@orders", "=", "[", "]", "start", "=", "months", "?", "(", "Date", ".", "today", "<<", "months", ".", "to_i", ")", ".", "strftime", "(", "'%Y-%m-%d'", ")", ":", "nil", "file", "=", "File", ".", "open", "(", "filename", ",", "\"r:UTF-8\"", ")", "do", "|", "f", "|", "while", "line", "=", "f", ".", "gets", "order", "=", "Halffare", "::", "Model", "::", "Order", ".", "new", "(", "line", ")", "if", "(", "start", ".", "nil?", "||", "line", "[", "0", ",", "10", "]", ">=", "start", ")", "&&", "(", "order", ".", "note", "!=", "Fetch", "::", "ORDER_NOTE_FILE_CREATED", ")", "@orders", ".", "push", "(", "order", ")", "end", "end", "end", "log_info", "\"read #{@orders.length} orders from #{filename}\"", "if", "@orders", ".", "length", "==", "0", "if", "start", ".", "nil?", "log_notice", "\"no orders found\"", "else", "log_notice", "\"no orders found after #{start}, maybe tweak the --months param\"", "end", "end", "end" ]
Reads orders from `filename` that date back to max `months` months. @param filename [String] The filename to read from @param months [Integer, nil] Number of months look back or nil for all
[ "Reads", "orders", "from", "filename", "that", "date", "back", "to", "max", "months", "months", "." ]
2c4c7563a9e0834e5d2d93c15bd052bb67f8996a
https://github.com/rndstr/halffare/blob/2c4c7563a9e0834e5d2d93c15bd052bb67f8996a/lib/halffare/stats.rb#L8-L27
train
rndstr/halffare
lib/halffare/stats.rb
Halffare.Stats.calculate
def calculate(strategy, halffare) @halfprice = 0 @fullprice = 0 if halffare log_info "assuming order prices as half-fare" else log_info "assuming order prices as full" end log_notice "please note that you are using a strategy that involves guessing the real price" if ['guess', 'sbbguess'].include? strategy strategy = price_factory(strategy) strategy.halffare = halffare log_info "using price strategy: #{strategy.class}" price = Price.new(strategy) log_info "calculating prices..." @date_min = false @date_max = false @orders.each do |order| if Halffare.debug log_order(order) end halfprice, fullprice = price.get(order) if Halffare.debug if halfprice != 0 && fullprice != 0 log_result "FOUND: #{order.description} (#{order.price}): half=#{currency(halfprice)}, full=#{currency(fullprice)}" if halffare log_emphasize "You would pay (full price): #{currency(fullprice)}, you save #{currency(fullprice - order.price)}" else log_emphasize "You would pay (half-fare): #{currency(halfprice)}, you pay #{currency(order.price - halfprice)} more" end end end @halfprice += halfprice @fullprice += fullprice @date_min = order.travel_date if !@date_min || order.travel_date < @date_min @date_max = order.travel_date if !@date_max || order.travel_date > @date_max end end
ruby
def calculate(strategy, halffare) @halfprice = 0 @fullprice = 0 if halffare log_info "assuming order prices as half-fare" else log_info "assuming order prices as full" end log_notice "please note that you are using a strategy that involves guessing the real price" if ['guess', 'sbbguess'].include? strategy strategy = price_factory(strategy) strategy.halffare = halffare log_info "using price strategy: #{strategy.class}" price = Price.new(strategy) log_info "calculating prices..." @date_min = false @date_max = false @orders.each do |order| if Halffare.debug log_order(order) end halfprice, fullprice = price.get(order) if Halffare.debug if halfprice != 0 && fullprice != 0 log_result "FOUND: #{order.description} (#{order.price}): half=#{currency(halfprice)}, full=#{currency(fullprice)}" if halffare log_emphasize "You would pay (full price): #{currency(fullprice)}, you save #{currency(fullprice - order.price)}" else log_emphasize "You would pay (half-fare): #{currency(halfprice)}, you pay #{currency(order.price - halfprice)} more" end end end @halfprice += halfprice @fullprice += fullprice @date_min = order.travel_date if !@date_min || order.travel_date < @date_min @date_max = order.travel_date if !@date_max || order.travel_date > @date_max end end
[ "def", "calculate", "(", "strategy", ",", "halffare", ")", "@halfprice", "=", "0", "@fullprice", "=", "0", "if", "halffare", "log_info", "\"assuming order prices as half-fare\"", "else", "log_info", "\"assuming order prices as full\"", "end", "log_notice", "\"please note that you are using a strategy that involves guessing the real price\"", "if", "[", "'guess'", ",", "'sbbguess'", "]", ".", "include?", "strategy", "strategy", "=", "price_factory", "(", "strategy", ")", "strategy", ".", "halffare", "=", "halffare", "log_info", "\"using price strategy: #{strategy.class}\"", "price", "=", "Price", ".", "new", "(", "strategy", ")", "log_info", "\"calculating prices...\"", "@date_min", "=", "false", "@date_max", "=", "false", "@orders", ".", "each", "do", "|", "order", "|", "if", "Halffare", ".", "debug", "log_order", "(", "order", ")", "end", "halfprice", ",", "fullprice", "=", "price", ".", "get", "(", "order", ")", "if", "Halffare", ".", "debug", "if", "halfprice", "!=", "0", "&&", "fullprice", "!=", "0", "log_result", "\"FOUND: #{order.description} (#{order.price}): half=#{currency(halfprice)}, full=#{currency(fullprice)}\"", "if", "halffare", "log_emphasize", "\"You would pay (full price): #{currency(fullprice)}, you save #{currency(fullprice - order.price)}\"", "else", "log_emphasize", "\"You would pay (half-fare): #{currency(halfprice)}, you pay #{currency(order.price - halfprice)} more\"", "end", "end", "end", "@halfprice", "+=", "halfprice", "@fullprice", "+=", "fullprice", "@date_min", "=", "order", ".", "travel_date", "if", "!", "@date_min", "||", "order", ".", "travel_date", "<", "@date_min", "@date_max", "=", "order", ".", "travel_date", "if", "!", "@date_max", "||", "order", ".", "travel_date", ">", "@date_max", "end", "end" ]
Calculates prices according to given strategy. @param strategy [String] Strategy name @param halffare [true, false] True if tickets were bought with a halffare card
[ "Calculates", "prices", "according", "to", "given", "strategy", "." ]
2c4c7563a9e0834e5d2d93c15bd052bb67f8996a
https://github.com/rndstr/halffare/blob/2c4c7563a9e0834e5d2d93c15bd052bb67f8996a/lib/halffare/stats.rb#L38-L84
train
barkerest/shells
lib/shells/shell_base/output.rb
Shells.ShellBase.buffer_output
def buffer_output(&block) #:doc: raise Shells::NotRunning unless running? block ||= Proc.new { } stdout_received do |data| self.last_output = Time.now append_stdout strip_ansi_escape(data), &block end stderr_received do |data| self.last_output = Time.now append_stderr strip_ansi_escape(data), &block end end
ruby
def buffer_output(&block) #:doc: raise Shells::NotRunning unless running? block ||= Proc.new { } stdout_received do |data| self.last_output = Time.now append_stdout strip_ansi_escape(data), &block end stderr_received do |data| self.last_output = Time.now append_stderr strip_ansi_escape(data), &block end end
[ "def", "buffer_output", "(", "&", "block", ")", "raise", "Shells", "::", "NotRunning", "unless", "running?", "block", "||=", "Proc", ".", "new", "{", "}", "stdout_received", "do", "|", "data", "|", "self", ".", "last_output", "=", "Time", ".", "now", "append_stdout", "strip_ansi_escape", "(", "data", ")", ",", "&", "block", "end", "stderr_received", "do", "|", "data", "|", "self", ".", "last_output", "=", "Time", ".", "now", "append_stderr", "strip_ansi_escape", "(", "data", ")", ",", "&", "block", "end", "end" ]
Sets the block to call when data is received. If no block is provided, then the shell will simply log all output from the program. If a block is provided, it will be passed the data as it is received. If the block returns a string, then that string will be sent to the shell. This method is called internally in the +exec+ method, but there may be legitimate use cases outside of that method as well.
[ "Sets", "the", "block", "to", "call", "when", "data", "is", "received", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/output.rb#L122-L133
train
barkerest/shells
lib/shells/shell_base/output.rb
Shells.ShellBase.push_buffer
def push_buffer raise Shells::NotRunning unless running? # push the buffer so we can get the output of a command. debug 'Pushing buffer >>' sync do output_stack.push [ stdout, stderr, output ] self.stdout = '' self.stderr = '' self.output = '' end end
ruby
def push_buffer raise Shells::NotRunning unless running? # push the buffer so we can get the output of a command. debug 'Pushing buffer >>' sync do output_stack.push [ stdout, stderr, output ] self.stdout = '' self.stderr = '' self.output = '' end end
[ "def", "push_buffer", "raise", "Shells", "::", "NotRunning", "unless", "running?", "debug", "'Pushing buffer >>'", "sync", "do", "output_stack", ".", "push", "[", "stdout", ",", "stderr", ",", "output", "]", "self", ".", "stdout", "=", "''", "self", ".", "stderr", "=", "''", "self", ".", "output", "=", "''", "end", "end" ]
Pushes the buffers for output capture. This method is called internally in the +exec+ method, but there may be legitimate use cases outside of that method as well.
[ "Pushes", "the", "buffers", "for", "output", "capture", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/output.rb#L164-L174
train
barkerest/shells
lib/shells/shell_base/output.rb
Shells.ShellBase.pop_merge_buffer
def pop_merge_buffer raise Shells::NotRunning unless running? # almost a standard pop, however we want to merge history with current. debug 'Merging buffer <<' sync do hist_stdout, hist_stderr, hist_output = (output_stack.pop || []) if hist_stdout self.stdout = hist_stdout + stdout end if hist_stderr self.stderr = hist_stderr + stderr end if hist_output self.output = hist_output + output end end end
ruby
def pop_merge_buffer raise Shells::NotRunning unless running? # almost a standard pop, however we want to merge history with current. debug 'Merging buffer <<' sync do hist_stdout, hist_stderr, hist_output = (output_stack.pop || []) if hist_stdout self.stdout = hist_stdout + stdout end if hist_stderr self.stderr = hist_stderr + stderr end if hist_output self.output = hist_output + output end end end
[ "def", "pop_merge_buffer", "raise", "Shells", "::", "NotRunning", "unless", "running?", "debug", "'Merging buffer <<'", "sync", "do", "hist_stdout", ",", "hist_stderr", ",", "hist_output", "=", "(", "output_stack", ".", "pop", "||", "[", "]", ")", "if", "hist_stdout", "self", ".", "stdout", "=", "hist_stdout", "+", "stdout", "end", "if", "hist_stderr", "self", ".", "stderr", "=", "hist_stderr", "+", "stderr", "end", "if", "hist_output", "self", ".", "output", "=", "hist_output", "+", "output", "end", "end", "end" ]
Pops the buffers and merges the captured output. This method is called internally in the +exec+ method, but there may be legitimate use cases outside of that method as well.
[ "Pops", "the", "buffers", "and", "merges", "the", "captured", "output", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/output.rb#L181-L197
train
barkerest/shells
lib/shells/shell_base/output.rb
Shells.ShellBase.pop_discard_buffer
def pop_discard_buffer raise Shells::NotRunning unless running? # a standard pop discarding current data and retrieving the history. debug 'Discarding buffer <<' sync do hist_stdout, hist_stderr, hist_output = (output_stack.pop || []) self.stdout = hist_stdout || '' self.stderr = hist_stderr || '' self.output = hist_output || '' end end
ruby
def pop_discard_buffer raise Shells::NotRunning unless running? # a standard pop discarding current data and retrieving the history. debug 'Discarding buffer <<' sync do hist_stdout, hist_stderr, hist_output = (output_stack.pop || []) self.stdout = hist_stdout || '' self.stderr = hist_stderr || '' self.output = hist_output || '' end end
[ "def", "pop_discard_buffer", "raise", "Shells", "::", "NotRunning", "unless", "running?", "debug", "'Discarding buffer <<'", "sync", "do", "hist_stdout", ",", "hist_stderr", ",", "hist_output", "=", "(", "output_stack", ".", "pop", "||", "[", "]", ")", "self", ".", "stdout", "=", "hist_stdout", "||", "''", "self", ".", "stderr", "=", "hist_stderr", "||", "''", "self", ".", "output", "=", "hist_output", "||", "''", "end", "end" ]
Pops the buffers and discards the captured output. This method is used internally in the +get_exit_code+ method, but there may be legitimate use cases outside of that method as well.
[ "Pops", "the", "buffers", "and", "discards", "the", "captured", "output", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/output.rb#L204-L214
train
devnull-tools/yummi
lib/yummi.rb
Yummi.BlockHandler.block_call
def block_call (context, &block) args = [] block.parameters.each do |parameter| args << context[parameter[1]] end block.call(*args) end
ruby
def block_call (context, &block) args = [] block.parameters.each do |parameter| args << context[parameter[1]] end block.call(*args) end
[ "def", "block_call", "(", "context", ",", "&", "block", ")", "args", "=", "[", "]", "block", ".", "parameters", ".", "each", "do", "|", "parameter", "|", "args", "<<", "context", "[", "parameter", "[", "1", "]", "]", "end", "block", ".", "call", "(", "*", "args", ")", "end" ]
Calls the block resolving the parameters by getting the parameter name from the given context. === Example context = :max => 10, :curr => 5, ratio => 0.15 percentage = BlockHandler.call_block(context) { |max,curr| curr.to_f / max }
[ "Calls", "the", "block", "resolving", "the", "parameters", "by", "getting", "the", "parameter", "name", "from", "the", "given", "context", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi.rb#L157-L163
train
devnull-tools/yummi
lib/yummi.rb
Yummi.GroupedComponent.call
def call (*args) result = nil @components.each do |component| break if result and not @call_all result = component.send @message, *args end result end
ruby
def call (*args) result = nil @components.each do |component| break if result and not @call_all result = component.send @message, *args end result end
[ "def", "call", "(", "*", "args", ")", "result", "=", "nil", "@components", ".", "each", "do", "|", "component", "|", "break", "if", "result", "and", "not", "@call_all", "result", "=", "component", ".", "send", "@message", ",", "*", "args", "end", "result", "end" ]
Calls the added components by sending the configured message and the given args.
[ "Calls", "the", "added", "components", "by", "sending", "the", "configured", "message", "and", "the", "given", "args", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi.rb#L229-L236
train
GemHQ/coin-op
lib/coin-op/bit/input.rb
CoinOp::Bit.Input.script_sig=
def script_sig=(blob) # This is only a setter because of the initial choice to do things # eagerly. Can become an attr_accessor when we move to lazy eval. script = Script.new(:blob => blob) @script_sig = script.to_s @native.script_sig = blob end
ruby
def script_sig=(blob) # This is only a setter because of the initial choice to do things # eagerly. Can become an attr_accessor when we move to lazy eval. script = Script.new(:blob => blob) @script_sig = script.to_s @native.script_sig = blob end
[ "def", "script_sig", "=", "(", "blob", ")", "script", "=", "Script", ".", "new", "(", ":blob", "=>", "blob", ")", "@script_sig", "=", "script", ".", "to_s", "@native", ".", "script_sig", "=", "blob", "end" ]
Set the scriptSig for this input using a string of bytes.
[ "Set", "the", "scriptSig", "for", "this", "input", "using", "a", "string", "of", "bytes", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/input.rb#L61-L67
train
epuber-io/bade
lib/bade/parser.rb
Bade.Parser.append_node
def append_node(type, indent: @indents.length, add: false, value: nil) # add necessary stack items to match required indent @stacks << @stacks.last.dup while indent >= @stacks.length parent = @stacks[indent].last node = AST::NodeRegistrator.create(type, @lineno) parent.children << node node.value = value unless value.nil? @stacks[indent] << node if add node end
ruby
def append_node(type, indent: @indents.length, add: false, value: nil) # add necessary stack items to match required indent @stacks << @stacks.last.dup while indent >= @stacks.length parent = @stacks[indent].last node = AST::NodeRegistrator.create(type, @lineno) parent.children << node node.value = value unless value.nil? @stacks[indent] << node if add node end
[ "def", "append_node", "(", "type", ",", "indent", ":", "@indents", ".", "length", ",", "add", ":", "false", ",", "value", ":", "nil", ")", "@stacks", "<<", "@stacks", ".", "last", ".", "dup", "while", "indent", ">=", "@stacks", ".", "length", "parent", "=", "@stacks", "[", "indent", "]", ".", "last", "node", "=", "AST", "::", "NodeRegistrator", ".", "create", "(", "type", ",", "@lineno", ")", "parent", ".", "children", "<<", "node", "node", ".", "value", "=", "value", "unless", "value", ".", "nil?", "@stacks", "[", "indent", "]", "<<", "node", "if", "add", "node", "end" ]
Append element to stacks and result tree @param [Symbol] type
[ "Append", "element", "to", "stacks", "and", "result", "tree" ]
fe128e0178d28b5a789d94b861ac6c6d2e4a3a8e
https://github.com/epuber-io/bade/blob/fe128e0178d28b5a789d94b861ac6c6d2e4a3a8e/lib/bade/parser.rb#L104-L117
train
JoshMcKin/hot_tub
lib/hot_tub/known_clients.rb
HotTub.KnownClients.clean_client
def clean_client(clnt) if @clean_client begin perform_action(clnt,@clean_client) rescue => e HotTub.logger.error "[HotTub] There was an error cleaning one of your #{self.class.name} clients: #{e}" if HotTub.logger end end clnt end
ruby
def clean_client(clnt) if @clean_client begin perform_action(clnt,@clean_client) rescue => e HotTub.logger.error "[HotTub] There was an error cleaning one of your #{self.class.name} clients: #{e}" if HotTub.logger end end clnt end
[ "def", "clean_client", "(", "clnt", ")", "if", "@clean_client", "begin", "perform_action", "(", "clnt", ",", "@clean_client", ")", "rescue", "=>", "e", "HotTub", ".", "logger", ".", "error", "\"[HotTub] There was an error cleaning one of your #{self.class.name} clients: #{e}\"", "if", "HotTub", ".", "logger", "end", "end", "clnt", "end" ]
Attempts to clean the provided client, checking the options first for a clean block then checking the known clients
[ "Attempts", "to", "clean", "the", "provided", "client", "checking", "the", "options", "first", "for", "a", "clean", "block", "then", "checking", "the", "known", "clients" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/known_clients.rb#L20-L29
train
JoshMcKin/hot_tub
lib/hot_tub/known_clients.rb
HotTub.KnownClients.close_client
def close_client(clnt) @close_client = (known_client_action(clnt,:close) || false) if @close_client.nil? if @close_client begin perform_action(clnt,@close_client) rescue => e HotTub.logger.error "[HotTub] There was an error closing one of your #{self.class.name} clients: #{e}" if HotTub.logger end end nil end
ruby
def close_client(clnt) @close_client = (known_client_action(clnt,:close) || false) if @close_client.nil? if @close_client begin perform_action(clnt,@close_client) rescue => e HotTub.logger.error "[HotTub] There was an error closing one of your #{self.class.name} clients: #{e}" if HotTub.logger end end nil end
[ "def", "close_client", "(", "clnt", ")", "@close_client", "=", "(", "known_client_action", "(", "clnt", ",", ":close", ")", "||", "false", ")", "if", "@close_client", ".", "nil?", "if", "@close_client", "begin", "perform_action", "(", "clnt", ",", "@close_client", ")", "rescue", "=>", "e", "HotTub", ".", "logger", ".", "error", "\"[HotTub] There was an error closing one of your #{self.class.name} clients: #{e}\"", "if", "HotTub", ".", "logger", "end", "end", "nil", "end" ]
Attempts to close the provided client, checking the options first for a close block then checking the known clients
[ "Attempts", "to", "close", "the", "provided", "client", "checking", "the", "options", "first", "for", "a", "close", "block", "then", "checking", "the", "known", "clients" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/known_clients.rb#L33-L43
train
JoshMcKin/hot_tub
lib/hot_tub/known_clients.rb
HotTub.KnownClients.reap_client?
def reap_client?(clnt) rc = false if @reap_client begin rc = perform_action(clnt,@reap_client) rescue => e HotTub.logger.error "[HotTub] There was an error reaping one of your #{self.class.name} clients: #{e}" if HotTub.logger end end rc end
ruby
def reap_client?(clnt) rc = false if @reap_client begin rc = perform_action(clnt,@reap_client) rescue => e HotTub.logger.error "[HotTub] There was an error reaping one of your #{self.class.name} clients: #{e}" if HotTub.logger end end rc end
[ "def", "reap_client?", "(", "clnt", ")", "rc", "=", "false", "if", "@reap_client", "begin", "rc", "=", "perform_action", "(", "clnt", ",", "@reap_client", ")", "rescue", "=>", "e", "HotTub", ".", "logger", ".", "error", "\"[HotTub] There was an error reaping one of your #{self.class.name} clients: #{e}\"", "if", "HotTub", ".", "logger", "end", "end", "rc", "end" ]
Attempts to determine if a client should be reaped, block should return a boolean
[ "Attempts", "to", "determine", "if", "a", "client", "should", "be", "reaped", "block", "should", "return", "a", "boolean" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/known_clients.rb#L46-L56
train
codescrum/bebox
lib/bebox/commands/commands_helper.rb
Bebox.CommandsHelper.get_environment
def get_environment(options) environment = options[:environment] # Ask for environment of node if flag environment not set environment ||= choose_option(Environment.list(project_root), _('cli.choose_environment')) # Check environment existence Bebox::Environment.environment_exists?(project_root, environment) ? (return environment) : exit_now!(error(_('cli.not_exist_environment')%{environment: environment})) end
ruby
def get_environment(options) environment = options[:environment] # Ask for environment of node if flag environment not set environment ||= choose_option(Environment.list(project_root), _('cli.choose_environment')) # Check environment existence Bebox::Environment.environment_exists?(project_root, environment) ? (return environment) : exit_now!(error(_('cli.not_exist_environment')%{environment: environment})) end
[ "def", "get_environment", "(", "options", ")", "environment", "=", "options", "[", ":environment", "]", "environment", "||=", "choose_option", "(", "Environment", ".", "list", "(", "project_root", ")", ",", "_", "(", "'cli.choose_environment'", ")", ")", "Bebox", "::", "Environment", ".", "environment_exists?", "(", "project_root", ",", "environment", ")", "?", "(", "return", "environment", ")", ":", "exit_now!", "(", "error", "(", "_", "(", "'cli.not_exist_environment'", ")", "%", "{", "environment", ":", "environment", "}", ")", ")", "end" ]
Obtain the environment from command parameters or menu
[ "Obtain", "the", "environment", "from", "command", "parameters", "or", "menu" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/commands_helper.rb#L8-L14
train
codescrum/bebox
lib/bebox/commands/commands_helper.rb
Bebox.CommandsHelper.default_environment
def default_environment environments = Bebox::Environment.list(project_root) if environments.count > 0 return environments.include?('vagrant') ? 'vagrant' : environments.first else return '' end end
ruby
def default_environment environments = Bebox::Environment.list(project_root) if environments.count > 0 return environments.include?('vagrant') ? 'vagrant' : environments.first else return '' end end
[ "def", "default_environment", "environments", "=", "Bebox", "::", "Environment", ".", "list", "(", "project_root", ")", "if", "environments", ".", "count", ">", "0", "return", "environments", ".", "include?", "(", "'vagrant'", ")", "?", "'vagrant'", ":", "environments", ".", "first", "else", "return", "''", "end", "end" ]
Obtain the default environment for a project
[ "Obtain", "the", "default", "environment", "for", "a", "project" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/commands_helper.rb#L17-L24
train
formatafacil/formatafacil
lib/formatafacil/artigo_tarefa.rb
Formatafacil.ArtigoTarefa.converte_configuracao_para_latex
def converte_configuracao_para_latex @artigo_latex.merge!(@artigo) ['resumo','abstract','bibliografia'].each {|key| Open3.popen3("pandoc --smart -f markdown -t latex --no-wrap") {|stdin, stdout, stderr, wait_thr| pid = wait_thr.pid # pid of the started process. stdin.write @artigo[key] stdin.close @artigo_latex[key] = stdout.read } } end
ruby
def converte_configuracao_para_latex @artigo_latex.merge!(@artigo) ['resumo','abstract','bibliografia'].each {|key| Open3.popen3("pandoc --smart -f markdown -t latex --no-wrap") {|stdin, stdout, stderr, wait_thr| pid = wait_thr.pid # pid of the started process. stdin.write @artigo[key] stdin.close @artigo_latex[key] = stdout.read } } end
[ "def", "converte_configuracao_para_latex", "@artigo_latex", ".", "merge!", "(", "@artigo", ")", "[", "'resumo'", ",", "'abstract'", ",", "'bibliografia'", "]", ".", "each", "{", "|", "key", "|", "Open3", ".", "popen3", "(", "\"pandoc --smart -f markdown -t latex --no-wrap\"", ")", "{", "|", "stdin", ",", "stdout", ",", "stderr", ",", "wait_thr", "|", "pid", "=", "wait_thr", ".", "pid", "stdin", ".", "write", "@artigo", "[", "key", "]", "stdin", ".", "close", "@artigo_latex", "[", "key", "]", "=", "stdout", ".", "read", "}", "}", "end" ]
Converte os arquivos de texto markdown para texto latex
[ "Converte", "os", "arquivos", "de", "texto", "markdown", "para", "texto", "latex" ]
f3dcf72128ded4168215f1e947c75264d6d38b38
https://github.com/formatafacil/formatafacil/blob/f3dcf72128ded4168215f1e947c75264d6d38b38/lib/formatafacil/artigo_tarefa.rb#L295-L306
train
formatafacil/formatafacil
lib/formatafacil/artigo_tarefa.rb
Formatafacil.ArtigoTarefa.salva_configuracao_yaml_para_inclusao_em_pandoc
def salva_configuracao_yaml_para_inclusao_em_pandoc File.open(@arquivo_saida_yaml, 'w'){ |file| file.write("\n") file.write @artigo_latex.to_yaml file.write("---\n") } end
ruby
def salva_configuracao_yaml_para_inclusao_em_pandoc File.open(@arquivo_saida_yaml, 'w'){ |file| file.write("\n") file.write @artigo_latex.to_yaml file.write("---\n") } end
[ "def", "salva_configuracao_yaml_para_inclusao_em_pandoc", "File", ".", "open", "(", "@arquivo_saida_yaml", ",", "'w'", ")", "{", "|", "file", "|", "file", ".", "write", "(", "\"\\n\"", ")", "file", ".", "write", "@artigo_latex", ".", "to_yaml", "file", ".", "write", "(", "\"---\\n\"", ")", "}", "end" ]
Precisa gerar arquivos com quebra de linha antes e depois porque pandoc utiliza
[ "Precisa", "gerar", "arquivos", "com", "quebra", "de", "linha", "antes", "e", "depois", "porque", "pandoc", "utiliza" ]
f3dcf72128ded4168215f1e947c75264d6d38b38
https://github.com/formatafacil/formatafacil/blob/f3dcf72128ded4168215f1e947c75264d6d38b38/lib/formatafacil/artigo_tarefa.rb#L340-L346
train
lingzhang-lyon/highwatermark
lib/highwatermark.rb
Highwatermark.HighWaterMark.last_records
def last_records(tag=@state_tag) if @state_type == 'file' return @data['last_records'][tag] elsif @state_type =='memory' return @data['last_records'][tag] elsif @state_type =='redis' begin [email protected](tag) return alertStart rescue Exception => e puts e.message puts e.backtrace.inspect end end end
ruby
def last_records(tag=@state_tag) if @state_type == 'file' return @data['last_records'][tag] elsif @state_type =='memory' return @data['last_records'][tag] elsif @state_type =='redis' begin [email protected](tag) return alertStart rescue Exception => e puts e.message puts e.backtrace.inspect end end end
[ "def", "last_records", "(", "tag", "=", "@state_tag", ")", "if", "@state_type", "==", "'file'", "return", "@data", "[", "'last_records'", "]", "[", "tag", "]", "elsif", "@state_type", "==", "'memory'", "return", "@data", "[", "'last_records'", "]", "[", "tag", "]", "elsif", "@state_type", "==", "'redis'", "begin", "alertStart", "=", "@redis", ".", "get", "(", "tag", ")", "return", "alertStart", "rescue", "Exception", "=>", "e", "puts", "e", ".", "message", "puts", "e", ".", "backtrace", ".", "inspect", "end", "end", "end" ]
end of intitialize
[ "end", "of", "intitialize" ]
704c7ea71a4ba638c4483e9e32eda853573b948d
https://github.com/lingzhang-lyon/highwatermark/blob/704c7ea71a4ba638c4483e9e32eda853573b948d/lib/highwatermark.rb#L90-L105
train
Montage-Inc/ruby-montage
lib/montage/query/query_parser.rb
Montage.QueryParser.get_query_operator
def get_query_operator(part) operator = Montage::Operators.find_operator(part) [operator.operator, operator.montage_operator] end
ruby
def get_query_operator(part) operator = Montage::Operators.find_operator(part) [operator.operator, operator.montage_operator] end
[ "def", "get_query_operator", "(", "part", ")", "operator", "=", "Montage", "::", "Operators", ".", "find_operator", "(", "part", ")", "[", "operator", ".", "operator", ",", "operator", ".", "montage_operator", "]", "end" ]
Grabs the proper query operator from the string * *Args* : - +part+ -> The query string * *Returns* : - An array containing the supplied logical operator and the Montage equivalent * *Examples* : @part = "tree_happiness_level > 9" get_query_operator(@part) => [">", "$gt"]
[ "Grabs", "the", "proper", "query", "operator", "from", "the", "string" ]
2e6f7e591f2f87158994c17ad9619fa29b716bad
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/query_parser.rb#L60-L63
train
Montage-Inc/ruby-montage
lib/montage/query/query_parser.rb
Montage.QueryParser.parse_part
def parse_part(part) parsed_part = JSON.parse(part) rescue part if is_i?(parsed_part) parsed_part.to_i elsif is_f?(parsed_part) parsed_part.to_f elsif parsed_part =~ /\(.*\)/ to_array(parsed_part) elsif parsed_part.is_a?(Array) parsed_part else parsed_part.gsub(/('|')/, "") end end
ruby
def parse_part(part) parsed_part = JSON.parse(part) rescue part if is_i?(parsed_part) parsed_part.to_i elsif is_f?(parsed_part) parsed_part.to_f elsif parsed_part =~ /\(.*\)/ to_array(parsed_part) elsif parsed_part.is_a?(Array) parsed_part else parsed_part.gsub(/('|')/, "") end end
[ "def", "parse_part", "(", "part", ")", "parsed_part", "=", "JSON", ".", "parse", "(", "part", ")", "rescue", "part", "if", "is_i?", "(", "parsed_part", ")", "parsed_part", ".", "to_i", "elsif", "is_f?", "(", "parsed_part", ")", "parsed_part", ".", "to_f", "elsif", "parsed_part", "=~", "/", "\\(", "\\)", "/", "to_array", "(", "parsed_part", ")", "elsif", "parsed_part", ".", "is_a?", "(", "Array", ")", "parsed_part", "else", "parsed_part", ".", "gsub", "(", "/", "/", ",", "\"\"", ")", "end", "end" ]
Parse a single portion of the query string. String values representing a float or integer are coerced into actual numerical values. Newline characters are removed and single quotes are replaced with double quotes * *Args* : - +part+ -> The value element extracted from the query string * *Returns* : - A parsed form of the value element * *Examples* : @part = "9" parse_part(@part) => 9
[ "Parse", "a", "single", "portion", "of", "the", "query", "string", ".", "String", "values", "representing", "a", "float", "or", "integer", "are", "coerced", "into", "actual", "numerical", "values", ".", "Newline", "characters", "are", "removed", "and", "single", "quotes", "are", "replaced", "with", "double", "quotes" ]
2e6f7e591f2f87158994c17ad9619fa29b716bad
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/query_parser.rb#L94-L108
train
Montage-Inc/ruby-montage
lib/montage/query/query_parser.rb
Montage.QueryParser.get_parts
def get_parts(str) operator, montage_operator = get_query_operator(str) fail QueryError, "Invalid Montage query operator!" unless montage_operator column_name = get_column_name(str, operator) fail QueryError, "Your query has an undetermined error" unless column_name value = parse_part(parse_condition_set(str, operator)) [column_name, montage_operator, value] end
ruby
def get_parts(str) operator, montage_operator = get_query_operator(str) fail QueryError, "Invalid Montage query operator!" unless montage_operator column_name = get_column_name(str, operator) fail QueryError, "Your query has an undetermined error" unless column_name value = parse_part(parse_condition_set(str, operator)) [column_name, montage_operator, value] end
[ "def", "get_parts", "(", "str", ")", "operator", ",", "montage_operator", "=", "get_query_operator", "(", "str", ")", "fail", "QueryError", ",", "\"Invalid Montage query operator!\"", "unless", "montage_operator", "column_name", "=", "get_column_name", "(", "str", ",", "operator", ")", "fail", "QueryError", ",", "\"Your query has an undetermined error\"", "unless", "column_name", "value", "=", "parse_part", "(", "parse_condition_set", "(", "str", ",", "operator", ")", ")", "[", "column_name", ",", "montage_operator", ",", "value", "]", "end" ]
Get all the parts of the query string * *Args* : - +str+ -> The query string * *Returns* : - An array containing the column name, the montage operator, and the value for comparison. * *Raises* : - +QueryError+ -> When incomplete queries or queries without valid operators are initialized * *Examples* : @part = "tree_happiness_level > 9" get_parts(@part) => ["tree_happiness_level", "$gt", 9]
[ "Get", "all", "the", "parts", "of", "the", "query", "string" ]
2e6f7e591f2f87158994c17ad9619fa29b716bad
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/query_parser.rb#L125-L137
train
Montage-Inc/ruby-montage
lib/montage/query/query_parser.rb
Montage.QueryParser.parse_hash
def parse_hash query.map do |key, value| new_value = value.is_a?(Array) ? ["$in", value] : value [key.to_s, new_value] end end
ruby
def parse_hash query.map do |key, value| new_value = value.is_a?(Array) ? ["$in", value] : value [key.to_s, new_value] end end
[ "def", "parse_hash", "query", ".", "map", "do", "|", "key", ",", "value", "|", "new_value", "=", "value", ".", "is_a?", "(", "Array", ")", "?", "[", "\"$in\"", ",", "value", "]", ":", "value", "[", "key", ".", "to_s", ",", "new_value", "]", "end", "end" ]
Parse a hash type query * *Returns* : - A ReQON compatible array * *Examples* : @test = Montage::QueryParser.new(tree_status: "happy") @test.parse_hash => [["tree_status", "happy"]]
[ "Parse", "a", "hash", "type", "query" ]
2e6f7e591f2f87158994c17ad9619fa29b716bad
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/query_parser.rb#L148-L153
train
Montage-Inc/ruby-montage
lib/montage/query/query_parser.rb
Montage.QueryParser.parse_string
def parse_string query.split(/\band\b(?=(?:[^']|'[^']*')*$)/i).map do |part| column_name, operator, value = get_parts(part) if operator == "" ["#{column_name}", value] else ["#{column_name}", ["#{operator}", value]] end end end
ruby
def parse_string query.split(/\band\b(?=(?:[^']|'[^']*')*$)/i).map do |part| column_name, operator, value = get_parts(part) if operator == "" ["#{column_name}", value] else ["#{column_name}", ["#{operator}", value]] end end end
[ "def", "parse_string", "query", ".", "split", "(", "/", "\\b", "\\b", "/i", ")", ".", "map", "do", "|", "part", "|", "column_name", ",", "operator", ",", "value", "=", "get_parts", "(", "part", ")", "if", "operator", "==", "\"\"", "[", "\"#{column_name}\"", ",", "value", "]", "else", "[", "\"#{column_name}\"", ",", "[", "\"#{operator}\"", ",", "value", "]", "]", "end", "end", "end" ]
Parse a string type query. Splits multiple conditions on case insensitive "and" strings that do not fall within single quotations. Note that the Montage equals operator is supplied as a blank string * *Returns* : - A ReQON compatible array * *Examples* : @test = Montage::QueryParser.new("tree_happiness_level > 9") @test.parse_string => [["tree_happiness_level", ["$__gt", 9]]]
[ "Parse", "a", "string", "type", "query", ".", "Splits", "multiple", "conditions", "on", "case", "insensitive", "and", "strings", "that", "do", "not", "fall", "within", "single", "quotations", ".", "Note", "that", "the", "Montage", "equals", "operator", "is", "supplied", "as", "a", "blank", "string" ]
2e6f7e591f2f87158994c17ad9619fa29b716bad
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/query_parser.rb#L166-L175
train
Montage-Inc/ruby-montage
lib/montage/query/query_parser.rb
Montage.QueryParser.to_array
def to_array(value) values = value.gsub(/('|\(|\))/, "").split(',') type = [:is_i?, :is_f?].find(Proc.new { :is_s? }) { |t| send(t, values.first) } values.map { |v| v.send(TYPE_MAP[type]) } end
ruby
def to_array(value) values = value.gsub(/('|\(|\))/, "").split(',') type = [:is_i?, :is_f?].find(Proc.new { :is_s? }) { |t| send(t, values.first) } values.map { |v| v.send(TYPE_MAP[type]) } end
[ "def", "to_array", "(", "value", ")", "values", "=", "value", ".", "gsub", "(", "/", "\\(", "\\)", "/", ",", "\"\"", ")", ".", "split", "(", "','", ")", "type", "=", "[", ":is_i?", ",", ":is_f?", "]", ".", "find", "(", "Proc", ".", "new", "{", ":is_s?", "}", ")", "{", "|", "t", "|", "send", "(", "t", ",", "values", ".", "first", ")", "}", "values", ".", "map", "{", "|", "v", "|", "v", ".", "send", "(", "TYPE_MAP", "[", "type", "]", ")", "}", "end" ]
Takes a string value and splits it into an array Will coerce all values into the type of the first type * *Args* : - +value+ -> A string value * *Returns* : - A array form of the value argument * *Examples* : @part = "(1, 2, 3)" to_array(@part) => [1, 2, 3]
[ "Takes", "a", "string", "value", "and", "splits", "it", "into", "an", "array", "Will", "coerce", "all", "values", "into", "the", "type", "of", "the", "first", "type" ]
2e6f7e591f2f87158994c17ad9619fa29b716bad
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/query_parser.rb#L199-L203
train
KatanaCode/evvnt
lib/evvnt/nested_resources.rb
Evvnt.NestedResources.belongs_to
def belongs_to(parent_resource) parent_resource = parent_resource.to_sym parent_resources << parent_resource unless parent_resource.in?(parent_resources) end
ruby
def belongs_to(parent_resource) parent_resource = parent_resource.to_sym parent_resources << parent_resource unless parent_resource.in?(parent_resources) end
[ "def", "belongs_to", "(", "parent_resource", ")", "parent_resource", "=", "parent_resource", ".", "to_sym", "parent_resources", "<<", "parent_resource", "unless", "parent_resource", ".", "in?", "(", "parent_resources", ")", "end" ]
Tell a class that it's resources may be nested within another named resource parent_resource - A Symbol with the name of the parent resource.
[ "Tell", "a", "class", "that", "it", "s", "resources", "may", "be", "nested", "within", "another", "named", "resource" ]
e13f6d84af09a71819356620fb25685a6cd159c9
https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/nested_resources.rb#L21-L24
train
atomicobject/kinetic-ruby
lib/kinetic_server.rb
KineticRuby.Client.receive
def receive(max_len=nil) max_len ||= 1024 begin data = @socket.recv(max_len) rescue IO::WaitReadable @logger.logv 'Retrying receive...' IO.select([@socket]) retry rescue Exception => e if e.class != 'IOError' && e.message != 'closed stream' @logger.log_exception(e, 'EXCEPTION during receive!') end end if (data.nil? || data.empty?) @logger.log "Client #{@socket.inspect} disconnected!" data = '' else @logger.log "Received #{data.length} bytes" end return data end
ruby
def receive(max_len=nil) max_len ||= 1024 begin data = @socket.recv(max_len) rescue IO::WaitReadable @logger.logv 'Retrying receive...' IO.select([@socket]) retry rescue Exception => e if e.class != 'IOError' && e.message != 'closed stream' @logger.log_exception(e, 'EXCEPTION during receive!') end end if (data.nil? || data.empty?) @logger.log "Client #{@socket.inspect} disconnected!" data = '' else @logger.log "Received #{data.length} bytes" end return data end
[ "def", "receive", "(", "max_len", "=", "nil", ")", "max_len", "||=", "1024", "begin", "data", "=", "@socket", ".", "recv", "(", "max_len", ")", "rescue", "IO", "::", "WaitReadable", "@logger", ".", "logv", "'Retrying receive...'", "IO", ".", "select", "(", "[", "@socket", "]", ")", "retry", "rescue", "Exception", "=>", "e", "if", "e", ".", "class", "!=", "'IOError'", "&&", "e", ".", "message", "!=", "'closed stream'", "@logger", ".", "log_exception", "(", "e", ",", "'EXCEPTION during receive!'", ")", "end", "end", "if", "(", "data", ".", "nil?", "||", "data", ".", "empty?", ")", "@logger", ".", "log", "\"Client #{@socket.inspect} disconnected!\"", "data", "=", "''", "else", "@logger", ".", "log", "\"Received #{data.length} bytes\"", "end", "return", "data", "end" ]
Wait to receive data from the client @param max_len Maximum number of bytes to receive @returns Received data (length <= max_len) or nil upon failure
[ "Wait", "to", "receive", "data", "from", "the", "client" ]
bc2a6331d75d30071f365d506e0a6abe2e808dc6
https://github.com/atomicobject/kinetic-ruby/blob/bc2a6331d75d30071f365d506e0a6abe2e808dc6/lib/kinetic_server.rb#L37-L60
train
barkerest/incline
lib/incline/validators/ip_address_validator.rb
Incline.IpAddressValidator.validate_each
def validate_each(record, attribute, value) begin unless value.blank? IPAddr.new(value) if options[:no_mask] if value =~ /\// record.errors[attribute] << (options[:message] || 'must not contain a mask') end elsif options[:require_mask] unless value =~ /\// record.errors[attribute] << (options[:message] || 'must contain a mask') end end end rescue IPAddr::InvalidAddressError record.errors[attribute] << (options[:message] || 'is not a valid IP address') end end
ruby
def validate_each(record, attribute, value) begin unless value.blank? IPAddr.new(value) if options[:no_mask] if value =~ /\// record.errors[attribute] << (options[:message] || 'must not contain a mask') end elsif options[:require_mask] unless value =~ /\// record.errors[attribute] << (options[:message] || 'must contain a mask') end end end rescue IPAddr::InvalidAddressError record.errors[attribute] << (options[:message] || 'is not a valid IP address') end end
[ "def", "validate_each", "(", "record", ",", "attribute", ",", "value", ")", "begin", "unless", "value", ".", "blank?", "IPAddr", ".", "new", "(", "value", ")", "if", "options", "[", ":no_mask", "]", "if", "value", "=~", "/", "\\/", "/", "record", ".", "errors", "[", "attribute", "]", "<<", "(", "options", "[", ":message", "]", "||", "'must not contain a mask'", ")", "end", "elsif", "options", "[", ":require_mask", "]", "unless", "value", "=~", "/", "\\/", "/", "record", ".", "errors", "[", "attribute", "]", "<<", "(", "options", "[", ":message", "]", "||", "'must contain a mask'", ")", "end", "end", "end", "rescue", "IPAddr", "::", "InvalidAddressError", "record", ".", "errors", "[", "attribute", "]", "<<", "(", "options", "[", ":message", "]", "||", "'is not a valid IP address'", ")", "end", "end" ]
Validates attributes to determine if the values contain valid IP addresses. Set the :no_mask option to restrict the IP address to singular addresses only.
[ "Validates", "attributes", "to", "determine", "if", "the", "values", "contain", "valid", "IP", "addresses", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/validators/ip_address_validator.rb#L12-L29
train
salesking/sk_sdk
lib/sk_sdk/ar_patches/ar3/base.rb
ActiveResource.Base.load_attributes_from_response
def load_attributes_from_response(response) if (response['Transfer-Encoding'] == 'chunked' || (!response['Content-Length'].blank? && response['Content-Length'] != "0")) && !response.body.nil? && response.body.strip.size > 0 load( self.class.format.decode(response.body)[self.class.element_name] ) #fix double nested items .. active resource SUCKS soooo bad if self.respond_to?(:items) new_items = [] self.items.each { |item| new_items << item.attributes.first[1] } self.items = new_items end @persisted = true end end
ruby
def load_attributes_from_response(response) if (response['Transfer-Encoding'] == 'chunked' || (!response['Content-Length'].blank? && response['Content-Length'] != "0")) && !response.body.nil? && response.body.strip.size > 0 load( self.class.format.decode(response.body)[self.class.element_name] ) #fix double nested items .. active resource SUCKS soooo bad if self.respond_to?(:items) new_items = [] self.items.each { |item| new_items << item.attributes.first[1] } self.items = new_items end @persisted = true end end
[ "def", "load_attributes_from_response", "(", "response", ")", "if", "(", "response", "[", "'Transfer-Encoding'", "]", "==", "'chunked'", "||", "(", "!", "response", "[", "'Content-Length'", "]", ".", "blank?", "&&", "response", "[", "'Content-Length'", "]", "!=", "\"0\"", ")", ")", "&&", "!", "response", ".", "body", ".", "nil?", "&&", "response", ".", "body", ".", "strip", ".", "size", ">", "0", "load", "(", "self", ".", "class", ".", "format", ".", "decode", "(", "response", ".", "body", ")", "[", "self", ".", "class", ".", "element_name", "]", ")", "if", "self", ".", "respond_to?", "(", ":items", ")", "new_items", "=", "[", "]", "self", ".", "items", ".", "each", "{", "|", "item", "|", "new_items", "<<", "item", ".", "attributes", ".", "first", "[", "1", "]", "}", "self", ".", "items", "=", "new_items", "end", "@persisted", "=", "true", "end", "end" ]
override ARes method to parse only the client part
[ "override", "ARes", "method", "to", "parse", "only", "the", "client", "part" ]
03170b2807cc4e1f1ba44c704c308370c6563dbc
https://github.com/salesking/sk_sdk/blob/03170b2807cc4e1f1ba44c704c308370c6563dbc/lib/sk_sdk/ar_patches/ar3/base.rb#L8-L19
train
roberthoner/encrypted_store
lib/encrypted_store/config.rb
EncryptedStore.Config.method_missing
def method_missing(meth, *args, &block) meth_str = meth.to_s if /^(\w+)\=$/.match(meth_str) _set($1, *args, &block) elsif args.length > 0 || block_given? _add(meth, *args, &block) elsif /^(\w+)\?$/.match(meth_str) !!_get($1) else _get_or_create_namespace(meth) end end
ruby
def method_missing(meth, *args, &block) meth_str = meth.to_s if /^(\w+)\=$/.match(meth_str) _set($1, *args, &block) elsif args.length > 0 || block_given? _add(meth, *args, &block) elsif /^(\w+)\?$/.match(meth_str) !!_get($1) else _get_or_create_namespace(meth) end end
[ "def", "method_missing", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "meth_str", "=", "meth", ".", "to_s", "if", "/", "\\w", "\\=", "/", ".", "match", "(", "meth_str", ")", "_set", "(", "$1", ",", "*", "args", ",", "&", "block", ")", "elsif", "args", ".", "length", ">", "0", "||", "block_given?", "_add", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "elsif", "/", "\\w", "\\?", "/", ".", "match", "(", "meth_str", ")", "!", "!", "_get", "(", "$1", ")", "else", "_get_or_create_namespace", "(", "meth", ")", "end", "end" ]
Deep dup all the values.
[ "Deep", "dup", "all", "the", "values", "." ]
89e78eb19e0cb710b08b71209e42eda085dcaa8a
https://github.com/roberthoner/encrypted_store/blob/89e78eb19e0cb710b08b71209e42eda085dcaa8a/lib/encrypted_store/config.rb#L59-L71
train
nrser/nrser.rb
lib/nrser/errors/attr_error.rb
NRSER.AttrError.default_message
def default_message message = [] if value? && name? message << format_message( value.class, "object", value.inspect, "has invalid ##{ name } attribute" ) end if expected? message << format_message( "expected", expected ) end if actual? message << format_message( "found", actual ) end if message.empty? super else message.join ', ' end end
ruby
def default_message message = [] if value? && name? message << format_message( value.class, "object", value.inspect, "has invalid ##{ name } attribute" ) end if expected? message << format_message( "expected", expected ) end if actual? message << format_message( "found", actual ) end if message.empty? super else message.join ', ' end end
[ "def", "default_message", "message", "=", "[", "]", "if", "value?", "&&", "name?", "message", "<<", "format_message", "(", "value", ".", "class", ",", "\"object\"", ",", "value", ".", "inspect", ",", "\"has invalid ##{ name } attribute\"", ")", "end", "if", "expected?", "message", "<<", "format_message", "(", "\"expected\"", ",", "expected", ")", "end", "if", "actual?", "message", "<<", "format_message", "(", "\"found\"", ",", "actual", ")", "end", "if", "message", ".", "empty?", "super", "else", "message", ".", "join", "', '", "end", "end" ]
Create a default message if none was provided. Uses whatever recognized {#context} values are present, falling back to {NicerError#default_message} if none are. @return [String]
[ "Create", "a", "default", "message", "if", "none", "was", "provided", "." ]
7db9a729ec65894dfac13fd50851beae8b809738
https://github.com/nrser/nrser.rb/blob/7db9a729ec65894dfac13fd50851beae8b809738/lib/nrser/errors/attr_error.rb#L137-L158
train
nafu/aws_sns_manager
lib/aws_sns_manager/client.rb
AwsSnsManager.Client.message
def message(text, options = {}, env = :prod, type = :normal) if type == :normal data = normal_notification(text, options) elsif type == :silent data = silent_notification(text, options) elsif type == :nosound data = nosound_notification(text, options) end return dev_json(data) if env == :dev prod_json(data) end
ruby
def message(text, options = {}, env = :prod, type = :normal) if type == :normal data = normal_notification(text, options) elsif type == :silent data = silent_notification(text, options) elsif type == :nosound data = nosound_notification(text, options) end return dev_json(data) if env == :dev prod_json(data) end
[ "def", "message", "(", "text", ",", "options", "=", "{", "}", ",", "env", "=", ":prod", ",", "type", "=", ":normal", ")", "if", "type", "==", ":normal", "data", "=", "normal_notification", "(", "text", ",", "options", ")", "elsif", "type", "==", ":silent", "data", "=", "silent_notification", "(", "text", ",", "options", ")", "elsif", "type", "==", ":nosound", "data", "=", "nosound_notification", "(", "text", ",", "options", ")", "end", "return", "dev_json", "(", "data", ")", "if", "env", "==", ":dev", "prod_json", "(", "data", ")", "end" ]
Return json payload +text+:: Text you want to send +options+:: Options you want on payload +env+:: Environments :prod, :dev +type+:: Notification type :normal, :silent, :nosound
[ "Return", "json", "payload" ]
9ec6ce1799d1195108e95a1efa2dd21437220a3e
https://github.com/nafu/aws_sns_manager/blob/9ec6ce1799d1195108e95a1efa2dd21437220a3e/lib/aws_sns_manager/client.rb#L37-L47
train
rightscale/right_amqp
lib/right_amqp/ha_client/broker_client.rb
RightAMQP.BrokerClient.subscribe
def subscribe(queue, exchange = nil, options = {}, &block) raise ArgumentError, "Must call this method with a block" unless block return false unless usable? return true unless @queues.select { |q| q.name == queue[:name] }.empty? to_exchange = if exchange if options[:exchange2] " to exchanges #{exchange[:name]} and #{options[:exchange2][:name]}" else " to exchange #{exchange[:name]}" end end queue_options = queue[:options] || {} exchange_options = (exchange && exchange[:options]) || {} begin logger.info("[setup] Subscribing queue #{queue[:name]}#{to_exchange} on broker #{@alias}") q = @channel.queue(queue[:name], queue_options) @queues << q if exchange x = @channel.__send__(exchange[:type], exchange[:name], exchange_options) binding = q.bind(x, options[:key] ? {:key => options[:key]} : {}) if (exchange2 = options[:exchange2]) q.bind(@channel.__send__(exchange2[:type], exchange2[:name], exchange2[:options] || {})) end q = binding end q.subscribe(options[:ack] ? {:ack => true} : {}) do |header, message| begin if (pool = (options[:fiber_pool] || @options[:fiber_pool])) pool.spawn { receive(queue[:name], header, message, options, &block) } else receive(queue[:name], header, message, options, &block) end rescue StandardError => e header.ack if options[:ack] logger.exception("Failed setting up to receive message from queue #{queue.inspect} " + "on broker #{@alias}", e, :trace) @exception_stats.track("receive", e) update_non_delivery_stats("receive failure", e) end end rescue StandardError => e logger.exception("Failed subscribing queue #{queue.inspect}#{to_exchange} on broker #{@alias}", e, :trace) @exception_stats.track("subscribe", e) false end end
ruby
def subscribe(queue, exchange = nil, options = {}, &block) raise ArgumentError, "Must call this method with a block" unless block return false unless usable? return true unless @queues.select { |q| q.name == queue[:name] }.empty? to_exchange = if exchange if options[:exchange2] " to exchanges #{exchange[:name]} and #{options[:exchange2][:name]}" else " to exchange #{exchange[:name]}" end end queue_options = queue[:options] || {} exchange_options = (exchange && exchange[:options]) || {} begin logger.info("[setup] Subscribing queue #{queue[:name]}#{to_exchange} on broker #{@alias}") q = @channel.queue(queue[:name], queue_options) @queues << q if exchange x = @channel.__send__(exchange[:type], exchange[:name], exchange_options) binding = q.bind(x, options[:key] ? {:key => options[:key]} : {}) if (exchange2 = options[:exchange2]) q.bind(@channel.__send__(exchange2[:type], exchange2[:name], exchange2[:options] || {})) end q = binding end q.subscribe(options[:ack] ? {:ack => true} : {}) do |header, message| begin if (pool = (options[:fiber_pool] || @options[:fiber_pool])) pool.spawn { receive(queue[:name], header, message, options, &block) } else receive(queue[:name], header, message, options, &block) end rescue StandardError => e header.ack if options[:ack] logger.exception("Failed setting up to receive message from queue #{queue.inspect} " + "on broker #{@alias}", e, :trace) @exception_stats.track("receive", e) update_non_delivery_stats("receive failure", e) end end rescue StandardError => e logger.exception("Failed subscribing queue #{queue.inspect}#{to_exchange} on broker #{@alias}", e, :trace) @exception_stats.track("subscribe", e) false end end
[ "def", "subscribe", "(", "queue", ",", "exchange", "=", "nil", ",", "options", "=", "{", "}", ",", "&", "block", ")", "raise", "ArgumentError", ",", "\"Must call this method with a block\"", "unless", "block", "return", "false", "unless", "usable?", "return", "true", "unless", "@queues", ".", "select", "{", "|", "q", "|", "q", ".", "name", "==", "queue", "[", ":name", "]", "}", ".", "empty?", "to_exchange", "=", "if", "exchange", "if", "options", "[", ":exchange2", "]", "\" to exchanges #{exchange[:name]} and #{options[:exchange2][:name]}\"", "else", "\" to exchange #{exchange[:name]}\"", "end", "end", "queue_options", "=", "queue", "[", ":options", "]", "||", "{", "}", "exchange_options", "=", "(", "exchange", "&&", "exchange", "[", ":options", "]", ")", "||", "{", "}", "begin", "logger", ".", "info", "(", "\"[setup] Subscribing queue #{queue[:name]}#{to_exchange} on broker #{@alias}\"", ")", "q", "=", "@channel", ".", "queue", "(", "queue", "[", ":name", "]", ",", "queue_options", ")", "@queues", "<<", "q", "if", "exchange", "x", "=", "@channel", ".", "__send__", "(", "exchange", "[", ":type", "]", ",", "exchange", "[", ":name", "]", ",", "exchange_options", ")", "binding", "=", "q", ".", "bind", "(", "x", ",", "options", "[", ":key", "]", "?", "{", ":key", "=>", "options", "[", ":key", "]", "}", ":", "{", "}", ")", "if", "(", "exchange2", "=", "options", "[", ":exchange2", "]", ")", "q", ".", "bind", "(", "@channel", ".", "__send__", "(", "exchange2", "[", ":type", "]", ",", "exchange2", "[", ":name", "]", ",", "exchange2", "[", ":options", "]", "||", "{", "}", ")", ")", "end", "q", "=", "binding", "end", "q", ".", "subscribe", "(", "options", "[", ":ack", "]", "?", "{", ":ack", "=>", "true", "}", ":", "{", "}", ")", "do", "|", "header", ",", "message", "|", "begin", "if", "(", "pool", "=", "(", "options", "[", ":fiber_pool", "]", "||", "@options", "[", ":fiber_pool", "]", ")", ")", "pool", ".", "spawn", "{", "receive", "(", "queue", "[", ":name", "]", ",", "header", ",", "message", ",", "options", ",", "&", "block", ")", "}", "else", "receive", "(", "queue", "[", ":name", "]", ",", "header", ",", "message", ",", "options", ",", "&", "block", ")", "end", "rescue", "StandardError", "=>", "e", "header", ".", "ack", "if", "options", "[", ":ack", "]", "logger", ".", "exception", "(", "\"Failed setting up to receive message from queue #{queue.inspect} \"", "+", "\"on broker #{@alias}\"", ",", "e", ",", ":trace", ")", "@exception_stats", ".", "track", "(", "\"receive\"", ",", "e", ")", "update_non_delivery_stats", "(", "\"receive failure\"", ",", "e", ")", "end", "end", "rescue", "StandardError", "=>", "e", "logger", ".", "exception", "(", "\"Failed subscribing queue #{queue.inspect}#{to_exchange} on broker #{@alias}\"", ",", "e", ",", ":trace", ")", "@exception_stats", ".", "track", "(", "\"subscribe\"", ",", "e", ")", "false", "end", "end" ]
Subscribe an AMQP queue to an AMQP exchange Do not wait for confirmation from broker that subscription is complete When a message is received, acknowledge, unserialize, and log it as specified If the message is unserialized and it is not of the right type, it is dropped after logging an error === Parameters queue(Hash):: AMQP queue being subscribed with keys :name and :options, which are the standard AMQP ones plus :no_declare(Boolean):: Whether to skip declaring this queue on the broker to cause its creation; for use when caller does not have permission to create or knows the queue already exists and wants to avoid declare overhead exchange(Hash|nil):: AMQP exchange to subscribe to with keys :type, :name, and :options, nil means use empty exchange by directly subscribing to queue; the :options are the standard AMQP ones plus :no_declare(Boolean):: Whether to skip declaring this exchange on the broker to cause its creation; for use when caller does not have create permission or knows the exchange already exists and wants to avoid declare overhead options(Hash):: Subscribe options: :ack(Boolean):: Whether caller takes responsibility for explicitly acknowledging each message received, defaults to implicit acknowledgement in AMQP as part of message receipt :no_unserialize(Boolean):: Do not unserialize message, this is an escape for special situations like enrollment, also implicitly disables receive filtering and logging; this option is implicitly invoked if initialize without a serializer (packet class)(Array(Symbol)):: Filters to be applied in to_s when logging packet to :info, only packet classes specified are accepted, others are not processed but are logged with error :category(String):: Packet category description to be used in error messages :log_data(String):: Additional data to display at end of log entry :no_log(Boolean):: Disable receive logging unless debug level :exchange2(Hash):: Additional exchange to which same queue is to be bound :brokers(Array):: Identity of brokers for which to subscribe, defaults to all usable if nil or empty :fiber_pool(FiberPool):: Pool of initialized fibers to be used for asynchronous message processing (non-nil value will override constructor option setting) === Block Required block with following parameters to be called each time exchange matches a message to the queue identity(String):: Serialized identity of broker delivering the message message(Packet|String):: Message received, which is unserialized unless :no_unserialize was specified header(AMQP::Protocol::Header):: Message header (optional block parameter) === Raise ArgumentError:: If a block is not supplied === Return (Boolean):: true if subscribe successfully or if already subscribed, otherwise false
[ "Subscribe", "an", "AMQP", "queue", "to", "an", "AMQP", "exchange", "Do", "not", "wait", "for", "confirmation", "from", "broker", "that", "subscription", "is", "complete", "When", "a", "message", "is", "received", "acknowledge", "unserialize", "and", "log", "it", "as", "specified", "If", "the", "message", "is", "unserialized", "and", "it", "is", "not", "of", "the", "right", "type", "it", "is", "dropped", "after", "logging", "an", "error" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L233-L280
train
rightscale/right_amqp
lib/right_amqp/ha_client/broker_client.rb
RightAMQP.BrokerClient.unsubscribe
def unsubscribe(queue_names, &block) unless failed? @queues.reject! do |q| if queue_names.include?(q.name) begin logger.info("[stop] Unsubscribing queue #{q.name} on broker #{@alias}") q.unsubscribe { block.call if block } rescue StandardError => e logger.exception("Failed unsubscribing queue #{q.name} on broker #{@alias}", e, :trace) @exception_stats.track("unsubscribe", e) block.call if block end true else false end end end true end
ruby
def unsubscribe(queue_names, &block) unless failed? @queues.reject! do |q| if queue_names.include?(q.name) begin logger.info("[stop] Unsubscribing queue #{q.name} on broker #{@alias}") q.unsubscribe { block.call if block } rescue StandardError => e logger.exception("Failed unsubscribing queue #{q.name} on broker #{@alias}", e, :trace) @exception_stats.track("unsubscribe", e) block.call if block end true else false end end end true end
[ "def", "unsubscribe", "(", "queue_names", ",", "&", "block", ")", "unless", "failed?", "@queues", ".", "reject!", "do", "|", "q", "|", "if", "queue_names", ".", "include?", "(", "q", ".", "name", ")", "begin", "logger", ".", "info", "(", "\"[stop] Unsubscribing queue #{q.name} on broker #{@alias}\"", ")", "q", ".", "unsubscribe", "{", "block", ".", "call", "if", "block", "}", "rescue", "StandardError", "=>", "e", "logger", ".", "exception", "(", "\"Failed unsubscribing queue #{q.name} on broker #{@alias}\"", ",", "e", ",", ":trace", ")", "@exception_stats", ".", "track", "(", "\"unsubscribe\"", ",", "e", ")", "block", ".", "call", "if", "block", "end", "true", "else", "false", "end", "end", "end", "true", "end" ]
Unsubscribe from the specified queues Silently ignore unknown queues === Parameters queue_names(Array):: Names of queues previously subscribed to === Block Optional block to be called with no parameters when each unsubscribe completes === Return true:: Always return true
[ "Unsubscribe", "from", "the", "specified", "queues", "Silently", "ignore", "unknown", "queues" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L293-L312
train
rightscale/right_amqp
lib/right_amqp/ha_client/broker_client.rb
RightAMQP.BrokerClient.queue_status
def queue_status(queue_names, &block) return false unless connected? @queues.each do |q| if queue_names.include?(q.name) begin q.status { |messages, consumers| block.call(q.name, messages, consumers) if block } rescue StandardError => e logger.exception("Failed checking status of queue #{q.name} on broker #{@alias}", e, :trace) @exception_stats.track("queue_status", e) block.call(q.name, nil, nil) if block end end end true end
ruby
def queue_status(queue_names, &block) return false unless connected? @queues.each do |q| if queue_names.include?(q.name) begin q.status { |messages, consumers| block.call(q.name, messages, consumers) if block } rescue StandardError => e logger.exception("Failed checking status of queue #{q.name} on broker #{@alias}", e, :trace) @exception_stats.track("queue_status", e) block.call(q.name, nil, nil) if block end end end true end
[ "def", "queue_status", "(", "queue_names", ",", "&", "block", ")", "return", "false", "unless", "connected?", "@queues", ".", "each", "do", "|", "q", "|", "if", "queue_names", ".", "include?", "(", "q", ".", "name", ")", "begin", "q", ".", "status", "{", "|", "messages", ",", "consumers", "|", "block", ".", "call", "(", "q", ".", "name", ",", "messages", ",", "consumers", ")", "if", "block", "}", "rescue", "StandardError", "=>", "e", "logger", ".", "exception", "(", "\"Failed checking status of queue #{q.name} on broker #{@alias}\"", ",", "e", ",", ":trace", ")", "@exception_stats", ".", "track", "(", "\"queue_status\"", ",", "e", ")", "block", ".", "call", "(", "q", ".", "name", ",", "nil", ",", "nil", ")", "if", "block", "end", "end", "end", "true", "end" ]
Check status of specified queues Silently ignore unknown queues If a queue whose status is being checked does not exist in the broker, this broker connection will fail and become unusable === Parameters queue_names(Array):: Names of queues previously subscribed to === Block Optional block to be called each time that status for a queue is retrieved with parameters queue name, message count, and consumer count; the counts are nil if there was a failure while trying to retrieve them; the block is not called for queues to which this client is not currently subscribed === Return (Boolean):: true if connected, otherwise false, in which case block never gets called
[ "Check", "status", "of", "specified", "queues", "Silently", "ignore", "unknown", "queues", "If", "a", "queue", "whose", "status", "is", "being", "checked", "does", "not", "exist", "in", "the", "broker", "this", "broker", "connection", "will", "fail", "and", "become", "unusable" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L353-L367
train
rightscale/right_amqp
lib/right_amqp/ha_client/broker_client.rb
RightAMQP.BrokerClient.publish
def publish(exchange, packet, message, options = {}) return false unless connected? begin exchange_options = exchange[:options] || {} unless options[:no_serialize] log_data = "" unless options[:no_log] && logger.level != :debug re = "RE-" if packet.respond_to?(:tries) && !packet.tries.empty? log_filter = options[:log_filter] unless logger.level == :debug log_data = "#{re}SEND #{@alias} #{packet.to_s(log_filter, :send_version)}" if logger.level == :debug log_data += ", publish options #{options.inspect}, exchange #{exchange[:name]}, " + "type #{exchange[:type]}, options #{exchange[:options].inspect}" end log_data += ", #{options[:log_data]}" if options[:log_data] logger.info(log_data) unless log_data.empty? end end delete_amqp_resources(exchange[:type], exchange[:name]) if exchange_options[:declare] @channel.__send__(exchange[:type], exchange[:name], exchange_options).publish(message, options) true rescue StandardError => e logger.exception("Failed publishing to exchange #{exchange.inspect} on broker #{@alias}", e, :trace) @exception_stats.track("publish", e) update_non_delivery_stats("publish failure", e) false end end
ruby
def publish(exchange, packet, message, options = {}) return false unless connected? begin exchange_options = exchange[:options] || {} unless options[:no_serialize] log_data = "" unless options[:no_log] && logger.level != :debug re = "RE-" if packet.respond_to?(:tries) && !packet.tries.empty? log_filter = options[:log_filter] unless logger.level == :debug log_data = "#{re}SEND #{@alias} #{packet.to_s(log_filter, :send_version)}" if logger.level == :debug log_data += ", publish options #{options.inspect}, exchange #{exchange[:name]}, " + "type #{exchange[:type]}, options #{exchange[:options].inspect}" end log_data += ", #{options[:log_data]}" if options[:log_data] logger.info(log_data) unless log_data.empty? end end delete_amqp_resources(exchange[:type], exchange[:name]) if exchange_options[:declare] @channel.__send__(exchange[:type], exchange[:name], exchange_options).publish(message, options) true rescue StandardError => e logger.exception("Failed publishing to exchange #{exchange.inspect} on broker #{@alias}", e, :trace) @exception_stats.track("publish", e) update_non_delivery_stats("publish failure", e) false end end
[ "def", "publish", "(", "exchange", ",", "packet", ",", "message", ",", "options", "=", "{", "}", ")", "return", "false", "unless", "connected?", "begin", "exchange_options", "=", "exchange", "[", ":options", "]", "||", "{", "}", "unless", "options", "[", ":no_serialize", "]", "log_data", "=", "\"\"", "unless", "options", "[", ":no_log", "]", "&&", "logger", ".", "level", "!=", ":debug", "re", "=", "\"RE-\"", "if", "packet", ".", "respond_to?", "(", ":tries", ")", "&&", "!", "packet", ".", "tries", ".", "empty?", "log_filter", "=", "options", "[", ":log_filter", "]", "unless", "logger", ".", "level", "==", ":debug", "log_data", "=", "\"#{re}SEND #{@alias} #{packet.to_s(log_filter, :send_version)}\"", "if", "logger", ".", "level", "==", ":debug", "log_data", "+=", "\", publish options #{options.inspect}, exchange #{exchange[:name]}, \"", "+", "\"type #{exchange[:type]}, options #{exchange[:options].inspect}\"", "end", "log_data", "+=", "\", #{options[:log_data]}\"", "if", "options", "[", ":log_data", "]", "logger", ".", "info", "(", "log_data", ")", "unless", "log_data", ".", "empty?", "end", "end", "delete_amqp_resources", "(", "exchange", "[", ":type", "]", ",", "exchange", "[", ":name", "]", ")", "if", "exchange_options", "[", ":declare", "]", "@channel", ".", "__send__", "(", "exchange", "[", ":type", "]", ",", "exchange", "[", ":name", "]", ",", "exchange_options", ")", ".", "publish", "(", "message", ",", "options", ")", "true", "rescue", "StandardError", "=>", "e", "logger", ".", "exception", "(", "\"Failed publishing to exchange #{exchange.inspect} on broker #{@alias}\"", ",", "e", ",", ":trace", ")", "@exception_stats", ".", "track", "(", "\"publish\"", ",", "e", ")", "update_non_delivery_stats", "(", "\"publish failure\"", ",", "e", ")", "false", "end", "end" ]
Publish message to AMQP exchange === Parameters exchange(Hash):: AMQP exchange to subscribe to with keys :type, :name, and :options, which are the standard AMQP ones plus :no_declare(Boolean):: Whether to skip declaring this exchange or queue on the broker to cause its creation; for use when caller does not have create permission or knows the object already exists and wants to avoid declare overhead :declare(Boolean):: Whether to delete this exchange or queue from the AMQP cache to force it to be declared on the broker and thus be created if it does not exist packet(Packet):: Message to serialize and publish (must respond to :to_s(log_filter, protocol_version) unless :no_serialize specified; if responds to :type, :from, :token, and/or :one_way, these value are used if this message is returned as non-deliverable) message(String):: Serialized message to be published options(Hash):: Publish options -- standard AMQP ones plus :no_serialize(Boolean):: Do not serialize packet because it is already serialized :log_filter(Array(Symbol)):: Filters to be applied in to_s when logging packet to :info :log_data(String):: Additional data to display at end of log entry :no_log(Boolean):: Disable publish logging unless debug level === Return (Boolean):: true if publish successfully, otherwise false
[ "Publish", "message", "to", "AMQP", "exchange" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L391-L418
train
rightscale/right_amqp
lib/right_amqp/ha_client/broker_client.rb
RightAMQP.BrokerClient.close
def close(propagate = true, normal = true, log = true, &block) final_status = normal ? :closed : :failed if ![:closed, :failed].include?(@status) begin logger.info("[stop] Closed connection to broker #{@alias}") if log update_status(final_status) if propagate @connection.close do @status = final_status yield if block_given? end rescue StandardError => e logger.exception("Failed to close broker #{@alias}", e, :trace) @exception_stats.track("close", e) @status = final_status yield if block_given? end else @status = final_status yield if block_given? end true end
ruby
def close(propagate = true, normal = true, log = true, &block) final_status = normal ? :closed : :failed if ![:closed, :failed].include?(@status) begin logger.info("[stop] Closed connection to broker #{@alias}") if log update_status(final_status) if propagate @connection.close do @status = final_status yield if block_given? end rescue StandardError => e logger.exception("Failed to close broker #{@alias}", e, :trace) @exception_stats.track("close", e) @status = final_status yield if block_given? end else @status = final_status yield if block_given? end true end
[ "def", "close", "(", "propagate", "=", "true", ",", "normal", "=", "true", ",", "log", "=", "true", ",", "&", "block", ")", "final_status", "=", "normal", "?", ":closed", ":", ":failed", "if", "!", "[", ":closed", ",", ":failed", "]", ".", "include?", "(", "@status", ")", "begin", "logger", ".", "info", "(", "\"[stop] Closed connection to broker #{@alias}\"", ")", "if", "log", "update_status", "(", "final_status", ")", "if", "propagate", "@connection", ".", "close", "do", "@status", "=", "final_status", "yield", "if", "block_given?", "end", "rescue", "StandardError", "=>", "e", "logger", ".", "exception", "(", "\"Failed to close broker #{@alias}\"", ",", "e", ",", ":trace", ")", "@exception_stats", ".", "track", "(", "\"close\"", ",", "e", ")", "@status", "=", "final_status", "yield", "if", "block_given?", "end", "else", "@status", "=", "final_status", "yield", "if", "block_given?", "end", "true", "end" ]
Close broker connection === Parameters propagate(Boolean):: Whether to propagate connection status updates, defaults to true normal(Boolean):: Whether this is a normal close vs. a failed connection, defaults to true log(Boolean):: Whether to log that closing, defaults to true === Block Optional block with no parameters to be called after connection closed === Return true:: Always return true
[ "Close", "broker", "connection" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L477-L498
train
rightscale/right_amqp
lib/right_amqp/ha_client/broker_client.rb
RightAMQP.BrokerClient.connect
def connect(address, reconnect_interval) begin logger.info("[setup] Connecting to broker #{@identity}, alias #{@alias}") @status = :connecting @connection = AMQP.connect(:user => @options[:user], :pass => @options[:pass], :vhost => @options[:vhost], :host => address[:host], :port => address[:port], :ssl => @options[:ssl], :identity => @identity, :insist => @options[:insist] || false, :heartbeat => @options[:heartbeat], :reconnect_delay => lambda { rand(reconnect_interval) }, :reconnect_interval => reconnect_interval) @channel = MQ.new(@connection) @channel.__send__(:connection).connection_status { |status| update_status(status) } @channel.prefetch(@options[:prefetch]) if @options[:prefetch] @channel.return_message { |header, message| handle_return(header, message) } rescue StandardError => e @status = :failed @failure_stats.update logger.exception("Failed connecting to broker #{@alias}", e, :trace) @exception_stats.track("connect", e) @connection.close if @connection end end
ruby
def connect(address, reconnect_interval) begin logger.info("[setup] Connecting to broker #{@identity}, alias #{@alias}") @status = :connecting @connection = AMQP.connect(:user => @options[:user], :pass => @options[:pass], :vhost => @options[:vhost], :host => address[:host], :port => address[:port], :ssl => @options[:ssl], :identity => @identity, :insist => @options[:insist] || false, :heartbeat => @options[:heartbeat], :reconnect_delay => lambda { rand(reconnect_interval) }, :reconnect_interval => reconnect_interval) @channel = MQ.new(@connection) @channel.__send__(:connection).connection_status { |status| update_status(status) } @channel.prefetch(@options[:prefetch]) if @options[:prefetch] @channel.return_message { |header, message| handle_return(header, message) } rescue StandardError => e @status = :failed @failure_stats.update logger.exception("Failed connecting to broker #{@alias}", e, :trace) @exception_stats.track("connect", e) @connection.close if @connection end end
[ "def", "connect", "(", "address", ",", "reconnect_interval", ")", "begin", "logger", ".", "info", "(", "\"[setup] Connecting to broker #{@identity}, alias #{@alias}\"", ")", "@status", "=", ":connecting", "@connection", "=", "AMQP", ".", "connect", "(", ":user", "=>", "@options", "[", ":user", "]", ",", ":pass", "=>", "@options", "[", ":pass", "]", ",", ":vhost", "=>", "@options", "[", ":vhost", "]", ",", ":host", "=>", "address", "[", ":host", "]", ",", ":port", "=>", "address", "[", ":port", "]", ",", ":ssl", "=>", "@options", "[", ":ssl", "]", ",", ":identity", "=>", "@identity", ",", ":insist", "=>", "@options", "[", ":insist", "]", "||", "false", ",", ":heartbeat", "=>", "@options", "[", ":heartbeat", "]", ",", ":reconnect_delay", "=>", "lambda", "{", "rand", "(", "reconnect_interval", ")", "}", ",", ":reconnect_interval", "=>", "reconnect_interval", ")", "@channel", "=", "MQ", ".", "new", "(", "@connection", ")", "@channel", ".", "__send__", "(", ":connection", ")", ".", "connection_status", "{", "|", "status", "|", "update_status", "(", "status", ")", "}", "@channel", ".", "prefetch", "(", "@options", "[", ":prefetch", "]", ")", "if", "@options", "[", ":prefetch", "]", "@channel", ".", "return_message", "{", "|", "header", ",", "message", "|", "handle_return", "(", "header", ",", "message", ")", "}", "rescue", "StandardError", "=>", "e", "@status", "=", ":failed", "@failure_stats", ".", "update", "logger", ".", "exception", "(", "\"Failed connecting to broker #{@alias}\"", ",", "e", ",", ":trace", ")", "@exception_stats", ".", "track", "(", "\"connect\"", ",", "e", ")", "@connection", ".", "close", "if", "@connection", "end", "end" ]
Connect to broker and register for status updates Also set prefetch value if specified and setup for message returns === Parameters address(Hash):: Broker address :host(String:: IP host name or address :port(Integer):: TCP port number for individual broker :index(String):: Unique index for broker within given set for use in forming alias reconnect_interval(Integer):: Number of seconds between reconnect attempts === Return true:: Always return true
[ "Connect", "to", "broker", "and", "register", "for", "status", "updates", "Also", "set", "prefetch", "value", "if", "specified", "and", "setup", "for", "message", "returns" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L594-L620
train
rightscale/right_amqp
lib/right_amqp/ha_client/broker_client.rb
RightAMQP.BrokerClient.receive
def receive(queue, header, message, options, &block) begin if options[:no_unserialize] || @serializer.nil? execute_callback(block, @identity, message, header) elsif message == "nil" # This happens as part of connecting an instance agent to a broker prior to version 13 header.ack if options[:ack] logger.debug("RECV #{@alias} nil message ignored") elsif (packet = unserialize(queue, message, options)) execute_callback(block, @identity, packet, header) elsif options[:ack] # Need to ack empty packet since no callback is being made header.ack end true rescue StandardError => e header.ack if options[:ack] logger.exception("Failed receiving message from queue #{queue.inspect} on broker #{@alias}", e, :trace) @exception_stats.track("receive", e) update_non_delivery_stats("receive failure", e) end end
ruby
def receive(queue, header, message, options, &block) begin if options[:no_unserialize] || @serializer.nil? execute_callback(block, @identity, message, header) elsif message == "nil" # This happens as part of connecting an instance agent to a broker prior to version 13 header.ack if options[:ack] logger.debug("RECV #{@alias} nil message ignored") elsif (packet = unserialize(queue, message, options)) execute_callback(block, @identity, packet, header) elsif options[:ack] # Need to ack empty packet since no callback is being made header.ack end true rescue StandardError => e header.ack if options[:ack] logger.exception("Failed receiving message from queue #{queue.inspect} on broker #{@alias}", e, :trace) @exception_stats.track("receive", e) update_non_delivery_stats("receive failure", e) end end
[ "def", "receive", "(", "queue", ",", "header", ",", "message", ",", "options", ",", "&", "block", ")", "begin", "if", "options", "[", ":no_unserialize", "]", "||", "@serializer", ".", "nil?", "execute_callback", "(", "block", ",", "@identity", ",", "message", ",", "header", ")", "elsif", "message", "==", "\"nil\"", "header", ".", "ack", "if", "options", "[", ":ack", "]", "logger", ".", "debug", "(", "\"RECV #{@alias} nil message ignored\"", ")", "elsif", "(", "packet", "=", "unserialize", "(", "queue", ",", "message", ",", "options", ")", ")", "execute_callback", "(", "block", ",", "@identity", ",", "packet", ",", "header", ")", "elsif", "options", "[", ":ack", "]", "header", ".", "ack", "end", "true", "rescue", "StandardError", "=>", "e", "header", ".", "ack", "if", "options", "[", ":ack", "]", "logger", ".", "exception", "(", "\"Failed receiving message from queue #{queue.inspect} on broker #{@alias}\"", ",", "e", ",", ":trace", ")", "@exception_stats", ".", "track", "(", "\"receive\"", ",", "e", ")", "update_non_delivery_stats", "(", "\"receive failure\"", ",", "e", ")", "end", "end" ]
Receive message by optionally unserializing it, passing it to the callback, and optionally acknowledging it === Parameters queue(String):: Name of queue header(AMQP::Protocol::Header):: Message header message(String):: Serialized packet options(Hash):: Subscribe options :ack(Boolean):: Whether caller takes responsibility for explicitly acknowledging each message received, defaults to implicit acknowledgement in AMQP as part of message receipt :no_unserialize(Boolean):: Do not unserialize message, this is an escape for special situations like enrollment, also implicitly disables receive filtering and logging; this option is implicitly invoked if initialize without a serializer === Block Block with following parameters to be called with received message identity(String):: Serialized identity of broker delivering the message message(Packet|String):: Message received, which is unserialized unless :no_unserialize was specified header(AMQP::Protocol::Header):: Message header (optional block parameter) === Return true:: Always return true
[ "Receive", "message", "by", "optionally", "unserializing", "it", "passing", "it", "to", "the", "callback", "and", "optionally", "acknowledging", "it" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L644-L665
train
rightscale/right_amqp
lib/right_amqp/ha_client/broker_client.rb
RightAMQP.BrokerClient.unserialize
def unserialize(queue, message, options = {}) begin received_at = Time.now.to_f packet = @serializer.method(:load).arity.abs > 1 ? @serializer.load(message, queue) : @serializer.load(message) if options.key?(packet.class) unless options[:no_log] && logger.level != :debug re = "RE-" if packet.respond_to?(:tries) && !packet.tries.empty? packet.received_at = received_at if packet.respond_to?(:received_at) log_filter = options[packet.class] unless logger.level == :debug logger.info("#{re}RECV #{@alias} #{packet.to_s(log_filter, :recv_version)} #{options[:log_data]}") end packet else category = options[:category] + " " if options[:category] logger.error("Received invalid #{category}packet type from queue #{queue} on broker #{@alias}: #{packet.class}\n" + caller.join("\n")) nil end rescue StandardError => e # TODO Taking advantage of Serializer knowledge here even though out of scope trace, track = case e.class.name.sub(/^.*::/, "") when "SerializationError" then [:caller, e.to_s !~ /MissingCertificate|MissingPrivateKey|InvalidSignature/] when "ConnectivityFailure" then [:caller, false] else [:trace, true] end logger.exception("Failed unserializing message from queue #{queue.inspect} on broker #{@alias}", e, trace) @exception_stats.track("receive", e) if track @options[:exception_on_receive_callback].call(message, e) if @options[:exception_on_receive_callback] update_non_delivery_stats("receive failure", e) nil end end
ruby
def unserialize(queue, message, options = {}) begin received_at = Time.now.to_f packet = @serializer.method(:load).arity.abs > 1 ? @serializer.load(message, queue) : @serializer.load(message) if options.key?(packet.class) unless options[:no_log] && logger.level != :debug re = "RE-" if packet.respond_to?(:tries) && !packet.tries.empty? packet.received_at = received_at if packet.respond_to?(:received_at) log_filter = options[packet.class] unless logger.level == :debug logger.info("#{re}RECV #{@alias} #{packet.to_s(log_filter, :recv_version)} #{options[:log_data]}") end packet else category = options[:category] + " " if options[:category] logger.error("Received invalid #{category}packet type from queue #{queue} on broker #{@alias}: #{packet.class}\n" + caller.join("\n")) nil end rescue StandardError => e # TODO Taking advantage of Serializer knowledge here even though out of scope trace, track = case e.class.name.sub(/^.*::/, "") when "SerializationError" then [:caller, e.to_s !~ /MissingCertificate|MissingPrivateKey|InvalidSignature/] when "ConnectivityFailure" then [:caller, false] else [:trace, true] end logger.exception("Failed unserializing message from queue #{queue.inspect} on broker #{@alias}", e, trace) @exception_stats.track("receive", e) if track @options[:exception_on_receive_callback].call(message, e) if @options[:exception_on_receive_callback] update_non_delivery_stats("receive failure", e) nil end end
[ "def", "unserialize", "(", "queue", ",", "message", ",", "options", "=", "{", "}", ")", "begin", "received_at", "=", "Time", ".", "now", ".", "to_f", "packet", "=", "@serializer", ".", "method", "(", ":load", ")", ".", "arity", ".", "abs", ">", "1", "?", "@serializer", ".", "load", "(", "message", ",", "queue", ")", ":", "@serializer", ".", "load", "(", "message", ")", "if", "options", ".", "key?", "(", "packet", ".", "class", ")", "unless", "options", "[", ":no_log", "]", "&&", "logger", ".", "level", "!=", ":debug", "re", "=", "\"RE-\"", "if", "packet", ".", "respond_to?", "(", ":tries", ")", "&&", "!", "packet", ".", "tries", ".", "empty?", "packet", ".", "received_at", "=", "received_at", "if", "packet", ".", "respond_to?", "(", ":received_at", ")", "log_filter", "=", "options", "[", "packet", ".", "class", "]", "unless", "logger", ".", "level", "==", ":debug", "logger", ".", "info", "(", "\"#{re}RECV #{@alias} #{packet.to_s(log_filter, :recv_version)} #{options[:log_data]}\"", ")", "end", "packet", "else", "category", "=", "options", "[", ":category", "]", "+", "\" \"", "if", "options", "[", ":category", "]", "logger", ".", "error", "(", "\"Received invalid #{category}packet type from queue #{queue} on broker #{@alias}: #{packet.class}\\n\"", "+", "caller", ".", "join", "(", "\"\\n\"", ")", ")", "nil", "end", "rescue", "StandardError", "=>", "e", "trace", ",", "track", "=", "case", "e", ".", "class", ".", "name", ".", "sub", "(", "/", "/", ",", "\"\"", ")", "when", "\"SerializationError\"", "then", "[", ":caller", ",", "e", ".", "to_s", "!~", "/", "/", "]", "when", "\"ConnectivityFailure\"", "then", "[", ":caller", ",", "false", "]", "else", "[", ":trace", ",", "true", "]", "end", "logger", ".", "exception", "(", "\"Failed unserializing message from queue #{queue.inspect} on broker #{@alias}\"", ",", "e", ",", "trace", ")", "@exception_stats", ".", "track", "(", "\"receive\"", ",", "e", ")", "if", "track", "@options", "[", ":exception_on_receive_callback", "]", ".", "call", "(", "message", ",", "e", ")", "if", "@options", "[", ":exception_on_receive_callback", "]", "update_non_delivery_stats", "(", "\"receive failure\"", ",", "e", ")", "nil", "end", "end" ]
Unserialize message, check that it is an acceptable type, and log it === Parameters queue(String):: Name of queue message(String):: Serialized packet options(Hash):: Subscribe options (packet class)(Array(Symbol)):: Filters to be applied in to_s when logging packet to :info, only packet classes specified are accepted, others are not processed but are logged with error :category(String):: Packet category description to be used in error messages :log_data(String):: Additional data to display at end of log entry :no_log(Boolean):: Disable receive logging unless debug level === Return (Packet|nil):: Unserialized packet or nil if not of right type or if there is an exception
[ "Unserialize", "message", "check", "that", "it", "is", "an", "acceptable", "type", "and", "log", "it" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L681-L711
train
rightscale/right_amqp
lib/right_amqp/ha_client/broker_client.rb
RightAMQP.BrokerClient.handle_return
def handle_return(header, message) begin to = if header.exchange && !header.exchange.empty? then header.exchange else header.routing_key end reason = header.reply_text callback = @options[:return_message_callback] logger.__send__(callback ? :debug : :info, "RETURN #{@alias} for #{to} because #{reason}") callback.call(@identity, to, reason, message) if callback rescue Exception => e logger.exception("Failed return #{header.inspect} of message from broker #{@alias}", e, :trace) @exception_stats.track("return", e) end true end
ruby
def handle_return(header, message) begin to = if header.exchange && !header.exchange.empty? then header.exchange else header.routing_key end reason = header.reply_text callback = @options[:return_message_callback] logger.__send__(callback ? :debug : :info, "RETURN #{@alias} for #{to} because #{reason}") callback.call(@identity, to, reason, message) if callback rescue Exception => e logger.exception("Failed return #{header.inspect} of message from broker #{@alias}", e, :trace) @exception_stats.track("return", e) end true end
[ "def", "handle_return", "(", "header", ",", "message", ")", "begin", "to", "=", "if", "header", ".", "exchange", "&&", "!", "header", ".", "exchange", ".", "empty?", "then", "header", ".", "exchange", "else", "header", ".", "routing_key", "end", "reason", "=", "header", ".", "reply_text", "callback", "=", "@options", "[", ":return_message_callback", "]", "logger", ".", "__send__", "(", "callback", "?", ":debug", ":", ":info", ",", "\"RETURN #{@alias} for #{to} because #{reason}\"", ")", "callback", ".", "call", "(", "@identity", ",", "to", ",", "reason", ",", "message", ")", "if", "callback", "rescue", "Exception", "=>", "e", "logger", ".", "exception", "(", "\"Failed return #{header.inspect} of message from broker #{@alias}\"", ",", "e", ",", ":trace", ")", "@exception_stats", ".", "track", "(", "\"return\"", ",", "e", ")", "end", "true", "end" ]
Handle message returned by broker because it could not deliver it === Parameters header(AMQP::Protocol::Header):: Message header message(String):: Serialized packet === Return true:: Always return true
[ "Handle", "message", "returned", "by", "broker", "because", "it", "could", "not", "deliver", "it" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L760-L772
train
rightscale/right_amqp
lib/right_amqp/ha_client/broker_client.rb
RightAMQP.BrokerClient.execute_callback
def execute_callback(callback, *args) (callback.arity == 2 ? callback.call(*args[0, 2]) : callback.call(*args)) if callback end
ruby
def execute_callback(callback, *args) (callback.arity == 2 ? callback.call(*args[0, 2]) : callback.call(*args)) if callback end
[ "def", "execute_callback", "(", "callback", ",", "*", "args", ")", "(", "callback", ".", "arity", "==", "2", "?", "callback", ".", "call", "(", "*", "args", "[", "0", ",", "2", "]", ")", ":", "callback", ".", "call", "(", "*", "args", ")", ")", "if", "callback", "end" ]
Execute packet receive callback, make it a separate method to ease instrumentation === Parameters callback(Proc):: Proc to run args(Array):: Array of pass-through arguments === Return (Object):: Callback return value
[ "Execute", "packet", "receive", "callback", "make", "it", "a", "separate", "method", "to", "ease", "instrumentation" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L782-L784
train
nestor-custodio/crapi
lib/crapi/client.rb
Crapi.Client.ensure_success!
def ensure_success!(response) return if response.is_a? Net::HTTPSuccess message = "#{response.code} - #{response.message}" message += "\n#{response.body}" if response.body.present? raise Crapi::BadHttpResponseError, message end
ruby
def ensure_success!(response) return if response.is_a? Net::HTTPSuccess message = "#{response.code} - #{response.message}" message += "\n#{response.body}" if response.body.present? raise Crapi::BadHttpResponseError, message end
[ "def", "ensure_success!", "(", "response", ")", "return", "if", "response", ".", "is_a?", "Net", "::", "HTTPSuccess", "message", "=", "\"#{response.code} - #{response.message}\"", "message", "+=", "\"\\n#{response.body}\"", "if", "response", ".", "body", ".", "present?", "raise", "Crapi", "::", "BadHttpResponseError", ",", "message", "end" ]
Verifies the given value is that of a successful HTTP response. @param response [Net::HTTPResponse] The response to evaluate as "successful" or not. @raise [Crapi::BadHttpResponseError] @return [nil]
[ "Verifies", "the", "given", "value", "is", "that", "of", "a", "successful", "HTTP", "response", "." ]
cd4741a7106135c0c9c2d99630487c43729ca801
https://github.com/nestor-custodio/crapi/blob/cd4741a7106135c0c9c2d99630487c43729ca801/lib/crapi/client.rb#L282-L289
train
nestor-custodio/crapi
lib/crapi/client.rb
Crapi.Client.format_payload
def format_payload(payload, as: JSON_CONTENT_TYPE) ## Non-Hash payloads are passed through as-is. return payload unless payload.is_a? Hash ## Massage Hash-like payloads into a suitable format. case as when JSON_CONTENT_TYPE JSON.generate(payload.as_json) when FORM_CONTENT_TYPE payload.to_query else payload.to_s end end
ruby
def format_payload(payload, as: JSON_CONTENT_TYPE) ## Non-Hash payloads are passed through as-is. return payload unless payload.is_a? Hash ## Massage Hash-like payloads into a suitable format. case as when JSON_CONTENT_TYPE JSON.generate(payload.as_json) when FORM_CONTENT_TYPE payload.to_query else payload.to_s end end
[ "def", "format_payload", "(", "payload", ",", "as", ":", "JSON_CONTENT_TYPE", ")", "return", "payload", "unless", "payload", ".", "is_a?", "Hash", "case", "as", "when", "JSON_CONTENT_TYPE", "JSON", ".", "generate", "(", "payload", ".", "as_json", ")", "when", "FORM_CONTENT_TYPE", "payload", ".", "to_query", "else", "payload", ".", "to_s", "end", "end" ]
Serializes the given payload per the requested content-type. @param payload [Hash, String] The payload to format. Strings are returned as-is; Hashes are serialized per the given *as* content-type. @param as [String] The target content-type. @return [String]
[ "Serializes", "the", "given", "payload", "per", "the", "requested", "content", "-", "type", "." ]
cd4741a7106135c0c9c2d99630487c43729ca801
https://github.com/nestor-custodio/crapi/blob/cd4741a7106135c0c9c2d99630487c43729ca801/lib/crapi/client.rb#L304-L317
train
nestor-custodio/crapi
lib/crapi/client.rb
Crapi.Client.parse_response
def parse_response(response) case response.content_type when JSON_CONTENT_TYPE JSON.parse(response.body, quirks_mode: true, symbolize_names: true) else response.body end end
ruby
def parse_response(response) case response.content_type when JSON_CONTENT_TYPE JSON.parse(response.body, quirks_mode: true, symbolize_names: true) else response.body end end
[ "def", "parse_response", "(", "response", ")", "case", "response", ".", "content_type", "when", "JSON_CONTENT_TYPE", "JSON", ".", "parse", "(", "response", ".", "body", ",", "quirks_mode", ":", "true", ",", "symbolize_names", ":", "true", ")", "else", "response", ".", "body", "end", "end" ]
Parses the given response as its claimed content-type. @param response [Net::HTTPResponse] The response whose body is to be parsed. @return [Object]
[ "Parses", "the", "given", "response", "as", "its", "claimed", "content", "-", "type", "." ]
cd4741a7106135c0c9c2d99630487c43729ca801
https://github.com/nestor-custodio/crapi/blob/cd4741a7106135c0c9c2d99630487c43729ca801/lib/crapi/client.rb#L328-L335
train
jinx/core
lib/jinx/metadata.rb
Jinx.Metadata.pretty_print
def pretty_print(q) map = pretty_print_attribute_hash.delete_if { |k, v| v.nil_or_empty? } # one indented line per entry, all but the last line ending in a comma content = map.map { |label, value| " #{label}=>#{format_print_value(value)}" }.join(",\n") # print the content to the log q.text("#{qp} structure:\n#{content}") end
ruby
def pretty_print(q) map = pretty_print_attribute_hash.delete_if { |k, v| v.nil_or_empty? } # one indented line per entry, all but the last line ending in a comma content = map.map { |label, value| " #{label}=>#{format_print_value(value)}" }.join(",\n") # print the content to the log q.text("#{qp} structure:\n#{content}") end
[ "def", "pretty_print", "(", "q", ")", "map", "=", "pretty_print_attribute_hash", ".", "delete_if", "{", "|", "k", ",", "v", "|", "v", ".", "nil_or_empty?", "}", "content", "=", "map", ".", "map", "{", "|", "label", ",", "value", "|", "\" #{label}=>#{format_print_value(value)}\"", "}", ".", "join", "(", "\",\\n\"", ")", "q", ".", "text", "(", "\"#{qp} structure:\\n#{content}\"", ")", "end" ]
Prints this classifier's content to the log.
[ "Prints", "this", "classifier", "s", "content", "to", "the", "log", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata.rb#L74-L80
train
gemeraldbeanstalk/stalk_climber
lib/stalk_climber/climber_enumerable.rb
StalkClimber.ClimberEnumerable.each_threaded
def each_threaded(&block) # :yields: Object threads = [] climber.connection_pool.connections.each do |connection| threads << Thread.new { connection.send(self.class.enumerator_method, &block) } end threads.each(&:join) return end
ruby
def each_threaded(&block) # :yields: Object threads = [] climber.connection_pool.connections.each do |connection| threads << Thread.new { connection.send(self.class.enumerator_method, &block) } end threads.each(&:join) return end
[ "def", "each_threaded", "(", "&", "block", ")", "threads", "=", "[", "]", "climber", ".", "connection_pool", ".", "connections", ".", "each", "do", "|", "connection", "|", "threads", "<<", "Thread", ".", "new", "{", "connection", ".", "send", "(", "self", ".", "class", ".", "enumerator_method", ",", "&", "block", ")", "}", "end", "threads", ".", "each", "(", "&", ":join", ")", "return", "end" ]
Perform a threaded iteration across all connections in the climber's connection pool. This method cannot be used for enumerable enumeration because a break called within one of the threads will cause a LocalJumpError. This could be fixed, but expected behavior on break varies as to whether or not to wait for all threads before returning a result. However, still useful for operations that always visit all elements. An instance of the element is yielded with each iteration. jobs = ClimberEnumerable.new(:each_job) instance = jobs.new(climber) instance.each_threaded do |job| ... end
[ "Perform", "a", "threaded", "iteration", "across", "all", "connections", "in", "the", "climber", "s", "connection", "pool", ".", "This", "method", "cannot", "be", "used", "for", "enumerable", "enumeration", "because", "a", "break", "called", "within", "one", "of", "the", "threads", "will", "cause", "a", "LocalJumpError", ".", "This", "could", "be", "fixed", "but", "expected", "behavior", "on", "break", "varies", "as", "to", "whether", "or", "not", "to", "wait", "for", "all", "threads", "before", "returning", "a", "result", ".", "However", "still", "useful", "for", "operations", "that", "always", "visit", "all", "elements", ".", "An", "instance", "of", "the", "element", "is", "yielded", "with", "each", "iteration", "." ]
d22f74bbae864ca2771d15621ccbf29d8e86521a
https://github.com/gemeraldbeanstalk/stalk_climber/blob/d22f74bbae864ca2771d15621ccbf29d8e86521a/lib/stalk_climber/climber_enumerable.rb#L65-L72
train
grandcloud/sndacs-ruby
lib/sndacs/object.rb
Sndacs.Object.temporary_url
def temporary_url(expires_at = Time.now + 3600) url = URI.escape("#{protocol}#{host(true)}/#{path_prefix}#{key}") signature = Signature.generate_temporary_url_signature(:bucket => name, :resource => key, :expires_at => expires_at, :secret_access_key => secret_access_key) "#{url}?SNDAAccessKeyId=#{access_key_id}&Expires=#{expires_at.to_i.to_s}&Signature=#{signature}" end
ruby
def temporary_url(expires_at = Time.now + 3600) url = URI.escape("#{protocol}#{host(true)}/#{path_prefix}#{key}") signature = Signature.generate_temporary_url_signature(:bucket => name, :resource => key, :expires_at => expires_at, :secret_access_key => secret_access_key) "#{url}?SNDAAccessKeyId=#{access_key_id}&Expires=#{expires_at.to_i.to_s}&Signature=#{signature}" end
[ "def", "temporary_url", "(", "expires_at", "=", "Time", ".", "now", "+", "3600", ")", "url", "=", "URI", ".", "escape", "(", "\"#{protocol}#{host(true)}/#{path_prefix}#{key}\"", ")", "signature", "=", "Signature", ".", "generate_temporary_url_signature", "(", ":bucket", "=>", "name", ",", ":resource", "=>", "key", ",", ":expires_at", "=>", "expires_at", ",", ":secret_access_key", "=>", "secret_access_key", ")", "\"#{url}?SNDAAccessKeyId=#{access_key_id}&Expires=#{expires_at.to_i.to_s}&Signature=#{signature}\"", "end" ]
Returns a temporary url to the object that expires on the timestamp given. Defaults to 5min expire time.
[ "Returns", "a", "temporary", "url", "to", "the", "object", "that", "expires", "on", "the", "timestamp", "given", ".", "Defaults", "to", "5min", "expire", "time", "." ]
4565e926473e3af9df2ae17f728c423662ca750a
https://github.com/grandcloud/sndacs-ruby/blob/4565e926473e3af9df2ae17f728c423662ca750a/lib/sndacs/object.rb#L122-L130
train
hetznerZA/log4r_auditor
lib/log4r_auditor/auditor.rb
Log4rAuditor.Log4rAuditor.configuration_is_valid?
def configuration_is_valid?(configuration) required_parameters = ['file_name', 'standard_stream'] required_parameters.each { |parameter| return false unless configuration.include?(parameter) } return false if configuration['file_name'].empty? return false unless ['stdout', 'stderr', 'none'].include?(configuration['standard_stream']) return true end
ruby
def configuration_is_valid?(configuration) required_parameters = ['file_name', 'standard_stream'] required_parameters.each { |parameter| return false unless configuration.include?(parameter) } return false if configuration['file_name'].empty? return false unless ['stdout', 'stderr', 'none'].include?(configuration['standard_stream']) return true end
[ "def", "configuration_is_valid?", "(", "configuration", ")", "required_parameters", "=", "[", "'file_name'", ",", "'standard_stream'", "]", "required_parameters", ".", "each", "{", "|", "parameter", "|", "return", "false", "unless", "configuration", ".", "include?", "(", "parameter", ")", "}", "return", "false", "if", "configuration", "[", "'file_name'", "]", ".", "empty?", "return", "false", "unless", "[", "'stdout'", ",", "'stderr'", ",", "'none'", "]", ".", "include?", "(", "configuration", "[", "'standard_stream'", "]", ")", "return", "true", "end" ]
inversion of control method required by the AuditorAPI to validate the configuration
[ "inversion", "of", "control", "method", "required", "by", "the", "AuditorAPI", "to", "validate", "the", "configuration" ]
a44218ecde0a3aca963c0b0ae69a9ccb03e8435e
https://github.com/hetznerZA/log4r_auditor/blob/a44218ecde0a3aca963c0b0ae69a9ccb03e8435e/lib/log4r_auditor/auditor.rb#L13-L19
train
barkerest/incline
app/models/incline/access_group.rb
Incline.AccessGroup.belongs_to?
def belongs_to?(group) group = AccessGroup.get(group) unless group.is_a?(::Incline::AccessGroup) return false unless group safe_belongs_to?(group) end
ruby
def belongs_to?(group) group = AccessGroup.get(group) unless group.is_a?(::Incline::AccessGroup) return false unless group safe_belongs_to?(group) end
[ "def", "belongs_to?", "(", "group", ")", "group", "=", "AccessGroup", ".", "get", "(", "group", ")", "unless", "group", ".", "is_a?", "(", "::", "Incline", "::", "AccessGroup", ")", "return", "false", "unless", "group", "safe_belongs_to?", "(", "group", ")", "end" ]
Determines if this group belongs to the specified group.
[ "Determines", "if", "this", "group", "belongs", "to", "the", "specified", "group", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/access_group.rb#L44-L48
train
barkerest/incline
app/models/incline/access_group.rb
Incline.AccessGroup.effective_groups
def effective_groups ret = [ self ] memberships.each do |m| unless ret.include?(m) # prevent infinite recursion tmp = m.effective_groups tmp.each do |g| ret << g unless ret.include?(g) end end end ret.sort{|a,b| a.name <=> b.name} end
ruby
def effective_groups ret = [ self ] memberships.each do |m| unless ret.include?(m) # prevent infinite recursion tmp = m.effective_groups tmp.each do |g| ret << g unless ret.include?(g) end end end ret.sort{|a,b| a.name <=> b.name} end
[ "def", "effective_groups", "ret", "=", "[", "self", "]", "memberships", ".", "each", "do", "|", "m", "|", "unless", "ret", ".", "include?", "(", "m", ")", "tmp", "=", "m", ".", "effective_groups", "tmp", ".", "each", "do", "|", "g", "|", "ret", "<<", "g", "unless", "ret", ".", "include?", "(", "g", ")", "end", "end", "end", "ret", ".", "sort", "{", "|", "a", ",", "b", "|", "a", ".", "name", "<=>", "b", ".", "name", "}", "end" ]
Gets a list of all the groups this group provides effective membership to.
[ "Gets", "a", "list", "of", "all", "the", "groups", "this", "group", "provides", "effective", "membership", "to", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/access_group.rb#L52-L63
train
barkerest/incline
app/models/incline/access_group.rb
Incline.AccessGroup.user_ids=
def user_ids=(values) values ||= [] values = [ values ] unless values.is_a?(::Array) values = values.reject{|v| v.blank?}.map{|v| v.to_i} self.users = Incline::User.where(id: values).to_a end
ruby
def user_ids=(values) values ||= [] values = [ values ] unless values.is_a?(::Array) values = values.reject{|v| v.blank?}.map{|v| v.to_i} self.users = Incline::User.where(id: values).to_a end
[ "def", "user_ids", "=", "(", "values", ")", "values", "||=", "[", "]", "values", "=", "[", "values", "]", "unless", "values", ".", "is_a?", "(", "::", "Array", ")", "values", "=", "values", ".", "reject", "{", "|", "v", "|", "v", ".", "blank?", "}", ".", "map", "{", "|", "v", "|", "v", ".", "to_i", "}", "self", ".", "users", "=", "Incline", "::", "User", ".", "where", "(", "id", ":", "values", ")", ".", "to_a", "end" ]
Sets the user IDs for the members of this group.
[ "Sets", "the", "user", "IDs", "for", "the", "members", "of", "this", "group", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/access_group.rb#L79-L84
train
starrhorne/konfig
lib/konfig/rails/railtie.rb
Konfig.InitializeKonfig.load_settings
def load_settings(path) # Load the data files Konfig.load_directory(path) # Load all adapters built_in_adapters = File.join(File.dirname(__FILE__), 'adapters', '*.rb') require_all built_in_adapters user_adapters = File.join(path, 'adapters', '*_adapter.rb') require_all user_adapters # Apply the adapters to the data Adapter.create_child_instances(Konfig.default_store.data) Adapter.send_to_child_instances :adapt end
ruby
def load_settings(path) # Load the data files Konfig.load_directory(path) # Load all adapters built_in_adapters = File.join(File.dirname(__FILE__), 'adapters', '*.rb') require_all built_in_adapters user_adapters = File.join(path, 'adapters', '*_adapter.rb') require_all user_adapters # Apply the adapters to the data Adapter.create_child_instances(Konfig.default_store.data) Adapter.send_to_child_instances :adapt end
[ "def", "load_settings", "(", "path", ")", "Konfig", ".", "load_directory", "(", "path", ")", "built_in_adapters", "=", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'adapters'", ",", "'*.rb'", ")", "require_all", "built_in_adapters", "user_adapters", "=", "File", ".", "join", "(", "path", ",", "'adapters'", ",", "'*_adapter.rb'", ")", "require_all", "user_adapters", "Adapter", ".", "create_child_instances", "(", "Konfig", ".", "default_store", ".", "data", ")", "Adapter", ".", "send_to_child_instances", ":adapt", "end" ]
Set up the Konfig system @param [String] path the path to the directory containing config files
[ "Set", "up", "the", "Konfig", "system" ]
5d655945586a489868bb868243d9c0da18c90228
https://github.com/starrhorne/konfig/blob/5d655945586a489868bb868243d9c0da18c90228/lib/konfig/rails/railtie.rb#L28-L43
train
riddopic/hoodie
lib/hoodie/utils/crypto.rb
Hoodie.Crypto.encrypt
def encrypt(plain_text, password = nil, salt = nil) password = password.nil? ? Hoodie.crypto.password : password salt = salt.nil? ? Hoodie.crypto.salt : salt cipher = new_cipher(:encrypt, password, salt) cipher.iv = iv = cipher.random_iv ciphertext = cipher.update(plain_text) ciphertext << cipher.final Base64.encode64(combine_iv_ciphertext(iv, ciphertext)) end
ruby
def encrypt(plain_text, password = nil, salt = nil) password = password.nil? ? Hoodie.crypto.password : password salt = salt.nil? ? Hoodie.crypto.salt : salt cipher = new_cipher(:encrypt, password, salt) cipher.iv = iv = cipher.random_iv ciphertext = cipher.update(plain_text) ciphertext << cipher.final Base64.encode64(combine_iv_ciphertext(iv, ciphertext)) end
[ "def", "encrypt", "(", "plain_text", ",", "password", "=", "nil", ",", "salt", "=", "nil", ")", "password", "=", "password", ".", "nil?", "?", "Hoodie", ".", "crypto", ".", "password", ":", "password", "salt", "=", "salt", ".", "nil?", "?", "Hoodie", ".", "crypto", ".", "salt", ":", "salt", "cipher", "=", "new_cipher", "(", ":encrypt", ",", "password", ",", "salt", ")", "cipher", ".", "iv", "=", "iv", "=", "cipher", ".", "random_iv", "ciphertext", "=", "cipher", ".", "update", "(", "plain_text", ")", "ciphertext", "<<", "cipher", ".", "final", "Base64", ".", "encode64", "(", "combine_iv_ciphertext", "(", "iv", ",", "ciphertext", ")", ")", "end" ]
Encrypt the given string using the AES-256-CBC algorithm. @param [String] plain_text The text to encrypt. @param [String] password Secret passphrase to encrypt with. @param [String] salt A cryptographically secure pseudo-random string (SecureRandom.base64) to add a little spice to your encryption. @return [String] Encrypted text, can be deciphered with #decrypt. @api public
[ "Encrypt", "the", "given", "string", "using", "the", "AES", "-", "256", "-", "CBC", "algorithm", "." ]
921601dd4849845d3f5d3765dafcf00178b2aa66
https://github.com/riddopic/hoodie/blob/921601dd4849845d3f5d3765dafcf00178b2aa66/lib/hoodie/utils/crypto.rb#L145-L154
train
codescrum/bebox
lib/bebox/environment.rb
Bebox.Environment.generate_hiera_template
def generate_hiera_template ssh_key = Bebox::Project.public_ssh_key_from_file(self.project_root, self.name) project_name = Bebox::Project.shortname_from_file(self.project_root) Bebox::PROVISION_STEPS.each do |step| step_dir = Bebox::Provision.step_name(step) generate_file_from_template("#{templates_path}/puppet/#{step}/hiera/data/environment.yaml.erb", "#{self.project_root}/puppet/steps/#{step_dir}/hiera/data/#{self.name}.yaml", {step_dir: step_dir, ssh_key: ssh_key, project_name: project_name}) end end
ruby
def generate_hiera_template ssh_key = Bebox::Project.public_ssh_key_from_file(self.project_root, self.name) project_name = Bebox::Project.shortname_from_file(self.project_root) Bebox::PROVISION_STEPS.each do |step| step_dir = Bebox::Provision.step_name(step) generate_file_from_template("#{templates_path}/puppet/#{step}/hiera/data/environment.yaml.erb", "#{self.project_root}/puppet/steps/#{step_dir}/hiera/data/#{self.name}.yaml", {step_dir: step_dir, ssh_key: ssh_key, project_name: project_name}) end end
[ "def", "generate_hiera_template", "ssh_key", "=", "Bebox", "::", "Project", ".", "public_ssh_key_from_file", "(", "self", ".", "project_root", ",", "self", ".", "name", ")", "project_name", "=", "Bebox", "::", "Project", ".", "shortname_from_file", "(", "self", ".", "project_root", ")", "Bebox", "::", "PROVISION_STEPS", ".", "each", "do", "|", "step", "|", "step_dir", "=", "Bebox", "::", "Provision", ".", "step_name", "(", "step", ")", "generate_file_from_template", "(", "\"#{templates_path}/puppet/#{step}/hiera/data/environment.yaml.erb\"", ",", "\"#{self.project_root}/puppet/steps/#{step_dir}/hiera/data/#{self.name}.yaml\"", ",", "{", "step_dir", ":", "step_dir", ",", "ssh_key", ":", "ssh_key", ",", "project_name", ":", "project_name", "}", ")", "end", "end" ]
Generate the hiera data template for the environment
[ "Generate", "the", "hiera", "data", "template", "for", "the", "environment" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/environment.rb#L72-L79
train
mrackwitz/CLIntegracon
lib/CLIntegracon/subject.rb
CLIntegracon.Subject.replace_path
def replace_path(path, name=nil) name ||= File.basename path self.replace_pattern path, name end
ruby
def replace_path(path, name=nil) name ||= File.basename path self.replace_pattern path, name end
[ "def", "replace_path", "(", "path", ",", "name", "=", "nil", ")", "name", "||=", "File", ".", "basename", "path", "self", ".", "replace_pattern", "path", ",", "name", "end" ]
Define a path, whose occurrences in the output should be replaced by either its basename or a given placeholder. @param [String] path The path @param [String] name The name of the path, or the basename of the given path
[ "Define", "a", "path", "whose", "occurrences", "in", "the", "output", "should", "be", "replaced", "by", "either", "its", "basename", "or", "a", "given", "placeholder", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/subject.rb#L94-L97
train
mrackwitz/CLIntegracon
lib/CLIntegracon/subject.rb
CLIntegracon.Subject.run
def run(command_line) require 'open3' env = Hash[environment_vars.map { |k, v| [k.to_s, v.to_s] }] Open3.capture2e(env, command_line.to_s) end
ruby
def run(command_line) require 'open3' env = Hash[environment_vars.map { |k, v| [k.to_s, v.to_s] }] Open3.capture2e(env, command_line.to_s) end
[ "def", "run", "(", "command_line", ")", "require", "'open3'", "env", "=", "Hash", "[", "environment_vars", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ".", "to_s", ",", "v", ".", "to_s", "]", "}", "]", "Open3", ".", "capture2e", "(", "env", ",", "command_line", ".", "to_s", ")", "end" ]
Run the command. @param [String] command_line THe command line to execute @return [[String, Process::Status]] The output, which is emitted during execution, and the exit status.
[ "Run", "the", "command", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/subject.rb#L161-L165
train
mrackwitz/CLIntegracon
lib/CLIntegracon/subject.rb
CLIntegracon.Subject.command_line
def command_line(head_arguments='', tail_arguments='') args = [head_arguments, default_args, tail_arguments].flatten.compact.select { |s| s.length > 0 }.join ' ' "#{executable} #{args}" end
ruby
def command_line(head_arguments='', tail_arguments='') args = [head_arguments, default_args, tail_arguments].flatten.compact.select { |s| s.length > 0 }.join ' ' "#{executable} #{args}" end
[ "def", "command_line", "(", "head_arguments", "=", "''", ",", "tail_arguments", "=", "''", ")", "args", "=", "[", "head_arguments", ",", "default_args", ",", "tail_arguments", "]", ".", "flatten", ".", "compact", ".", "select", "{", "|", "s", "|", "s", ".", "length", ">", "0", "}", ".", "join", "' '", "\"#{executable} #{args}\"", "end" ]
Merges the given with the configured arguments and returns the command line to execute. @param [String] head_arguments The arguments to pass to the executable before the default arguments. @param [String] tail_arguments The arguments to pass to the executable after the default arguments. @return [String] The command line to execute.
[ "Merges", "the", "given", "with", "the", "configured", "arguments", "and", "returns", "the", "command", "line", "to", "execute", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/subject.rb#L179-L182
train
mrackwitz/CLIntegracon
lib/CLIntegracon/subject.rb
CLIntegracon.Subject.apply_replacements
def apply_replacements(output) replace_patterns.reduce(output) do |output, replacement_pattern| replacement_pattern.replace(output) end end
ruby
def apply_replacements(output) replace_patterns.reduce(output) do |output, replacement_pattern| replacement_pattern.replace(output) end end
[ "def", "apply_replacements", "(", "output", ")", "replace_patterns", ".", "reduce", "(", "output", ")", "do", "|", "output", ",", "replacement_pattern", "|", "replacement_pattern", ".", "replace", "(", "output", ")", "end", "end" ]
Apply the configured replacements to the output. @param [String] output The output, which was emitted while execution. @return [String] The redacted output.
[ "Apply", "the", "configured", "replacements", "to", "the", "output", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/subject.rb#L192-L196
train
mova-rb/mova
lib/mova/translator.rb
Mova.Translator.get
def get(key, locale, opts = {}) keys = resolve_scopes(key) locales = resolve_locales(locale) read_first(locales, keys) || opts[:default] || default(locales, keys, opts) end
ruby
def get(key, locale, opts = {}) keys = resolve_scopes(key) locales = resolve_locales(locale) read_first(locales, keys) || opts[:default] || default(locales, keys, opts) end
[ "def", "get", "(", "key", ",", "locale", ",", "opts", "=", "{", "}", ")", "keys", "=", "resolve_scopes", "(", "key", ")", "locales", "=", "resolve_locales", "(", "locale", ")", "read_first", "(", "locales", ",", "keys", ")", "||", "opts", "[", ":default", "]", "||", "default", "(", "locales", ",", "keys", ",", "opts", ")", "end" ]
Retrieves translation from the storage or return default value. @return [String] translation or default value if nothing found @example translator.put(en: {hello: "world"}) translator.get("hello", :en) #=> "world" translator.get("bye", :en) #=> "" @example Providing the default if nothing found translator.get("hello", :de, default: "nothing") #=> "nothing" @overload get(key, locale, opts = {}) @param key [String, Symbol] @param locale [String, Symbol] @overload get(keys, locale, opts = {}) @param keys [Array<String, Symbol>] use this to redefine an array returned by {#keys_to_try}. @param locale [String, Symbol] @example translator.put(en: {fail: "Fail"}) translator.get(["big.fail", "mine.fail"], :en) #=> ""; tried "en.big.fail", then "en.mine.fail" @overload get(key, locales, opts = {}) @param key [String, Symbol] @param locales [Array<String, Symbol>] use this to redefine an array returned by {#locales_to_try}. @example translator.put(en: {hello: "world"}) translator.get(:hello, :de) #=> ""; tried only "de.hello" translator.get(:hello, [:de, :en]) #=> "world"; tried "de.hello", then "en.hello" @example Disable locale fallbacks locally translator.put(en: {hello: "world"}) # suppose this instance has fallback to :en locale translator.get(:hello, :de) #=> "world"; tried "de.hello", then "en.hello" translator.get(:hello, [:de]) #=> ""; tried only "de.hello" @overload get(keys, locales, opts = {}) @param keys [Array<String, Symbol>] @param locales [Array<String, Symbol>] @note Keys fallback has a higher priority than locales one, that is, Mova tries to find a translation for any given key and only then it fallbacks to another locale. @param opts [Hash] @option opts [String] :default use this to redefine default value returned by {#default}. @see #locales_to_try @see #keys_to_try @see #default
[ "Retrieves", "translation", "from", "the", "storage", "or", "return", "default", "value", "." ]
27f981c1f29dc20e5d11068d9342088f0e6bb318
https://github.com/mova-rb/mova/blob/27f981c1f29dc20e5d11068d9342088f0e6bb318/lib/mova/translator.rb#L136-L140
train
mova-rb/mova
lib/mova/translator.rb
Mova.Translator.put
def put(translations) Scope.flatten(translations).each do |key, value| storage.write(key, value) unless storage.exist?(key) end end
ruby
def put(translations) Scope.flatten(translations).each do |key, value| storage.write(key, value) unless storage.exist?(key) end end
[ "def", "put", "(", "translations", ")", "Scope", ".", "flatten", "(", "translations", ")", ".", "each", "do", "|", "key", ",", "value", "|", "storage", ".", "write", "(", "key", ",", "value", ")", "unless", "storage", ".", "exist?", "(", "key", ")", "end", "end" ]
Writes translations to the storage. @return [void] @param translations [Hash{String, Symbol => String, Hash}] where root key/keys must be a locale @example translator.put(en: {world: "world"}, uk: {world: "світ"}) translator.get("world", :uk) #=> "світ"
[ "Writes", "translations", "to", "the", "storage", "." ]
27f981c1f29dc20e5d11068d9342088f0e6bb318
https://github.com/mova-rb/mova/blob/27f981c1f29dc20e5d11068d9342088f0e6bb318/lib/mova/translator.rb#L151-L155
train
wynst/email_direct
lib/email_direct/service_proxy_patch.rb
EmailDirect.ServiceProxyPatch.build_request
def build_request(method, options) builder = underscore("build_#{method}") self.respond_to?(builder) ? self.send(builder, options) : soap_envelope(options).target! end
ruby
def build_request(method, options) builder = underscore("build_#{method}") self.respond_to?(builder) ? self.send(builder, options) : soap_envelope(options).target! end
[ "def", "build_request", "(", "method", ",", "options", ")", "builder", "=", "underscore", "(", "\"build_#{method}\"", ")", "self", ".", "respond_to?", "(", "builder", ")", "?", "self", ".", "send", "(", "builder", ",", "options", ")", ":", "soap_envelope", "(", "options", ")", ".", "target!", "end" ]
same as original, but don't call .target! on custom builder
[ "same", "as", "original", "but", "don", "t", "call", ".", "target!", "on", "custom", "builder" ]
a6ab948c362c695cfbf12cc4f9c7c0ca8e805c54
https://github.com/wynst/email_direct/blob/a6ab948c362c695cfbf12cc4f9c7c0ca8e805c54/lib/email_direct/service_proxy_patch.rb#L4-L8
train
wedesoft/multiarray
lib/multiarray/complex.rb
Hornetseye.InternalComplex.*
def *(other) if other.is_a?(InternalComplex) or other.is_a?(Complex) InternalComplex.new @real * other.real - @imag * other.imag, @real * other.imag + @imag * other.real elsif InternalComplex.generic? other InternalComplex.new @real * other, @imag * other else x, y = other.coerce self x * y end end
ruby
def *(other) if other.is_a?(InternalComplex) or other.is_a?(Complex) InternalComplex.new @real * other.real - @imag * other.imag, @real * other.imag + @imag * other.real elsif InternalComplex.generic? other InternalComplex.new @real * other, @imag * other else x, y = other.coerce self x * y end end
[ "def", "*", "(", "other", ")", "if", "other", ".", "is_a?", "(", "InternalComplex", ")", "or", "other", ".", "is_a?", "(", "Complex", ")", "InternalComplex", ".", "new", "@real", "*", "other", ".", "real", "-", "@imag", "*", "other", ".", "imag", ",", "@real", "*", "other", ".", "imag", "+", "@imag", "*", "other", ".", "real", "elsif", "InternalComplex", ".", "generic?", "other", "InternalComplex", ".", "new", "@real", "*", "other", ",", "@imag", "*", "other", "else", "x", ",", "y", "=", "other", ".", "coerce", "self", "x", "*", "y", "end", "end" ]
Multiply complex values @param [Object] Second operand for binary operation. @return [InternalComplex] The result @private
[ "Multiply", "complex", "values" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/complex.rb#L227-L237
train
wedesoft/multiarray
lib/multiarray/complex.rb
Hornetseye.InternalComplex./
def /(other) if other.is_a?(InternalComplex) or other.is_a?(Complex) self * other.conj / other.abs2 elsif InternalComplex.generic? other InternalComplex.new @real / other, @imag / other else x, y = other.coerce self x / y end end
ruby
def /(other) if other.is_a?(InternalComplex) or other.is_a?(Complex) self * other.conj / other.abs2 elsif InternalComplex.generic? other InternalComplex.new @real / other, @imag / other else x, y = other.coerce self x / y end end
[ "def", "/", "(", "other", ")", "if", "other", ".", "is_a?", "(", "InternalComplex", ")", "or", "other", ".", "is_a?", "(", "Complex", ")", "self", "*", "other", ".", "conj", "/", "other", ".", "abs2", "elsif", "InternalComplex", ".", "generic?", "other", "InternalComplex", ".", "new", "@real", "/", "other", ",", "@imag", "/", "other", "else", "x", ",", "y", "=", "other", ".", "coerce", "self", "x", "/", "y", "end", "end" ]
Divide complex values @param [Object] Second operand for binary operation. @return [InternalComplex] The result @private
[ "Divide", "complex", "values" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/complex.rb#L246-L255
train
wedesoft/multiarray
lib/multiarray/complex.rb
Hornetseye.COMPLEX_.assign
def assign(value) value = value.simplify if @value.real.respond_to? :assign @value.real.assign value.get.real else @value.real = value.get.real end if @value.imag.respond_to? :assign @value.imag.assign value.get.imag else @value.imag = value.get.imag end value end
ruby
def assign(value) value = value.simplify if @value.real.respond_to? :assign @value.real.assign value.get.real else @value.real = value.get.real end if @value.imag.respond_to? :assign @value.imag.assign value.get.imag else @value.imag = value.get.imag end value end
[ "def", "assign", "(", "value", ")", "value", "=", "value", ".", "simplify", "if", "@value", ".", "real", ".", "respond_to?", ":assign", "@value", ".", "real", ".", "assign", "value", ".", "get", ".", "real", "else", "@value", ".", "real", "=", "value", ".", "get", ".", "real", "end", "if", "@value", ".", "imag", ".", "respond_to?", ":assign", "@value", ".", "imag", ".", "assign", "value", ".", "get", ".", "imag", "else", "@value", ".", "imag", "=", "value", ".", "get", ".", "imag", "end", "value", "end" ]
Constructor for native complex number @param [Complex,InternalComplex] value Complex number. Duplicate object @return [COMPLEX_] Duplicate of +self+. Store new value in this object @param [Object] value New value for this object. @return [Object] Returns +value+. @private
[ "Constructor", "for", "native", "complex", "number" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/complex.rb#L890-L903
train
wedesoft/multiarray
lib/multiarray/complex.rb
Hornetseye.Node.real_with_decompose
def real_with_decompose if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy] real_without_decompose elsif typecode < COMPLEX_ decompose 0 else self end end
ruby
def real_with_decompose if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy] real_without_decompose elsif typecode < COMPLEX_ decompose 0 else self end end
[ "def", "real_with_decompose", "if", "typecode", "==", "OBJECT", "or", "is_a?", "(", "Variable", ")", "or", "Thread", ".", "current", "[", ":lazy", "]", "real_without_decompose", "elsif", "typecode", "<", "COMPLEX_", "decompose", "0", "else", "self", "end", "end" ]
Fast extraction for real values of complex array @return [Node] Array with real values.
[ "Fast", "extraction", "for", "real", "values", "of", "complex", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/complex.rb#L990-L998
train
wedesoft/multiarray
lib/multiarray/complex.rb
Hornetseye.Node.real=
def real=(value) if typecode < COMPLEX_ decompose( 0 )[] = value elsif typecode == OBJECT self[] = Hornetseye::lazy do value + imag * Complex::I end else self[] = value end end
ruby
def real=(value) if typecode < COMPLEX_ decompose( 0 )[] = value elsif typecode == OBJECT self[] = Hornetseye::lazy do value + imag * Complex::I end else self[] = value end end
[ "def", "real", "=", "(", "value", ")", "if", "typecode", "<", "COMPLEX_", "decompose", "(", "0", ")", "[", "]", "=", "value", "elsif", "typecode", "==", "OBJECT", "self", "[", "]", "=", "Hornetseye", "::", "lazy", "do", "value", "+", "imag", "*", "Complex", "::", "I", "end", "else", "self", "[", "]", "=", "value", "end", "end" ]
Assignment for real values of complex array @param [Object] Value or array of values to assign to real components. @return [Object] Returns +value+.
[ "Assignment", "for", "real", "values", "of", "complex", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/complex.rb#L1007-L1017
train
wedesoft/multiarray
lib/multiarray/complex.rb
Hornetseye.Node.imag_with_decompose
def imag_with_decompose if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy] imag_without_decompose elsif typecode < COMPLEX_ decompose 1 else Hornetseye::lazy( *shape ) { typecode.new( 0 ) } end end
ruby
def imag_with_decompose if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy] imag_without_decompose elsif typecode < COMPLEX_ decompose 1 else Hornetseye::lazy( *shape ) { typecode.new( 0 ) } end end
[ "def", "imag_with_decompose", "if", "typecode", "==", "OBJECT", "or", "is_a?", "(", "Variable", ")", "or", "Thread", ".", "current", "[", ":lazy", "]", "imag_without_decompose", "elsif", "typecode", "<", "COMPLEX_", "decompose", "1", "else", "Hornetseye", "::", "lazy", "(", "*", "shape", ")", "{", "typecode", ".", "new", "(", "0", ")", "}", "end", "end" ]
Fast extraction of imaginary values of complex array @return [Node] Array with imaginary values.
[ "Fast", "extraction", "of", "imaginary", "values", "of", "complex", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/complex.rb#L1022-L1030
train
tongueroo/balancer
lib/balancer/core.rb
Balancer.Core.set_profile
def set_profile(value) path = "#{root}/.balancer/profiles/#{value}.yml" unless File.exist?(path) puts "The profile file #{path} does not exist. Exiting.".colorize(:red) exit 1 end ENV['BALANCER_PROFILE'] = value end
ruby
def set_profile(value) path = "#{root}/.balancer/profiles/#{value}.yml" unless File.exist?(path) puts "The profile file #{path} does not exist. Exiting.".colorize(:red) exit 1 end ENV['BALANCER_PROFILE'] = value end
[ "def", "set_profile", "(", "value", ")", "path", "=", "\"#{root}/.balancer/profiles/#{value}.yml\"", "unless", "File", ".", "exist?", "(", "path", ")", "puts", "\"The profile file #{path} does not exist. Exiting.\"", ".", "colorize", "(", ":red", ")", "exit", "1", "end", "ENV", "[", "'BALANCER_PROFILE'", "]", "=", "value", "end" ]
Only set the BALANCER_PROFILE if not set already at the CLI. CLI takes highest precedence.
[ "Only", "set", "the", "BALANCER_PROFILE", "if", "not", "set", "already", "at", "the", "CLI", ".", "CLI", "takes", "highest", "precedence", "." ]
c149498e78f73b1dc0a433cc693ec4327c409bab
https://github.com/tongueroo/balancer/blob/c149498e78f73b1dc0a433cc693ec4327c409bab/lib/balancer/core.rb#L24-L31
train
Rafaherrero/lpp_11
lib/doublylinkedlist/doublylinkedlist.rb
Doublylinkedlist.Doublylinkedlist.to_s
def to_s actual = @inicio cadena = "|" while !actual.nil? cadena << actual[:valor].to_s if !actual[:sig].nil? cadena << ", " end actual = actual[:sig] end cadena << "|" return cadena end
ruby
def to_s actual = @inicio cadena = "|" while !actual.nil? cadena << actual[:valor].to_s if !actual[:sig].nil? cadena << ", " end actual = actual[:sig] end cadena << "|" return cadena end
[ "def", "to_s", "actual", "=", "@inicio", "cadena", "=", "\"|\"", "while", "!", "actual", ".", "nil?", "cadena", "<<", "actual", "[", ":valor", "]", ".", "to_s", "if", "!", "actual", "[", ":sig", "]", ".", "nil?", "cadena", "<<", "\", \"", "end", "actual", "=", "actual", "[", ":sig", "]", "end", "cadena", "<<", "\"|\"", "return", "cadena", "end" ]
Iniciar los punteros de la lista, inicio y final Metodo para imprimir la lista con formato @return la lista formateada en un string
[ "Iniciar", "los", "punteros", "de", "la", "lista", "inicio", "y", "final", "Metodo", "para", "imprimir", "la", "lista", "con", "formato" ]
7b9a89138db96d603f1f1b1b93735feee5e4c2a2
https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/doublylinkedlist/doublylinkedlist.rb#L14-L28
train
Rafaherrero/lpp_11
lib/doublylinkedlist/doublylinkedlist.rb
Doublylinkedlist.Doublylinkedlist.insertar_inicio
def insertar_inicio(val) if @inicio.nil? @inicio = Struct::Nodo.new(nil, val, nil) @final = @inicio else copia = @inicio @inicio = Struct::Nodo.new(nil, val, copia) copia[:ant] = @inicio end end
ruby
def insertar_inicio(val) if @inicio.nil? @inicio = Struct::Nodo.new(nil, val, nil) @final = @inicio else copia = @inicio @inicio = Struct::Nodo.new(nil, val, copia) copia[:ant] = @inicio end end
[ "def", "insertar_inicio", "(", "val", ")", "if", "@inicio", ".", "nil?", "@inicio", "=", "Struct", "::", "Nodo", ".", "new", "(", "nil", ",", "val", ",", "nil", ")", "@final", "=", "@inicio", "else", "copia", "=", "@inicio", "@inicio", "=", "Struct", "::", "Nodo", ".", "new", "(", "nil", ",", "val", ",", "copia", ")", "copia", "[", ":ant", "]", "=", "@inicio", "end", "end" ]
Metodo que nos permite insertar algo al inicio de la lista @param [val] val recibe el valor a insertar en la lista
[ "Metodo", "que", "nos", "permite", "insertar", "algo", "al", "inicio", "de", "la", "lista" ]
7b9a89138db96d603f1f1b1b93735feee5e4c2a2
https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/doublylinkedlist/doublylinkedlist.rb#L32-L41
train
Rafaherrero/lpp_11
lib/doublylinkedlist/doublylinkedlist.rb
Doublylinkedlist.Doublylinkedlist.insertar_final
def insertar_final(val) if @final.nil? @inicio = Struct::Nodo.new(nil, val, nil) @final = @inicio else copia = @final @final[:sig] = Struct::Nodo.new(copia, val, nil) copia2 = @final[:sig] @final = copia2 end end
ruby
def insertar_final(val) if @final.nil? @inicio = Struct::Nodo.new(nil, val, nil) @final = @inicio else copia = @final @final[:sig] = Struct::Nodo.new(copia, val, nil) copia2 = @final[:sig] @final = copia2 end end
[ "def", "insertar_final", "(", "val", ")", "if", "@final", ".", "nil?", "@inicio", "=", "Struct", "::", "Nodo", ".", "new", "(", "nil", ",", "val", ",", "nil", ")", "@final", "=", "@inicio", "else", "copia", "=", "@final", "@final", "[", ":sig", "]", "=", "Struct", "::", "Nodo", ".", "new", "(", "copia", ",", "val", ",", "nil", ")", "copia2", "=", "@final", "[", ":sig", "]", "@final", "=", "copia2", "end", "end" ]
Metodo que nos permite insertar algo al final de la lista @param [val] val recibe el valor a insertar en la lista
[ "Metodo", "que", "nos", "permite", "insertar", "algo", "al", "final", "de", "la", "lista" ]
7b9a89138db96d603f1f1b1b93735feee5e4c2a2
https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/doublylinkedlist/doublylinkedlist.rb#L45-L55
train
Rafaherrero/lpp_11
lib/doublylinkedlist/doublylinkedlist.rb
Doublylinkedlist.Doublylinkedlist.tamano
def tamano() if [email protected]? contador = 1 copia = @inicio while !copia[:sig].nil? contador += 1 copia2 = copia[:sig] copia = copia2 end end return contador end
ruby
def tamano() if [email protected]? contador = 1 copia = @inicio while !copia[:sig].nil? contador += 1 copia2 = copia[:sig] copia = copia2 end end return contador end
[ "def", "tamano", "(", ")", "if", "!", "@inicio", ".", "nil?", "contador", "=", "1", "copia", "=", "@inicio", "while", "!", "copia", "[", ":sig", "]", ".", "nil?", "contador", "+=", "1", "copia2", "=", "copia", "[", ":sig", "]", "copia", "=", "copia2", "end", "end", "return", "contador", "end" ]
Metodo que nos devuelve la cantidad de elementos en la lista @return cantidad de elementos en la lista
[ "Metodo", "que", "nos", "devuelve", "la", "cantidad", "de", "elementos", "en", "la", "lista" ]
7b9a89138db96d603f1f1b1b93735feee5e4c2a2
https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/doublylinkedlist/doublylinkedlist.rb#L97-L110
train
Rafaherrero/lpp_11
lib/doublylinkedlist/doublylinkedlist.rb
Doublylinkedlist.Doublylinkedlist.posicion
def posicion (pos) if @inicio.nil? raise RuntimeError, "La lista esta vacia" end if pos<0 || pos>tamano-1 raise RuntimeError, "La posicion no es correcta" end contador=0 copia=@inicio while contador<pos && !copia.nil? copia2 = copia[:sig] copia = copia2 contador += 1 end return copia[:valor] end
ruby
def posicion (pos) if @inicio.nil? raise RuntimeError, "La lista esta vacia" end if pos<0 || pos>tamano-1 raise RuntimeError, "La posicion no es correcta" end contador=0 copia=@inicio while contador<pos && !copia.nil? copia2 = copia[:sig] copia = copia2 contador += 1 end return copia[:valor] end
[ "def", "posicion", "(", "pos", ")", "if", "@inicio", ".", "nil?", "raise", "RuntimeError", ",", "\"La lista esta vacia\"", "end", "if", "pos", "<", "0", "||", "pos", ">", "tamano", "-", "1", "raise", "RuntimeError", ",", "\"La posicion no es correcta\"", "end", "contador", "=", "0", "copia", "=", "@inicio", "while", "contador", "<", "pos", "&&", "!", "copia", ".", "nil?", "copia2", "=", "copia", "[", ":sig", "]", "copia", "=", "copia2", "contador", "+=", "1", "end", "return", "copia", "[", ":valor", "]", "end" ]
Metodo que devuelve lo contenido en una posicion de la lista @param [pos] pos del elemento deseado @return nodo de la posicion de la lista
[ "Metodo", "que", "devuelve", "lo", "contenido", "en", "una", "posicion", "de", "la", "lista" ]
7b9a89138db96d603f1f1b1b93735feee5e4c2a2
https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/doublylinkedlist/doublylinkedlist.rb#L114-L132
train
Rafaherrero/lpp_11
lib/doublylinkedlist/doublylinkedlist.rb
Doublylinkedlist.Doublylinkedlist.ordenar!
def ordenar! cambio = true while cambio cambio = false i = @inicio i_1 = @inicio[:sig] while i_1 != nil if(i[:valor] > i_1[:valor]) i[:valor], i_1[:valor] = i_1[:valor], i[:valor] cambio = true end i = i_1 i_1 = i_1[:sig] end end end
ruby
def ordenar! cambio = true while cambio cambio = false i = @inicio i_1 = @inicio[:sig] while i_1 != nil if(i[:valor] > i_1[:valor]) i[:valor], i_1[:valor] = i_1[:valor], i[:valor] cambio = true end i = i_1 i_1 = i_1[:sig] end end end
[ "def", "ordenar!", "cambio", "=", "true", "while", "cambio", "cambio", "=", "false", "i", "=", "@inicio", "i_1", "=", "@inicio", "[", ":sig", "]", "while", "i_1", "!=", "nil", "if", "(", "i", "[", ":valor", "]", ">", "i_1", "[", ":valor", "]", ")", "i", "[", ":valor", "]", ",", "i_1", "[", ":valor", "]", "=", "i_1", "[", ":valor", "]", ",", "i", "[", ":valor", "]", "cambio", "=", "true", "end", "i", "=", "i_1", "i_1", "=", "i_1", "[", ":sig", "]", "end", "end", "end" ]
Metodo que nos ordenada la lista segun los criterios de la APA
[ "Metodo", "que", "nos", "ordenada", "la", "lista", "segun", "los", "criterios", "de", "la", "APA" ]
7b9a89138db96d603f1f1b1b93735feee5e4c2a2
https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/doublylinkedlist/doublylinkedlist.rb#L144-L159
train
djellemah/philtre-rails
lib/philtre-rails/philtre_view_helpers.rb
PhiltreRails.PhiltreViewHelpers.order_by
def order_by( filter, *fields, label: fields.first.to_s.titleize, order_link_class: default_order_link_class ) return label if filter.nil? # current ordering from the filter # each expr is a Sequel::SQL::Expression exprs = Hash[ filter.order_expressions ] # Invert each ordering for the generated link. Current sort order will be displayed. order_links = fields.map do |field| if exprs[field] order_link_class.new exprs[field].invert, active: true else order_link_class.new Sequel.asc(field) end end # filter params must have order in the right format filter_params = filter.filter_parameters.dup filter_params[:order] = unify_array( order_links.map( &:name ) ) params_hash = {filter.class::Model.model_name.param_key.to_sym => filter_params} link_text = raw( [label, order_links.first.andand.icon].compact.join(' ') ) link_to link_text, params_hash, {class: order_links.first.andand.css_class} end
ruby
def order_by( filter, *fields, label: fields.first.to_s.titleize, order_link_class: default_order_link_class ) return label if filter.nil? # current ordering from the filter # each expr is a Sequel::SQL::Expression exprs = Hash[ filter.order_expressions ] # Invert each ordering for the generated link. Current sort order will be displayed. order_links = fields.map do |field| if exprs[field] order_link_class.new exprs[field].invert, active: true else order_link_class.new Sequel.asc(field) end end # filter params must have order in the right format filter_params = filter.filter_parameters.dup filter_params[:order] = unify_array( order_links.map( &:name ) ) params_hash = {filter.class::Model.model_name.param_key.to_sym => filter_params} link_text = raw( [label, order_links.first.andand.icon].compact.join(' ') ) link_to link_text, params_hash, {class: order_links.first.andand.css_class} end
[ "def", "order_by", "(", "filter", ",", "*", "fields", ",", "label", ":", "fields", ".", "first", ".", "to_s", ".", "titleize", ",", "order_link_class", ":", "default_order_link_class", ")", "return", "label", "if", "filter", ".", "nil?", "exprs", "=", "Hash", "[", "filter", ".", "order_expressions", "]", "order_links", "=", "fields", ".", "map", "do", "|", "field", "|", "if", "exprs", "[", "field", "]", "order_link_class", ".", "new", "exprs", "[", "field", "]", ".", "invert", ",", "active", ":", "true", "else", "order_link_class", ".", "new", "Sequel", ".", "asc", "(", "field", ")", "end", "end", "filter_params", "=", "filter", ".", "filter_parameters", ".", "dup", "filter_params", "[", ":order", "]", "=", "unify_array", "(", "order_links", ".", "map", "(", "&", ":name", ")", ")", "params_hash", "=", "{", "filter", ".", "class", "::", "Model", ".", "model_name", ".", "param_key", ".", "to_sym", "=>", "filter_params", "}", "link_text", "=", "raw", "(", "[", "label", ",", "order_links", ".", "first", ".", "andand", ".", "icon", "]", ".", "compact", ".", "join", "(", "' '", ")", ")", "link_to", "link_text", ",", "params_hash", ",", "{", "class", ":", "order_links", ".", "first", ".", "andand", ".", "css_class", "}", "end" ]
Heavily modified from SearchLogic.
[ "Heavily", "modified", "from", "SearchLogic", "." ]
d37c7c564d7556081b89b434e34633320dbb28d8
https://github.com/djellemah/philtre-rails/blob/d37c7c564d7556081b89b434e34633320dbb28d8/lib/philtre-rails/philtre_view_helpers.rb#L20-L43
train
openSUSE/dm-bugzilla-adapter
lib/dm-bugzilla-adapter/delete.rb
DataMapper::Adapters.BugzillaAdapter.delete
def delete(collection) each_resource_with_edit_url(collection) do |resource, edit_url| connection.delete(edit_url, 'If-Match' => "*") end # return count collection.size end
ruby
def delete(collection) each_resource_with_edit_url(collection) do |resource, edit_url| connection.delete(edit_url, 'If-Match' => "*") end # return count collection.size end
[ "def", "delete", "(", "collection", ")", "each_resource_with_edit_url", "(", "collection", ")", "do", "|", "resource", ",", "edit_url", "|", "connection", ".", "delete", "(", "edit_url", ",", "'If-Match'", "=>", "\"*\"", ")", "end", "collection", ".", "size", "end" ]
Constructs and executes DELETE statement for given query @param [Collection] collection collection of records to be deleted @return [Integer] the number of records deleted @api semipublic
[ "Constructs", "and", "executes", "DELETE", "statement", "for", "given", "query" ]
d56a64918f315d5038145b3f0d94852fc38bcca2
https://github.com/openSUSE/dm-bugzilla-adapter/blob/d56a64918f315d5038145b3f0d94852fc38bcca2/lib/dm-bugzilla-adapter/delete.rb#L14-L20
train
varyonic/pocus
lib/pocus/session.rb
Pocus.Session.send_request
def send_request(method, path, fields = {}) response = send_logged_request(URI(BASE_URL + path), method, request_data(fields)) fail UnexpectedHttpResponse, response unless response.is_a? Net::HTTPSuccess JSON.parse(response.body) end
ruby
def send_request(method, path, fields = {}) response = send_logged_request(URI(BASE_URL + path), method, request_data(fields)) fail UnexpectedHttpResponse, response unless response.is_a? Net::HTTPSuccess JSON.parse(response.body) end
[ "def", "send_request", "(", "method", ",", "path", ",", "fields", "=", "{", "}", ")", "response", "=", "send_logged_request", "(", "URI", "(", "BASE_URL", "+", "path", ")", ",", "method", ",", "request_data", "(", "fields", ")", ")", "fail", "UnexpectedHttpResponse", ",", "response", "unless", "response", ".", "is_a?", "Net", "::", "HTTPSuccess", "JSON", ".", "parse", "(", "response", ".", "body", ")", "end" ]
Accepts hash of fields to send. Returns parsed response body, always a hash.
[ "Accepts", "hash", "of", "fields", "to", "send", ".", "Returns", "parsed", "response", "body", "always", "a", "hash", "." ]
84cbbda509456fc8afaffd6916dccfc585d23b41
https://github.com/varyonic/pocus/blob/84cbbda509456fc8afaffd6916dccfc585d23b41/lib/pocus/session.rb#L42-L46
train
lulibrary/aspire
lib/aspire/user_lookup.rb
Aspire.UserLookup.[]
def [](uri, factory = nil) data = store[uri] data.nil? ? nil : Aspire::Object::User.new(uri, factory, json: data) end
ruby
def [](uri, factory = nil) data = store[uri] data.nil? ? nil : Aspire::Object::User.new(uri, factory, json: data) end
[ "def", "[]", "(", "uri", ",", "factory", "=", "nil", ")", "data", "=", "store", "[", "uri", "]", "data", ".", "nil?", "?", "nil", ":", "Aspire", "::", "Object", "::", "User", ".", "new", "(", "uri", ",", "factory", ",", "json", ":", "data", ")", "end" ]
Initialises a new UserLookup instance @see (Hash#initialize) @param filename [String] the filename of the CSV file to populate the hash @return [void] Returns an Aspire::Object::User instance for a URI @param uri [String] the URI of the user @param factory [Aspire::Object::Factory] the data object factory @return [Aspire::Object::User] the user
[ "Initialises", "a", "new", "UserLookup", "instance" ]
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/user_lookup.rb#L27-L30
train
lulibrary/aspire
lib/aspire/user_lookup.rb
Aspire.UserLookup.load
def load(filename = nil) delim = /\s*;\s*/ # The delimiter for email and role lists enum = Aspire::Enumerator::ReportEnumerator.new(filename).enumerator enum.each do |row| # Construct a JSON data structure for the user uri = row[3] data = csv_to_json_api(row, email_delim: delim, role_delim: delim) csv_to_json_other(row, data) # Store the JSON data in the lookup table store[uri] = data end end
ruby
def load(filename = nil) delim = /\s*;\s*/ # The delimiter for email and role lists enum = Aspire::Enumerator::ReportEnumerator.new(filename).enumerator enum.each do |row| # Construct a JSON data structure for the user uri = row[3] data = csv_to_json_api(row, email_delim: delim, role_delim: delim) csv_to_json_other(row, data) # Store the JSON data in the lookup table store[uri] = data end end
[ "def", "load", "(", "filename", "=", "nil", ")", "delim", "=", "/", "\\s", "\\s", "/", "enum", "=", "Aspire", "::", "Enumerator", "::", "ReportEnumerator", ".", "new", "(", "filename", ")", ".", "enumerator", "enum", ".", "each", "do", "|", "row", "|", "uri", "=", "row", "[", "3", "]", "data", "=", "csv_to_json_api", "(", "row", ",", "email_delim", ":", "delim", ",", "role_delim", ":", "delim", ")", "csv_to_json_other", "(", "row", ",", "data", ")", "store", "[", "uri", "]", "=", "data", "end", "end" ]
Populates the store from an All User Profiles report CSV file @param filename [String] the filename of the CSV file @return [void]
[ "Populates", "the", "store", "from", "an", "All", "User", "Profiles", "report", "CSV", "file" ]
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/user_lookup.rb#L35-L46
train
lulibrary/aspire
lib/aspire/user_lookup.rb
Aspire.UserLookup.method_missing
def method_missing(method, *args, &block) super unless store.respond_to?(method) store.public_send(method, *args, &block) end
ruby
def method_missing(method, *args, &block) super unless store.respond_to?(method) store.public_send(method, *args, &block) end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "super", "unless", "store", ".", "respond_to?", "(", "method", ")", "store", ".", "public_send", "(", "method", ",", "*", "args", ",", "&", "block", ")", "end" ]
Proxies missing methods to the store @param method [Symbol] the method name @param args [Array] the method arguments @param block [Proc] the code block @return [Object] the store method result
[ "Proxies", "missing", "methods", "to", "the", "store" ]
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/user_lookup.rb#L53-L56
train
lulibrary/aspire
lib/aspire/user_lookup.rb
Aspire.UserLookup.csv_to_json_api
def csv_to_json_api(row, data = {}, email_delim: nil, role_delim: nil) data['email'] = (row[4] || '').split(email_delim) data['firstName'] = row[0] data['role'] = (row[7] || '').split(role_delim) data['surname'] = row[1] data['uri'] = row[3] data end
ruby
def csv_to_json_api(row, data = {}, email_delim: nil, role_delim: nil) data['email'] = (row[4] || '').split(email_delim) data['firstName'] = row[0] data['role'] = (row[7] || '').split(role_delim) data['surname'] = row[1] data['uri'] = row[3] data end
[ "def", "csv_to_json_api", "(", "row", ",", "data", "=", "{", "}", ",", "email_delim", ":", "nil", ",", "role_delim", ":", "nil", ")", "data", "[", "'email'", "]", "=", "(", "row", "[", "4", "]", "||", "''", ")", ".", "split", "(", "email_delim", ")", "data", "[", "'firstName'", "]", "=", "row", "[", "0", "]", "data", "[", "'role'", "]", "=", "(", "row", "[", "7", "]", "||", "''", ")", ".", "split", "(", "role_delim", ")", "data", "[", "'surname'", "]", "=", "row", "[", "1", "]", "data", "[", "'uri'", "]", "=", "row", "[", "3", "]", "data", "end" ]
Adds CSV fields which mirror the Aspire user profile JSON API fields @param row [Array] the fields from the All User Profiles report CSV @param data [Hash] the JSON representation of the user profile @return [Hash] the JSON data hash
[ "Adds", "CSV", "fields", "which", "mirror", "the", "Aspire", "user", "profile", "JSON", "API", "fields" ]
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/user_lookup.rb#L80-L87
train
lulibrary/aspire
lib/aspire/user_lookup.rb
Aspire.UserLookup.csv_to_json_other
def csv_to_json_other(row, data = {}) # The following fields are not present in the JSON API response but are in # the All User Profiles report - they are included for completeness. data['jobRole'] = row[5] || '' data['lastLogin'] = row[8] data['name'] = row[2] || '' data['visibility'] = row[6] || '' data end
ruby
def csv_to_json_other(row, data = {}) # The following fields are not present in the JSON API response but are in # the All User Profiles report - they are included for completeness. data['jobRole'] = row[5] || '' data['lastLogin'] = row[8] data['name'] = row[2] || '' data['visibility'] = row[6] || '' data end
[ "def", "csv_to_json_other", "(", "row", ",", "data", "=", "{", "}", ")", "data", "[", "'jobRole'", "]", "=", "row", "[", "5", "]", "||", "''", "data", "[", "'lastLogin'", "]", "=", "row", "[", "8", "]", "data", "[", "'name'", "]", "=", "row", "[", "2", "]", "||", "''", "data", "[", "'visibility'", "]", "=", "row", "[", "6", "]", "||", "''", "data", "end" ]
Adds CSV fields which aren't part of the Aspire user profile JSON API @param row [Array] the fields from the All User Profiles report CSV @param data [Hash] the JSON representation of the user profile @return [Hash] the JSON data hash
[ "Adds", "CSV", "fields", "which", "aren", "t", "part", "of", "the", "Aspire", "user", "profile", "JSON", "API" ]
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/user_lookup.rb#L93-L101
train
cotag/couchbase-id
lib/couchbase-id/generator.rb
CouchbaseId.Generator.generate_id
def generate_id if self.id.nil? # # Generate the id (incrementing values as required) # overflow = self.class.__overflow__ ||= self.class.bucket.get("#{self.class.design_document}:#{CLUSTER_ID}:overflow", :quiet => true) # Don't error if not there count = self.class.bucket.incr("#{self.class.design_document}:#{CLUSTER_ID}:count", :create => true) # This models current id count if count == 0 || overflow.nil? overflow ||= 0 overflow += 1 # We shouldn't need to worry about concurrency here due to the size of count # Would require ~18446744073709551615 concurrent writes self.class.bucket.set("#{self.class.design_document}:#{CLUSTER_ID}:overflow", overflow) self.class.__overflow__ = overflow end self.id = self.class.__class_id_generator__.call(overflow, count) # # So an existing id would only be present if: # => something crashed before incrementing the overflow # => this is another request was occurring before the overflow is incremented # # Basically only the overflow should be able to cause issues, we'll increment the count just to be sure # One would hope this code only ever runs under high load during an overflow event # while self.class.bucket.get(self.id, :quiet => true).present? # Set in-case we are here due to a crash (concurrency is not an issue) # Note we are not incrementing the @__overflow__ variable self.class.bucket.set("#{self.class.design_document}:#{CLUSTER_ID}:overflow", overflow + 1) count = self.class.bucket.incr("#{self.class.design_document}:#{CLUSTER_ID}:count") # Increment just in case (attempt to avoid infinite loops) # Reset the overflow if self.class.__overflow__ == overflow self.class.__overflow__ = nil end # Generate the new id self.id = self.class.__class_id_generator__.call(overflow + 1, count) end end end
ruby
def generate_id if self.id.nil? # # Generate the id (incrementing values as required) # overflow = self.class.__overflow__ ||= self.class.bucket.get("#{self.class.design_document}:#{CLUSTER_ID}:overflow", :quiet => true) # Don't error if not there count = self.class.bucket.incr("#{self.class.design_document}:#{CLUSTER_ID}:count", :create => true) # This models current id count if count == 0 || overflow.nil? overflow ||= 0 overflow += 1 # We shouldn't need to worry about concurrency here due to the size of count # Would require ~18446744073709551615 concurrent writes self.class.bucket.set("#{self.class.design_document}:#{CLUSTER_ID}:overflow", overflow) self.class.__overflow__ = overflow end self.id = self.class.__class_id_generator__.call(overflow, count) # # So an existing id would only be present if: # => something crashed before incrementing the overflow # => this is another request was occurring before the overflow is incremented # # Basically only the overflow should be able to cause issues, we'll increment the count just to be sure # One would hope this code only ever runs under high load during an overflow event # while self.class.bucket.get(self.id, :quiet => true).present? # Set in-case we are here due to a crash (concurrency is not an issue) # Note we are not incrementing the @__overflow__ variable self.class.bucket.set("#{self.class.design_document}:#{CLUSTER_ID}:overflow", overflow + 1) count = self.class.bucket.incr("#{self.class.design_document}:#{CLUSTER_ID}:count") # Increment just in case (attempt to avoid infinite loops) # Reset the overflow if self.class.__overflow__ == overflow self.class.__overflow__ = nil end # Generate the new id self.id = self.class.__class_id_generator__.call(overflow + 1, count) end end end
[ "def", "generate_id", "if", "self", ".", "id", ".", "nil?", "overflow", "=", "self", ".", "class", ".", "__overflow__", "||=", "self", ".", "class", ".", "bucket", ".", "get", "(", "\"#{self.class.design_document}:#{CLUSTER_ID}:overflow\"", ",", ":quiet", "=>", "true", ")", "count", "=", "self", ".", "class", ".", "bucket", ".", "incr", "(", "\"#{self.class.design_document}:#{CLUSTER_ID}:count\"", ",", ":create", "=>", "true", ")", "if", "count", "==", "0", "||", "overflow", ".", "nil?", "overflow", "||=", "0", "overflow", "+=", "1", "self", ".", "class", ".", "bucket", ".", "set", "(", "\"#{self.class.design_document}:#{CLUSTER_ID}:overflow\"", ",", "overflow", ")", "self", ".", "class", ".", "__overflow__", "=", "overflow", "end", "self", ".", "id", "=", "self", ".", "class", ".", "__class_id_generator__", ".", "call", "(", "overflow", ",", "count", ")", "while", "self", ".", "class", ".", "bucket", ".", "get", "(", "self", ".", "id", ",", ":quiet", "=>", "true", ")", ".", "present?", "self", ".", "class", ".", "bucket", ".", "set", "(", "\"#{self.class.design_document}:#{CLUSTER_ID}:overflow\"", ",", "overflow", "+", "1", ")", "count", "=", "self", ".", "class", ".", "bucket", ".", "incr", "(", "\"#{self.class.design_document}:#{CLUSTER_ID}:count\"", ")", "if", "self", ".", "class", ".", "__overflow__", "==", "overflow", "self", ".", "class", ".", "__overflow__", "=", "nil", "end", "self", ".", "id", "=", "self", ".", "class", ".", "__class_id_generator__", ".", "call", "(", "overflow", "+", "1", ",", "count", ")", "end", "end", "end" ]
Cluster ID number instance method
[ "Cluster", "ID", "number", "instance", "method" ]
d62bf8d72aa4cda4603104f2e2f1b81e8f4e88e4
https://github.com/cotag/couchbase-id/blob/d62bf8d72aa4cda4603104f2e2f1b81e8f4e88e4/lib/couchbase-id/generator.rb#L36-L78
train
PragTob/wingtips
lib/wingtips/dsl.rb
Wingtips.DSL.merge_template_options
def merge_template_options(default_options, template_key, custom_options = {}) template_options = configuration.template_options.fetch template_key, {} options = Wingtips::HashUtils.deep_merge(default_options, template_options) Wingtips::HashUtils.deep_merge(options, custom_options) end
ruby
def merge_template_options(default_options, template_key, custom_options = {}) template_options = configuration.template_options.fetch template_key, {} options = Wingtips::HashUtils.deep_merge(default_options, template_options) Wingtips::HashUtils.deep_merge(options, custom_options) end
[ "def", "merge_template_options", "(", "default_options", ",", "template_key", ",", "custom_options", "=", "{", "}", ")", "template_options", "=", "configuration", ".", "template_options", ".", "fetch", "template_key", ",", "{", "}", "options", "=", "Wingtips", "::", "HashUtils", ".", "deep_merge", "(", "default_options", ",", "template_options", ")", "Wingtips", "::", "HashUtils", ".", "deep_merge", "(", "options", ",", "custom_options", ")", "end" ]
merge order is = defaults, template, custom
[ "merge", "order", "is", "=", "defaults", "template", "custom" ]
df47ecdf19fdd9e7091e96232a24c2d7fb43a3ab
https://github.com/PragTob/wingtips/blob/df47ecdf19fdd9e7091e96232a24c2d7fb43a3ab/lib/wingtips/dsl.rb#L40-L44
train
feduxorg/the_array_comparator
lib/the_array_comparator/cache.rb
TheArrayComparator.Cache.add
def add(cache, strategy) c = cache.to_sym s = strategy.to_sym fail Exceptions::UnknownCachingStrategy, "Unknown caching strategy \":#{strategy}\" given. Did you register it in advance?" unless caching_strategies.key?(strategy) caches[c] = caching_strategies[s].new caches[c] end
ruby
def add(cache, strategy) c = cache.to_sym s = strategy.to_sym fail Exceptions::UnknownCachingStrategy, "Unknown caching strategy \":#{strategy}\" given. Did you register it in advance?" unless caching_strategies.key?(strategy) caches[c] = caching_strategies[s].new caches[c] end
[ "def", "add", "(", "cache", ",", "strategy", ")", "c", "=", "cache", ".", "to_sym", "s", "=", "strategy", ".", "to_sym", "fail", "Exceptions", "::", "UnknownCachingStrategy", ",", "\"Unknown caching strategy \\\":#{strategy}\\\" given. Did you register it in advance?\"", "unless", "caching_strategies", ".", "key?", "(", "strategy", ")", "caches", "[", "c", "]", "=", "caching_strategies", "[", "s", "]", ".", "new", "caches", "[", "c", "]", "end" ]
Add a new cache @param [Symbol] cache the cache to be created @param [Symbol] strategy the cache strategy to be used
[ "Add", "a", "new", "cache" ]
66cdaf953909a34366cbee2b519dfcf306bc03c7
https://github.com/feduxorg/the_array_comparator/blob/66cdaf953909a34366cbee2b519dfcf306bc03c7/lib/the_array_comparator/cache.rb#L54-L62
train