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 |
---|---|---|---|---|---|---|---|---|---|---|---|
threez/ruby-vmstat | lib/vmstat/procfs.rb | Vmstat.ProcFS.procfs_file | def procfs_file(*names, &block)
path = File.join(procfs_path, *names)
File.open(path, "r", &block)
end | ruby | def procfs_file(*names, &block)
path = File.join(procfs_path, *names)
File.open(path, "r", &block)
end | [
"def",
"procfs_file",
"(",
"*",
"names",
",",
"&",
"block",
")",
"path",
"=",
"File",
".",
"join",
"(",
"procfs_path",
",",
"*",
"names",
")",
"File",
".",
"open",
"(",
"path",
",",
"\"r\"",
",",
"&",
"block",
")",
"end"
]
| Opens a proc file system file handle and returns the handle in the
passed block. Closes the file handle.
@see File#open
@param [Array<String>] names parts of the path to the procfs file
@example
procfs_file("net", "dev") { |file| }
procfs_file("stat") { |file| }
@yieldparam [IO] file the file handle
@api private | [
"Opens",
"a",
"proc",
"file",
"system",
"file",
"handle",
"and",
"returns",
"the",
"handle",
"in",
"the",
"passed",
"block",
".",
"Closes",
"the",
"file",
"handle",
"."
]
| f762a6a5c6627182d6c1bb33f6605da2d3d4ef45 | https://github.com/threez/ruby-vmstat/blob/f762a6a5c6627182d6c1bb33f6605da2d3d4ef45/lib/vmstat/procfs.rb#L148-L151 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/search_atom.rb | ActsAsIndexed.SearchAtom.+ | def +(other)
SearchAtom.new(@records.clone.merge!(other.records) { |key, _old, _new|
_old + _new
})
end | ruby | def +(other)
SearchAtom.new(@records.clone.merge!(other.records) { |key, _old, _new|
_old + _new
})
end | [
"def",
"+",
"(",
"other",
")",
"SearchAtom",
".",
"new",
"(",
"@records",
".",
"clone",
".",
"merge!",
"(",
"other",
".",
"records",
")",
"{",
"|",
"key",
",",
"_old",
",",
"_new",
"|",
"_old",
"+",
"_new",
"}",
")",
"end"
]
| Creates a new SearchAtom with the combined records from self and other | [
"Creates",
"a",
"new",
"SearchAtom",
"with",
"the",
"combined",
"records",
"from",
"self",
"and",
"other"
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_atom.rb#L50-L54 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/search_atom.rb | ActsAsIndexed.SearchAtom.- | def -(other)
records = @records.clone.reject { |name, records| other.records.include?(name) }
SearchAtom.new(records)
end | ruby | def -(other)
records = @records.clone.reject { |name, records| other.records.include?(name) }
SearchAtom.new(records)
end | [
"def",
"-",
"(",
"other",
")",
"records",
"=",
"@records",
".",
"clone",
".",
"reject",
"{",
"|",
"name",
",",
"records",
"|",
"other",
".",
"records",
".",
"include?",
"(",
"name",
")",
"}",
"SearchAtom",
".",
"new",
"(",
"records",
")",
"end"
]
| Creates a new SearchAtom with records in other removed from self. | [
"Creates",
"a",
"new",
"SearchAtom",
"with",
"records",
"in",
"other",
"removed",
"from",
"self",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_atom.rb#L57-L60 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/search_atom.rb | ActsAsIndexed.SearchAtom.preceded_by | def preceded_by(former)
matches = SearchAtom.new
latter = ActiveSupport::OrderedHash.new
former.record_ids.each do |rid|
latter[rid] = @records[rid] if @records[rid]
end
# Iterate over each record in latter.
latter.each do |record_id,pos|
# Iterate over each position.
pos.each do |p|
# Check if previous position is in former.
if former.include_position?(record_id,p-1)
matches.add_record(record_id) unless matches.include_record?(record_id)
matches.add_position(record_id,p)
end
end
end
matches
end | ruby | def preceded_by(former)
matches = SearchAtom.new
latter = ActiveSupport::OrderedHash.new
former.record_ids.each do |rid|
latter[rid] = @records[rid] if @records[rid]
end
# Iterate over each record in latter.
latter.each do |record_id,pos|
# Iterate over each position.
pos.each do |p|
# Check if previous position is in former.
if former.include_position?(record_id,p-1)
matches.add_record(record_id) unless matches.include_record?(record_id)
matches.add_position(record_id,p)
end
end
end
matches
end | [
"def",
"preceded_by",
"(",
"former",
")",
"matches",
"=",
"SearchAtom",
".",
"new",
"latter",
"=",
"ActiveSupport",
"::",
"OrderedHash",
".",
"new",
"former",
".",
"record_ids",
".",
"each",
"do",
"|",
"rid",
"|",
"latter",
"[",
"rid",
"]",
"=",
"@records",
"[",
"rid",
"]",
"if",
"@records",
"[",
"rid",
"]",
"end",
"latter",
".",
"each",
"do",
"|",
"record_id",
",",
"pos",
"|",
"pos",
".",
"each",
"do",
"|",
"p",
"|",
"if",
"former",
".",
"include_position?",
"(",
"record_id",
",",
"p",
"-",
"1",
")",
"matches",
".",
"add_record",
"(",
"record_id",
")",
"unless",
"matches",
".",
"include_record?",
"(",
"record_id",
")",
"matches",
".",
"add_position",
"(",
"record_id",
",",
"p",
")",
"end",
"end",
"end",
"matches",
"end"
]
| Returns at atom containing the records and positions of +self+ preceded by +former+
"former latter" or "big dog" where "big" is the former and "dog" is the latter. | [
"Returns",
"at",
"atom",
"containing",
"the",
"records",
"and",
"positions",
"of",
"+",
"self",
"+",
"preceded",
"by",
"+",
"former",
"+",
"former",
"latter",
"or",
"big",
"dog",
"where",
"big",
"is",
"the",
"former",
"and",
"dog",
"is",
"the",
"latter",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_atom.rb#L64-L84 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/search_atom.rb | ActsAsIndexed.SearchAtom.weightings | def weightings(records_size)
out = ActiveSupport::OrderedHash.new
## phurni 2012-09-21 when records_size is exactly the @records.size (all records are matches), the Math.log would
## return 0 which means the frequency (pos.size) will have no effect. Cheat to make it like the matching
## record is one less, so that we still can weight on frequency.
matching_records_size = (records_size == @records.size ? @records.size - 1 : @records.size)
@records.each do |r_id, pos|
# Fixes a bug when the records_size is zero. i.e. The only record
# contaning the word has been deleted.
if records_size < 1
out[r_id] = 0.0
next
end
# weighting = frequency * log (records.size / records_with_atom)
## parndt 2010/05/03 changed to records_size.to_f to avoid -Infinity Errno::ERANGE exceptions
## which would happen for example Math.log(1 / 20) == -Infinity but Math.log(1.0 / 20) == -2.99573227355399
out[r_id] = pos.size * Math.log(records_size.to_f / matching_records_size)
end
out
end | ruby | def weightings(records_size)
out = ActiveSupport::OrderedHash.new
## phurni 2012-09-21 when records_size is exactly the @records.size (all records are matches), the Math.log would
## return 0 which means the frequency (pos.size) will have no effect. Cheat to make it like the matching
## record is one less, so that we still can weight on frequency.
matching_records_size = (records_size == @records.size ? @records.size - 1 : @records.size)
@records.each do |r_id, pos|
# Fixes a bug when the records_size is zero. i.e. The only record
# contaning the word has been deleted.
if records_size < 1
out[r_id] = 0.0
next
end
# weighting = frequency * log (records.size / records_with_atom)
## parndt 2010/05/03 changed to records_size.to_f to avoid -Infinity Errno::ERANGE exceptions
## which would happen for example Math.log(1 / 20) == -Infinity but Math.log(1.0 / 20) == -2.99573227355399
out[r_id] = pos.size * Math.log(records_size.to_f / matching_records_size)
end
out
end | [
"def",
"weightings",
"(",
"records_size",
")",
"out",
"=",
"ActiveSupport",
"::",
"OrderedHash",
".",
"new",
"matching_records_size",
"=",
"(",
"records_size",
"==",
"@records",
".",
"size",
"?",
"@records",
".",
"size",
"-",
"1",
":",
"@records",
".",
"size",
")",
"@records",
".",
"each",
"do",
"|",
"r_id",
",",
"pos",
"|",
"if",
"records_size",
"<",
"1",
"out",
"[",
"r_id",
"]",
"=",
"0.0",
"next",
"end",
"out",
"[",
"r_id",
"]",
"=",
"pos",
".",
"size",
"*",
"Math",
".",
"log",
"(",
"records_size",
".",
"to_f",
"/",
"matching_records_size",
")",
"end",
"out",
"end"
]
| Returns a hash of record_ids and weightings for each record in the
atom. | [
"Returns",
"a",
"hash",
"of",
"record_ids",
"and",
"weightings",
"for",
"each",
"record",
"in",
"the",
"atom",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_atom.rb#L88-L112 | train |
tsrivishnu/alexa-rails | lib/alexa/response.rb | Alexa.Response.elicit_slot! | def elicit_slot!(slot_to_elicit, skip_render: false)
directives << {
type: "Dialog.ElicitSlot",
slotToElicit: slot_to_elicit
}
if skip_render
@slots_to_not_render_elicitation << slot_to_elicit
end
end | ruby | def elicit_slot!(slot_to_elicit, skip_render: false)
directives << {
type: "Dialog.ElicitSlot",
slotToElicit: slot_to_elicit
}
if skip_render
@slots_to_not_render_elicitation << slot_to_elicit
end
end | [
"def",
"elicit_slot!",
"(",
"slot_to_elicit",
",",
"skip_render",
":",
"false",
")",
"directives",
"<<",
"{",
"type",
":",
"\"Dialog.ElicitSlot\"",
",",
"slotToElicit",
":",
"slot_to_elicit",
"}",
"if",
"skip_render",
"@slots_to_not_render_elicitation",
"<<",
"slot_to_elicit",
"end",
"end"
]
| Marks a slot for elicitation.
Options:
- skip_render: Lets you skip the rendering of the elicited slot's view.
Helpful when you have the elication text already in the
response and don't wanna override it. | [
"Marks",
"a",
"slot",
"for",
"elicitation",
"."
]
| bc9fda6610c8e563116bc53d64af7c41a13f1014 | https://github.com/tsrivishnu/alexa-rails/blob/bc9fda6610c8e563116bc53d64af7c41a13f1014/lib/alexa/response.rb#L23-L32 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/storage.rb | ActsAsIndexed.Storage.fetch | def fetch(atom_names, start=false)
atoms = ActiveSupport::OrderedHash.new
atom_names.uniq.collect{|a| encoded_prefix(a) }.uniq.each do |prefix|
pattern = @path.join(prefix.to_s).to_s
pattern += '*' if start
pattern += INDEX_FILE_EXTENSION
Pathname.glob(pattern).each do |atom_file|
atom_file.open do |f|
atoms.merge!(Marshal.load(f))
end
end # Pathname.glob
end # atom_names.uniq
atoms
end | ruby | def fetch(atom_names, start=false)
atoms = ActiveSupport::OrderedHash.new
atom_names.uniq.collect{|a| encoded_prefix(a) }.uniq.each do |prefix|
pattern = @path.join(prefix.to_s).to_s
pattern += '*' if start
pattern += INDEX_FILE_EXTENSION
Pathname.glob(pattern).each do |atom_file|
atom_file.open do |f|
atoms.merge!(Marshal.load(f))
end
end # Pathname.glob
end # atom_names.uniq
atoms
end | [
"def",
"fetch",
"(",
"atom_names",
",",
"start",
"=",
"false",
")",
"atoms",
"=",
"ActiveSupport",
"::",
"OrderedHash",
".",
"new",
"atom_names",
".",
"uniq",
".",
"collect",
"{",
"|",
"a",
"|",
"encoded_prefix",
"(",
"a",
")",
"}",
".",
"uniq",
".",
"each",
"do",
"|",
"prefix",
"|",
"pattern",
"=",
"@path",
".",
"join",
"(",
"prefix",
".",
"to_s",
")",
".",
"to_s",
"pattern",
"+=",
"'*'",
"if",
"start",
"pattern",
"+=",
"INDEX_FILE_EXTENSION",
"Pathname",
".",
"glob",
"(",
"pattern",
")",
".",
"each",
"do",
"|",
"atom_file",
"|",
"atom_file",
".",
"open",
"do",
"|",
"f",
"|",
"atoms",
".",
"merge!",
"(",
"Marshal",
".",
"load",
"(",
"f",
")",
")",
"end",
"end",
"end",
"atoms",
"end"
]
| Takes a string array of atoms names
return a hash of the relevant atoms. | [
"Takes",
"a",
"string",
"array",
"of",
"atoms",
"names",
"return",
"a",
"hash",
"of",
"the",
"relevant",
"atoms",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/storage.rb#L35-L51 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/storage.rb | ActsAsIndexed.Storage.operate | def operate(operation, atoms)
# ActiveSupport always available?
atoms_sorted = ActiveSupport::OrderedHash.new
# Sort the atoms into the appropriate shards for writing to individual
# files.
atoms.each do |atom_name, records|
(atoms_sorted[encoded_prefix(atom_name)] ||= ActiveSupport::OrderedHash.new)[atom_name] = records
end
atoms_sorted.each do |e_p, atoms|
path = @path.join(e_p.to_s + INDEX_FILE_EXTENSION)
lock_file(path) do
if path.exist?
from_file = path.open do |f|
Marshal.load(f)
end
else
from_file = ActiveSupport::OrderedHash.new
end
atoms = from_file.merge(atoms){ |k,o,n| o.send(operation, n) }
write_file(path) do |f|
Marshal.dump(atoms,f)
end
end # end lock.
end
end | ruby | def operate(operation, atoms)
# ActiveSupport always available?
atoms_sorted = ActiveSupport::OrderedHash.new
# Sort the atoms into the appropriate shards for writing to individual
# files.
atoms.each do |atom_name, records|
(atoms_sorted[encoded_prefix(atom_name)] ||= ActiveSupport::OrderedHash.new)[atom_name] = records
end
atoms_sorted.each do |e_p, atoms|
path = @path.join(e_p.to_s + INDEX_FILE_EXTENSION)
lock_file(path) do
if path.exist?
from_file = path.open do |f|
Marshal.load(f)
end
else
from_file = ActiveSupport::OrderedHash.new
end
atoms = from_file.merge(atoms){ |k,o,n| o.send(operation, n) }
write_file(path) do |f|
Marshal.dump(atoms,f)
end
end # end lock.
end
end | [
"def",
"operate",
"(",
"operation",
",",
"atoms",
")",
"atoms_sorted",
"=",
"ActiveSupport",
"::",
"OrderedHash",
".",
"new",
"atoms",
".",
"each",
"do",
"|",
"atom_name",
",",
"records",
"|",
"(",
"atoms_sorted",
"[",
"encoded_prefix",
"(",
"atom_name",
")",
"]",
"||=",
"ActiveSupport",
"::",
"OrderedHash",
".",
"new",
")",
"[",
"atom_name",
"]",
"=",
"records",
"end",
"atoms_sorted",
".",
"each",
"do",
"|",
"e_p",
",",
"atoms",
"|",
"path",
"=",
"@path",
".",
"join",
"(",
"e_p",
".",
"to_s",
"+",
"INDEX_FILE_EXTENSION",
")",
"lock_file",
"(",
"path",
")",
"do",
"if",
"path",
".",
"exist?",
"from_file",
"=",
"path",
".",
"open",
"do",
"|",
"f",
"|",
"Marshal",
".",
"load",
"(",
"f",
")",
"end",
"else",
"from_file",
"=",
"ActiveSupport",
"::",
"OrderedHash",
".",
"new",
"end",
"atoms",
"=",
"from_file",
".",
"merge",
"(",
"atoms",
")",
"{",
"|",
"k",
",",
"o",
",",
"n",
"|",
"o",
".",
"send",
"(",
"operation",
",",
"n",
")",
"}",
"write_file",
"(",
"path",
")",
"do",
"|",
"f",
"|",
"Marshal",
".",
"dump",
"(",
"atoms",
",",
"f",
")",
"end",
"end",
"end",
"end"
]
| Takes atoms and adds or removes them from the index depending on the
passed operation. | [
"Takes",
"atoms",
"and",
"adds",
"or",
"removes",
"them",
"from",
"the",
"index",
"depending",
"on",
"the",
"passed",
"operation",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/storage.rb#L68-L99 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/storage.rb | ActsAsIndexed.Storage.lock_file | def lock_file(file_path, &block) # :nodoc:
@@file_lock.synchronize do
# Windows does not support file locking.
if !windows? && file_path.exist?
file_path.open('r+') do |f|
begin
f.flock File::LOCK_EX
yield
ensure
f.flock File::LOCK_UN
end
end
else
yield
end
end
end | ruby | def lock_file(file_path, &block) # :nodoc:
@@file_lock.synchronize do
# Windows does not support file locking.
if !windows? && file_path.exist?
file_path.open('r+') do |f|
begin
f.flock File::LOCK_EX
yield
ensure
f.flock File::LOCK_UN
end
end
else
yield
end
end
end | [
"def",
"lock_file",
"(",
"file_path",
",",
"&",
"block",
")",
"@@file_lock",
".",
"synchronize",
"do",
"if",
"!",
"windows?",
"&&",
"file_path",
".",
"exist?",
"file_path",
".",
"open",
"(",
"'r+'",
")",
"do",
"|",
"f",
"|",
"begin",
"f",
".",
"flock",
"File",
"::",
"LOCK_EX",
"yield",
"ensure",
"f",
".",
"flock",
"File",
"::",
"LOCK_UN",
"end",
"end",
"else",
"yield",
"end",
"end",
"end"
]
| Borrowed from Rails' ActiveSupport FileStore. Also under MIT licence.
Lock a file for a block so only one process or thread can modify it at a time. | [
"Borrowed",
"from",
"Rails",
"ActiveSupport",
"FileStore",
".",
"Also",
"under",
"MIT",
"licence",
".",
"Lock",
"a",
"file",
"for",
"a",
"block",
"so",
"only",
"one",
"process",
"or",
"thread",
"can",
"modify",
"it",
"at",
"a",
"time",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/storage.rb#L174-L192 | train |
tsrivishnu/alexa-rails | lib/alexa/device.rb | Alexa.Device.location | def location
@_location ||= begin
if Alexa.configuration.location_permission_type == :full_address
get_address
elsif Alexa.configuration.location_permission_type == :country_and_postal_code
get_address(only: :country_and_postal_code)
end
end
end | ruby | def location
@_location ||= begin
if Alexa.configuration.location_permission_type == :full_address
get_address
elsif Alexa.configuration.location_permission_type == :country_and_postal_code
get_address(only: :country_and_postal_code)
end
end
end | [
"def",
"location",
"@_location",
"||=",
"begin",
"if",
"Alexa",
".",
"configuration",
".",
"location_permission_type",
"==",
":full_address",
"get_address",
"elsif",
"Alexa",
".",
"configuration",
".",
"location_permission_type",
"==",
":country_and_postal_code",
"get_address",
"(",
"only",
":",
":country_and_postal_code",
")",
"end",
"end",
"end"
]
| Return device location from amazon.
Makes an API to amazon alexa's device location service and returns the
location hash | [
"Return",
"device",
"location",
"from",
"amazon",
".",
"Makes",
"an",
"API",
"to",
"amazon",
"alexa",
"s",
"device",
"location",
"service",
"and",
"returns",
"the",
"location",
"hash"
]
| bc9fda6610c8e563116bc53d64af7c41a13f1014 | https://github.com/tsrivishnu/alexa-rails/blob/bc9fda6610c8e563116bc53d64af7c41a13f1014/lib/alexa/device.rb#L30-L38 | train |
odlp/simplify_rb | lib/simplify_rb/douglas_peucker_simplifier.rb | SimplifyRb.DouglasPeuckerSimplifier.get_sq_seg_dist | def get_sq_seg_dist(point, point_1, point_2)
x = point_1.x
y = point_1.y
dx = point_2.x - x
dy = point_2.y - y
if dx != 0 || dy != 0
t = ((point.x - x) * dx + (point.y - y) * dy) / (dx * dx + dy * dy)
if t > 1
x = point_2.x
y = point_2.y
elsif t > 0
x += dx * t
y += dy * t
end
end
dx = point.x - x
dy = point.y - y
dx * dx + dy * dy
end | ruby | def get_sq_seg_dist(point, point_1, point_2)
x = point_1.x
y = point_1.y
dx = point_2.x - x
dy = point_2.y - y
if dx != 0 || dy != 0
t = ((point.x - x) * dx + (point.y - y) * dy) / (dx * dx + dy * dy)
if t > 1
x = point_2.x
y = point_2.y
elsif t > 0
x += dx * t
y += dy * t
end
end
dx = point.x - x
dy = point.y - y
dx * dx + dy * dy
end | [
"def",
"get_sq_seg_dist",
"(",
"point",
",",
"point_1",
",",
"point_2",
")",
"x",
"=",
"point_1",
".",
"x",
"y",
"=",
"point_1",
".",
"y",
"dx",
"=",
"point_2",
".",
"x",
"-",
"x",
"dy",
"=",
"point_2",
".",
"y",
"-",
"y",
"if",
"dx",
"!=",
"0",
"||",
"dy",
"!=",
"0",
"t",
"=",
"(",
"(",
"point",
".",
"x",
"-",
"x",
")",
"*",
"dx",
"+",
"(",
"point",
".",
"y",
"-",
"y",
")",
"*",
"dy",
")",
"/",
"(",
"dx",
"*",
"dx",
"+",
"dy",
"*",
"dy",
")",
"if",
"t",
">",
"1",
"x",
"=",
"point_2",
".",
"x",
"y",
"=",
"point_2",
".",
"y",
"elsif",
"t",
">",
"0",
"x",
"+=",
"dx",
"*",
"t",
"y",
"+=",
"dy",
"*",
"t",
"end",
"end",
"dx",
"=",
"point",
".",
"x",
"-",
"x",
"dy",
"=",
"point",
".",
"y",
"-",
"y",
"dx",
"*",
"dx",
"+",
"dy",
"*",
"dy",
"end"
]
| Square distance from a point to a segment | [
"Square",
"distance",
"from",
"a",
"point",
"to",
"a",
"segment"
]
| e5a68f049051a64184ada02e47df751cbda1e14b | https://github.com/odlp/simplify_rb/blob/e5a68f049051a64184ada02e47df751cbda1e14b/lib/simplify_rb/douglas_peucker_simplifier.rb#L57-L80 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/class_methods.rb | ActsAsIndexed.ClassMethods.acts_as_indexed | def acts_as_indexed(options = {})
class_eval do
extend ActsAsIndexed::SingletonMethods
end
include ActsAsIndexed::InstanceMethods
after_create :add_to_index
before_update :update_index
after_destroy :remove_from_index
# scope for Rails 3.x, named_scope for Rails 2.x.
if self.respond_to?(:where)
scope :with_query, lambda { |query| where("#{table_name}.#{primary_key} IN (?)", search_index(query, {}, {:ids_only => true})) }
else
named_scope :with_query, lambda { |query| { :conditions => ["#{table_name}.#{primary_key} IN (?)", search_index(query, {}, {:ids_only => true}) ] } }
end
cattr_accessor :aai_config, :aai_fields
self.aai_fields = options.delete(:fields)
raise(ArgumentError, 'no fields specified') if self.aai_fields.nil? || self.aai_fields.empty?
self.aai_config = ActsAsIndexed.configuration.dup
self.aai_config.if_proc = options.delete(:if)
options.each do |k, v|
self.aai_config.send("#{k}=", v)
end
# Add the Rails environment and this model's name to the index file path.
self.aai_config.index_file = self.aai_config.index_file.join(Rails.env, self.name.underscore)
end | ruby | def acts_as_indexed(options = {})
class_eval do
extend ActsAsIndexed::SingletonMethods
end
include ActsAsIndexed::InstanceMethods
after_create :add_to_index
before_update :update_index
after_destroy :remove_from_index
# scope for Rails 3.x, named_scope for Rails 2.x.
if self.respond_to?(:where)
scope :with_query, lambda { |query| where("#{table_name}.#{primary_key} IN (?)", search_index(query, {}, {:ids_only => true})) }
else
named_scope :with_query, lambda { |query| { :conditions => ["#{table_name}.#{primary_key} IN (?)", search_index(query, {}, {:ids_only => true}) ] } }
end
cattr_accessor :aai_config, :aai_fields
self.aai_fields = options.delete(:fields)
raise(ArgumentError, 'no fields specified') if self.aai_fields.nil? || self.aai_fields.empty?
self.aai_config = ActsAsIndexed.configuration.dup
self.aai_config.if_proc = options.delete(:if)
options.each do |k, v|
self.aai_config.send("#{k}=", v)
end
# Add the Rails environment and this model's name to the index file path.
self.aai_config.index_file = self.aai_config.index_file.join(Rails.env, self.name.underscore)
end | [
"def",
"acts_as_indexed",
"(",
"options",
"=",
"{",
"}",
")",
"class_eval",
"do",
"extend",
"ActsAsIndexed",
"::",
"SingletonMethods",
"end",
"include",
"ActsAsIndexed",
"::",
"InstanceMethods",
"after_create",
":add_to_index",
"before_update",
":update_index",
"after_destroy",
":remove_from_index",
"if",
"self",
".",
"respond_to?",
"(",
":where",
")",
"scope",
":with_query",
",",
"lambda",
"{",
"|",
"query",
"|",
"where",
"(",
"\"#{table_name}.#{primary_key} IN (?)\"",
",",
"search_index",
"(",
"query",
",",
"{",
"}",
",",
"{",
":ids_only",
"=>",
"true",
"}",
")",
")",
"}",
"else",
"named_scope",
":with_query",
",",
"lambda",
"{",
"|",
"query",
"|",
"{",
":conditions",
"=>",
"[",
"\"#{table_name}.#{primary_key} IN (?)\"",
",",
"search_index",
"(",
"query",
",",
"{",
"}",
",",
"{",
":ids_only",
"=>",
"true",
"}",
")",
"]",
"}",
"}",
"end",
"cattr_accessor",
":aai_config",
",",
":aai_fields",
"self",
".",
"aai_fields",
"=",
"options",
".",
"delete",
"(",
":fields",
")",
"raise",
"(",
"ArgumentError",
",",
"'no fields specified'",
")",
"if",
"self",
".",
"aai_fields",
".",
"nil?",
"||",
"self",
".",
"aai_fields",
".",
"empty?",
"self",
".",
"aai_config",
"=",
"ActsAsIndexed",
".",
"configuration",
".",
"dup",
"self",
".",
"aai_config",
".",
"if_proc",
"=",
"options",
".",
"delete",
"(",
":if",
")",
"options",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"self",
".",
"aai_config",
".",
"send",
"(",
"\"#{k}=\"",
",",
"v",
")",
"end",
"self",
".",
"aai_config",
".",
"index_file",
"=",
"self",
".",
"aai_config",
".",
"index_file",
".",
"join",
"(",
"Rails",
".",
"env",
",",
"self",
".",
"name",
".",
"underscore",
")",
"end"
]
| Declares a class as searchable.
====options:
fields:: Names of fields to include in the index. Symbols pointing to
instance methods of your model may also be given here.
index_file_depth:: Tuning value for the index partitioning. Larger
values result in quicker searches, but slower
indexing. Default is 3.
min_word_size:: Sets the minimum length for a word in a query. Words
shorter than this value are ignored in searches
unless preceded by the '+' operator. Default is 3.
index_file:: Sets the location for the index. By default this is
RAILS_ROOT/tmp/index. Specify as an array. The default, for
example, would be set as [Rails.root,'tmp','index]. | [
"Declares",
"a",
"class",
"as",
"searchable",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/class_methods.rb#L20-L50 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/class_methods.rb | ActsAsIndexed.ClassMethods.index_add | def index_add(record)
return if self.aai_config.disable_auto_indexing
build_index
index = new_index
index.add_record(record)
@query_cache = {}
end | ruby | def index_add(record)
return if self.aai_config.disable_auto_indexing
build_index
index = new_index
index.add_record(record)
@query_cache = {}
end | [
"def",
"index_add",
"(",
"record",
")",
"return",
"if",
"self",
".",
"aai_config",
".",
"disable_auto_indexing",
"build_index",
"index",
"=",
"new_index",
"index",
".",
"add_record",
"(",
"record",
")",
"@query_cache",
"=",
"{",
"}",
"end"
]
| Adds the passed +record+ to the index. Index is built if it does not already exist. Clears the query cache. | [
"Adds",
"the",
"passed",
"+",
"record",
"+",
"to",
"the",
"index",
".",
"Index",
"is",
"built",
"if",
"it",
"does",
"not",
"already",
"exist",
".",
"Clears",
"the",
"query",
"cache",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/class_methods.rb#L54-L61 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/class_methods.rb | ActsAsIndexed.ClassMethods.index_update | def index_update(record)
return if self.aai_config.disable_auto_indexing
build_index
index = new_index
index.update_record(record,find(record.id))
@query_cache = {}
end | ruby | def index_update(record)
return if self.aai_config.disable_auto_indexing
build_index
index = new_index
index.update_record(record,find(record.id))
@query_cache = {}
end | [
"def",
"index_update",
"(",
"record",
")",
"return",
"if",
"self",
".",
"aai_config",
".",
"disable_auto_indexing",
"build_index",
"index",
"=",
"new_index",
"index",
".",
"update_record",
"(",
"record",
",",
"find",
"(",
"record",
".",
"id",
")",
")",
"@query_cache",
"=",
"{",
"}",
"end"
]
| Updates the index.
1. Removes the previous version of the record from the index
2. Adds the new version to the index. | [
"Updates",
"the",
"index",
".",
"1",
".",
"Removes",
"the",
"previous",
"version",
"of",
"the",
"record",
"from",
"the",
"index",
"2",
".",
"Adds",
"the",
"new",
"version",
"to",
"the",
"index",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/class_methods.rb#L77-L84 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/class_methods.rb | ActsAsIndexed.ClassMethods.search_index | def search_index(query, find_options={}, options={})
# Clear the query cache off if the key is set.
@query_cache = {} if options[:no_query_cache]
# Run the query if not already in cache.
if !@query_cache || !@query_cache[query]
build_index
(@query_cache ||= {})[query] = new_index.search(query)
end
if options[:ids_only]
find_option_keys = find_options.keys.map{ |k| k.to_sym }
find_option_keys -= [:limit, :offset]
if find_option_keys.any?
raise ArgumentError, 'ids_only can not be combined with find option keys other than :offset or :limit'
end
end
if find_options.include?(:order)
part_query = @query_cache[query].map{ |r| r.first }
else
# slice up the results by offset and limit
offset = find_options[:offset] || 0
limit = find_options.include?(:limit) ? find_options[:limit] : @query_cache[query].size
part_query = sort(@query_cache[query]).slice(offset,limit).map{ |r| r.first }
# Set these to nil as we are dealing with the pagination by setting
# exactly what records we want.
find_options[:offset] = nil
find_options[:limit] = nil
end
return part_query if options[:ids_only]
with_scope :find => find_options do
# Doing the find like this eliminates the possibility of errors occuring
# on either missing records (out-of-sync) or an empty results array.
records = find(:all, :conditions => [ "#{table_name}.#{primary_key} IN (?)", part_query])
if find_options.include?(:order)
records # Just return the records without ranking them.
else
# Results come back in random order from SQL, so order again.
ranked_records = ActiveSupport::OrderedHash.new
records.each do |r|
ranked_records[r] = @query_cache[query][r.id]
end
sort(ranked_records.to_a).map{ |r| r.first }
end
end
end | ruby | def search_index(query, find_options={}, options={})
# Clear the query cache off if the key is set.
@query_cache = {} if options[:no_query_cache]
# Run the query if not already in cache.
if !@query_cache || !@query_cache[query]
build_index
(@query_cache ||= {})[query] = new_index.search(query)
end
if options[:ids_only]
find_option_keys = find_options.keys.map{ |k| k.to_sym }
find_option_keys -= [:limit, :offset]
if find_option_keys.any?
raise ArgumentError, 'ids_only can not be combined with find option keys other than :offset or :limit'
end
end
if find_options.include?(:order)
part_query = @query_cache[query].map{ |r| r.first }
else
# slice up the results by offset and limit
offset = find_options[:offset] || 0
limit = find_options.include?(:limit) ? find_options[:limit] : @query_cache[query].size
part_query = sort(@query_cache[query]).slice(offset,limit).map{ |r| r.first }
# Set these to nil as we are dealing with the pagination by setting
# exactly what records we want.
find_options[:offset] = nil
find_options[:limit] = nil
end
return part_query if options[:ids_only]
with_scope :find => find_options do
# Doing the find like this eliminates the possibility of errors occuring
# on either missing records (out-of-sync) or an empty results array.
records = find(:all, :conditions => [ "#{table_name}.#{primary_key} IN (?)", part_query])
if find_options.include?(:order)
records # Just return the records without ranking them.
else
# Results come back in random order from SQL, so order again.
ranked_records = ActiveSupport::OrderedHash.new
records.each do |r|
ranked_records[r] = @query_cache[query][r.id]
end
sort(ranked_records.to_a).map{ |r| r.first }
end
end
end | [
"def",
"search_index",
"(",
"query",
",",
"find_options",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
")",
"@query_cache",
"=",
"{",
"}",
"if",
"options",
"[",
":no_query_cache",
"]",
"if",
"!",
"@query_cache",
"||",
"!",
"@query_cache",
"[",
"query",
"]",
"build_index",
"(",
"@query_cache",
"||=",
"{",
"}",
")",
"[",
"query",
"]",
"=",
"new_index",
".",
"search",
"(",
"query",
")",
"end",
"if",
"options",
"[",
":ids_only",
"]",
"find_option_keys",
"=",
"find_options",
".",
"keys",
".",
"map",
"{",
"|",
"k",
"|",
"k",
".",
"to_sym",
"}",
"find_option_keys",
"-=",
"[",
":limit",
",",
":offset",
"]",
"if",
"find_option_keys",
".",
"any?",
"raise",
"ArgumentError",
",",
"'ids_only can not be combined with find option keys other than :offset or :limit'",
"end",
"end",
"if",
"find_options",
".",
"include?",
"(",
":order",
")",
"part_query",
"=",
"@query_cache",
"[",
"query",
"]",
".",
"map",
"{",
"|",
"r",
"|",
"r",
".",
"first",
"}",
"else",
"offset",
"=",
"find_options",
"[",
":offset",
"]",
"||",
"0",
"limit",
"=",
"find_options",
".",
"include?",
"(",
":limit",
")",
"?",
"find_options",
"[",
":limit",
"]",
":",
"@query_cache",
"[",
"query",
"]",
".",
"size",
"part_query",
"=",
"sort",
"(",
"@query_cache",
"[",
"query",
"]",
")",
".",
"slice",
"(",
"offset",
",",
"limit",
")",
".",
"map",
"{",
"|",
"r",
"|",
"r",
".",
"first",
"}",
"find_options",
"[",
":offset",
"]",
"=",
"nil",
"find_options",
"[",
":limit",
"]",
"=",
"nil",
"end",
"return",
"part_query",
"if",
"options",
"[",
":ids_only",
"]",
"with_scope",
":find",
"=>",
"find_options",
"do",
"records",
"=",
"find",
"(",
":all",
",",
":conditions",
"=>",
"[",
"\"#{table_name}.#{primary_key} IN (?)\"",
",",
"part_query",
"]",
")",
"if",
"find_options",
".",
"include?",
"(",
":order",
")",
"records",
"else",
"ranked_records",
"=",
"ActiveSupport",
"::",
"OrderedHash",
".",
"new",
"records",
".",
"each",
"do",
"|",
"r",
"|",
"ranked_records",
"[",
"r",
"]",
"=",
"@query_cache",
"[",
"query",
"]",
"[",
"r",
".",
"id",
"]",
"end",
"sort",
"(",
"ranked_records",
".",
"to_a",
")",
".",
"map",
"{",
"|",
"r",
"|",
"r",
".",
"first",
"}",
"end",
"end",
"end"
]
| Finds instances matching the terms passed in +query+. Terms are ANDed by
default. Returns an array of model instances or, if +ids_only+ is
true, an array of integer IDs.
Keeps a cache of matched IDs for the current session to speed up
multiple identical searches.
====find_options
Same as ActiveRecord#find options hash. An :order key will override
the relevance ranking
====options
ids_only:: Method returns an array of integer IDs when set to true.
no_query_cache:: Turns off the query cache when set to true. Useful for testing. | [
"Finds",
"instances",
"matching",
"the",
"terms",
"passed",
"in",
"+",
"query",
"+",
".",
"Terms",
"are",
"ANDed",
"by",
"default",
".",
"Returns",
"an",
"array",
"of",
"model",
"instances",
"or",
"if",
"+",
"ids_only",
"+",
"is",
"true",
"an",
"array",
"of",
"integer",
"IDs",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/class_methods.rb#L101-L156 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/class_methods.rb | ActsAsIndexed.ClassMethods.build_index | def build_index
return if aai_config.index_file.directory?
index = new_index
find_in_batches({ :batch_size => 500 }) do |records|
index.add_records(records)
end
end | ruby | def build_index
return if aai_config.index_file.directory?
index = new_index
find_in_batches({ :batch_size => 500 }) do |records|
index.add_records(records)
end
end | [
"def",
"build_index",
"return",
"if",
"aai_config",
".",
"index_file",
".",
"directory?",
"index",
"=",
"new_index",
"find_in_batches",
"(",
"{",
":batch_size",
"=>",
"500",
"}",
")",
"do",
"|",
"records",
"|",
"index",
".",
"add_records",
"(",
"records",
")",
"end",
"end"
]
| Builds an index from scratch for the current model class.
Does not run if the index already exists. | [
"Builds",
"an",
"index",
"from",
"scratch",
"for",
"the",
"current",
"model",
"class",
".",
"Does",
"not",
"run",
"if",
"the",
"index",
"already",
"exists",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/class_methods.rb#L161-L168 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/class_methods.rb | ActsAsIndexed.ClassMethods.sort | def sort(ranked_records)
ranked_records.sort { |a, b|
a_score = a.last
a_id = a.first.is_a?(Fixnum) ? a.first : a.first.id
b_score = b.last
b_id = b.first.is_a?(Fixnum) ? b.first : b.first.id
if a_score == b_score
a_id <=> b_id
else
b_score <=> a_score # We want the records with better relevance first.
end
}
end | ruby | def sort(ranked_records)
ranked_records.sort { |a, b|
a_score = a.last
a_id = a.first.is_a?(Fixnum) ? a.first : a.first.id
b_score = b.last
b_id = b.first.is_a?(Fixnum) ? b.first : b.first.id
if a_score == b_score
a_id <=> b_id
else
b_score <=> a_score # We want the records with better relevance first.
end
}
end | [
"def",
"sort",
"(",
"ranked_records",
")",
"ranked_records",
".",
"sort",
"{",
"|",
"a",
",",
"b",
"|",
"a_score",
"=",
"a",
".",
"last",
"a_id",
"=",
"a",
".",
"first",
".",
"is_a?",
"(",
"Fixnum",
")",
"?",
"a",
".",
"first",
":",
"a",
".",
"first",
".",
"id",
"b_score",
"=",
"b",
".",
"last",
"b_id",
"=",
"b",
".",
"first",
".",
"is_a?",
"(",
"Fixnum",
")",
"?",
"b",
".",
"first",
":",
"b",
".",
"first",
".",
"id",
"if",
"a_score",
"==",
"b_score",
"a_id",
"<=>",
"b_id",
"else",
"b_score",
"<=>",
"a_score",
"end",
"}",
"end"
]
| If two records or record IDs have the same rank, sort them by ID.
This prevents a different order being returned by different Rubies. | [
"If",
"two",
"records",
"or",
"record",
"IDs",
"have",
"the",
"same",
"rank",
"sort",
"them",
"by",
"ID",
".",
"This",
"prevents",
"a",
"different",
"order",
"being",
"returned",
"by",
"different",
"Rubies",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/class_methods.rb#L174-L189 | train |
le0pard/mongodb_logger | lib/mongodb_logger.rb | MongodbLogger.Base.mongo_fix_session_keys | def mongo_fix_session_keys(session = {})
new_session = Hash.new
session.to_hash.each do |i, j|
new_session[i.gsub(/\./i, "|")] = j.inspect
end unless session.empty?
new_session
end | ruby | def mongo_fix_session_keys(session = {})
new_session = Hash.new
session.to_hash.each do |i, j|
new_session[i.gsub(/\./i, "|")] = j.inspect
end unless session.empty?
new_session
end | [
"def",
"mongo_fix_session_keys",
"(",
"session",
"=",
"{",
"}",
")",
"new_session",
"=",
"Hash",
".",
"new",
"session",
".",
"to_hash",
".",
"each",
"do",
"|",
"i",
",",
"j",
"|",
"new_session",
"[",
"i",
".",
"gsub",
"(",
"/",
"\\.",
"/i",
",",
"\"|\"",
")",
"]",
"=",
"j",
".",
"inspect",
"end",
"unless",
"session",
".",
"empty?",
"new_session",
"end"
]
| session keys can be with dots. It is invalid keys for BSON | [
"session",
"keys",
"can",
"be",
"with",
"dots",
".",
"It",
"is",
"invalid",
"keys",
"for",
"BSON"
]
| 102ee484f8c93ae52a46b4605a8b9bdfd538bb66 | https://github.com/le0pard/mongodb_logger/blob/102ee484f8c93ae52a46b4605a8b9bdfd538bb66/lib/mongodb_logger.rb#L40-L46 | train |
andreapavoni/panoramic | lib/panoramic/resolver.rb | Panoramic.Resolver.find_templates | def find_templates(name, prefix, partial, details, key=nil, locals=[])
return [] if @@resolver_options[:only] && !@@resolver_options[:only].include?(prefix)
path = build_path(name, prefix)
conditions = {
:path => path,
:locale => [normalize_array(details[:locale]).first, nil],
:format => normalize_array(details[:formats]),
:handler => normalize_array(details[:handlers]),
:partial => partial || false
}.merge(details[:additional_criteria].presence || {})
@@model.find_model_templates(conditions).map do |record|
Rails.logger.debug "Rendering template from database: #{path} (#{record.format})"
initialize_template(record)
end
end | ruby | def find_templates(name, prefix, partial, details, key=nil, locals=[])
return [] if @@resolver_options[:only] && !@@resolver_options[:only].include?(prefix)
path = build_path(name, prefix)
conditions = {
:path => path,
:locale => [normalize_array(details[:locale]).first, nil],
:format => normalize_array(details[:formats]),
:handler => normalize_array(details[:handlers]),
:partial => partial || false
}.merge(details[:additional_criteria].presence || {})
@@model.find_model_templates(conditions).map do |record|
Rails.logger.debug "Rendering template from database: #{path} (#{record.format})"
initialize_template(record)
end
end | [
"def",
"find_templates",
"(",
"name",
",",
"prefix",
",",
"partial",
",",
"details",
",",
"key",
"=",
"nil",
",",
"locals",
"=",
"[",
"]",
")",
"return",
"[",
"]",
"if",
"@@resolver_options",
"[",
":only",
"]",
"&&",
"!",
"@@resolver_options",
"[",
":only",
"]",
".",
"include?",
"(",
"prefix",
")",
"path",
"=",
"build_path",
"(",
"name",
",",
"prefix",
")",
"conditions",
"=",
"{",
":path",
"=>",
"path",
",",
":locale",
"=>",
"[",
"normalize_array",
"(",
"details",
"[",
":locale",
"]",
")",
".",
"first",
",",
"nil",
"]",
",",
":format",
"=>",
"normalize_array",
"(",
"details",
"[",
":formats",
"]",
")",
",",
":handler",
"=>",
"normalize_array",
"(",
"details",
"[",
":handlers",
"]",
")",
",",
":partial",
"=>",
"partial",
"||",
"false",
"}",
".",
"merge",
"(",
"details",
"[",
":additional_criteria",
"]",
".",
"presence",
"||",
"{",
"}",
")",
"@@model",
".",
"find_model_templates",
"(",
"conditions",
")",
".",
"map",
"do",
"|",
"record",
"|",
"Rails",
".",
"logger",
".",
"debug",
"\"Rendering template from database: #{path} (#{record.format})\"",
"initialize_template",
"(",
"record",
")",
"end",
"end"
]
| this method is mandatory to implement a Resolver | [
"this",
"method",
"is",
"mandatory",
"to",
"implement",
"a",
"Resolver"
]
| 47b3e222b8611914863aa576694e6ee4b619c7f4 | https://github.com/andreapavoni/panoramic/blob/47b3e222b8611914863aa576694e6ee4b619c7f4/lib/panoramic/resolver.rb#L7-L23 | train |
andreapavoni/panoramic | lib/panoramic/resolver.rb | Panoramic.Resolver.virtual_path | def virtual_path(path, partial)
return path unless partial
if index = path.rindex("/")
path.insert(index + 1, "_")
else
"_#{path}"
end
end | ruby | def virtual_path(path, partial)
return path unless partial
if index = path.rindex("/")
path.insert(index + 1, "_")
else
"_#{path}"
end
end | [
"def",
"virtual_path",
"(",
"path",
",",
"partial",
")",
"return",
"path",
"unless",
"partial",
"if",
"index",
"=",
"path",
".",
"rindex",
"(",
"\"/\"",
")",
"path",
".",
"insert",
"(",
"index",
"+",
"1",
",",
"\"_\"",
")",
"else",
"\"_#{path}\"",
"end",
"end"
]
| returns a path depending if its a partial or template | [
"returns",
"a",
"path",
"depending",
"if",
"its",
"a",
"partial",
"or",
"template"
]
| 47b3e222b8611914863aa576694e6ee4b619c7f4 | https://github.com/andreapavoni/panoramic/blob/47b3e222b8611914863aa576694e6ee4b619c7f4/lib/panoramic/resolver.rb#L60-L67 | train |
rikas/slack-poster | lib/slack/poster.rb | Slack.Poster.send_message | def send_message(message)
body = message.is_a?(String) ? options.merge(text: message) : options.merge(message.as_json)
conn = Faraday.new(url: @base_uri)
response = conn.post('', payload: body.to_json)
response
end | ruby | def send_message(message)
body = message.is_a?(String) ? options.merge(text: message) : options.merge(message.as_json)
conn = Faraday.new(url: @base_uri)
response = conn.post('', payload: body.to_json)
response
end | [
"def",
"send_message",
"(",
"message",
")",
"body",
"=",
"message",
".",
"is_a?",
"(",
"String",
")",
"?",
"options",
".",
"merge",
"(",
"text",
":",
"message",
")",
":",
"options",
".",
"merge",
"(",
"message",
".",
"as_json",
")",
"conn",
"=",
"Faraday",
".",
"new",
"(",
"url",
":",
"@base_uri",
")",
"response",
"=",
"conn",
".",
"post",
"(",
"''",
",",
"payload",
":",
"body",
".",
"to_json",
")",
"response",
"end"
]
| Initializes a Poster instance to post messages with an incoming webhook URL.
It also accepts an options hash. If no options are given then the poster uses the default
configuration from Slack integration.
==== Examples
# Without options
Slack::Poster.new('https://hooks.slack.com/services/T044G6VBA//TCIzZQQd7IKhQzCKc6W310va')
# With options using a custom username and icon avatar
Slack::Poster.new('https://hooks.slack.com/services/T044G6VBA//TCIzZQQd7IKhQzCKc6W310va',
username: 'Ricardo',
icon_url: 'http://www.gravatar.com/avatar/92e00fd27c64c94d04140cef88039468.png')
# You can also use an emoji as avatar
Slack::Poster.new('https://hooks.slack.com/services/T044G6VBA//TCIzZQQd7IKhQzCKc6W310va',
username: 'Ricardo',
icon_emoji: 'ghost')
Sends a message to Slack. The message can be either plain text or a Slack::Message object.
==== Examples
# Plain text message
poster.send_message('hello world')
# Using a message object
poster.send_message(Slack::Message.new(text: 'hello world'))
You can have messages with attachments if you build your message with a Slack::Message object
and add Slack::Attachment objects. | [
"Initializes",
"a",
"Poster",
"instance",
"to",
"post",
"messages",
"with",
"an",
"incoming",
"webhook",
"URL",
".",
"It",
"also",
"accepts",
"an",
"options",
"hash",
".",
"If",
"no",
"options",
"are",
"given",
"then",
"the",
"poster",
"uses",
"the",
"default",
"configuration",
"from",
"Slack",
"integration",
"."
]
| b38d539f3162c286b33b1c3c3f3fbed5bde15654 | https://github.com/rikas/slack-poster/blob/b38d539f3162c286b33b1c3c3f3fbed5bde15654/lib/slack/poster.rb#L59-L67 | train |
le0pard/mongodb_logger | lib/mongodb_logger/logger.rb | MongodbLogger.Logger.record_serializer | def record_serializer(rec, nice = true)
[:messages, :params].each do |key|
if msgs = rec[key]
msgs.each do |i, j|
msgs[i] = (true == nice ? nice_serialize_object(j) : j.inspect)
end
end
end
end | ruby | def record_serializer(rec, nice = true)
[:messages, :params].each do |key|
if msgs = rec[key]
msgs.each do |i, j|
msgs[i] = (true == nice ? nice_serialize_object(j) : j.inspect)
end
end
end
end | [
"def",
"record_serializer",
"(",
"rec",
",",
"nice",
"=",
"true",
")",
"[",
":messages",
",",
":params",
"]",
".",
"each",
"do",
"|",
"key",
"|",
"if",
"msgs",
"=",
"rec",
"[",
"key",
"]",
"msgs",
".",
"each",
"do",
"|",
"i",
",",
"j",
"|",
"msgs",
"[",
"i",
"]",
"=",
"(",
"true",
"==",
"nice",
"?",
"nice_serialize_object",
"(",
"j",
")",
":",
"j",
".",
"inspect",
")",
"end",
"end",
"end",
"end"
]
| try to serialyze data by each key and found invalid object | [
"try",
"to",
"serialyze",
"data",
"by",
"each",
"key",
"and",
"found",
"invalid",
"object"
]
| 102ee484f8c93ae52a46b4605a8b9bdfd538bb66 | https://github.com/le0pard/mongodb_logger/blob/102ee484f8c93ae52a46b4605a8b9bdfd538bb66/lib/mongodb_logger/logger.rb#L210-L218 | train |
le0pard/mongodb_logger | lib/mongodb_logger/replica_set_helper.rb | MongodbLogger.ReplicaSetHelper.rescue_connection_failure | def rescue_connection_failure(max_retries = 40)
success = false
retries = 0
while !success
begin
yield
success = true
rescue mongo_error_type => e
raise e if (retries += 1) >= max_retries
sleep 0.25
end
end
end | ruby | def rescue_connection_failure(max_retries = 40)
success = false
retries = 0
while !success
begin
yield
success = true
rescue mongo_error_type => e
raise e if (retries += 1) >= max_retries
sleep 0.25
end
end
end | [
"def",
"rescue_connection_failure",
"(",
"max_retries",
"=",
"40",
")",
"success",
"=",
"false",
"retries",
"=",
"0",
"while",
"!",
"success",
"begin",
"yield",
"success",
"=",
"true",
"rescue",
"mongo_error_type",
"=>",
"e",
"raise",
"e",
"if",
"(",
"retries",
"+=",
"1",
")",
">=",
"max_retries",
"sleep",
"0.25",
"end",
"end",
"end"
]
| Use retry alg from mongodb to gobble up connection failures during replica set master vote
Defaults to a 10 second wait | [
"Use",
"retry",
"alg",
"from",
"mongodb",
"to",
"gobble",
"up",
"connection",
"failures",
"during",
"replica",
"set",
"master",
"vote",
"Defaults",
"to",
"a",
"10",
"second",
"wait"
]
| 102ee484f8c93ae52a46b4605a8b9bdfd538bb66 | https://github.com/le0pard/mongodb_logger/blob/102ee484f8c93ae52a46b4605a8b9bdfd538bb66/lib/mongodb_logger/replica_set_helper.rb#L5-L17 | train |
kameeoze/jruby-poi | lib/poi/workbook/cell.rb | POI.Cell.error_value | def error_value
if poi_cell.cell_type == CELL_TYPE_ERROR
error_value_from(poi_cell.error_cell_value)
elsif poi_cell.cell_type == CELL_TYPE_FORMULA &&
poi_cell.cached_formula_result_type == CELL_TYPE_ERROR
cell_value = formula_evaluator.evaluate(poi_cell)
cell_value && error_value_from(cell_value.error_value)
else
nil
end
end | ruby | def error_value
if poi_cell.cell_type == CELL_TYPE_ERROR
error_value_from(poi_cell.error_cell_value)
elsif poi_cell.cell_type == CELL_TYPE_FORMULA &&
poi_cell.cached_formula_result_type == CELL_TYPE_ERROR
cell_value = formula_evaluator.evaluate(poi_cell)
cell_value && error_value_from(cell_value.error_value)
else
nil
end
end | [
"def",
"error_value",
"if",
"poi_cell",
".",
"cell_type",
"==",
"CELL_TYPE_ERROR",
"error_value_from",
"(",
"poi_cell",
".",
"error_cell_value",
")",
"elsif",
"poi_cell",
".",
"cell_type",
"==",
"CELL_TYPE_FORMULA",
"&&",
"poi_cell",
".",
"cached_formula_result_type",
"==",
"CELL_TYPE_ERROR",
"cell_value",
"=",
"formula_evaluator",
".",
"evaluate",
"(",
"poi_cell",
")",
"cell_value",
"&&",
"error_value_from",
"(",
"cell_value",
".",
"error_value",
")",
"else",
"nil",
"end",
"end"
]
| This is NOT an inexpensive operation. The purpose of this method is merely to get more information
out of cell when one thinks the value returned is incorrect. It may have more value in development
than in production. | [
"This",
"is",
"NOT",
"an",
"inexpensive",
"operation",
".",
"The",
"purpose",
"of",
"this",
"method",
"is",
"merely",
"to",
"get",
"more",
"information",
"out",
"of",
"cell",
"when",
"one",
"thinks",
"the",
"value",
"returned",
"is",
"incorrect",
".",
"It",
"may",
"have",
"more",
"value",
"in",
"development",
"than",
"in",
"production",
"."
]
| c10b7e7ccfd19f132d153834ea0372a67a1d4981 | https://github.com/kameeoze/jruby-poi/blob/c10b7e7ccfd19f132d153834ea0372a67a1d4981/lib/poi/workbook/cell.rb#L51-L62 | train |
kameeoze/jruby-poi | lib/poi/workbook/cell.rb | POI.Cell.to_s | def to_s(evaluate_formulas=true)
return '' if poi_cell.nil?
if poi_cell.cell_type == CELL_TYPE_FORMULA && evaluate_formulas == false
formula_value
else
value.to_s
end
end | ruby | def to_s(evaluate_formulas=true)
return '' if poi_cell.nil?
if poi_cell.cell_type == CELL_TYPE_FORMULA && evaluate_formulas == false
formula_value
else
value.to_s
end
end | [
"def",
"to_s",
"(",
"evaluate_formulas",
"=",
"true",
")",
"return",
"''",
"if",
"poi_cell",
".",
"nil?",
"if",
"poi_cell",
".",
"cell_type",
"==",
"CELL_TYPE_FORMULA",
"&&",
"evaluate_formulas",
"==",
"false",
"formula_value",
"else",
"value",
".",
"to_s",
"end",
"end"
]
| Get the String representation of this Cell's value.
If this Cell is a formula you can pass a false to this method and
get the formula instead of the String representation. | [
"Get",
"the",
"String",
"representation",
"of",
"this",
"Cell",
"s",
"value",
"."
]
| c10b7e7ccfd19f132d153834ea0372a67a1d4981 | https://github.com/kameeoze/jruby-poi/blob/c10b7e7ccfd19f132d153834ea0372a67a1d4981/lib/poi/workbook/cell.rb#L106-L114 | train |
domgetter/dare | lib/dare/window.rb | Dare.Window.add_mouse_event_listener | def add_mouse_event_listener
Element.find("##{@canvas.id}").on :mousemove do |event|
coords = get_cursor_position(event)
@mouse_x = coords.x[:x]
@mouse_y = coords.x[:y]
end
end | ruby | def add_mouse_event_listener
Element.find("##{@canvas.id}").on :mousemove do |event|
coords = get_cursor_position(event)
@mouse_x = coords.x[:x]
@mouse_y = coords.x[:y]
end
end | [
"def",
"add_mouse_event_listener",
"Element",
".",
"find",
"(",
"\"##{@canvas.id}\"",
")",
".",
"on",
":mousemove",
"do",
"|",
"event",
"|",
"coords",
"=",
"get_cursor_position",
"(",
"event",
")",
"@mouse_x",
"=",
"coords",
".",
"x",
"[",
":x",
"]",
"@mouse_y",
"=",
"coords",
".",
"x",
"[",
":y",
"]",
"end",
"end"
]
| adds mousemove event listener to main canvas | [
"adds",
"mousemove",
"event",
"listener",
"to",
"main",
"canvas"
]
| a017efd98275992912f016fefe45a17f00117fe5 | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/lib/dare/window.rb#L68-L74 | train |
domgetter/dare | lib/dare/window.rb | Dare.Window.add_keyboard_event_listeners | def add_keyboard_event_listeners
Element.find("html").on :keydown do |event|
@keys[get_key_id(event)] = true
end
Element.find("html").on :keyup do |event|
@keys[get_key_id(event)] = false
end
::Window.on :blur do |event|
@keys.fill false
end
end | ruby | def add_keyboard_event_listeners
Element.find("html").on :keydown do |event|
@keys[get_key_id(event)] = true
end
Element.find("html").on :keyup do |event|
@keys[get_key_id(event)] = false
end
::Window.on :blur do |event|
@keys.fill false
end
end | [
"def",
"add_keyboard_event_listeners",
"Element",
".",
"find",
"(",
"\"html\"",
")",
".",
"on",
":keydown",
"do",
"|",
"event",
"|",
"@keys",
"[",
"get_key_id",
"(",
"event",
")",
"]",
"=",
"true",
"end",
"Element",
".",
"find",
"(",
"\"html\"",
")",
".",
"on",
":keyup",
"do",
"|",
"event",
"|",
"@keys",
"[",
"get_key_id",
"(",
"event",
")",
"]",
"=",
"false",
"end",
"::",
"Window",
".",
"on",
":blur",
"do",
"|",
"event",
"|",
"@keys",
".",
"fill",
"false",
"end",
"end"
]
| adds keyboard event listeners to entire page | [
"adds",
"keyboard",
"event",
"listeners",
"to",
"entire",
"page"
]
| a017efd98275992912f016fefe45a17f00117fe5 | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/lib/dare/window.rb#L77-L87 | train |
kameeoze/jruby-poi | lib/poi/workbook/worksheet.rb | POI.Worksheet.[] | def [](row_index)
if Fixnum === row_index
rows[row_index]
else
ref = org.apache.poi.ss.util.CellReference.new(row_index)
cell = rows[ref.row][ref.col]
cell && cell.value ? cell.value : cell
end
end | ruby | def [](row_index)
if Fixnum === row_index
rows[row_index]
else
ref = org.apache.poi.ss.util.CellReference.new(row_index)
cell = rows[ref.row][ref.col]
cell && cell.value ? cell.value : cell
end
end | [
"def",
"[]",
"(",
"row_index",
")",
"if",
"Fixnum",
"===",
"row_index",
"rows",
"[",
"row_index",
"]",
"else",
"ref",
"=",
"org",
".",
"apache",
".",
"poi",
".",
"ss",
".",
"util",
".",
"CellReference",
".",
"new",
"(",
"row_index",
")",
"cell",
"=",
"rows",
"[",
"ref",
".",
"row",
"]",
"[",
"ref",
".",
"col",
"]",
"cell",
"&&",
"cell",
".",
"value",
"?",
"cell",
".",
"value",
":",
"cell",
"end",
"end"
]
| Accepts a Fixnum or a String as the row_index
row_index as Fixnum: returns the 0-based row
row_index as String: assumes a cell reference within this sheet
if the value of the reference is non-nil the value is returned,
otherwise the referenced cell is returned | [
"Accepts",
"a",
"Fixnum",
"or",
"a",
"String",
"as",
"the",
"row_index"
]
| c10b7e7ccfd19f132d153834ea0372a67a1d4981 | https://github.com/kameeoze/jruby-poi/blob/c10b7e7ccfd19f132d153834ea0372a67a1d4981/lib/poi/workbook/worksheet.rb#L59-L67 | train |
antw/iniparse | lib/iniparse/generator.rb | IniParse.Generator.section | def section(name, opts = {})
if @in_section
# Nesting sections is bad, mmmkay?
raise LineNotAllowed, "You can't nest sections in INI files."
end
# Add to a section if it already exists
if @document.has_section?(name.to_s())
@context = @document[name.to_s()]
else
@context = Lines::Section.new(name, line_options(opts))
@document.lines << @context
end
if block_given?
begin
@in_section = true
with_options(opts) { yield self }
@context = @document
blank()
ensure
@in_section = false
end
end
end | ruby | def section(name, opts = {})
if @in_section
# Nesting sections is bad, mmmkay?
raise LineNotAllowed, "You can't nest sections in INI files."
end
# Add to a section if it already exists
if @document.has_section?(name.to_s())
@context = @document[name.to_s()]
else
@context = Lines::Section.new(name, line_options(opts))
@document.lines << @context
end
if block_given?
begin
@in_section = true
with_options(opts) { yield self }
@context = @document
blank()
ensure
@in_section = false
end
end
end | [
"def",
"section",
"(",
"name",
",",
"opts",
"=",
"{",
"}",
")",
"if",
"@in_section",
"raise",
"LineNotAllowed",
",",
"\"You can't nest sections in INI files.\"",
"end",
"if",
"@document",
".",
"has_section?",
"(",
"name",
".",
"to_s",
"(",
")",
")",
"@context",
"=",
"@document",
"[",
"name",
".",
"to_s",
"(",
")",
"]",
"else",
"@context",
"=",
"Lines",
"::",
"Section",
".",
"new",
"(",
"name",
",",
"line_options",
"(",
"opts",
")",
")",
"@document",
".",
"lines",
"<<",
"@context",
"end",
"if",
"block_given?",
"begin",
"@in_section",
"=",
"true",
"with_options",
"(",
"opts",
")",
"{",
"yield",
"self",
"}",
"@context",
"=",
"@document",
"blank",
"(",
")",
"ensure",
"@in_section",
"=",
"false",
"end",
"end",
"end"
]
| Creates a new section with the given name and adds it to the document.
You can optionally supply a block (as detailed in the documentation for
Generator#gen) in order to add options to the section.
==== Parameters
name<String>:: A name for the given section. | [
"Creates",
"a",
"new",
"section",
"with",
"the",
"given",
"name",
"and",
"adds",
"it",
"to",
"the",
"document",
"."
]
| 72715aa116aa303b05f5415362fb2611e597cb48 | https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/generator.rb#L107-L131 | train |
antw/iniparse | lib/iniparse/generator.rb | IniParse.Generator.option | def option(key, value, opts = {})
@context.lines << Lines::Option.new(
key, value, line_options(opts)
)
rescue LineNotAllowed
# Tried to add an Option to a Document.
raise NoSectionError,
'Your INI document contains an option before the first section is ' \
'declared which is not allowed.'
end | ruby | def option(key, value, opts = {})
@context.lines << Lines::Option.new(
key, value, line_options(opts)
)
rescue LineNotAllowed
# Tried to add an Option to a Document.
raise NoSectionError,
'Your INI document contains an option before the first section is ' \
'declared which is not allowed.'
end | [
"def",
"option",
"(",
"key",
",",
"value",
",",
"opts",
"=",
"{",
"}",
")",
"@context",
".",
"lines",
"<<",
"Lines",
"::",
"Option",
".",
"new",
"(",
"key",
",",
"value",
",",
"line_options",
"(",
"opts",
")",
")",
"rescue",
"LineNotAllowed",
"raise",
"NoSectionError",
",",
"'Your INI document contains an option before the first section is '",
"'declared which is not allowed.'",
"end"
]
| Adds a new option to the current section.
Can only be called as part of a section block, or after at least one
section has been added to the document.
==== Parameters
key<String>:: The key (name) for this option.
value:: The option's value.
opts<Hash>:: Extra options for the line (formatting, etc).
==== Raises
IniParse::NoSectionError::
If no section has been added to the document yet. | [
"Adds",
"a",
"new",
"option",
"to",
"the",
"current",
"section",
"."
]
| 72715aa116aa303b05f5415362fb2611e597cb48 | https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/generator.rb#L147-L156 | train |
antw/iniparse | lib/iniparse/generator.rb | IniParse.Generator.comment | def comment(comment, opts = {})
@context.lines << Lines::Comment.new(
line_options(opts.merge(:comment => comment))
)
end | ruby | def comment(comment, opts = {})
@context.lines << Lines::Comment.new(
line_options(opts.merge(:comment => comment))
)
end | [
"def",
"comment",
"(",
"comment",
",",
"opts",
"=",
"{",
"}",
")",
"@context",
".",
"lines",
"<<",
"Lines",
"::",
"Comment",
".",
"new",
"(",
"line_options",
"(",
"opts",
".",
"merge",
"(",
":comment",
"=>",
"comment",
")",
")",
")",
"end"
]
| Adds a new comment line to the document.
==== Parameters
comment<String>:: The text for the comment line. | [
"Adds",
"a",
"new",
"comment",
"line",
"to",
"the",
"document",
"."
]
| 72715aa116aa303b05f5415362fb2611e597cb48 | https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/generator.rb#L163-L167 | train |
antw/iniparse | lib/iniparse/generator.rb | IniParse.Generator.with_options | def with_options(opts = {}) # :nodoc:
opts = opts.dup
opts.delete(:comment)
@opt_stack.push( @opt_stack.last.merge(opts))
yield self
@opt_stack.pop
end | ruby | def with_options(opts = {}) # :nodoc:
opts = opts.dup
opts.delete(:comment)
@opt_stack.push( @opt_stack.last.merge(opts))
yield self
@opt_stack.pop
end | [
"def",
"with_options",
"(",
"opts",
"=",
"{",
"}",
")",
"opts",
"=",
"opts",
".",
"dup",
"opts",
".",
"delete",
"(",
":comment",
")",
"@opt_stack",
".",
"push",
"(",
"@opt_stack",
".",
"last",
".",
"merge",
"(",
"opts",
")",
")",
"yield",
"self",
"@opt_stack",
".",
"pop",
"end"
]
| Wraps lines, setting default options for each. | [
"Wraps",
"lines",
"setting",
"default",
"options",
"for",
"each",
"."
]
| 72715aa116aa303b05f5415362fb2611e597cb48 | https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/generator.rb#L175-L181 | train |
Fullscreen/yt-core | lib/yt/response.rb | Yt.Response.videos_for | def videos_for(items, key, options)
items.body['items'].map{|item| item['id'] = item[key]['videoId']}
if options[:parts] == %i(id)
items
else
options[:ids] = items.body['items'].map{|item| item['id']}
options[:offset] = nil
get('/youtube/v3/videos', resource_params(options)).tap do |response|
response.body['nextPageToken'] = items.body['nextPageToken']
end
end
end | ruby | def videos_for(items, key, options)
items.body['items'].map{|item| item['id'] = item[key]['videoId']}
if options[:parts] == %i(id)
items
else
options[:ids] = items.body['items'].map{|item| item['id']}
options[:offset] = nil
get('/youtube/v3/videos', resource_params(options)).tap do |response|
response.body['nextPageToken'] = items.body['nextPageToken']
end
end
end | [
"def",
"videos_for",
"(",
"items",
",",
"key",
",",
"options",
")",
"items",
".",
"body",
"[",
"'items'",
"]",
".",
"map",
"{",
"|",
"item",
"|",
"item",
"[",
"'id'",
"]",
"=",
"item",
"[",
"key",
"]",
"[",
"'videoId'",
"]",
"}",
"if",
"options",
"[",
":parts",
"]",
"==",
"%i(",
"id",
")",
"items",
"else",
"options",
"[",
":ids",
"]",
"=",
"items",
".",
"body",
"[",
"'items'",
"]",
".",
"map",
"{",
"|",
"item",
"|",
"item",
"[",
"'id'",
"]",
"}",
"options",
"[",
":offset",
"]",
"=",
"nil",
"get",
"(",
"'/youtube/v3/videos'",
",",
"resource_params",
"(",
"options",
")",
")",
".",
"tap",
"do",
"|",
"response",
"|",
"response",
".",
"body",
"[",
"'nextPageToken'",
"]",
"=",
"items",
".",
"body",
"[",
"'nextPageToken'",
"]",
"end",
"end",
"end"
]
| Expands the resultset into a collection of videos by fetching missing
parts, eventually with an additional HTTP request. | [
"Expands",
"the",
"resultset",
"into",
"a",
"collection",
"of",
"videos",
"by",
"fetching",
"missing",
"parts",
"eventually",
"with",
"an",
"additional",
"HTTP",
"request",
"."
]
| 65b7fd61285c90beb72df241648eeff5b81ae321 | https://github.com/Fullscreen/yt-core/blob/65b7fd61285c90beb72df241648eeff5b81ae321/lib/yt/response.rb#L124-L136 | train |
kangguru/rack-google-analytics | lib/google-analytics/instance_methods.rb | GoogleAnalytics.InstanceMethods.ga_track_event | def ga_track_event(category, action, label = nil, value = nil)
ga_events.push(GoogleAnalytics::Event.new(category, action, label, value))
end | ruby | def ga_track_event(category, action, label = nil, value = nil)
ga_events.push(GoogleAnalytics::Event.new(category, action, label, value))
end | [
"def",
"ga_track_event",
"(",
"category",
",",
"action",
",",
"label",
"=",
"nil",
",",
"value",
"=",
"nil",
")",
"ga_events",
".",
"push",
"(",
"GoogleAnalytics",
"::",
"Event",
".",
"new",
"(",
"category",
",",
"action",
",",
"label",
",",
"value",
")",
")",
"end"
]
| Tracks an event or goal on a page load
e.g. writes
ga.('send', 'event', 'Videos', 'Play', 'Gone With the Wind'); | [
"Tracks",
"an",
"event",
"or",
"goal",
"on",
"a",
"page",
"load"
]
| ac21206f1844abf00bedea7f0caa1b485873b238 | https://github.com/kangguru/rack-google-analytics/blob/ac21206f1844abf00bedea7f0caa1b485873b238/lib/google-analytics/instance_methods.rb#L27-L29 | train |
antw/iniparse | lib/iniparse/document.rb | IniParse.Document.to_ini | def to_ini
string = @lines.to_a.map { |line| line.to_ini }.join($/)
string = "#{ string }\n" unless string[-1] == "\n"
string
end | ruby | def to_ini
string = @lines.to_a.map { |line| line.to_ini }.join($/)
string = "#{ string }\n" unless string[-1] == "\n"
string
end | [
"def",
"to_ini",
"string",
"=",
"@lines",
".",
"to_a",
".",
"map",
"{",
"|",
"line",
"|",
"line",
".",
"to_ini",
"}",
".",
"join",
"(",
"$/",
")",
"string",
"=",
"\"#{ string }\\n\"",
"unless",
"string",
"[",
"-",
"1",
"]",
"==",
"\"\\n\"",
"string",
"end"
]
| Returns this document as a string suitable for saving to a file. | [
"Returns",
"this",
"document",
"as",
"a",
"string",
"suitable",
"for",
"saving",
"to",
"a",
"file",
"."
]
| 72715aa116aa303b05f5415362fb2611e597cb48 | https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/document.rb#L53-L58 | train |
antw/iniparse | lib/iniparse/document.rb | IniParse.Document.to_hash | def to_hash
result = {}
@lines.entries.each do |section|
result[section.key] ||= {}
section.entries.each do |option|
opts = Array(option)
val = opts.map { |o| o.respond_to?(:value) ? o.value : o }
val = val.size > 1 ? val : val.first
result[section.key][opts.first.key] = val
end
end
result
end | ruby | def to_hash
result = {}
@lines.entries.each do |section|
result[section.key] ||= {}
section.entries.each do |option|
opts = Array(option)
val = opts.map { |o| o.respond_to?(:value) ? o.value : o }
val = val.size > 1 ? val : val.first
result[section.key][opts.first.key] = val
end
end
result
end | [
"def",
"to_hash",
"result",
"=",
"{",
"}",
"@lines",
".",
"entries",
".",
"each",
"do",
"|",
"section",
"|",
"result",
"[",
"section",
".",
"key",
"]",
"||=",
"{",
"}",
"section",
".",
"entries",
".",
"each",
"do",
"|",
"option",
"|",
"opts",
"=",
"Array",
"(",
"option",
")",
"val",
"=",
"opts",
".",
"map",
"{",
"|",
"o",
"|",
"o",
".",
"respond_to?",
"(",
":value",
")",
"?",
"o",
".",
"value",
":",
"o",
"}",
"val",
"=",
"val",
".",
"size",
">",
"1",
"?",
"val",
":",
"val",
".",
"first",
"result",
"[",
"section",
".",
"key",
"]",
"[",
"opts",
".",
"first",
".",
"key",
"]",
"=",
"val",
"end",
"end",
"result",
"end"
]
| Returns a has representation of the INI with multi-line options
as an array | [
"Returns",
"a",
"has",
"representation",
"of",
"the",
"INI",
"with",
"multi",
"-",
"line",
"options",
"as",
"an",
"array"
]
| 72715aa116aa303b05f5415362fb2611e597cb48 | https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/document.rb#L64-L76 | train |
antw/iniparse | lib/iniparse/document.rb | IniParse.Document.save | def save(path = nil)
@path = path if path
raise IniParseError, 'No path given to Document#save' if @path !~ /\S/
File.open(@path, 'w') { |f| f.write(self.to_ini) }
end | ruby | def save(path = nil)
@path = path if path
raise IniParseError, 'No path given to Document#save' if @path !~ /\S/
File.open(@path, 'w') { |f| f.write(self.to_ini) }
end | [
"def",
"save",
"(",
"path",
"=",
"nil",
")",
"@path",
"=",
"path",
"if",
"path",
"raise",
"IniParseError",
",",
"'No path given to Document#save'",
"if",
"@path",
"!~",
"/",
"\\S",
"/",
"File",
".",
"open",
"(",
"@path",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"self",
".",
"to_ini",
")",
"}",
"end"
]
| Saves a copy of this Document to disk.
If a path was supplied when the Document was initialized then nothing
needs to be given to Document#save. If Document was not given a file
path, or you wish to save the document elsewhere, supply a path when
calling Document#save.
==== Parameters
path<String>:: A path to which this document will be saved.
==== Raises
IniParseError:: If your document couldn't be saved. | [
"Saves",
"a",
"copy",
"of",
"this",
"Document",
"to",
"disk",
"."
]
| 72715aa116aa303b05f5415362fb2611e597cb48 | https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/document.rb#L104-L108 | train |
kameeoze/jruby-poi | lib/poi/workbook/workbook.rb | POI.Workbook.[] | def [](reference)
if Fixnum === reference
return worksheets[reference]
end
if sheet = worksheets.detect{|e| e.name == reference}
return sheet.poi_worksheet.nil? ? nil : sheet
end
cell = cell(reference)
if Array === cell
cell.collect{|e| e.value}
elsif Hash === cell
values = {}
cell.each_pair{|column_name, cells| values[column_name] = cells.collect{|e| e.value}}
values
else
cell.value
end
end | ruby | def [](reference)
if Fixnum === reference
return worksheets[reference]
end
if sheet = worksheets.detect{|e| e.name == reference}
return sheet.poi_worksheet.nil? ? nil : sheet
end
cell = cell(reference)
if Array === cell
cell.collect{|e| e.value}
elsif Hash === cell
values = {}
cell.each_pair{|column_name, cells| values[column_name] = cells.collect{|e| e.value}}
values
else
cell.value
end
end | [
"def",
"[]",
"(",
"reference",
")",
"if",
"Fixnum",
"===",
"reference",
"return",
"worksheets",
"[",
"reference",
"]",
"end",
"if",
"sheet",
"=",
"worksheets",
".",
"detect",
"{",
"|",
"e",
"|",
"e",
".",
"name",
"==",
"reference",
"}",
"return",
"sheet",
".",
"poi_worksheet",
".",
"nil?",
"?",
"nil",
":",
"sheet",
"end",
"cell",
"=",
"cell",
"(",
"reference",
")",
"if",
"Array",
"===",
"cell",
"cell",
".",
"collect",
"{",
"|",
"e",
"|",
"e",
".",
"value",
"}",
"elsif",
"Hash",
"===",
"cell",
"values",
"=",
"{",
"}",
"cell",
".",
"each_pair",
"{",
"|",
"column_name",
",",
"cells",
"|",
"values",
"[",
"column_name",
"]",
"=",
"cells",
".",
"collect",
"{",
"|",
"e",
"|",
"e",
".",
"value",
"}",
"}",
"values",
"else",
"cell",
".",
"value",
"end",
"end"
]
| reference can be a Fixnum, referring to the 0-based sheet or
a String which is the sheet name or a cell reference.
If a cell reference is passed the value of that cell is returned.
If the reference refers to a contiguous range of cells an Array of values will be returned.
If the reference refers to a multiple columns a Hash of values will be returned by column name. | [
"reference",
"can",
"be",
"a",
"Fixnum",
"referring",
"to",
"the",
"0",
"-",
"based",
"sheet",
"or",
"a",
"String",
"which",
"is",
"the",
"sheet",
"name",
"or",
"a",
"cell",
"reference",
"."
]
| c10b7e7ccfd19f132d153834ea0372a67a1d4981 | https://github.com/kameeoze/jruby-poi/blob/c10b7e7ccfd19f132d153834ea0372a67a1d4981/lib/poi/workbook/workbook.rb#L147-L166 | train |
antw/iniparse | lib/iniparse/parser.rb | IniParse.Parser.parse | def parse
IniParse::Generator.gen do |generator|
@source.split("\n", -1).each do |line|
generator.send(*Parser.parse_line(line))
end
end
end | ruby | def parse
IniParse::Generator.gen do |generator|
@source.split("\n", -1).each do |line|
generator.send(*Parser.parse_line(line))
end
end
end | [
"def",
"parse",
"IniParse",
"::",
"Generator",
".",
"gen",
"do",
"|",
"generator",
"|",
"@source",
".",
"split",
"(",
"\"\\n\"",
",",
"-",
"1",
")",
".",
"each",
"do",
"|",
"line",
"|",
"generator",
".",
"send",
"(",
"*",
"Parser",
".",
"parse_line",
"(",
"line",
")",
")",
"end",
"end",
"end"
]
| Creates a new Parser instance for parsing string +source+.
==== Parameters
source<String>:: The source string.
Parses the source string and returns the resulting data structure.
==== Returns
IniParse::Document | [
"Creates",
"a",
"new",
"Parser",
"instance",
"for",
"parsing",
"string",
"+",
"source",
"+",
"."
]
| 72715aa116aa303b05f5415362fb2611e597cb48 | https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/parser.rb#L40-L46 | train |
antw/iniparse | lib/iniparse/line_collection.rb | IniParse.LineCollection.[]= | def []=(key, value)
key = key.to_s
if has_key?(key)
@lines[ @indicies[key] ] = value
else
@lines << value
@indicies[key] = @lines.length - 1
end
end | ruby | def []=(key, value)
key = key.to_s
if has_key?(key)
@lines[ @indicies[key] ] = value
else
@lines << value
@indicies[key] = @lines.length - 1
end
end | [
"def",
"[]=",
"(",
"key",
",",
"value",
")",
"key",
"=",
"key",
".",
"to_s",
"if",
"has_key?",
"(",
"key",
")",
"@lines",
"[",
"@indicies",
"[",
"key",
"]",
"]",
"=",
"value",
"else",
"@lines",
"<<",
"value",
"@indicies",
"[",
"key",
"]",
"=",
"@lines",
".",
"length",
"-",
"1",
"end",
"end"
]
| Set a +value+ identified by +key+.
If a value with the given key already exists, the value will be replaced
with the new one, with the new value taking the position of the old. | [
"Set",
"a",
"+",
"value",
"+",
"identified",
"by",
"+",
"key",
"+",
"."
]
| 72715aa116aa303b05f5415362fb2611e597cb48 | https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/line_collection.rb#L30-L39 | train |
antw/iniparse | lib/iniparse/line_collection.rb | IniParse.LineCollection.each | def each(include_blank = false)
@lines.each do |line|
if include_blank || ! (line.is_a?(Array) ? line.empty? : line.blank?)
yield(line)
end
end
end | ruby | def each(include_blank = false)
@lines.each do |line|
if include_blank || ! (line.is_a?(Array) ? line.empty? : line.blank?)
yield(line)
end
end
end | [
"def",
"each",
"(",
"include_blank",
"=",
"false",
")",
"@lines",
".",
"each",
"do",
"|",
"line",
"|",
"if",
"include_blank",
"||",
"!",
"(",
"line",
".",
"is_a?",
"(",
"Array",
")",
"?",
"line",
".",
"empty?",
":",
"line",
".",
"blank?",
")",
"yield",
"(",
"line",
")",
"end",
"end",
"end"
]
| Enumerates through the collection.
By default #each does not yield blank and comment lines.
==== Parameters
include_blank<Boolean>:: Include blank/comment lines? | [
"Enumerates",
"through",
"the",
"collection",
"."
]
| 72715aa116aa303b05f5415362fb2611e597cb48 | https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/line_collection.rb#L59-L65 | train |
antw/iniparse | lib/iniparse/line_collection.rb | IniParse.LineCollection.delete | def delete(key)
key = key.key if key.respond_to?(:key)
unless (idx = @indicies[key]).nil?
@indicies.delete(key)
@indicies.each { |k,v| @indicies[k] = v -= 1 if v > idx }
@lines.delete_at(idx)
end
end | ruby | def delete(key)
key = key.key if key.respond_to?(:key)
unless (idx = @indicies[key]).nil?
@indicies.delete(key)
@indicies.each { |k,v| @indicies[k] = v -= 1 if v > idx }
@lines.delete_at(idx)
end
end | [
"def",
"delete",
"(",
"key",
")",
"key",
"=",
"key",
".",
"key",
"if",
"key",
".",
"respond_to?",
"(",
":key",
")",
"unless",
"(",
"idx",
"=",
"@indicies",
"[",
"key",
"]",
")",
".",
"nil?",
"@indicies",
".",
"delete",
"(",
"key",
")",
"@indicies",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"@indicies",
"[",
"k",
"]",
"=",
"v",
"-=",
"1",
"if",
"v",
">",
"idx",
"}",
"@lines",
".",
"delete_at",
"(",
"idx",
")",
"end",
"end"
]
| Removes the value identified by +key+. | [
"Removes",
"the",
"value",
"identified",
"by",
"+",
"key",
"+",
"."
]
| 72715aa116aa303b05f5415362fb2611e597cb48 | https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/line_collection.rb#L68-L76 | train |
antw/iniparse | lib/iniparse/line_collection.rb | IniParse.OptionCollection.<< | def <<(line)
if line.kind_of?(IniParse::Lines::Section)
raise IniParse::LineNotAllowed,
"You can't add a Section to an OptionCollection."
end
if line.blank? || (! has_key?(line.key))
super # Adding a new option, comment or blank line.
else
self[line.key] = [self[line.key], line].flatten
end
self
end | ruby | def <<(line)
if line.kind_of?(IniParse::Lines::Section)
raise IniParse::LineNotAllowed,
"You can't add a Section to an OptionCollection."
end
if line.blank? || (! has_key?(line.key))
super # Adding a new option, comment or blank line.
else
self[line.key] = [self[line.key], line].flatten
end
self
end | [
"def",
"<<",
"(",
"line",
")",
"if",
"line",
".",
"kind_of?",
"(",
"IniParse",
"::",
"Lines",
"::",
"Section",
")",
"raise",
"IniParse",
"::",
"LineNotAllowed",
",",
"\"You can't add a Section to an OptionCollection.\"",
"end",
"if",
"line",
".",
"blank?",
"||",
"(",
"!",
"has_key?",
"(",
"line",
".",
"key",
")",
")",
"super",
"else",
"self",
"[",
"line",
".",
"key",
"]",
"=",
"[",
"self",
"[",
"line",
".",
"key",
"]",
",",
"line",
"]",
".",
"flatten",
"end",
"self",
"end"
]
| Appends a line to the collection.
If you push an Option with a key already represented in the collection,
the previous Option will not be overwritten, but treated as a duplicate.
==== Parameters
line<IniParse::LineType::Line>:: The line to be added to this section. | [
"Appends",
"a",
"line",
"to",
"the",
"collection",
"."
]
| 72715aa116aa303b05f5415362fb2611e597cb48 | https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/line_collection.rb#L149-L162 | train |
antw/iniparse | lib/iniparse/line_collection.rb | IniParse.OptionCollection.keys | def keys
map { |line| line.kind_of?(Array) ? line.first.key : line.key }
end | ruby | def keys
map { |line| line.kind_of?(Array) ? line.first.key : line.key }
end | [
"def",
"keys",
"map",
"{",
"|",
"line",
"|",
"line",
".",
"kind_of?",
"(",
"Array",
")",
"?",
"line",
".",
"first",
".",
"key",
":",
"line",
".",
"key",
"}",
"end"
]
| Return an array containing the keys for the lines added to this
collection. | [
"Return",
"an",
"array",
"containing",
"the",
"keys",
"for",
"the",
"lines",
"added",
"to",
"this",
"collection",
"."
]
| 72715aa116aa303b05f5415362fb2611e597cb48 | https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/line_collection.rb#L166-L168 | train |
beatrichartz/exchange | lib/exchange/helper.rb | Exchange.Helper.assure_time | def assure_time arg=nil, opts={}
if arg
arg.kind_of?(Time) ? arg : Time.gm(*arg.split('-'))
elsif opts[:default]
Time.send(opts[:default])
end
end | ruby | def assure_time arg=nil, opts={}
if arg
arg.kind_of?(Time) ? arg : Time.gm(*arg.split('-'))
elsif opts[:default]
Time.send(opts[:default])
end
end | [
"def",
"assure_time",
"arg",
"=",
"nil",
",",
"opts",
"=",
"{",
"}",
"if",
"arg",
"arg",
".",
"kind_of?",
"(",
"Time",
")",
"?",
"arg",
":",
"Time",
".",
"gm",
"(",
"*",
"arg",
".",
"split",
"(",
"'-'",
")",
")",
"elsif",
"opts",
"[",
":default",
"]",
"Time",
".",
"send",
"(",
"opts",
"[",
":default",
"]",
")",
"end",
"end"
]
| A helper function to assure a value is an instance of time
@param [Time, String, NilClass] arg The value to be asserted
@param [Hash] opts Options for assertion
@option opts [Symbol] :default a method that can be sent to Time if the argument is nil (:now for example) | [
"A",
"helper",
"function",
"to",
"assure",
"a",
"value",
"is",
"an",
"instance",
"of",
"time"
]
| 4318b9dad3cce5e933827126160fafe30c68dc2a | https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/helper.rb#L21-L27 | train |
BadrIT/translation_center | app/controllers/translation_center/center_controller.rb | TranslationCenter.CenterController.set_language_from | def set_language_from
session[:lang_from] = params[:lang].to_sym
I18n.locale = session[:lang_from]
render nothing: true
end | ruby | def set_language_from
session[:lang_from] = params[:lang].to_sym
I18n.locale = session[:lang_from]
render nothing: true
end | [
"def",
"set_language_from",
"session",
"[",
":lang_from",
"]",
"=",
"params",
"[",
":lang",
"]",
".",
"to_sym",
"I18n",
".",
"locale",
"=",
"session",
"[",
":lang_from",
"]",
"render",
"nothing",
":",
"true",
"end"
]
| set language user translating from | [
"set",
"language",
"user",
"translating",
"from"
]
| 439cbf70323e629a630fe939d02b44361afae13e | https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/controllers/translation_center/center_controller.rb#L10-L14 | train |
BadrIT/translation_center | app/controllers/translation_center/center_controller.rb | TranslationCenter.CenterController.set_language_to | def set_language_to
session[:lang_to] = params[:lang].to_sym
respond_to do |format|
format.html { redirect_to root_url }
format.js { render nothing: true }
end
end | ruby | def set_language_to
session[:lang_to] = params[:lang].to_sym
respond_to do |format|
format.html { redirect_to root_url }
format.js { render nothing: true }
end
end | [
"def",
"set_language_to",
"session",
"[",
":lang_to",
"]",
"=",
"params",
"[",
":lang",
"]",
".",
"to_sym",
"respond_to",
"do",
"|",
"format",
"|",
"format",
".",
"html",
"{",
"redirect_to",
"root_url",
"}",
"format",
".",
"js",
"{",
"render",
"nothing",
":",
"true",
"}",
"end",
"end"
]
| set language user translating to | [
"set",
"language",
"user",
"translating",
"to"
]
| 439cbf70323e629a630fe939d02b44361afae13e | https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/controllers/translation_center/center_controller.rb#L17-L24 | train |
BadrIT/translation_center | app/models/translation_center/activity_query.rb | TranslationCenter.ActivityQuery.translation_ids | def translation_ids
query = Translation.all
query = query.where(lang: lang) unless lang.blank?
query = query.joins(:translation_key).where("translation_center_translation_keys.name LIKE ?", "%#{translation_key_name}%") unless translation_key_name.blank?
if translator_identifier
translator_class = TranslationCenter::CONFIG['translator_type'].camelize.constantize
translators_ids = translator_class.where("#{TranslationCenter::CONFIG['identifier_type']} LIKE ? ", "%#{translator_identifier}%").map(&:id)
query = query.where(translator_id: translators_ids)
end
query.map(&:id)
end | ruby | def translation_ids
query = Translation.all
query = query.where(lang: lang) unless lang.blank?
query = query.joins(:translation_key).where("translation_center_translation_keys.name LIKE ?", "%#{translation_key_name}%") unless translation_key_name.blank?
if translator_identifier
translator_class = TranslationCenter::CONFIG['translator_type'].camelize.constantize
translators_ids = translator_class.where("#{TranslationCenter::CONFIG['identifier_type']} LIKE ? ", "%#{translator_identifier}%").map(&:id)
query = query.where(translator_id: translators_ids)
end
query.map(&:id)
end | [
"def",
"translation_ids",
"query",
"=",
"Translation",
".",
"all",
"query",
"=",
"query",
".",
"where",
"(",
"lang",
":",
"lang",
")",
"unless",
"lang",
".",
"blank?",
"query",
"=",
"query",
".",
"joins",
"(",
":translation_key",
")",
".",
"where",
"(",
"\"translation_center_translation_keys.name LIKE ?\"",
",",
"\"%#{translation_key_name}%\"",
")",
"unless",
"translation_key_name",
".",
"blank?",
"if",
"translator_identifier",
"translator_class",
"=",
"TranslationCenter",
"::",
"CONFIG",
"[",
"'translator_type'",
"]",
".",
"camelize",
".",
"constantize",
"translators_ids",
"=",
"translator_class",
".",
"where",
"(",
"\"#{TranslationCenter::CONFIG['identifier_type']} LIKE ? \"",
",",
"\"%#{translator_identifier}%\"",
")",
".",
"map",
"(",
"&",
":id",
")",
"query",
"=",
"query",
".",
"where",
"(",
"translator_id",
":",
"translators_ids",
")",
"end",
"query",
".",
"map",
"(",
"&",
":id",
")",
"end"
]
| return translation ids that matches this search criteria | [
"return",
"translation",
"ids",
"that",
"matches",
"this",
"search",
"criteria"
]
| 439cbf70323e629a630fe939d02b44361afae13e | https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/activity_query.rb#L30-L43 | train |
BadrIT/translation_center | app/models/translation_center/translation_key.rb | TranslationCenter.TranslationKey.add_category | def add_category
category_name = self.name.to_s.split('.').first
# if one word then add to general category
category_name = self.name.to_s.split('.').size == 1 ? 'general' : self.name.to_s.split('.').first
self.category = TranslationCenter::Category.where(name: category_name).first_or_create
self.last_accessed = Time.now
end | ruby | def add_category
category_name = self.name.to_s.split('.').first
# if one word then add to general category
category_name = self.name.to_s.split('.').size == 1 ? 'general' : self.name.to_s.split('.').first
self.category = TranslationCenter::Category.where(name: category_name).first_or_create
self.last_accessed = Time.now
end | [
"def",
"add_category",
"category_name",
"=",
"self",
".",
"name",
".",
"to_s",
".",
"split",
"(",
"'.'",
")",
".",
"first",
"category_name",
"=",
"self",
".",
"name",
".",
"to_s",
".",
"split",
"(",
"'.'",
")",
".",
"size",
"==",
"1",
"?",
"'general'",
":",
"self",
".",
"name",
".",
"to_s",
".",
"split",
"(",
"'.'",
")",
".",
"first",
"self",
".",
"category",
"=",
"TranslationCenter",
"::",
"Category",
".",
"where",
"(",
"name",
":",
"category_name",
")",
".",
"first_or_create",
"self",
".",
"last_accessed",
"=",
"Time",
".",
"now",
"end"
]
| add a category of this translation key | [
"add",
"a",
"category",
"of",
"this",
"translation",
"key"
]
| 439cbf70323e629a630fe939d02b44361afae13e | https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/translation_key.rb#L28-L34 | train |
BadrIT/translation_center | app/models/translation_center/translation_key.rb | TranslationCenter.TranslationKey.update_status | def update_status(lang)
if self.translations.in(lang).blank?
self.update_attribute("#{lang}_status", UNTRANSLATED)
elsif !self.translations.in(lang).accepted.blank?
self.update_attribute("#{lang}_status", TRANSLATED)
else
self.update_attribute("#{lang}_status", PENDING)
end
end | ruby | def update_status(lang)
if self.translations.in(lang).blank?
self.update_attribute("#{lang}_status", UNTRANSLATED)
elsif !self.translations.in(lang).accepted.blank?
self.update_attribute("#{lang}_status", TRANSLATED)
else
self.update_attribute("#{lang}_status", PENDING)
end
end | [
"def",
"update_status",
"(",
"lang",
")",
"if",
"self",
".",
"translations",
".",
"in",
"(",
"lang",
")",
".",
"blank?",
"self",
".",
"update_attribute",
"(",
"\"#{lang}_status\"",
",",
"UNTRANSLATED",
")",
"elsif",
"!",
"self",
".",
"translations",
".",
"in",
"(",
"lang",
")",
".",
"accepted",
".",
"blank?",
"self",
".",
"update_attribute",
"(",
"\"#{lang}_status\"",
",",
"TRANSLATED",
")",
"else",
"self",
".",
"update_attribute",
"(",
"\"#{lang}_status\"",
",",
"PENDING",
")",
"end",
"end"
]
| updates the status of the translation key depending on the translations | [
"updates",
"the",
"status",
"of",
"the",
"translation",
"key",
"depending",
"on",
"the",
"translations"
]
| 439cbf70323e629a630fe939d02b44361afae13e | https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/translation_key.rb#L37-L45 | train |
BadrIT/translation_center | app/models/translation_center/translation_key.rb | TranslationCenter.TranslationKey.create_default_translation | def create_default_translation
translation = self.translations.build(value: self.name.to_s.split('.').last.titleize,
lang: :en, status: 'accepted')
translation.translator = TranslationCenter.prepare_translator
translation.save
end | ruby | def create_default_translation
translation = self.translations.build(value: self.name.to_s.split('.').last.titleize,
lang: :en, status: 'accepted')
translation.translator = TranslationCenter.prepare_translator
translation.save
end | [
"def",
"create_default_translation",
"translation",
"=",
"self",
".",
"translations",
".",
"build",
"(",
"value",
":",
"self",
".",
"name",
".",
"to_s",
".",
"split",
"(",
"'.'",
")",
".",
"last",
".",
"titleize",
",",
"lang",
":",
":en",
",",
"status",
":",
"'accepted'",
")",
"translation",
".",
"translator",
"=",
"TranslationCenter",
".",
"prepare_translator",
"translation",
".",
"save",
"end"
]
| create default translation | [
"create",
"default",
"translation"
]
| 439cbf70323e629a630fe939d02b44361afae13e | https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/translation_key.rb#L86-L92 | train |
BadrIT/translation_center | app/models/translation_center/translation_key.rb | TranslationCenter.TranslationKey.add_to_hash | def add_to_hash(all_translations, lang)
levels = self.name.split('.')
add_to_hash_rec(all_translations, levels, lang.to_s)
end | ruby | def add_to_hash(all_translations, lang)
levels = self.name.split('.')
add_to_hash_rec(all_translations, levels, lang.to_s)
end | [
"def",
"add_to_hash",
"(",
"all_translations",
",",
"lang",
")",
"levels",
"=",
"self",
".",
"name",
".",
"split",
"(",
"'.'",
")",
"add_to_hash_rec",
"(",
"all_translations",
",",
"levels",
",",
"lang",
".",
"to_s",
")",
"end"
]
| adds a translation key with its translation to a translation yaml hash
send the hash and the language as parameters | [
"adds",
"a",
"translation",
"key",
"with",
"its",
"translation",
"to",
"a",
"translation",
"yaml",
"hash",
"send",
"the",
"hash",
"and",
"the",
"language",
"as",
"parameters"
]
| 439cbf70323e629a630fe939d02b44361afae13e | https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/translation_key.rb#L164-L167 | train |
beatrichartz/exchange | lib/exchange/typecasting.rb | Exchange.Typecasting.money | def money *attributes
options = attributes.last.is_a?(Hash) ? attributes.pop : {}
attributes.each do |attribute|
# Get the attribute typecasted into money
# @return [Exchange::Money] an instance of money
#
install_money_getter attribute, options
# Set the attribute either with money or just any data
# Implicitly converts values given that are not in the same currency as the currency option evaluates to
# @param [Exchange::Money, String, Numberic] data The data to set the attribute to
#
install_money_setter attribute, options
end
# Evaluates options given either as symbols or as procs
# @param [Symbol, Proc] option The option to evaluate
#
install_money_option_eval
# Evaluates whether an error should be raised because there is no currency present
# @param [Symbol] currency The currency, if given
#
install_currency_error_tester
end | ruby | def money *attributes
options = attributes.last.is_a?(Hash) ? attributes.pop : {}
attributes.each do |attribute|
# Get the attribute typecasted into money
# @return [Exchange::Money] an instance of money
#
install_money_getter attribute, options
# Set the attribute either with money or just any data
# Implicitly converts values given that are not in the same currency as the currency option evaluates to
# @param [Exchange::Money, String, Numberic] data The data to set the attribute to
#
install_money_setter attribute, options
end
# Evaluates options given either as symbols or as procs
# @param [Symbol, Proc] option The option to evaluate
#
install_money_option_eval
# Evaluates whether an error should be raised because there is no currency present
# @param [Symbol] currency The currency, if given
#
install_currency_error_tester
end | [
"def",
"money",
"*",
"attributes",
"options",
"=",
"attributes",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"attributes",
".",
"pop",
":",
"{",
"}",
"attributes",
".",
"each",
"do",
"|",
"attribute",
"|",
"install_money_getter",
"attribute",
",",
"options",
"install_money_setter",
"attribute",
",",
"options",
"end",
"install_money_option_eval",
"install_currency_error_tester",
"end"
]
| installs a setter and a getter for the attribute you want to typecast as exchange money
@overload def money(*attributes, options={})
@param [Symbol] attributes The attributes you want to typecast as money.
@param [Hash] options Pass a hash as last argument as options
@option options [Symbol, Proc] :currency The currency to evaluate the money with. Can be a symbol or a proc
@option options [Symbol, Proc] :at The time at which the currency should be casted. All conversions of this currency will take place at this time
@raise [NoCurrencyError] if no currency option is given or the currency evals to nil
@example configure money with symbols, the currency option here will call the method currency in the object context
money :price, :currency => :currency, :time => :created_at
@example configure money with a proc, the proc will be called with the object as an argument. This is equivalent to the example above
money :price, :currency => lambda {|o| o.currency}, :time => lambda{|o| o.created_at} | [
"installs",
"a",
"setter",
"and",
"a",
"getter",
"for",
"the",
"attribute",
"you",
"want",
"to",
"typecast",
"as",
"exchange",
"money"
]
| 4318b9dad3cce5e933827126160fafe30c68dc2a | https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/typecasting.rb#L135-L163 | train |
akarzim/capybara-bootstrap-datepicker | lib/capybara-bootstrap-datepicker.rb | Capybara.BootstrapDatepicker.select_date | def select_date(value, datepicker: :bootstrap, format: nil, from: nil, xpath: nil, **args)
fail "Must pass a hash containing 'from' or 'xpath'" if from.nil? && xpath.nil?
value = value.respond_to?(:to_date) ? value.to_date : Date.parse(value)
date_input = xpath ? find(:xpath, xpath, **args) : find_field(from, **args)
case datepicker
when :bootstrap
select_bootstrap_date date_input, value
else
select_simple_date date_input, value, format
end
first(:xpath, '//body').click
end | ruby | def select_date(value, datepicker: :bootstrap, format: nil, from: nil, xpath: nil, **args)
fail "Must pass a hash containing 'from' or 'xpath'" if from.nil? && xpath.nil?
value = value.respond_to?(:to_date) ? value.to_date : Date.parse(value)
date_input = xpath ? find(:xpath, xpath, **args) : find_field(from, **args)
case datepicker
when :bootstrap
select_bootstrap_date date_input, value
else
select_simple_date date_input, value, format
end
first(:xpath, '//body').click
end | [
"def",
"select_date",
"(",
"value",
",",
"datepicker",
":",
":bootstrap",
",",
"format",
":",
"nil",
",",
"from",
":",
"nil",
",",
"xpath",
":",
"nil",
",",
"**",
"args",
")",
"fail",
"\"Must pass a hash containing 'from' or 'xpath'\"",
"if",
"from",
".",
"nil?",
"&&",
"xpath",
".",
"nil?",
"value",
"=",
"value",
".",
"respond_to?",
"(",
":to_date",
")",
"?",
"value",
".",
"to_date",
":",
"Date",
".",
"parse",
"(",
"value",
")",
"date_input",
"=",
"xpath",
"?",
"find",
"(",
":xpath",
",",
"xpath",
",",
"**",
"args",
")",
":",
"find_field",
"(",
"from",
",",
"**",
"args",
")",
"case",
"datepicker",
"when",
":bootstrap",
"select_bootstrap_date",
"date_input",
",",
"value",
"else",
"select_simple_date",
"date_input",
",",
"value",
",",
"format",
"end",
"first",
"(",
":xpath",
",",
"'//body'",
")",
".",
"click",
"end"
]
| Selects a date by simulating human interaction with the datepicker or filling the input field
@param value [#to_date, String] any object that responds to `#to_date` or a parsable date string
@param datepicker [:bootstrap, :simple] the datepicker to use (are supported: bootstrap or input field)
@param format [String, nil] a valid date format used to format value
@param from [String, nil] the path to input field (required if `xpath` is nil)
@param xpath [String, nil] the xpath to input field (required if `from` is nil)
@param args [Hash] extra args to find the input field | [
"Selects",
"a",
"date",
"by",
"simulating",
"human",
"interaction",
"with",
"the",
"datepicker",
"or",
"filling",
"the",
"input",
"field"
]
| fb2349436a8ca31337936e8b8f9a89998f9e38b1 | https://github.com/akarzim/capybara-bootstrap-datepicker/blob/fb2349436a8ca31337936e8b8f9a89998f9e38b1/lib/capybara-bootstrap-datepicker.rb#L13-L27 | train |
akarzim/capybara-bootstrap-datepicker | lib/capybara-bootstrap-datepicker.rb | Capybara.BootstrapDatepicker.select_simple_date | def select_simple_date(date_input, value, format = nil)
value = value.strftime format unless format.nil?
date_input.set "#{value}\e"
end | ruby | def select_simple_date(date_input, value, format = nil)
value = value.strftime format unless format.nil?
date_input.set "#{value}\e"
end | [
"def",
"select_simple_date",
"(",
"date_input",
",",
"value",
",",
"format",
"=",
"nil",
")",
"value",
"=",
"value",
".",
"strftime",
"format",
"unless",
"format",
".",
"nil?",
"date_input",
".",
"set",
"\"#{value}\\e\"",
"end"
]
| Selects a date by filling the input field
@param date_input the input field
@param value [Date] the date to set
@param format [String, nil] a valid date format used to format value | [
"Selects",
"a",
"date",
"by",
"filling",
"the",
"input",
"field"
]
| fb2349436a8ca31337936e8b8f9a89998f9e38b1 | https://github.com/akarzim/capybara-bootstrap-datepicker/blob/fb2349436a8ca31337936e8b8f9a89998f9e38b1/lib/capybara-bootstrap-datepicker.rb#L33-L37 | train |
akarzim/capybara-bootstrap-datepicker | lib/capybara-bootstrap-datepicker.rb | Capybara.BootstrapDatepicker.select_bootstrap_date | def select_bootstrap_date(date_input, value)
date_input.click
picker = Picker.new
picker.goto_decade_panel
picker.navigate_through_decades value.year
picker.find_year(value.year).click
picker.find_month(value.month).click
picker.find_day(value.day).click
fail if Date.parse(date_input.value) != value
end | ruby | def select_bootstrap_date(date_input, value)
date_input.click
picker = Picker.new
picker.goto_decade_panel
picker.navigate_through_decades value.year
picker.find_year(value.year).click
picker.find_month(value.month).click
picker.find_day(value.day).click
fail if Date.parse(date_input.value) != value
end | [
"def",
"select_bootstrap_date",
"(",
"date_input",
",",
"value",
")",
"date_input",
".",
"click",
"picker",
"=",
"Picker",
".",
"new",
"picker",
".",
"goto_decade_panel",
"picker",
".",
"navigate_through_decades",
"value",
".",
"year",
"picker",
".",
"find_year",
"(",
"value",
".",
"year",
")",
".",
"click",
"picker",
".",
"find_month",
"(",
"value",
".",
"month",
")",
".",
"click",
"picker",
".",
"find_day",
"(",
"value",
".",
"day",
")",
".",
"click",
"fail",
"if",
"Date",
".",
"parse",
"(",
"date_input",
".",
"value",
")",
"!=",
"value",
"end"
]
| Selects a date by simulating human interaction with the datepicker
@param (see #select_simple_date) | [
"Selects",
"a",
"date",
"by",
"simulating",
"human",
"interaction",
"with",
"the",
"datepicker"
]
| fb2349436a8ca31337936e8b8f9a89998f9e38b1 | https://github.com/akarzim/capybara-bootstrap-datepicker/blob/fb2349436a8ca31337936e8b8f9a89998f9e38b1/lib/capybara-bootstrap-datepicker.rb#L41-L54 | train |
beatrichartz/exchange | lib/exchange/configurable.rb | Exchange.Configurable.subclass_with_constantize | def subclass_with_constantize
self.subclass = parent_module.const_get camelize(self.subclass_without_constantize) unless !self.subclass_without_constantize || self.subclass_without_constantize.is_a?(Class)
subclass_without_constantize
end | ruby | def subclass_with_constantize
self.subclass = parent_module.const_get camelize(self.subclass_without_constantize) unless !self.subclass_without_constantize || self.subclass_without_constantize.is_a?(Class)
subclass_without_constantize
end | [
"def",
"subclass_with_constantize",
"self",
".",
"subclass",
"=",
"parent_module",
".",
"const_get",
"camelize",
"(",
"self",
".",
"subclass_without_constantize",
")",
"unless",
"!",
"self",
".",
"subclass_without_constantize",
"||",
"self",
".",
"subclass_without_constantize",
".",
"is_a?",
"(",
"Class",
")",
"subclass_without_constantize",
"end"
]
| Alias method chain to instantiate the subclass from a symbol should it not be a class
@return [NilClass, Class] The subclass or nil | [
"Alias",
"method",
"chain",
"to",
"instantiate",
"the",
"subclass",
"from",
"a",
"symbol",
"should",
"it",
"not",
"be",
"a",
"class"
]
| 4318b9dad3cce5e933827126160fafe30c68dc2a | https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/configurable.rb#L18-L21 | train |
beatrichartz/exchange | lib/exchange/iso.rb | Exchange.ISO.assert_currency! | def assert_currency! arg
defines?(arg) ? (country_map[arg] || arg) : raise(Exchange::NoCurrencyError.new("#{arg} is not a currency nor a country code matchable to a currency"))
end | ruby | def assert_currency! arg
defines?(arg) ? (country_map[arg] || arg) : raise(Exchange::NoCurrencyError.new("#{arg} is not a currency nor a country code matchable to a currency"))
end | [
"def",
"assert_currency!",
"arg",
"defines?",
"(",
"arg",
")",
"?",
"(",
"country_map",
"[",
"arg",
"]",
"||",
"arg",
")",
":",
"raise",
"(",
"Exchange",
"::",
"NoCurrencyError",
".",
"new",
"(",
"\"#{arg} is not a currency nor a country code matchable to a currency\"",
")",
")",
"end"
]
| Asserts a given argument is a currency. Tries to match with a country code if the argument is not a currency
@param [Symbol, String] arg The argument to assert
@return [Symbol] The matching currency as a symbol | [
"Asserts",
"a",
"given",
"argument",
"is",
"a",
"currency",
".",
"Tries",
"to",
"match",
"with",
"a",
"country",
"code",
"if",
"the",
"argument",
"is",
"not",
"a",
"currency"
]
| 4318b9dad3cce5e933827126160fafe30c68dc2a | https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/iso.rb#L77-L79 | train |
beatrichartz/exchange | lib/exchange/iso.rb | Exchange.ISO.instantiate | def instantiate amount, currency
if amount.is_a?(BigDecimal)
amount
else
BigDecimal.new(amount.to_s, precision_for(amount, currency))
end
end | ruby | def instantiate amount, currency
if amount.is_a?(BigDecimal)
amount
else
BigDecimal.new(amount.to_s, precision_for(amount, currency))
end
end | [
"def",
"instantiate",
"amount",
",",
"currency",
"if",
"amount",
".",
"is_a?",
"(",
"BigDecimal",
")",
"amount",
"else",
"BigDecimal",
".",
"new",
"(",
"amount",
".",
"to_s",
",",
"precision_for",
"(",
"amount",
",",
"currency",
")",
")",
"end",
"end"
]
| Use this to instantiate a currency amount. For one, it is important that we use BigDecimal here so nothing gets lost because
of floating point errors. For the other, This allows us to set the precision exactly according to the iso definition
@param [BigDecimal, Fixed, Float, String] amount The amount of money you want to instantiate
@param [String, Symbol] currency The currency you want to instantiate the money in
@return [BigDecimal] The instantiated currency
@example instantiate a currency from a string
Exchange::ISO.instantiate("4523", "usd") #=> #<Bigdecimal 4523.00>
@note Reinstantiation is not needed in case the amount is already a big decimal. In this case, the maximum precision is already given. | [
"Use",
"this",
"to",
"instantiate",
"a",
"currency",
"amount",
".",
"For",
"one",
"it",
"is",
"important",
"that",
"we",
"use",
"BigDecimal",
"here",
"so",
"nothing",
"gets",
"lost",
"because",
"of",
"floating",
"point",
"errors",
".",
"For",
"the",
"other",
"This",
"allows",
"us",
"to",
"set",
"the",
"precision",
"exactly",
"according",
"to",
"the",
"iso",
"definition"
]
| 4318b9dad3cce5e933827126160fafe30c68dc2a | https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/iso.rb#L90-L96 | train |
beatrichartz/exchange | lib/exchange/iso.rb | Exchange.ISO.stringify | def stringify amount, currency, opts={}
definition = definitions[currency]
separators = definition[:separators] || {}
format = "%.#{definition[:minor_unit]}f"
string = format % amount
major, minor = string.split('.')
major.gsub!(/(\d)(?=(\d\d\d)+(?!\d))/) { $1 + separators[:major] } if separators[:major] && opts[:format] != :plain
string = minor ? major + (opts[:format] == :plain || !separators[:minor] ? '.' : separators[:minor]) + minor : major
pre = [[:amount, :plain].include?(opts[:format]) && '', opts[:format] == :symbol && definition[:symbol], currency.to_s.upcase + ' '].detect{|a| a.is_a?(String)}
"#{pre}#{string}"
end | ruby | def stringify amount, currency, opts={}
definition = definitions[currency]
separators = definition[:separators] || {}
format = "%.#{definition[:minor_unit]}f"
string = format % amount
major, minor = string.split('.')
major.gsub!(/(\d)(?=(\d\d\d)+(?!\d))/) { $1 + separators[:major] } if separators[:major] && opts[:format] != :plain
string = minor ? major + (opts[:format] == :plain || !separators[:minor] ? '.' : separators[:minor]) + minor : major
pre = [[:amount, :plain].include?(opts[:format]) && '', opts[:format] == :symbol && definition[:symbol], currency.to_s.upcase + ' '].detect{|a| a.is_a?(String)}
"#{pre}#{string}"
end | [
"def",
"stringify",
"amount",
",",
"currency",
",",
"opts",
"=",
"{",
"}",
"definition",
"=",
"definitions",
"[",
"currency",
"]",
"separators",
"=",
"definition",
"[",
":separators",
"]",
"||",
"{",
"}",
"format",
"=",
"\"%.#{definition[:minor_unit]}f\"",
"string",
"=",
"format",
"%",
"amount",
"major",
",",
"minor",
"=",
"string",
".",
"split",
"(",
"'.'",
")",
"major",
".",
"gsub!",
"(",
"/",
"\\d",
"\\d",
"\\d",
"\\d",
"\\d",
"/",
")",
"{",
"$1",
"+",
"separators",
"[",
":major",
"]",
"}",
"if",
"separators",
"[",
":major",
"]",
"&&",
"opts",
"[",
":format",
"]",
"!=",
":plain",
"string",
"=",
"minor",
"?",
"major",
"+",
"(",
"opts",
"[",
":format",
"]",
"==",
":plain",
"||",
"!",
"separators",
"[",
":minor",
"]",
"?",
"'.'",
":",
"separators",
"[",
":minor",
"]",
")",
"+",
"minor",
":",
"major",
"pre",
"=",
"[",
"[",
":amount",
",",
":plain",
"]",
".",
"include?",
"(",
"opts",
"[",
":format",
"]",
")",
"&&",
"''",
",",
"opts",
"[",
":format",
"]",
"==",
":symbol",
"&&",
"definition",
"[",
":symbol",
"]",
",",
"currency",
".",
"to_s",
".",
"upcase",
"+",
"' '",
"]",
".",
"detect",
"{",
"|",
"a",
"|",
"a",
".",
"is_a?",
"(",
"String",
")",
"}",
"\"#{pre}#{string}\"",
"end"
]
| Converts the currency to a string in ISO 4217 standardized format, either with or without the currency. This leaves you
with no worries how to display the currency.
@param [BigDecimal, Fixed, Float] amount The amount of currency you want to stringify
@param [String, Symbol] currency The currency you want to stringify
@param [Hash] opts The options for formatting
@option opts [Boolean] :format The format to put the string out in: :amount for only the amount, :symbol for a string with a currency symbol
@return [String] The formatted string
@example Convert a currency to a string
Exchange::ISO.stringify(49.567, :usd) #=> "USD 49.57"
@example Convert a currency without minor to a string
Exchange::ISO.stringif(45, :jpy) #=> "JPY 45"
@example Convert a currency with a three decimal minor to a string
Exchange::ISO.stringif(34.34, :omr) #=> "OMR 34.340"
@example Convert a currency to a string without the currency
Exchange::ISO.stringif(34.34, :omr, :amount_only => true) #=> "34.340" | [
"Converts",
"the",
"currency",
"to",
"a",
"string",
"in",
"ISO",
"4217",
"standardized",
"format",
"either",
"with",
"or",
"without",
"the",
"currency",
".",
"This",
"leaves",
"you",
"with",
"no",
"worries",
"how",
"to",
"display",
"the",
"currency",
"."
]
| 4318b9dad3cce5e933827126160fafe30c68dc2a | https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/iso.rb#L114-L127 | train |
beatrichartz/exchange | lib/exchange/iso.rb | Exchange.ISO.symbolize_keys | def symbolize_keys hsh
new_hsh = Hash.new
hsh.each_pair do |k,v|
v = symbolize_keys v if v.is_a?(Hash)
new_hsh[k.downcase.to_sym] = v
end
new_hsh
end | ruby | def symbolize_keys hsh
new_hsh = Hash.new
hsh.each_pair do |k,v|
v = symbolize_keys v if v.is_a?(Hash)
new_hsh[k.downcase.to_sym] = v
end
new_hsh
end | [
"def",
"symbolize_keys",
"hsh",
"new_hsh",
"=",
"Hash",
".",
"new",
"hsh",
".",
"each_pair",
"do",
"|",
"k",
",",
"v",
"|",
"v",
"=",
"symbolize_keys",
"v",
"if",
"v",
".",
"is_a?",
"(",
"Hash",
")",
"new_hsh",
"[",
"k",
".",
"downcase",
".",
"to_sym",
"]",
"=",
"v",
"end",
"new_hsh",
"end"
]
| symbolizes keys and returns a new hash | [
"symbolizes",
"keys",
"and",
"returns",
"a",
"new",
"hash"
]
| 4318b9dad3cce5e933827126160fafe30c68dc2a | https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/iso.rb#L172-L181 | train |
beatrichartz/exchange | lib/exchange/iso.rb | Exchange.ISO.precision_for | def precision_for amount, currency
defined_minor_precision = definitions[currency][:minor_unit]
match = amount.to_s.match(/^-?(\d*)\.?(\d*)e?(-?\d+)?$/).to_a[1..3]
given_major_precision, given_minor_precision = precision_from_match *match
given_major_precision + [defined_minor_precision, given_minor_precision].max
end | ruby | def precision_for amount, currency
defined_minor_precision = definitions[currency][:minor_unit]
match = amount.to_s.match(/^-?(\d*)\.?(\d*)e?(-?\d+)?$/).to_a[1..3]
given_major_precision, given_minor_precision = precision_from_match *match
given_major_precision + [defined_minor_precision, given_minor_precision].max
end | [
"def",
"precision_for",
"amount",
",",
"currency",
"defined_minor_precision",
"=",
"definitions",
"[",
"currency",
"]",
"[",
":minor_unit",
"]",
"match",
"=",
"amount",
".",
"to_s",
".",
"match",
"(",
"/",
"\\d",
"\\.",
"\\d",
"\\d",
"/",
")",
".",
"to_a",
"[",
"1",
"..",
"3",
"]",
"given_major_precision",
",",
"given_minor_precision",
"=",
"precision_from_match",
"*",
"match",
"given_major_precision",
"+",
"[",
"defined_minor_precision",
",",
"given_minor_precision",
"]",
".",
"max",
"end"
]
| get a precision for a specified amount and a specified currency
@params [Float, Integer] amount The amount to get the precision for
@params [Symbol] currency the currency to get the precision for | [
"get",
"a",
"precision",
"for",
"a",
"specified",
"amount",
"and",
"a",
"specified",
"currency"
]
| 4318b9dad3cce5e933827126160fafe30c68dc2a | https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/iso.rb#L188-L194 | train |
BadrIT/translation_center | lib/translation_center/acts_as_translator.rb | ActsAsTranslator.InstanceMethods.translation_for | def translation_for(key, lang)
self.translations.find_or_initialize_by(translation_key_id: key.id, lang: lang.to_s, translator_type: self.class.name)
end | ruby | def translation_for(key, lang)
self.translations.find_or_initialize_by(translation_key_id: key.id, lang: lang.to_s, translator_type: self.class.name)
end | [
"def",
"translation_for",
"(",
"key",
",",
"lang",
")",
"self",
".",
"translations",
".",
"find_or_initialize_by",
"(",
"translation_key_id",
":",
"key",
".",
"id",
",",
"lang",
":",
"lang",
".",
"to_s",
",",
"translator_type",
":",
"self",
".",
"class",
".",
"name",
")",
"end"
]
| returns the translation a user has made for a certain key in a certain language | [
"returns",
"the",
"translation",
"a",
"user",
"has",
"made",
"for",
"a",
"certain",
"key",
"in",
"a",
"certain",
"language"
]
| 439cbf70323e629a630fe939d02b44361afae13e | https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/lib/translation_center/acts_as_translator.rb#L11-L13 | train |
BadrIT/translation_center | app/models/translation_center/category.rb | TranslationCenter.Category.complete_percentage_in | def complete_percentage_in(lang)
if self.keys.blank?
100
else
accepted_keys = accepted_keys(lang)
100 * accepted_keys.count / self.keys.count
end
end | ruby | def complete_percentage_in(lang)
if self.keys.blank?
100
else
accepted_keys = accepted_keys(lang)
100 * accepted_keys.count / self.keys.count
end
end | [
"def",
"complete_percentage_in",
"(",
"lang",
")",
"if",
"self",
".",
"keys",
".",
"blank?",
"100",
"else",
"accepted_keys",
"=",
"accepted_keys",
"(",
"lang",
")",
"100",
"*",
"accepted_keys",
".",
"count",
"/",
"self",
".",
"keys",
".",
"count",
"end",
"end"
]
| gets how much complete translation of category is in a certain language | [
"gets",
"how",
"much",
"complete",
"translation",
"of",
"category",
"is",
"in",
"a",
"certain",
"language"
]
| 439cbf70323e629a630fe939d02b44361afae13e | https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/category.rb#L12-L19 | train |
beatrichartz/exchange | lib/exchange/money.rb | Exchange.Money.to | def to other, options={}
other = ISO.assert_currency!(other)
if api_supports_currency?(currency) && api_supports_currency?(other)
opts = { :at => time, :from => self }.merge(options)
Money.new(api.new.convert(value, currency, other, opts), other, opts)
elsif fallback!
to other, options
else
raise_no_rate_error(other)
end
rescue ExternalAPI::APIError
if fallback!
to other, options
else
raise
end
end | ruby | def to other, options={}
other = ISO.assert_currency!(other)
if api_supports_currency?(currency) && api_supports_currency?(other)
opts = { :at => time, :from => self }.merge(options)
Money.new(api.new.convert(value, currency, other, opts), other, opts)
elsif fallback!
to other, options
else
raise_no_rate_error(other)
end
rescue ExternalAPI::APIError
if fallback!
to other, options
else
raise
end
end | [
"def",
"to",
"other",
",",
"options",
"=",
"{",
"}",
"other",
"=",
"ISO",
".",
"assert_currency!",
"(",
"other",
")",
"if",
"api_supports_currency?",
"(",
"currency",
")",
"&&",
"api_supports_currency?",
"(",
"other",
")",
"opts",
"=",
"{",
":at",
"=>",
"time",
",",
":from",
"=>",
"self",
"}",
".",
"merge",
"(",
"options",
")",
"Money",
".",
"new",
"(",
"api",
".",
"new",
".",
"convert",
"(",
"value",
",",
"currency",
",",
"other",
",",
"opts",
")",
",",
"other",
",",
"opts",
")",
"elsif",
"fallback!",
"to",
"other",
",",
"options",
"else",
"raise_no_rate_error",
"(",
"other",
")",
"end",
"rescue",
"ExternalAPI",
"::",
"APIError",
"if",
"fallback!",
"to",
"other",
",",
"options",
"else",
"raise",
"end",
"end"
]
| Converts this instance of currency into another currency
@return [Exchange::Money] An instance of Exchange::Money with the converted number and the converted currency
@param [Symbol, String] other The currency to convert the number to
@param [Hash] options An options hash
@option [Time] :at The timestamp of the rate the conversion took place in
@example convert to 'chf'
Exchange::Money.new(40,:usd).to(:chf)
@example convert to 'sek' at a specific rate
Exchange::Money.new(40,:nok).to(:sek, :at => Time.gm(2012,2,2)) | [
"Converts",
"this",
"instance",
"of",
"currency",
"into",
"another",
"currency"
]
| 4318b9dad3cce5e933827126160fafe30c68dc2a | https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/money.rb#L86-L103 | train |
beatrichartz/exchange | lib/exchange/money.rb | Exchange.Money.fallback! | def fallback!
fallback = Exchange.configuration.api.fallback
new_api = fallback.index(api) ? fallback[fallback.index(api) + 1] : fallback.first
if new_api
@api = new_api
return true
end
return false
end | ruby | def fallback!
fallback = Exchange.configuration.api.fallback
new_api = fallback.index(api) ? fallback[fallback.index(api) + 1] : fallback.first
if new_api
@api = new_api
return true
end
return false
end | [
"def",
"fallback!",
"fallback",
"=",
"Exchange",
".",
"configuration",
".",
"api",
".",
"fallback",
"new_api",
"=",
"fallback",
".",
"index",
"(",
"api",
")",
"?",
"fallback",
"[",
"fallback",
".",
"index",
"(",
"api",
")",
"+",
"1",
"]",
":",
"fallback",
".",
"first",
"if",
"new_api",
"@api",
"=",
"new_api",
"return",
"true",
"end",
"return",
"false",
"end"
]
| Fallback to the next api defined in the api fallbacks. Changes the api for the given instance
@return [Boolean] true if the fallback was successful, false if not
@since 1.0
@version 1.0 | [
"Fallback",
"to",
"the",
"next",
"api",
"defined",
"in",
"the",
"api",
"fallbacks",
".",
"Changes",
"the",
"api",
"for",
"the",
"given",
"instance"
]
| 4318b9dad3cce5e933827126160fafe30c68dc2a | https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/money.rb#L334-L344 | train |
BadrIT/translation_center | app/models/translation_center/translation.rb | TranslationCenter.Translation.accept | def accept
# If translation is accepted do nothing
unless self.accepted?
self.translation_key.accepted_translation_in(self.lang)
.try(:update_attribute, :status, TranslationKey::PENDING)
# reload the translation key as it has changed
self.translation_key.reload
self.update_attribute(:status, ACCEPTED)
end
end | ruby | def accept
# If translation is accepted do nothing
unless self.accepted?
self.translation_key.accepted_translation_in(self.lang)
.try(:update_attribute, :status, TranslationKey::PENDING)
# reload the translation key as it has changed
self.translation_key.reload
self.update_attribute(:status, ACCEPTED)
end
end | [
"def",
"accept",
"unless",
"self",
".",
"accepted?",
"self",
".",
"translation_key",
".",
"accepted_translation_in",
"(",
"self",
".",
"lang",
")",
".",
"try",
"(",
":update_attribute",
",",
":status",
",",
"TranslationKey",
"::",
"PENDING",
")",
"self",
".",
"translation_key",
".",
"reload",
"self",
".",
"update_attribute",
"(",
":status",
",",
"ACCEPTED",
")",
"end",
"end"
]
| Accept translation by changing its status and if there is an accepting translation
make it pending | [
"Accept",
"translation",
"by",
"changing",
"its",
"status",
"and",
"if",
"there",
"is",
"an",
"accepting",
"translation",
"make",
"it",
"pending"
]
| 439cbf70323e629a630fe939d02b44361afae13e | https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/translation.rb#L71-L81 | train |
BadrIT/translation_center | app/models/translation_center/translation.rb | TranslationCenter.Translation.one_translation_per_lang_per_key | def one_translation_per_lang_per_key
translation_exists = Translation.exists?(
lang: self.lang,
translator_id: self.translator.id,
translator_type: self.translator.class.name,
translation_key_id: self.key.id
)
unless translation_exists
true
else
false
self.errors.add(:lang, I18n.t('.one_translation_per_lang_per_key'))
end
end | ruby | def one_translation_per_lang_per_key
translation_exists = Translation.exists?(
lang: self.lang,
translator_id: self.translator.id,
translator_type: self.translator.class.name,
translation_key_id: self.key.id
)
unless translation_exists
true
else
false
self.errors.add(:lang, I18n.t('.one_translation_per_lang_per_key'))
end
end | [
"def",
"one_translation_per_lang_per_key",
"translation_exists",
"=",
"Translation",
".",
"exists?",
"(",
"lang",
":",
"self",
".",
"lang",
",",
"translator_id",
":",
"self",
".",
"translator",
".",
"id",
",",
"translator_type",
":",
"self",
".",
"translator",
".",
"class",
".",
"name",
",",
"translation_key_id",
":",
"self",
".",
"key",
".",
"id",
")",
"unless",
"translation_exists",
"true",
"else",
"false",
"self",
".",
"errors",
".",
"add",
"(",
":lang",
",",
"I18n",
".",
"t",
"(",
"'.one_translation_per_lang_per_key'",
")",
")",
"end",
"end"
]
| make sure user has one translation per key per lang | [
"make",
"sure",
"user",
"has",
"one",
"translation",
"per",
"key",
"per",
"lang"
]
| 439cbf70323e629a630fe939d02b44361afae13e | https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/translation.rb#L89-L103 | train |
vigetlabs/pointless-feedback | app/helpers/pointless_feedback/application_helper.rb | PointlessFeedback.ApplicationHelper.method_missing | def method_missing(method, *args, &block)
if main_app_url_helper?(method)
main_app.send(method, *args)
else
super
end
end | ruby | def method_missing(method, *args, &block)
if main_app_url_helper?(method)
main_app.send(method, *args)
else
super
end
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"main_app_url_helper?",
"(",
"method",
")",
"main_app",
".",
"send",
"(",
"method",
",",
"*",
"args",
")",
"else",
"super",
"end",
"end"
]
| Can search for named routes directly in the main app, omitting
the "main_app." prefix | [
"Can",
"search",
"for",
"named",
"routes",
"directly",
"in",
"the",
"main",
"app",
"omitting",
"the",
"main_app",
".",
"prefix"
]
| be7ca04bf51a46ca9a1db6710665857d0e21fcc8 | https://github.com/vigetlabs/pointless-feedback/blob/be7ca04bf51a46ca9a1db6710665857d0e21fcc8/app/helpers/pointless_feedback/application_helper.rb#L7-L13 | train |
change/aws-swf | lib/swf/decision_task_handler.rb | SWF.DecisionTaskHandler.tags | def tags
runner.tag_lists[decision_task.workflow_execution] ||= begin
collision = 0
begin
decision_task.workflow_execution.tags
rescue => e
collision += 1 if collision < 10
max_slot_delay = 2**collision - 1
sleep(slot_time * rand(0 .. max_slot_delay))
retry
end
end
end | ruby | def tags
runner.tag_lists[decision_task.workflow_execution] ||= begin
collision = 0
begin
decision_task.workflow_execution.tags
rescue => e
collision += 1 if collision < 10
max_slot_delay = 2**collision - 1
sleep(slot_time * rand(0 .. max_slot_delay))
retry
end
end
end | [
"def",
"tags",
"runner",
".",
"tag_lists",
"[",
"decision_task",
".",
"workflow_execution",
"]",
"||=",
"begin",
"collision",
"=",
"0",
"begin",
"decision_task",
".",
"workflow_execution",
".",
"tags",
"rescue",
"=>",
"e",
"collision",
"+=",
"1",
"if",
"collision",
"<",
"10",
"max_slot_delay",
"=",
"2",
"**",
"collision",
"-",
"1",
"sleep",
"(",
"slot_time",
"*",
"rand",
"(",
"0",
"..",
"max_slot_delay",
")",
")",
"retry",
"end",
"end",
"end"
]
| exponential backoff handles rate limiting exceptions
when querying tags on a workflow execution. | [
"exponential",
"backoff",
"handles",
"rate",
"limiting",
"exceptions",
"when",
"querying",
"tags",
"on",
"a",
"workflow",
"execution",
"."
]
| a025d5b1009371f48c9386b8a717e2e54738094d | https://github.com/change/aws-swf/blob/a025d5b1009371f48c9386b8a717e2e54738094d/lib/swf/decision_task_handler.rb#L70-L82 | train |
damianFC/alexa-rubykit | lib/alexa_rubykit/response.rb | AlexaRubykit.Response.say_response | def say_response(speech, end_session = true, ssml = false)
output_speech = add_speech(speech,ssml)
{ :outputSpeech => output_speech, :shouldEndSession => end_session }
end | ruby | def say_response(speech, end_session = true, ssml = false)
output_speech = add_speech(speech,ssml)
{ :outputSpeech => output_speech, :shouldEndSession => end_session }
end | [
"def",
"say_response",
"(",
"speech",
",",
"end_session",
"=",
"true",
",",
"ssml",
"=",
"false",
")",
"output_speech",
"=",
"add_speech",
"(",
"speech",
",",
"ssml",
")",
"{",
":outputSpeech",
"=>",
"output_speech",
",",
":shouldEndSession",
"=>",
"end_session",
"}",
"end"
]
| Adds a speech to the object, also returns a outputspeech object. | [
"Adds",
"a",
"speech",
"to",
"the",
"object",
"also",
"returns",
"a",
"outputspeech",
"object",
"."
]
| 06c9506b20adbd6fb0f37d6a1df223e1d8469338 | https://github.com/damianFC/alexa-rubykit/blob/06c9506b20adbd6fb0f37d6a1df223e1d8469338/lib/alexa_rubykit/response.rb#L104-L107 | train |
damianFC/alexa-rubykit | lib/alexa_rubykit/response.rb | AlexaRubykit.Response.say_response_with_reprompt | def say_response_with_reprompt(speech, reprompt_speech, end_session = true, speech_ssml = false, reprompt_ssml = false)
output_speech = add_speech(speech,speech_ssml)
reprompt_speech = add_reprompt(reprompt_speech,reprompt_ssml)
{ :outputSpeech => output_speech, :reprompt => reprompt_speech, :shouldEndSession => end_session }
end | ruby | def say_response_with_reprompt(speech, reprompt_speech, end_session = true, speech_ssml = false, reprompt_ssml = false)
output_speech = add_speech(speech,speech_ssml)
reprompt_speech = add_reprompt(reprompt_speech,reprompt_ssml)
{ :outputSpeech => output_speech, :reprompt => reprompt_speech, :shouldEndSession => end_session }
end | [
"def",
"say_response_with_reprompt",
"(",
"speech",
",",
"reprompt_speech",
",",
"end_session",
"=",
"true",
",",
"speech_ssml",
"=",
"false",
",",
"reprompt_ssml",
"=",
"false",
")",
"output_speech",
"=",
"add_speech",
"(",
"speech",
",",
"speech_ssml",
")",
"reprompt_speech",
"=",
"add_reprompt",
"(",
"reprompt_speech",
",",
"reprompt_ssml",
")",
"{",
":outputSpeech",
"=>",
"output_speech",
",",
":reprompt",
"=>",
"reprompt_speech",
",",
":shouldEndSession",
"=>",
"end_session",
"}",
"end"
]
| Incorporates reprompt in the SDK 2015-05 | [
"Incorporates",
"reprompt",
"in",
"the",
"SDK",
"2015",
"-",
"05"
]
| 06c9506b20adbd6fb0f37d6a1df223e1d8469338 | https://github.com/damianFC/alexa-rubykit/blob/06c9506b20adbd6fb0f37d6a1df223e1d8469338/lib/alexa_rubykit/response.rb#L110-L114 | train |
damianFC/alexa-rubykit | lib/alexa_rubykit/response.rb | AlexaRubykit.Response.build_response | def build_response(session_end = true)
response_object = build_response_object(session_end)
response = Hash.new
response[:version] = @version
response[:sessionAttributes] = @session_attributes unless @session_attributes.empty?
response[:response] = response_object
response.to_json
end | ruby | def build_response(session_end = true)
response_object = build_response_object(session_end)
response = Hash.new
response[:version] = @version
response[:sessionAttributes] = @session_attributes unless @session_attributes.empty?
response[:response] = response_object
response.to_json
end | [
"def",
"build_response",
"(",
"session_end",
"=",
"true",
")",
"response_object",
"=",
"build_response_object",
"(",
"session_end",
")",
"response",
"=",
"Hash",
".",
"new",
"response",
"[",
":version",
"]",
"=",
"@version",
"response",
"[",
":sessionAttributes",
"]",
"=",
"@session_attributes",
"unless",
"@session_attributes",
".",
"empty?",
"response",
"[",
":response",
"]",
"=",
"response_object",
"response",
".",
"to_json",
"end"
]
| Builds a response.
Takes the version, response and should_end_session variables and builds a JSON object. | [
"Builds",
"a",
"response",
".",
"Takes",
"the",
"version",
"response",
"and",
"should_end_session",
"variables",
"and",
"builds",
"a",
"JSON",
"object",
"."
]
| 06c9506b20adbd6fb0f37d6a1df223e1d8469338 | https://github.com/damianFC/alexa-rubykit/blob/06c9506b20adbd6fb0f37d6a1df223e1d8469338/lib/alexa_rubykit/response.rb#L139-L146 | train |
damianFC/alexa-rubykit | lib/alexa_rubykit/intent_request.rb | AlexaRubykit.IntentRequest.add_hash_slots | def add_hash_slots(slots)
raise ArgumentError, 'Slots can\'t be empty'
slots.each do |slot|
@slots[:slot[:name]] = Slot.new(slot[:name], slot[:value])
end
@slots
end | ruby | def add_hash_slots(slots)
raise ArgumentError, 'Slots can\'t be empty'
slots.each do |slot|
@slots[:slot[:name]] = Slot.new(slot[:name], slot[:value])
end
@slots
end | [
"def",
"add_hash_slots",
"(",
"slots",
")",
"raise",
"ArgumentError",
",",
"'Slots can\\'t be empty'",
"slots",
".",
"each",
"do",
"|",
"slot",
"|",
"@slots",
"[",
":slot",
"[",
":name",
"]",
"]",
"=",
"Slot",
".",
"new",
"(",
"slot",
"[",
":name",
"]",
",",
"slot",
"[",
":value",
"]",
")",
"end",
"@slots",
"end"
]
| We still don't know if all of the parameters in the request are required.
Checking for the presence of intent on an IntentRequest.
Takes a Hash object. | [
"We",
"still",
"don",
"t",
"know",
"if",
"all",
"of",
"the",
"parameters",
"in",
"the",
"request",
"are",
"required",
".",
"Checking",
"for",
"the",
"presence",
"of",
"intent",
"on",
"an",
"IntentRequest",
".",
"Takes",
"a",
"Hash",
"object",
"."
]
| 06c9506b20adbd6fb0f37d6a1df223e1d8469338 | https://github.com/damianFC/alexa-rubykit/blob/06c9506b20adbd6fb0f37d6a1df223e1d8469338/lib/alexa_rubykit/intent_request.rb#L17-L23 | train |
damianFC/alexa-rubykit | lib/alexa_rubykit/intent_request.rb | AlexaRubykit.IntentRequest.add_slot | def add_slot(name, value)
slot = Slot.new(name, value)
@slots[:name] = slot
slot
end | ruby | def add_slot(name, value)
slot = Slot.new(name, value)
@slots[:name] = slot
slot
end | [
"def",
"add_slot",
"(",
"name",
",",
"value",
")",
"slot",
"=",
"Slot",
".",
"new",
"(",
"name",
",",
"value",
")",
"@slots",
"[",
":name",
"]",
"=",
"slot",
"slot",
"end"
]
| Adds a slot from a name and a value. | [
"Adds",
"a",
"slot",
"from",
"a",
"name",
"and",
"a",
"value",
"."
]
| 06c9506b20adbd6fb0f37d6a1df223e1d8469338 | https://github.com/damianFC/alexa-rubykit/blob/06c9506b20adbd6fb0f37d6a1df223e1d8469338/lib/alexa_rubykit/intent_request.rb#L32-L36 | train |
ankane/activejob_backport | lib/active_job/execution.rb | ActiveJob.Execution.perform_now | def perform_now
deserialize_arguments_if_needed
run_callbacks :perform do
perform(*arguments)
end
rescue => exception
rescue_with_handler(exception) || raise(exception)
end | ruby | def perform_now
deserialize_arguments_if_needed
run_callbacks :perform do
perform(*arguments)
end
rescue => exception
rescue_with_handler(exception) || raise(exception)
end | [
"def",
"perform_now",
"deserialize_arguments_if_needed",
"run_callbacks",
":perform",
"do",
"perform",
"(",
"*",
"arguments",
")",
"end",
"rescue",
"=>",
"exception",
"rescue_with_handler",
"(",
"exception",
")",
"||",
"raise",
"(",
"exception",
")",
"end"
]
| Performs the job immediately. The job is not sent to the queueing adapter
and will block the execution until it's finished.
MyJob.new(*args).perform_now | [
"Performs",
"the",
"job",
"immediately",
".",
"The",
"job",
"is",
"not",
"sent",
"to",
"the",
"queueing",
"adapter",
"and",
"will",
"block",
"the",
"execution",
"until",
"it",
"s",
"finished",
"."
]
| daa74738d1a241a01f2c373145ac81ec1e822c7c | https://github.com/ankane/activejob_backport/blob/daa74738d1a241a01f2c373145ac81ec1e822c7c/lib/active_job/execution.rb#L28-L35 | train |
jeremy/rack-ratelimit | lib/rack/ratelimit.rb | Rack.Ratelimit.apply_rate_limit? | def apply_rate_limit?(env)
@exceptions.none? { |e| e.call(env) } && @conditions.all? { |c| c.call(env) }
end | ruby | def apply_rate_limit?(env)
@exceptions.none? { |e| e.call(env) } && @conditions.all? { |c| c.call(env) }
end | [
"def",
"apply_rate_limit?",
"(",
"env",
")",
"@exceptions",
".",
"none?",
"{",
"|",
"e",
"|",
"e",
".",
"call",
"(",
"env",
")",
"}",
"&&",
"@conditions",
".",
"all?",
"{",
"|",
"c",
"|",
"c",
".",
"call",
"(",
"env",
")",
"}",
"end"
]
| Apply the rate limiter if none of the exceptions apply and all the
conditions are met. | [
"Apply",
"the",
"rate",
"limiter",
"if",
"none",
"of",
"the",
"exceptions",
"apply",
"and",
"all",
"the",
"conditions",
"are",
"met",
"."
]
| f40b928d456b08532a3226270b2bbf4878d1a320 | https://github.com/jeremy/rack-ratelimit/blob/f40b928d456b08532a3226270b2bbf4878d1a320/lib/rack/ratelimit.rb#L108-L110 | train |
jeremy/rack-ratelimit | lib/rack/ratelimit.rb | Rack.Ratelimit.seconds_until_epoch | def seconds_until_epoch(epoch)
sec = (epoch - Time.now.to_f).ceil
sec = 0 if sec < 0
sec
end | ruby | def seconds_until_epoch(epoch)
sec = (epoch - Time.now.to_f).ceil
sec = 0 if sec < 0
sec
end | [
"def",
"seconds_until_epoch",
"(",
"epoch",
")",
"sec",
"=",
"(",
"epoch",
"-",
"Time",
".",
"now",
".",
"to_f",
")",
".",
"ceil",
"sec",
"=",
"0",
"if",
"sec",
"<",
"0",
"sec",
"end"
]
| Clamp negative durations in case we're in a new rate-limiting window. | [
"Clamp",
"negative",
"durations",
"in",
"case",
"we",
"re",
"in",
"a",
"new",
"rate",
"-",
"limiting",
"window",
"."
]
| f40b928d456b08532a3226270b2bbf4878d1a320 | https://github.com/jeremy/rack-ratelimit/blob/f40b928d456b08532a3226270b2bbf4878d1a320/lib/rack/ratelimit.rb#L176-L180 | train |
ankane/activejob_backport | lib/active_job/enqueuing.rb | ActiveJob.Enqueuing.enqueue | def enqueue(options={})
self.scheduled_at = options[:wait].seconds.from_now.to_f if options[:wait]
self.scheduled_at = options[:wait_until].to_f if options[:wait_until]
self.queue_name = self.class.queue_name_from_part(options[:queue]) if options[:queue]
run_callbacks :enqueue do
if self.scheduled_at
self.class.queue_adapter.enqueue_at self, self.scheduled_at
else
self.class.queue_adapter.enqueue self
end
end
self
end | ruby | def enqueue(options={})
self.scheduled_at = options[:wait].seconds.from_now.to_f if options[:wait]
self.scheduled_at = options[:wait_until].to_f if options[:wait_until]
self.queue_name = self.class.queue_name_from_part(options[:queue]) if options[:queue]
run_callbacks :enqueue do
if self.scheduled_at
self.class.queue_adapter.enqueue_at self, self.scheduled_at
else
self.class.queue_adapter.enqueue self
end
end
self
end | [
"def",
"enqueue",
"(",
"options",
"=",
"{",
"}",
")",
"self",
".",
"scheduled_at",
"=",
"options",
"[",
":wait",
"]",
".",
"seconds",
".",
"from_now",
".",
"to_f",
"if",
"options",
"[",
":wait",
"]",
"self",
".",
"scheduled_at",
"=",
"options",
"[",
":wait_until",
"]",
".",
"to_f",
"if",
"options",
"[",
":wait_until",
"]",
"self",
".",
"queue_name",
"=",
"self",
".",
"class",
".",
"queue_name_from_part",
"(",
"options",
"[",
":queue",
"]",
")",
"if",
"options",
"[",
":queue",
"]",
"run_callbacks",
":enqueue",
"do",
"if",
"self",
".",
"scheduled_at",
"self",
".",
"class",
".",
"queue_adapter",
".",
"enqueue_at",
"self",
",",
"self",
".",
"scheduled_at",
"else",
"self",
".",
"class",
".",
"queue_adapter",
".",
"enqueue",
"self",
"end",
"end",
"self",
"end"
]
| Equeue the job to be performed by the queue adapter.
==== Options
* <tt>:wait</tt> - Enqueues the job with the specified delay
* <tt>:wait_until</tt> - Enqueues the job at the time specified
* <tt>:queue</tt> - Enqueues the job on the specified queue
==== Examples
my_job_instance.enqueue
my_job_instance.enqueue wait: 5.minutes
my_job_instance.enqueue queue: :important
my_job_instance.enqueue wait_until: Date.tomorrow.midnight | [
"Equeue",
"the",
"job",
"to",
"be",
"performed",
"by",
"the",
"queue",
"adapter",
"."
]
| daa74738d1a241a01f2c373145ac81ec1e822c7c | https://github.com/ankane/activejob_backport/blob/daa74738d1a241a01f2c373145ac81ec1e822c7c/lib/active_job/enqueuing.rb#L61-L73 | train |
ozfortress/tournament-system | lib/tournament_system/driver.rb | TournamentSystem.Driver.create_match | def create_match(home_team, away_team)
home_team, away_team = away_team, home_team unless home_team
raise 'Invalid match' unless home_team
build_match(home_team, away_team)
end | ruby | def create_match(home_team, away_team)
home_team, away_team = away_team, home_team unless home_team
raise 'Invalid match' unless home_team
build_match(home_team, away_team)
end | [
"def",
"create_match",
"(",
"home_team",
",",
"away_team",
")",
"home_team",
",",
"away_team",
"=",
"away_team",
",",
"home_team",
"unless",
"home_team",
"raise",
"'Invalid match'",
"unless",
"home_team",
"build_match",
"(",
"home_team",
",",
"away_team",
")",
"end"
]
| Create a match. Used by tournament systems.
Specially handles byes, swapping home/away if required.
@param home_team [team, nil]
@param away_team [team, nil]
@return [nil]
@raise when both teams are +nil+ | [
"Create",
"a",
"match",
".",
"Used",
"by",
"tournament",
"systems",
"."
]
| d4c8dc77933ba97d369f287b1c21d7fcda78830b | https://github.com/ozfortress/tournament-system/blob/d4c8dc77933ba97d369f287b1c21d7fcda78830b/lib/tournament_system/driver.rb#L207-L212 | train |
ozfortress/tournament-system | lib/tournament_system/driver.rb | TournamentSystem.Driver.loss_count_hash | def loss_count_hash
@loss_count_hash ||= matches.each_with_object(Hash.new(0)) { |match, hash| hash[get_match_loser(match)] += 1 }
end | ruby | def loss_count_hash
@loss_count_hash ||= matches.each_with_object(Hash.new(0)) { |match, hash| hash[get_match_loser(match)] += 1 }
end | [
"def",
"loss_count_hash",
"@loss_count_hash",
"||=",
"matches",
".",
"each_with_object",
"(",
"Hash",
".",
"new",
"(",
"0",
")",
")",
"{",
"|",
"match",
",",
"hash",
"|",
"hash",
"[",
"get_match_loser",
"(",
"match",
")",
"]",
"+=",
"1",
"}",
"end"
]
| Get a hash of the number of losses of each team. Used by tournament systems.
@return [Hash{team => Number}] a mapping from teams to losses | [
"Get",
"a",
"hash",
"of",
"the",
"number",
"of",
"losses",
"of",
"each",
"team",
".",
"Used",
"by",
"tournament",
"systems",
"."
]
| d4c8dc77933ba97d369f287b1c21d7fcda78830b | https://github.com/ozfortress/tournament-system/blob/d4c8dc77933ba97d369f287b1c21d7fcda78830b/lib/tournament_system/driver.rb#L235-L237 | train |
jarthod/survey-gizmo-ruby | lib/survey_gizmo/api/answer.rb | SurveyGizmo::API.Answer.to_hash | def to_hash
{
response_id: response_id,
question_id: question_id,
option_id: option_id,
question_pipe: question_pipe,
submitted_at: submitted_at,
survey_id: survey_id,
other_text: other_text,
answer_text: option_id || other_text ? nil : answer_text
}.reject { |k, v| v.nil? }
end | ruby | def to_hash
{
response_id: response_id,
question_id: question_id,
option_id: option_id,
question_pipe: question_pipe,
submitted_at: submitted_at,
survey_id: survey_id,
other_text: other_text,
answer_text: option_id || other_text ? nil : answer_text
}.reject { |k, v| v.nil? }
end | [
"def",
"to_hash",
"{",
"response_id",
":",
"response_id",
",",
"question_id",
":",
"question_id",
",",
"option_id",
":",
"option_id",
",",
"question_pipe",
":",
"question_pipe",
",",
"submitted_at",
":",
"submitted_at",
",",
"survey_id",
":",
"survey_id",
",",
"other_text",
":",
"other_text",
",",
"answer_text",
":",
"option_id",
"||",
"other_text",
"?",
"nil",
":",
"answer_text",
"}",
".",
"reject",
"{",
"|",
"k",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"end"
]
| Strips out the answer_text when there is a valid option_id | [
"Strips",
"out",
"the",
"answer_text",
"when",
"there",
"is",
"a",
"valid",
"option_id"
]
| 757b91399b03bd5bf8d3e61b2224da5b77503a88 | https://github.com/jarthod/survey-gizmo-ruby/blob/757b91399b03bd5bf8d3e61b2224da5b77503a88/lib/survey_gizmo/api/answer.rb#L51-L62 | train |
smalruby/smalruby | lib/smalruby/color.rb | Smalruby.Color.rgb_to_hsl | def rgb_to_hsl(red, green, blue)
red = round_rgb_color(red)
green = round_rgb_color(green)
blue = round_rgb_color(blue)
color_max = [red, green, blue].max
color_min = [red, green, blue].min
color_range = color_max - color_min
if color_range == 0
return [0, 0, (color_max * 100.0 / 255).to_i]
end
color_range = color_range.to_f
hue = (case color_max
when red then
HUE_PER_6 * ((green - blue) / color_range)
when green then
HUE_PER_6 * ((blue - red) / color_range) + HUE_PER_6 * 2
else
HUE_PER_6 * ((red - green) / color_range) + HUE_PER_6 * 4
end)
cnt = color_range / 2.0
if cnt <= 127
saturation = color_range / (color_max + color_min) * 100
else
saturation = color_range / (510 - color_max - color_min) * 100
end
lightness = (color_max + color_min) / 2.0 / 255.0 * 100
[hue.round, saturation.round, lightness.round]
end | ruby | def rgb_to_hsl(red, green, blue)
red = round_rgb_color(red)
green = round_rgb_color(green)
blue = round_rgb_color(blue)
color_max = [red, green, blue].max
color_min = [red, green, blue].min
color_range = color_max - color_min
if color_range == 0
return [0, 0, (color_max * 100.0 / 255).to_i]
end
color_range = color_range.to_f
hue = (case color_max
when red then
HUE_PER_6 * ((green - blue) / color_range)
when green then
HUE_PER_6 * ((blue - red) / color_range) + HUE_PER_6 * 2
else
HUE_PER_6 * ((red - green) / color_range) + HUE_PER_6 * 4
end)
cnt = color_range / 2.0
if cnt <= 127
saturation = color_range / (color_max + color_min) * 100
else
saturation = color_range / (510 - color_max - color_min) * 100
end
lightness = (color_max + color_min) / 2.0 / 255.0 * 100
[hue.round, saturation.round, lightness.round]
end | [
"def",
"rgb_to_hsl",
"(",
"red",
",",
"green",
",",
"blue",
")",
"red",
"=",
"round_rgb_color",
"(",
"red",
")",
"green",
"=",
"round_rgb_color",
"(",
"green",
")",
"blue",
"=",
"round_rgb_color",
"(",
"blue",
")",
"color_max",
"=",
"[",
"red",
",",
"green",
",",
"blue",
"]",
".",
"max",
"color_min",
"=",
"[",
"red",
",",
"green",
",",
"blue",
"]",
".",
"min",
"color_range",
"=",
"color_max",
"-",
"color_min",
"if",
"color_range",
"==",
"0",
"return",
"[",
"0",
",",
"0",
",",
"(",
"color_max",
"*",
"100.0",
"/",
"255",
")",
".",
"to_i",
"]",
"end",
"color_range",
"=",
"color_range",
".",
"to_f",
"hue",
"=",
"(",
"case",
"color_max",
"when",
"red",
"then",
"HUE_PER_6",
"*",
"(",
"(",
"green",
"-",
"blue",
")",
"/",
"color_range",
")",
"when",
"green",
"then",
"HUE_PER_6",
"*",
"(",
"(",
"blue",
"-",
"red",
")",
"/",
"color_range",
")",
"+",
"HUE_PER_6",
"*",
"2",
"else",
"HUE_PER_6",
"*",
"(",
"(",
"red",
"-",
"green",
")",
"/",
"color_range",
")",
"+",
"HUE_PER_6",
"*",
"4",
"end",
")",
"cnt",
"=",
"color_range",
"/",
"2.0",
"if",
"cnt",
"<=",
"127",
"saturation",
"=",
"color_range",
"/",
"(",
"color_max",
"+",
"color_min",
")",
"*",
"100",
"else",
"saturation",
"=",
"color_range",
"/",
"(",
"510",
"-",
"color_max",
"-",
"color_min",
")",
"*",
"100",
"end",
"lightness",
"=",
"(",
"color_max",
"+",
"color_min",
")",
"/",
"2.0",
"/",
"255.0",
"*",
"100",
"[",
"hue",
".",
"round",
",",
"saturation",
".",
"round",
",",
"lightness",
".",
"round",
"]",
"end"
]
| Convert RGB Color model to HSL Color model
@param [Integer] red
@param [Integer] green
@param [Integer] blue
@return [Array] hue, saturation, lightness
hue in the range [0,200],
saturation and lightness in the range [0, 100] | [
"Convert",
"RGB",
"Color",
"model",
"to",
"HSL",
"Color",
"model"
]
| 859a5f0b503bc55a790fda38f2bce27414226ada | https://github.com/smalruby/smalruby/blob/859a5f0b503bc55a790fda38f2bce27414226ada/lib/smalruby/color.rb#L183-L213 | train |
smalruby/smalruby | lib/smalruby/color.rb | Smalruby.Color.hsl_to_rgb | def hsl_to_rgb(h, s, l)
h %= 201
s %= 101
l %= 101
if l <= 49
color_max = 255.0 * (l + l * (s / 100.0)) / 100.0
color_min = 255.0 * (l - l * (s / 100.0)) / 100.0
else
color_max = 255.0 * (l + (100 - l) * (s / 100.0)) / 100.0
color_min = 255.0 * (l - (100 - l) * (s / 100.0)) / 100.0
end
if h < HUE_PER_6
base = h
elsif h < HUE_PER_6 * 3
base = (h - HUE_PER_6 * 2).abs
elsif h < HUE_PER_6 * 5
base = (h - HUE_PER_6 * 4).abs
else
base = (200 - h)
end
base = base / HUE_PER_6 * (color_max - color_min) + color_min
divide = (h / HUE_PER_6).to_i
red, green, blue = (case divide
when 0 then [color_max, base, color_min]
when 1 then [base, color_max, color_min]
when 2 then [color_min, color_max, base]
when 3 then [color_min, base, color_max]
when 4 then [base, color_min, color_max]
else [color_max, color_min, base]
end)
[red.round, green.round, blue.round]
end | ruby | def hsl_to_rgb(h, s, l)
h %= 201
s %= 101
l %= 101
if l <= 49
color_max = 255.0 * (l + l * (s / 100.0)) / 100.0
color_min = 255.0 * (l - l * (s / 100.0)) / 100.0
else
color_max = 255.0 * (l + (100 - l) * (s / 100.0)) / 100.0
color_min = 255.0 * (l - (100 - l) * (s / 100.0)) / 100.0
end
if h < HUE_PER_6
base = h
elsif h < HUE_PER_6 * 3
base = (h - HUE_PER_6 * 2).abs
elsif h < HUE_PER_6 * 5
base = (h - HUE_PER_6 * 4).abs
else
base = (200 - h)
end
base = base / HUE_PER_6 * (color_max - color_min) + color_min
divide = (h / HUE_PER_6).to_i
red, green, blue = (case divide
when 0 then [color_max, base, color_min]
when 1 then [base, color_max, color_min]
when 2 then [color_min, color_max, base]
when 3 then [color_min, base, color_max]
when 4 then [base, color_min, color_max]
else [color_max, color_min, base]
end)
[red.round, green.round, blue.round]
end | [
"def",
"hsl_to_rgb",
"(",
"h",
",",
"s",
",",
"l",
")",
"h",
"%=",
"201",
"s",
"%=",
"101",
"l",
"%=",
"101",
"if",
"l",
"<=",
"49",
"color_max",
"=",
"255.0",
"*",
"(",
"l",
"+",
"l",
"*",
"(",
"s",
"/",
"100.0",
")",
")",
"/",
"100.0",
"color_min",
"=",
"255.0",
"*",
"(",
"l",
"-",
"l",
"*",
"(",
"s",
"/",
"100.0",
")",
")",
"/",
"100.0",
"else",
"color_max",
"=",
"255.0",
"*",
"(",
"l",
"+",
"(",
"100",
"-",
"l",
")",
"*",
"(",
"s",
"/",
"100.0",
")",
")",
"/",
"100.0",
"color_min",
"=",
"255.0",
"*",
"(",
"l",
"-",
"(",
"100",
"-",
"l",
")",
"*",
"(",
"s",
"/",
"100.0",
")",
")",
"/",
"100.0",
"end",
"if",
"h",
"<",
"HUE_PER_6",
"base",
"=",
"h",
"elsif",
"h",
"<",
"HUE_PER_6",
"*",
"3",
"base",
"=",
"(",
"h",
"-",
"HUE_PER_6",
"*",
"2",
")",
".",
"abs",
"elsif",
"h",
"<",
"HUE_PER_6",
"*",
"5",
"base",
"=",
"(",
"h",
"-",
"HUE_PER_6",
"*",
"4",
")",
".",
"abs",
"else",
"base",
"=",
"(",
"200",
"-",
"h",
")",
"end",
"base",
"=",
"base",
"/",
"HUE_PER_6",
"*",
"(",
"color_max",
"-",
"color_min",
")",
"+",
"color_min",
"divide",
"=",
"(",
"h",
"/",
"HUE_PER_6",
")",
".",
"to_i",
"red",
",",
"green",
",",
"blue",
"=",
"(",
"case",
"divide",
"when",
"0",
"then",
"[",
"color_max",
",",
"base",
",",
"color_min",
"]",
"when",
"1",
"then",
"[",
"base",
",",
"color_max",
",",
"color_min",
"]",
"when",
"2",
"then",
"[",
"color_min",
",",
"color_max",
",",
"base",
"]",
"when",
"3",
"then",
"[",
"color_min",
",",
"base",
",",
"color_max",
"]",
"when",
"4",
"then",
"[",
"base",
",",
"color_min",
",",
"color_max",
"]",
"else",
"[",
"color_max",
",",
"color_min",
",",
"base",
"]",
"end",
")",
"[",
"red",
".",
"round",
",",
"green",
".",
"round",
",",
"blue",
".",
"round",
"]",
"end"
]
| Convert HSV Color model to RGB Color model
@param [Integer] h
@param [Integer] s
@param [Integer] l
@return [Array] red,green,blue color
red,green,blue in the range [0,255] | [
"Convert",
"HSV",
"Color",
"model",
"to",
"RGB",
"Color",
"model"
]
| 859a5f0b503bc55a790fda38f2bce27414226ada | https://github.com/smalruby/smalruby/blob/859a5f0b503bc55a790fda38f2bce27414226ada/lib/smalruby/color.rb#L236-L270 | train |
aspring/racker | lib/racker/template.rb | Racker.Template.to_packer | def to_packer
# Create the new smash
packer = Smash.new
# Variables
packer['variables'] = self['variables'].dup unless self['variables'].nil? || self['variables'].empty?
# Builders
packer['builders'] = [] unless self['builders'].nil? || self['builders'].empty?
logger.info("Processing builders...")
self['builders'].each do |name,config|
logger.info("Processing builder: #{name} with type: #{config['type']}")
# Get the builder for this config
builder = get_builder(config['type'])
# Have the builder convert the config to packer format
packer['builders'] << builder.to_packer(name, config.dup)
end
# Provisioners
packer['provisioners'] = [] unless self['provisioners'].nil? || self['provisioners'].empty?
logger.info("Processing provisioners...")
self['provisioners'].sort.map do |index, provisioners|
provisioners.each do |name,config|
logger.debug("Processing provisioner: #{name}")
packer['provisioners'] << config.dup
end
end
# Post-Processors
packer['post-processors'] = [] unless self['postprocessors'].nil? || self['postprocessors'].empty?
logger.info("Processing post-processors...")
self['postprocessors'].each do |name,config|
logger.debug("Processing post-processor: #{name}")
packer['post-processors'] << config.dup unless config.nil?
end
packer
end | ruby | def to_packer
# Create the new smash
packer = Smash.new
# Variables
packer['variables'] = self['variables'].dup unless self['variables'].nil? || self['variables'].empty?
# Builders
packer['builders'] = [] unless self['builders'].nil? || self['builders'].empty?
logger.info("Processing builders...")
self['builders'].each do |name,config|
logger.info("Processing builder: #{name} with type: #{config['type']}")
# Get the builder for this config
builder = get_builder(config['type'])
# Have the builder convert the config to packer format
packer['builders'] << builder.to_packer(name, config.dup)
end
# Provisioners
packer['provisioners'] = [] unless self['provisioners'].nil? || self['provisioners'].empty?
logger.info("Processing provisioners...")
self['provisioners'].sort.map do |index, provisioners|
provisioners.each do |name,config|
logger.debug("Processing provisioner: #{name}")
packer['provisioners'] << config.dup
end
end
# Post-Processors
packer['post-processors'] = [] unless self['postprocessors'].nil? || self['postprocessors'].empty?
logger.info("Processing post-processors...")
self['postprocessors'].each do |name,config|
logger.debug("Processing post-processor: #{name}")
packer['post-processors'] << config.dup unless config.nil?
end
packer
end | [
"def",
"to_packer",
"packer",
"=",
"Smash",
".",
"new",
"packer",
"[",
"'variables'",
"]",
"=",
"self",
"[",
"'variables'",
"]",
".",
"dup",
"unless",
"self",
"[",
"'variables'",
"]",
".",
"nil?",
"||",
"self",
"[",
"'variables'",
"]",
".",
"empty?",
"packer",
"[",
"'builders'",
"]",
"=",
"[",
"]",
"unless",
"self",
"[",
"'builders'",
"]",
".",
"nil?",
"||",
"self",
"[",
"'builders'",
"]",
".",
"empty?",
"logger",
".",
"info",
"(",
"\"Processing builders...\"",
")",
"self",
"[",
"'builders'",
"]",
".",
"each",
"do",
"|",
"name",
",",
"config",
"|",
"logger",
".",
"info",
"(",
"\"Processing builder: #{name} with type: #{config['type']}\"",
")",
"builder",
"=",
"get_builder",
"(",
"config",
"[",
"'type'",
"]",
")",
"packer",
"[",
"'builders'",
"]",
"<<",
"builder",
".",
"to_packer",
"(",
"name",
",",
"config",
".",
"dup",
")",
"end",
"packer",
"[",
"'provisioners'",
"]",
"=",
"[",
"]",
"unless",
"self",
"[",
"'provisioners'",
"]",
".",
"nil?",
"||",
"self",
"[",
"'provisioners'",
"]",
".",
"empty?",
"logger",
".",
"info",
"(",
"\"Processing provisioners...\"",
")",
"self",
"[",
"'provisioners'",
"]",
".",
"sort",
".",
"map",
"do",
"|",
"index",
",",
"provisioners",
"|",
"provisioners",
".",
"each",
"do",
"|",
"name",
",",
"config",
"|",
"logger",
".",
"debug",
"(",
"\"Processing provisioner: #{name}\"",
")",
"packer",
"[",
"'provisioners'",
"]",
"<<",
"config",
".",
"dup",
"end",
"end",
"packer",
"[",
"'post-processors'",
"]",
"=",
"[",
"]",
"unless",
"self",
"[",
"'postprocessors'",
"]",
".",
"nil?",
"||",
"self",
"[",
"'postprocessors'",
"]",
".",
"empty?",
"logger",
".",
"info",
"(",
"\"Processing post-processors...\"",
")",
"self",
"[",
"'postprocessors'",
"]",
".",
"each",
"do",
"|",
"name",
",",
"config",
"|",
"logger",
".",
"debug",
"(",
"\"Processing post-processor: #{name}\"",
")",
"packer",
"[",
"'post-processors'",
"]",
"<<",
"config",
".",
"dup",
"unless",
"config",
".",
"nil?",
"end",
"packer",
"end"
]
| This formats the template into packer format hash | [
"This",
"formats",
"the",
"template",
"into",
"packer",
"format",
"hash"
]
| 78453d3d5e204486b1df99015ab1b2be821663f5 | https://github.com/aspring/racker/blob/78453d3d5e204486b1df99015ab1b2be821663f5/lib/racker/template.rb#L21-L60 | train |
jarthod/survey-gizmo-ruby | lib/survey_gizmo/resource.rb | SurveyGizmo.Resource.route_params | def route_params
params = { id: id }
self.class.routes.values.each do |route|
route.gsub(/:(\w+)/) do |m|
m = m.delete(':').to_sym
params[m] = self.send(m)
end
end
params
end | ruby | def route_params
params = { id: id }
self.class.routes.values.each do |route|
route.gsub(/:(\w+)/) do |m|
m = m.delete(':').to_sym
params[m] = self.send(m)
end
end
params
end | [
"def",
"route_params",
"params",
"=",
"{",
"id",
":",
"id",
"}",
"self",
".",
"class",
".",
"routes",
".",
"values",
".",
"each",
"do",
"|",
"route",
"|",
"route",
".",
"gsub",
"(",
"/",
"\\w",
"/",
")",
"do",
"|",
"m",
"|",
"m",
"=",
"m",
".",
"delete",
"(",
"':'",
")",
".",
"to_sym",
"params",
"[",
"m",
"]",
"=",
"self",
".",
"send",
"(",
"m",
")",
"end",
"end",
"params",
"end"
]
| Extract attributes required for API calls about this object | [
"Extract",
"attributes",
"required",
"for",
"API",
"calls",
"about",
"this",
"object"
]
| 757b91399b03bd5bf8d3e61b2224da5b77503a88 | https://github.com/jarthod/survey-gizmo-ruby/blob/757b91399b03bd5bf8d3e61b2224da5b77503a88/lib/survey_gizmo/resource.rb#L173-L184 | train |
smalruby/smalruby | lib/smalruby/character.rb | Smalruby.Character.pen_color= | def pen_color=(val)
if val.is_a?(Numeric)
val %= 201
_, s, l = Color.rgb_to_hsl(*pen_color)
val = Color.hsl_to_rgb(val, s, l)
end
@pen_color = val
end | ruby | def pen_color=(val)
if val.is_a?(Numeric)
val %= 201
_, s, l = Color.rgb_to_hsl(*pen_color)
val = Color.hsl_to_rgb(val, s, l)
end
@pen_color = val
end | [
"def",
"pen_color",
"=",
"(",
"val",
")",
"if",
"val",
".",
"is_a?",
"(",
"Numeric",
")",
"val",
"%=",
"201",
"_",
",",
"s",
",",
"l",
"=",
"Color",
".",
"rgb_to_hsl",
"(",
"*",
"pen_color",
")",
"val",
"=",
"Color",
".",
"hsl_to_rgb",
"(",
"val",
",",
"s",
",",
"l",
")",
"end",
"@pen_color",
"=",
"val",
"end"
]
| set pen color
@param [Array<Integer>|Symbol|Integer] val color
When color is Array<Integer>, it means [R, G, B].
When color is Symbol, it means the color code; like :white, :black, etc...
When color is Integer, it means hue. | [
"set",
"pen",
"color"
]
| 859a5f0b503bc55a790fda38f2bce27414226ada | https://github.com/smalruby/smalruby/blob/859a5f0b503bc55a790fda38f2bce27414226ada/lib/smalruby/character.rb#L414-L421 | train |
smalruby/smalruby | lib/smalruby/character.rb | Smalruby.Character.change_pen_color_by | def change_pen_color_by(val)
h, s, l = Color.rgb_to_hsl(*pen_color)
@pen_color = Color.hsl_to_rgb(h + val, s, l)
end | ruby | def change_pen_color_by(val)
h, s, l = Color.rgb_to_hsl(*pen_color)
@pen_color = Color.hsl_to_rgb(h + val, s, l)
end | [
"def",
"change_pen_color_by",
"(",
"val",
")",
"h",
",",
"s",
",",
"l",
"=",
"Color",
".",
"rgb_to_hsl",
"(",
"*",
"pen_color",
")",
"@pen_color",
"=",
"Color",
".",
"hsl_to_rgb",
"(",
"h",
"+",
"val",
",",
"s",
",",
"l",
")",
"end"
]
| change pen color
@param [Integer] val color | [
"change",
"pen",
"color"
]
| 859a5f0b503bc55a790fda38f2bce27414226ada | https://github.com/smalruby/smalruby/blob/859a5f0b503bc55a790fda38f2bce27414226ada/lib/smalruby/character.rb#L426-L429 | train |
smalruby/smalruby | lib/smalruby/character.rb | Smalruby.Character.pen_shade= | def pen_shade=(val)
val %= 101
h, s, = *Color.rgb_to_hsl(*pen_color)
@pen_color = Color.hsl_to_rgb(h, s, val)
end | ruby | def pen_shade=(val)
val %= 101
h, s, = *Color.rgb_to_hsl(*pen_color)
@pen_color = Color.hsl_to_rgb(h, s, val)
end | [
"def",
"pen_shade",
"=",
"(",
"val",
")",
"val",
"%=",
"101",
"h",
",",
"s",
",",
"=",
"*",
"Color",
".",
"rgb_to_hsl",
"(",
"*",
"pen_color",
")",
"@pen_color",
"=",
"Color",
".",
"hsl_to_rgb",
"(",
"h",
",",
"s",
",",
"val",
")",
"end"
]
| set pen shade
@param Integer val shade | [
"set",
"pen",
"shade"
]
| 859a5f0b503bc55a790fda38f2bce27414226ada | https://github.com/smalruby/smalruby/blob/859a5f0b503bc55a790fda38f2bce27414226ada/lib/smalruby/character.rb#L434-L438 | train |
sandipransing/rails_tiny_mce | plugins/will_paginate/lib/will_paginate/view_helpers.rb | WillPaginate.ViewHelpers.page_entries_info | def page_entries_info(collection, options = {})
entry_name = options[:entry_name] ||
(collection.empty?? 'entry' : collection.first.class.name.underscore.sub('_', ' '))
if collection.total_pages < 2
case collection.size
when 0; "No #{entry_name.pluralize} found"
when 1; "Displaying <b>1</b> #{entry_name}"
else; "Displaying <b>all #{collection.size}</b> #{entry_name.pluralize}"
end
else
%{Displaying #{entry_name.pluralize} <b>%d - %d</b> of <b>%d</b> in total} % [
collection.offset + 1,
collection.offset + collection.length,
collection.total_entries
]
end
end | ruby | def page_entries_info(collection, options = {})
entry_name = options[:entry_name] ||
(collection.empty?? 'entry' : collection.first.class.name.underscore.sub('_', ' '))
if collection.total_pages < 2
case collection.size
when 0; "No #{entry_name.pluralize} found"
when 1; "Displaying <b>1</b> #{entry_name}"
else; "Displaying <b>all #{collection.size}</b> #{entry_name.pluralize}"
end
else
%{Displaying #{entry_name.pluralize} <b>%d - %d</b> of <b>%d</b> in total} % [
collection.offset + 1,
collection.offset + collection.length,
collection.total_entries
]
end
end | [
"def",
"page_entries_info",
"(",
"collection",
",",
"options",
"=",
"{",
"}",
")",
"entry_name",
"=",
"options",
"[",
":entry_name",
"]",
"||",
"(",
"collection",
".",
"empty?",
"?",
"'entry'",
":",
"collection",
".",
"first",
".",
"class",
".",
"name",
".",
"underscore",
".",
"sub",
"(",
"'_'",
",",
"' '",
")",
")",
"if",
"collection",
".",
"total_pages",
"<",
"2",
"case",
"collection",
".",
"size",
"when",
"0",
";",
"\"No #{entry_name.pluralize} found\"",
"when",
"1",
";",
"\"Displaying <b>1</b> #{entry_name}\"",
"else",
";",
"\"Displaying <b>all #{collection.size}</b> #{entry_name.pluralize}\"",
"end",
"else",
"%{Displaying #{entry_name.pluralize} <b>%d - %d</b> of <b>%d</b> in total}",
"%",
"[",
"collection",
".",
"offset",
"+",
"1",
",",
"collection",
".",
"offset",
"+",
"collection",
".",
"length",
",",
"collection",
".",
"total_entries",
"]",
"end",
"end"
]
| Renders a helpful message with numbers of displayed vs. total entries.
You can use this as a blueprint for your own, similar helpers.
<%= page_entries_info @posts %>
#-> Displaying posts 6 - 10 of 26 in total
By default, the message will use the humanized class name of objects
in collection: for instance, "project types" for ProjectType models.
Override this to your liking with the <tt>:entry_name</tt> parameter:
<%= page_entries_info @posts, :entry_name => 'item' %>
#-> Displaying items 6 - 10 of 26 in total | [
"Renders",
"a",
"helpful",
"message",
"with",
"numbers",
"of",
"displayed",
"vs",
".",
"total",
"entries",
".",
"You",
"can",
"use",
"this",
"as",
"a",
"blueprint",
"for",
"your",
"own",
"similar",
"helpers",
"."
]
| 4e91040e62784061aa7cca37fd8a95a87df379ce | https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/will_paginate/lib/will_paginate/view_helpers.rb#L150-L167 | train |
sandipransing/rails_tiny_mce | plugins/will_paginate/lib/will_paginate/view_helpers.rb | WillPaginate.LinkRenderer.to_html | def to_html
links = @options[:page_links] ? windowed_links : []
# previous/next buttons
links.unshift page_link_or_span(@collection.previous_page, 'disabled prev_page', @options[:prev_label])
links.push page_link_or_span(@collection.next_page, 'disabled next_page', @options[:next_label])
html = links.join(@options[:separator])
@options[:container] ? @template.content_tag(:div, html, html_attributes) : html
end | ruby | def to_html
links = @options[:page_links] ? windowed_links : []
# previous/next buttons
links.unshift page_link_or_span(@collection.previous_page, 'disabled prev_page', @options[:prev_label])
links.push page_link_or_span(@collection.next_page, 'disabled next_page', @options[:next_label])
html = links.join(@options[:separator])
@options[:container] ? @template.content_tag(:div, html, html_attributes) : html
end | [
"def",
"to_html",
"links",
"=",
"@options",
"[",
":page_links",
"]",
"?",
"windowed_links",
":",
"[",
"]",
"links",
".",
"unshift",
"page_link_or_span",
"(",
"@collection",
".",
"previous_page",
",",
"'disabled prev_page'",
",",
"@options",
"[",
":prev_label",
"]",
")",
"links",
".",
"push",
"page_link_or_span",
"(",
"@collection",
".",
"next_page",
",",
"'disabled next_page'",
",",
"@options",
"[",
":next_label",
"]",
")",
"html",
"=",
"links",
".",
"join",
"(",
"@options",
"[",
":separator",
"]",
")",
"@options",
"[",
":container",
"]",
"?",
"@template",
".",
"content_tag",
"(",
":div",
",",
"html",
",",
"html_attributes",
")",
":",
"html",
"end"
]
| Process it! This method returns the complete HTML string which contains
pagination links. Feel free to subclass LinkRenderer and change this
method as you see fit. | [
"Process",
"it!",
"This",
"method",
"returns",
"the",
"complete",
"HTML",
"string",
"which",
"contains",
"pagination",
"links",
".",
"Feel",
"free",
"to",
"subclass",
"LinkRenderer",
"and",
"change",
"this",
"method",
"as",
"you",
"see",
"fit",
"."
]
| 4e91040e62784061aa7cca37fd8a95a87df379ce | https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/will_paginate/lib/will_paginate/view_helpers.rb#L214-L222 | train |
sandipransing/rails_tiny_mce | plugins/will_paginate/lib/will_paginate/view_helpers.rb | WillPaginate.LinkRenderer.html_attributes | def html_attributes
return @html_attributes if @html_attributes
@html_attributes = @options.except *(WillPaginate::ViewHelpers.pagination_options.keys - [:class])
# pagination of Post models will have the ID of "posts_pagination"
if @options[:container] and @options[:id] === true
@html_attributes[:id] = @collection.first.class.name.underscore.pluralize + '_pagination'
end
@html_attributes
end | ruby | def html_attributes
return @html_attributes if @html_attributes
@html_attributes = @options.except *(WillPaginate::ViewHelpers.pagination_options.keys - [:class])
# pagination of Post models will have the ID of "posts_pagination"
if @options[:container] and @options[:id] === true
@html_attributes[:id] = @collection.first.class.name.underscore.pluralize + '_pagination'
end
@html_attributes
end | [
"def",
"html_attributes",
"return",
"@html_attributes",
"if",
"@html_attributes",
"@html_attributes",
"=",
"@options",
".",
"except",
"*",
"(",
"WillPaginate",
"::",
"ViewHelpers",
".",
"pagination_options",
".",
"keys",
"-",
"[",
":class",
"]",
")",
"if",
"@options",
"[",
":container",
"]",
"and",
"@options",
"[",
":id",
"]",
"===",
"true",
"@html_attributes",
"[",
":id",
"]",
"=",
"@collection",
".",
"first",
".",
"class",
".",
"name",
".",
"underscore",
".",
"pluralize",
"+",
"'_pagination'",
"end",
"@html_attributes",
"end"
]
| Returns the subset of +options+ this instance was initialized with that
represent HTML attributes for the container element of pagination links. | [
"Returns",
"the",
"subset",
"of",
"+",
"options",
"+",
"this",
"instance",
"was",
"initialized",
"with",
"that",
"represent",
"HTML",
"attributes",
"for",
"the",
"container",
"element",
"of",
"pagination",
"links",
"."
]
| 4e91040e62784061aa7cca37fd8a95a87df379ce | https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/will_paginate/lib/will_paginate/view_helpers.rb#L226-L234 | train |
sandipransing/rails_tiny_mce | plugins/will_paginate/lib/will_paginate/view_helpers.rb | WillPaginate.LinkRenderer.windowed_links | def windowed_links
prev = nil
visible_page_numbers.inject [] do |links, n|
# detect gaps:
links << gap_marker if prev and n > prev + 1
links << page_link_or_span(n, 'current')
prev = n
links
end
end | ruby | def windowed_links
prev = nil
visible_page_numbers.inject [] do |links, n|
# detect gaps:
links << gap_marker if prev and n > prev + 1
links << page_link_or_span(n, 'current')
prev = n
links
end
end | [
"def",
"windowed_links",
"prev",
"=",
"nil",
"visible_page_numbers",
".",
"inject",
"[",
"]",
"do",
"|",
"links",
",",
"n",
"|",
"links",
"<<",
"gap_marker",
"if",
"prev",
"and",
"n",
">",
"prev",
"+",
"1",
"links",
"<<",
"page_link_or_span",
"(",
"n",
",",
"'current'",
")",
"prev",
"=",
"n",
"links",
"end",
"end"
]
| Collects link items for visible page numbers. | [
"Collects",
"link",
"items",
"for",
"visible",
"page",
"numbers",
"."
]
| 4e91040e62784061aa7cca37fd8a95a87df379ce | https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/will_paginate/lib/will_paginate/view_helpers.rb#L239-L249 | train |
sandipransing/rails_tiny_mce | plugins/will_paginate/lib/will_paginate/view_helpers.rb | WillPaginate.LinkRenderer.stringified_merge | def stringified_merge(target, other)
other.each do |key, value|
key = key.to_s # this line is what it's all about!
existing = target[key]
if value.is_a?(Hash) and (existing.is_a?(Hash) or existing.nil?)
stringified_merge(existing || (target[key] = {}), value)
else
target[key] = value
end
end
end | ruby | def stringified_merge(target, other)
other.each do |key, value|
key = key.to_s # this line is what it's all about!
existing = target[key]
if value.is_a?(Hash) and (existing.is_a?(Hash) or existing.nil?)
stringified_merge(existing || (target[key] = {}), value)
else
target[key] = value
end
end
end | [
"def",
"stringified_merge",
"(",
"target",
",",
"other",
")",
"other",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"key",
"=",
"key",
".",
"to_s",
"existing",
"=",
"target",
"[",
"key",
"]",
"if",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"and",
"(",
"existing",
".",
"is_a?",
"(",
"Hash",
")",
"or",
"existing",
".",
"nil?",
")",
"stringified_merge",
"(",
"existing",
"||",
"(",
"target",
"[",
"key",
"]",
"=",
"{",
"}",
")",
",",
"value",
")",
"else",
"target",
"[",
"key",
"]",
"=",
"value",
"end",
"end",
"end"
]
| Recursively merge into target hash by using stringified keys from the other one | [
"Recursively",
"merge",
"into",
"target",
"hash",
"by",
"using",
"stringified",
"keys",
"from",
"the",
"other",
"one"
]
| 4e91040e62784061aa7cca37fd8a95a87df379ce | https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/will_paginate/lib/will_paginate/view_helpers.rb#L360-L371 | train |
drewtempelmeyer/tax_cloud | lib/tax_cloud/tax_code_group.rb | TaxCloud.TaxCodeGroup.tax_codes | def tax_codes
@tax_codes ||= begin
response = TaxCloud.client.request :get_ti_cs_by_group, tic_group: group_id
tax_codes = TaxCloud::Responses::TaxCodesByGroup.parse response
Hash[tax_codes.map { |tic| [tic.ticid, tic] }]
end
end | ruby | def tax_codes
@tax_codes ||= begin
response = TaxCloud.client.request :get_ti_cs_by_group, tic_group: group_id
tax_codes = TaxCloud::Responses::TaxCodesByGroup.parse response
Hash[tax_codes.map { |tic| [tic.ticid, tic] }]
end
end | [
"def",
"tax_codes",
"@tax_codes",
"||=",
"begin",
"response",
"=",
"TaxCloud",
".",
"client",
".",
"request",
":get_ti_cs_by_group",
",",
"tic_group",
":",
"group_id",
"tax_codes",
"=",
"TaxCloud",
"::",
"Responses",
"::",
"TaxCodesByGroup",
".",
"parse",
"response",
"Hash",
"[",
"tax_codes",
".",
"map",
"{",
"|",
"tic",
"|",
"[",
"tic",
".",
"ticid",
",",
"tic",
"]",
"}",
"]",
"end",
"end"
]
| All Tax Codes in this group. | [
"All",
"Tax",
"Codes",
"in",
"this",
"group",
"."
]
| ace4fae5586bc993e10a39989efbd048849ecad0 | https://github.com/drewtempelmeyer/tax_cloud/blob/ace4fae5586bc993e10a39989efbd048849ecad0/lib/tax_cloud/tax_code_group.rb#L12-L18 | train |
drewtempelmeyer/tax_cloud | lib/tax_cloud/transaction.rb | TaxCloud.Transaction.authorized | def authorized(options = {})
options = { date_authorized: Date.today }.merge(options)
request_params = {
'customerID' => customer_id,
'cartID' => cart_id,
'orderID' => order_id,
'dateAuthorized' => xml_date(options[:date_authorized])
}
response = TaxCloud.client.request :authorized, request_params
TaxCloud::Responses::Authorized.parse response
end | ruby | def authorized(options = {})
options = { date_authorized: Date.today }.merge(options)
request_params = {
'customerID' => customer_id,
'cartID' => cart_id,
'orderID' => order_id,
'dateAuthorized' => xml_date(options[:date_authorized])
}
response = TaxCloud.client.request :authorized, request_params
TaxCloud::Responses::Authorized.parse response
end | [
"def",
"authorized",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"date_authorized",
":",
"Date",
".",
"today",
"}",
".",
"merge",
"(",
"options",
")",
"request_params",
"=",
"{",
"'customerID'",
"=>",
"customer_id",
",",
"'cartID'",
"=>",
"cart_id",
",",
"'orderID'",
"=>",
"order_id",
",",
"'dateAuthorized'",
"=>",
"xml_date",
"(",
"options",
"[",
":date_authorized",
"]",
")",
"}",
"response",
"=",
"TaxCloud",
".",
"client",
".",
"request",
":authorized",
",",
"request_params",
"TaxCloud",
"::",
"Responses",
"::",
"Authorized",
".",
"parse",
"response",
"end"
]
| Once a purchase has been made and payment has been authorized, this method must be called. A matching Lookup call must have been made before this is called.
=== Options
* <tt>date_authorized</tt> - The date the transaction was authorized. Default is today. | [
"Once",
"a",
"purchase",
"has",
"been",
"made",
"and",
"payment",
"has",
"been",
"authorized",
"this",
"method",
"must",
"be",
"called",
".",
"A",
"matching",
"Lookup",
"call",
"must",
"have",
"been",
"made",
"before",
"this",
"is",
"called",
"."
]
| ace4fae5586bc993e10a39989efbd048849ecad0 | https://github.com/drewtempelmeyer/tax_cloud/blob/ace4fae5586bc993e10a39989efbd048849ecad0/lib/tax_cloud/transaction.rb#L46-L58 | train |
drewtempelmeyer/tax_cloud | lib/tax_cloud/transaction.rb | TaxCloud.Transaction.returned | def returned(options = {})
options = { returned_date: Date.today }.merge(options)
request_params = {
'orderID' => order_id,
'cartItems' => { 'CartItem' => cart_items.map(&:to_hash) },
'returnedDate' => xml_date(options[:returned_date])
}
response = TaxCloud.client.request :returned, request_params
TaxCloud::Responses::Returned.parse response
end | ruby | def returned(options = {})
options = { returned_date: Date.today }.merge(options)
request_params = {
'orderID' => order_id,
'cartItems' => { 'CartItem' => cart_items.map(&:to_hash) },
'returnedDate' => xml_date(options[:returned_date])
}
response = TaxCloud.client.request :returned, request_params
TaxCloud::Responses::Returned.parse response
end | [
"def",
"returned",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"returned_date",
":",
"Date",
".",
"today",
"}",
".",
"merge",
"(",
"options",
")",
"request_params",
"=",
"{",
"'orderID'",
"=>",
"order_id",
",",
"'cartItems'",
"=>",
"{",
"'CartItem'",
"=>",
"cart_items",
".",
"map",
"(",
"&",
":to_hash",
")",
"}",
",",
"'returnedDate'",
"=>",
"xml_date",
"(",
"options",
"[",
":returned_date",
"]",
")",
"}",
"response",
"=",
"TaxCloud",
".",
"client",
".",
"request",
":returned",
",",
"request_params",
"TaxCloud",
"::",
"Responses",
"::",
"Returned",
".",
"parse",
"response",
"end"
]
| Marks any included cart items as returned.
=== Options
[returned_date] The date the return occured. Default is today. | [
"Marks",
"any",
"included",
"cart",
"items",
"as",
"returned",
"."
]
| ace4fae5586bc993e10a39989efbd048849ecad0 | https://github.com/drewtempelmeyer/tax_cloud/blob/ace4fae5586bc993e10a39989efbd048849ecad0/lib/tax_cloud/transaction.rb#L100-L110 | train |
sandipransing/rails_tiny_mce | plugins/paperclip/lib/paperclip/geometry.rb | Paperclip.Geometry.to_s | def to_s
s = ""
s << width.to_i.to_s if width > 0
s << "x#{height.to_i}" if height > 0
s << modifier.to_s
s
end | ruby | def to_s
s = ""
s << width.to_i.to_s if width > 0
s << "x#{height.to_i}" if height > 0
s << modifier.to_s
s
end | [
"def",
"to_s",
"s",
"=",
"\"\"",
"s",
"<<",
"width",
".",
"to_i",
".",
"to_s",
"if",
"width",
">",
"0",
"s",
"<<",
"\"x#{height.to_i}\"",
"if",
"height",
">",
"0",
"s",
"<<",
"modifier",
".",
"to_s",
"s",
"end"
]
| Returns the width and height in a format suitable to be passed to Geometry.parse | [
"Returns",
"the",
"width",
"and",
"height",
"in",
"a",
"format",
"suitable",
"to",
"be",
"passed",
"to",
"Geometry",
".",
"parse"
]
| 4e91040e62784061aa7cca37fd8a95a87df379ce | https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/geometry.rb#L65-L71 | train |
sandipransing/rails_tiny_mce | plugins/paperclip/shoulda_macros/paperclip.rb | Paperclip.Shoulda.should_have_attached_file | def should_have_attached_file name
klass = self.name.gsub(/Test$/, '').constantize
matcher = have_attached_file name
should matcher.description do
assert_accepts(matcher, klass)
end
end | ruby | def should_have_attached_file name
klass = self.name.gsub(/Test$/, '').constantize
matcher = have_attached_file name
should matcher.description do
assert_accepts(matcher, klass)
end
end | [
"def",
"should_have_attached_file",
"name",
"klass",
"=",
"self",
".",
"name",
".",
"gsub",
"(",
"/",
"/",
",",
"''",
")",
".",
"constantize",
"matcher",
"=",
"have_attached_file",
"name",
"should",
"matcher",
".",
"description",
"do",
"assert_accepts",
"(",
"matcher",
",",
"klass",
")",
"end",
"end"
]
| This will test whether you have defined your attachment correctly by
checking for all the required fields exist after the definition of the
attachment. | [
"This",
"will",
"test",
"whether",
"you",
"have",
"defined",
"your",
"attachment",
"correctly",
"by",
"checking",
"for",
"all",
"the",
"required",
"fields",
"exist",
"after",
"the",
"definition",
"of",
"the",
"attachment",
"."
]
| 4e91040e62784061aa7cca37fd8a95a87df379ce | https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/shoulda_macros/paperclip.rb#L16-L22 | train |
sandipransing/rails_tiny_mce | plugins/paperclip/shoulda_macros/paperclip.rb | Paperclip.Shoulda.should_validate_attachment_presence | def should_validate_attachment_presence name
klass = self.name.gsub(/Test$/, '').constantize
matcher = validate_attachment_presence name
should matcher.description do
assert_accepts(matcher, klass)
end
end | ruby | def should_validate_attachment_presence name
klass = self.name.gsub(/Test$/, '').constantize
matcher = validate_attachment_presence name
should matcher.description do
assert_accepts(matcher, klass)
end
end | [
"def",
"should_validate_attachment_presence",
"name",
"klass",
"=",
"self",
".",
"name",
".",
"gsub",
"(",
"/",
"/",
",",
"''",
")",
".",
"constantize",
"matcher",
"=",
"validate_attachment_presence",
"name",
"should",
"matcher",
".",
"description",
"do",
"assert_accepts",
"(",
"matcher",
",",
"klass",
")",
"end",
"end"
]
| Tests for validations on the presence of the attachment. | [
"Tests",
"for",
"validations",
"on",
"the",
"presence",
"of",
"the",
"attachment",
"."
]
| 4e91040e62784061aa7cca37fd8a95a87df379ce | https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/shoulda_macros/paperclip.rb#L25-L31 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.