repo stringlengths 5 58 | path stringlengths 9 168 | func_name stringlengths 9 130 | original_string stringlengths 66 10.5k | language stringclasses 1
value | code stringlengths 66 10.5k | code_tokens list | docstring stringlengths 8 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 94 266 | 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!... | 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!... | [
"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",
"(",
":depen... | 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",
")",
"# the new object",
"logger",
".",
"debug",
"{",
"\"The migrator is building #{klass.qp}...\"",
"}",
"created",
"<<",
"obj",
"=",
"klass",
".",
"new",
"migrate_properties",
"(",
"obj",
",",
... | 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 ins... | [
"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 ... | 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 ... | [
"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",
"]",
... | 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",
")",
"# create the intermediate objects as needed (or return obj if path is empty)",
"path",
".",
"inject",
"(",
"obj",
")",
"do",
"|",
"parent",
",",
"prop",
"|",
"# the referenced object",
"p... | 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)
... | 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)
... | [
"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}\"",
... | 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",
")",
"# collect the class => path => value entries from each defaults file",
"hash",
"=",
"LazyHash",
".",
"new",
"{",
"Hash",
".",
"new",
"}",
"files",
".",
"enumerate",
"{",
"|",
"file",
"|",
"load_defaults_file",
"(",
"... | 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?
... | 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?
... | [
"def",
"load_defaults_file",
"(",
"file",
",",
"hash",
")",
"begin",
"config",
"=",
"YAML",
"::",
"load_file",
"(",
"file",
")",
"rescue",
"raise",
"MigrationError",
".",
"new",
"(",
"\"Could not read defaults file #{file}: \"",
"+",
"$!",
")",
"end",
"# collect... | 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",
")",
"# collect the class => path => value entries from each defaults file",
"hash",
"=",
"{",
"}",
"files",
".",
"enumerate",
"{",
"|",
"file",
"|",
"load_filter_file",
"(",
"file",
",",
"hash",
")",
"}",
"logger",
".",
"... | 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... | 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... | [
"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",
"... | 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] = ar... | 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] = ar... | [
"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_me... | 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 o... | [
"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_readonl... | 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_readonl... | [
"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",
"[",
"... | 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 authorit... | [
"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_t... | 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 [Hash... | [
"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",
"(",
"v... | 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) ... | 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) ... | [
"def",
"easter",
"(",
"year",
")",
"golden_number",
"=",
"(",
"year",
"%",
"19",
")",
"+",
"1",
"if",
"year",
"<=",
"1752",
"then",
"# Julian calendar",
"dominical_number",
"=",
"(",
"year",
"+",
"(",
"year",
"/",
"4",
")",
"+",
"5",
")",
"%",
"7",... | 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",
"}",
... | 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.not... | 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.not... | [
"def",
"read",
"(",
"filename",
",",
"months",
"=",
"nil",
")",
"@orders",
"=",
"[",
"]",
"start",
"=",
"months",
"?",
"(",
"Date",
".",
"today",
"<<",
"months",
".",
"to_i",
")",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
":",
"nil",
"file",
"=",
... | 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" i... | 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" i... | [
"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 ... | 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
... | 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
... | [
"def",
"buffer_output",
"(",
"&",
"block",
")",
"#:doc:\r",
"raise",
"Shells",
"::",
"NotRunning",
"unless",
"running?",
"block",
"||=",
"Proc",
".",
"new",
"{",
"}",
"stdout_received",
"do",
"|",
"data",
"|",
"self",
".",
"last_output",
"=",
"Time",
".",
... | 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 t... | [
"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
... | 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
... | [
"def",
"push_buffer",
"raise",
"Shells",
"::",
"NotRunning",
"unless",
"running?",
"# push the buffer so we can get the output of a command.\r",
"debug",
"'Pushing buffer >>'",
"sync",
"do",
"output_stack",
".",
"push",
"[",
"stdout",
",",
"stderr",
",",
"output",
"]",
... | 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 = h... | 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 = h... | [
"def",
"pop_merge_buffer",
"raise",
"Shells",
"::",
"NotRunning",
"unless",
"running?",
"# almost a standard pop, however we want to merge history with current.\r",
"debug",
"'Merging buffer <<'",
"sync",
"do",
"hist_stdout",
",",
"hist_stderr",
",",
"hist_output",
"=",
"(",
... | 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 || ''
... | 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 || ''
... | [
"def",
"pop_discard_buffer",
"raise",
"Shells",
"::",
"NotRunning",
"unless",
"running?",
"# a standard pop discarding current data and retrieving the history.\r",
"debug",
"'Discarding buffer <<'",
"sync",
"do",
"hist_stdout",
",",
"hist_stderr",
",",
"hist_output",
"=",
"(",
... | 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",
"(... | 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",
... | 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",
")",
"# 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",
"=",
"s... | 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
... | 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
... | [
"def",
"append_node",
"(",
"type",
",",
"indent",
":",
"@indents",
".",
"length",
",",
"add",
":",
"false",
",",
"value",
":",
"nil",
")",
"# add necessary stack items to match required indent",
"@stacks",
"<<",
"@stacks",
".",
"last",
".",
"dup",
"while",
"in... | 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: #... | 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: ... | 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: ... | [
"def",
"close_client",
"(",
"clnt",
")",
"@close_client",
"=",
"(",
"known_client_action",
"(",
"clnt",
",",
":close",
")",
"||",
"false",
")",
"if",
"@close_client",
".",
"nil?",
"if",
"@close_client",
"begin",
"perform_action",
"(",
"clnt",
",",
"@close_clie... | 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... | 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... | 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... | [
"def",
"get_environment",
"(",
"options",
")",
"environment",
"=",
"options",
"[",
":environment",
"]",
"# Ask for environment of node if flag environment not set",
"environment",
"||=",
"choose_option",
"(",
"Environment",
".",
"list",
"(",
"project_root",
")",
",",
"_... | 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'",
":",
"envi... | 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 @arti... | 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 @arti... | [
"def",
"converte_configuracao_para_latex",
"@artigo_latex",
".",
"merge!",
"(",
"@artigo",
")",
"[",
"'resumo'",
",",
"'abstract'",
",",
"'bibliografia'",
"]",
".",
"each",
"{",
"|",
"key",
"|",
"Open3",
".",
"popen3",
"(",
"\"pandoc --smart -f markdown -t latex --n... | 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",
".",
"w... | 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
alertStart=@redis.get(tag)
return alertStart
... | 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
alertStart=@redis.get(tag)
return alertStart
... | [
"def",
"last_records",
"(",
"tag",
"=",
"@state_tag",
")",
"if",
"@state_type",
"==",
"'file'",
"return",
"@data",
"[",
"'last_records'",
"]",
"[",
"tag",
"]",
"elsif",
"@state_type",
"==",
"'memory'",
"return",
"@data",
"[",
"'last_records'",
"]",
"[",
"tag... | 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
... | 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
... | [
"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",
... | 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 par... | [
"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... | 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(... | 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(... | [
"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",
","... | 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
* *Examp... | [
"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",
... | 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... | 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_lev... | [
"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",
... | 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",
"{",
... | 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'
@log... | 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'
@log... | [
"def",
"receive",
"(",
"max_len",
"=",
"nil",
")",
"max_len",
"||=",
"1024",
"begin",
"data",
"=",
"@socket",
".",
"recv",
"(",
"max_len",
")",
"rescue",
"IO",
"::",
"WaitReadable",
"@logger",
".",
"logv",
"'Retrying receive...'",
"IO",
".",
"select",
"(",... | 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]
... | 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]
... | [
"def",
"validate_each",
"(",
"record",
",",
"attribute",
",",
"value",
")",
"begin",
"unless",
"value",
".",
"blank?",
"IPAddr",
".",
"new",
"(",
"value",
")",
"if",
"options",
"[",
":no_mask",
"]",
"if",
"value",
"=~",
"/",
"\\/",
"/",
"record",
".",
... | 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] )
#... | 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] )
#... | [
"def",
"load_attributes_from_response",
"(",
"response",
")",
"if",
"(",
"response",
"[",
"'Transfer-Encoding'",
"]",
"==",
"'chunked'",
"||",
"(",
"!",
"response",
"[",
"'Content-Length'",
"]",
".",
"blank?",
"&&",
"response",
"[",
"'Content-Length'",
"]",
"!="... | 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(me... | 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(me... | [
"def",
"method_missing",
"(",
"meth",
",",
"*",
"args",
",",
"&",
"block",
")",
"meth_str",
"=",
"meth",
".",
"to_s",
"if",
"/",
"\\w",
"\\=",
"/",
".",
"match",
"(",
"meth_str",
")",
"_set",
"(",
"$1",
",",
"args",
",",
"block",
")",
"elsif",
"a... | 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?
mess... | 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?
mess... | [
"def",
"default_message",
"message",
"=",
"[",
"]",
"if",
"value?",
"&&",
"name?",
"message",
"<<",
"format_message",
"(",
"value",
".",
"class",
",",
"\"object\"",
",",
"value",
".",
"inspect",
",",
"\"has invalid ##{ name } attribute\"",
")",
"end",
"if",
"e... | 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... | 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... | [
"def",
"message",
"(",
"text",
",",
"options",
"=",
"{",
"}",
",",
"env",
"=",
":prod",
",",
"type",
"=",
":normal",
")",
"if",
"type",
"==",
":normal",
"data",
"=",
"normal_notification",
"(",
"text",
",",
"options",
")",
"elsif",
"type",
"==",
":si... | 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]
... | 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]
... | [
"def",
"subscribe",
"(",
"queue",
",",
"exchange",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"raise",
"ArgumentError",
",",
"\"Must call this method with a block\"",
"unless",
"block",
"return",
"false",
"unless",
"usable?",
"return",
... | 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... | [
"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",
"i... | 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 ... | 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 ... | [
"def",
"unsubscribe",
"(",
"queue_names",
",",
"&",
"block",
")",
"unless",
"failed?",
"@queues",
".",
"reject!",
"do",
"|",
"q",
"|",
"if",
"queue_names",
".",
"include?",
"(",
"q",
".",
"name",
")",
"begin",
"logger",
".",
"info",
"(",
"\"[stop] Unsubs... | 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("F... | 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("F... | [
"def",
"queue_status",
"(",
"queue_names",
",",
"&",
"block",
")",
"return",
"false",
"unless",
"connected?",
"@queues",
".",
"each",
"do",
"|",
"q",
"|",
"if",
"queue_names",
".",
"include?",
"(",
"q",
".",
"name",
")",
"begin",
"q",
".",
"status",
"{... | 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 tim... | [
"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",
... | 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?... | 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?... | [
"def",
"publish",
"(",
"exchange",
",",
"packet",
",",
"message",
",",
"options",
"=",
"{",
"}",
")",
"return",
"false",
"unless",
"connected?",
"begin",
"exchange_options",
"=",
"exchange",
"[",
":options",
"]",
"||",
"{",
"}",
"unless",
"options",
"[",
... | 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 do... | [
"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
@connectio... | 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
@connectio... | [
"def",
"close",
"(",
"propagate",
"=",
"true",
",",
"normal",
"=",
"true",
",",
"log",
"=",
"true",
",",
"&",
"block",
")",
"final_status",
"=",
"normal",
"?",
":closed",
":",
":failed",
"if",
"!",
"[",
":closed",
",",
":failed",
"]",
".",
"include?"... | 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 pa... | [
"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],
... | 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],
... | [
"def",
"connect",
"(",
"address",
",",
"reconnect_interval",
")",
"begin",
"logger",
".",
"info",
"(",
"\"[setup] Connecting to broker #{@identity}, alias #{@alias}\"",
")",
"@status",
"=",
":connecting",
"@connection",
"=",
"AMQP",
".",
"connect",
"(",
":user",
"=>",... | 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 gi... | [
"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
... | 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
... | [
"def",
"receive",
"(",
"queue",
",",
"header",
",",
"message",
",",
"options",
",",
"&",
"block",
")",
"begin",
"if",
"options",
"[",
":no_unserialize",
"]",
"||",
"@serializer",
".",
"nil?",
"execute_callback",
"(",
"block",
",",
"@identity",
",",
"messag... | 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 re... | [
"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
... | 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
... | [
"def",
"unserialize",
"(",
"queue",
",",
"message",
",",
"options",
"=",
"{",
"}",
")",
"begin",
"received_at",
"=",
"Time",
".",
"now",
".",
"to_f",
"packet",
"=",
"@serializer",
".",
"method",
"(",
":load",
")",
".",
"arity",
".",
"abs",
">",
"1",
... | 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 a... | [
"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 #{t... | 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 #{t... | [
"def",
"handle_return",
"(",
"header",
",",
"message",
")",
"begin",
"to",
"=",
"if",
"header",
".",
"exchange",
"&&",
"!",
"header",
".",
"exchange",
".",
"empty?",
"then",
"header",
".",
"exchange",
"else",
"header",
".",
"routing_key",
"end",
"reason",
... | 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",
"call... | 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... | 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_TY... | 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_TY... | [
"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",
... | 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",
"respons... | 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.tex... | 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.tex... | [
"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",
".",
"ma... | 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",
")",
"# :yields: Object",
"threads",
"=",
"[",
"]",
"climber",
".",
"connection_pool",
".",
"connections",
".",
"each",
"do",
"|",
"connection",
"|",
"threads",
"<<",
"Thread",
".",
"new",
"{",
"connection",
".",
... | 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 th... | [
"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",
"... | 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,
... | 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,
... | [
"def",
"temporary_url",
"(",
"expires_at",
"=",
"Time",
".",
"now",
"+",
"3600",
")",
"url",
"=",
"URI",
".",
"escape",
"(",
"\"#{protocol}#{host(true)}/#{path_prefix}#{key}\"",
")",
"signature",
"=",
"Signature",
".",
"generate_temporary_url_signature",
"(",
":buck... | 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'].incl... | 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'].incl... | [
"def",
"configuration_is_valid?",
"(",
"configuration",
")",
"required_parameters",
"=",
"[",
"'file_name'",
",",
"'standard_stream'",
"]",
"required_parameters",
".",
"each",
"{",
"|",
"parameter",
"|",
"return",
"false",
"unless",
"configuration",
".",
"include?",
... | 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",
")... | 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}
en... | 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}
en... | [
"def",
"effective_groups",
"ret",
"=",
"[",
"self",
"]",
"memberships",
".",
"each",
"do",
"|",
"m",
"|",
"unless",
"ret",
".",
"include?",
"(",
"m",
")",
"# prevent infinite recursion",
"tmp",
"=",
"m",
".",
"effective_groups",
"tmp",
".",
"each",
"do",
... | 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?",
"... | 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')
req... | 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')
req... | [
"def",
"load_settings",
"(",
"path",
")",
"# Load the data files",
"Konfig",
".",
"load_directory",
"(",
"path",
")",
"# Load all adapters",
"built_in_adapters",
"=",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
",",
"'adapters'",
",",... | 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(plai... | 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(plai... | [
"def",
"encrypt",
"(",
"plain_text",
",",
"password",
"=",
"nil",
",",
"salt",
"=",
"nil",
")",
"password",
"=",
"password",
".",
"nil?",
"?",
"Hoodie",
".",
"crypto",
".",
"password",
":",
"password",
"salt",
"=",
"salt",
".",
"nil?",
"?",
"Hoodie",
... | 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.
@... | [
"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... | 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... | [
"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",
... | 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... | 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",
"... | 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.
@ret... | [
"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",
"[",
":defa... | 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
transl... | [
"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",
")",
... | 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",
... | 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
... | 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
... | [
"def",
"*",
"(",
"other",
")",
"if",
"other",
".",
"is_a?",
"(",
"InternalComplex",
")",
"or",
"other",
".",
"is_a?",
"(",
"Complex",
")",
"InternalComplex",
".",
"new",
"@real",
"*",
"other",
".",
"real",
"-",
"@imag",
"*",
"other",
".",
"imag",
","... | 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... | 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
... | 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
... | [
"def",
"assign",
"(",
"value",
")",
"value",
"=",
"value",
".",
"simplify",
"if",
"@value",
".",
"real",
".",
"respond_to?",
":assign",
"@value",
".",
"real",
".",
"assign",
"value",
".",
"get",
".",
"real",
"else",
"@value",
".",
"real",
"=",
"value",... | 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",
"en... | 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",
"*",
"... | 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",
"::",
... | 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",
"e... | 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",
"act... | 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",
... | 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",
"]",
... | 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 !@inicio.nil?
contador = 1
copia = @inicio
while !copia[:sig].nil?
contador += 1
copia2 = copia[:sig]
copia = copia2
end
end
return contador
end | ruby | 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 | [
"def",
"tamano",
"(",
")",
"if",
"!",
"@inicio",
".",
"nil?",
"contador",
"=",
"1",
"copia",
"=",
"@inicio",
"while",
"!",
"copia",
"[",
":sig",
"]",
".",
"nil?",
"contador",
"+=",
"1",
"copia2",
"=",
"copia",
"[",
":sig",
"]",
"copia",
"=",
"copia... | 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 ... | 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 ... | [
"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"... | 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",
"]",
")",... | 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 g... | 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 g... | [
"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 fr... | 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",
"# return count",
"collection... | 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",
"UnexpectedH... | 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",
")"... | 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
@retur... | [
"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... | 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... | [
"def",
"load",
"(",
"filename",
"=",
"nil",
")",
"delim",
"=",
"/",
"\\s",
"\\s",
"/",
"# The delimiter for email and role lists",
"enum",
"=",
"Aspire",
"::",
"Enumerator",
"::",
"ReportEnumerator",
".",
"new",
"(",
"filename",
")",
".",
"enumerator",
"enum",... | 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",
... | 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... | 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... | [
"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",
... | 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... | 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... | [
"def",
"generate_id",
"if",
"self",
".",
"id",
".",
"nil?",
"#",
"# Generate the id (incrementing values as required)",
"#",
"overflow",
"=",
"self",
".",
"class",
".",
"__overflow__",
"||=",
"self",
".",
"class",
".",
"bucket",
".",
"get",
"(",
"\"#{self.class.... | 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",
"::... | 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?\"",
... | 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 |
Subsets and Splits
SQL Console for semeru/code-text-ruby
Retrieves 20,000 non-null code samples labeled as Ruby, providing a basic overview of the dataset but without deeper analysis.