id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
|
---|---|---|---|---|---|---|---|---|---|---|---|
3,100 | rossf7/elasticrawl | lib/elasticrawl/config.rb | Elasticrawl.Config.delete_config_dir | def delete_config_dir
begin
FileUtils.rm_r(config_dir) if dir_exists?
rescue StandardError => e
raise FileAccessError, e.message
end
end | ruby | def delete_config_dir
begin
FileUtils.rm_r(config_dir) if dir_exists?
rescue StandardError => e
raise FileAccessError, e.message
end
end | [
"def",
"delete_config_dir",
"begin",
"FileUtils",
".",
"rm_r",
"(",
"config_dir",
")",
"if",
"dir_exists?",
"rescue",
"StandardError",
"=>",
"e",
"raise",
"FileAccessError",
",",
"e",
".",
"message",
"end",
"end"
] | Deletes the config directory including its contents. | [
"Deletes",
"the",
"config",
"directory",
"including",
"its",
"contents",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L222-L229 |
3,101 | rossf7/elasticrawl | lib/elasticrawl/config.rb | Elasticrawl.Config.status_message | def status_message(bucket_name, state)
message = ['', "Bucket s3://#{bucket_name} #{state}"]
message << "Config dir #{config_dir} #{state}"
state = 'complete' if state == 'created'
message << "Config #{state}"
message.join("\n")
end | ruby | def status_message(bucket_name, state)
message = ['', "Bucket s3://#{bucket_name} #{state}"]
message << "Config dir #{config_dir} #{state}"
state = 'complete' if state == 'created'
message << "Config #{state}"
message.join("\n")
end | [
"def",
"status_message",
"(",
"bucket_name",
",",
"state",
")",
"message",
"=",
"[",
"''",
",",
"\"Bucket s3://#{bucket_name} #{state}\"",
"]",
"message",
"<<",
"\"Config dir #{config_dir} #{state}\"",
"state",
"=",
"'complete'",
"if",
"state",
"==",
"'created'",
"message",
"<<",
"\"Config #{state}\"",
"message",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | Notifies user of results of init or destroy commands. | [
"Notifies",
"user",
"of",
"results",
"of",
"init",
"or",
"destroy",
"commands",
"."
] | db70bb6819c86805869f389daf1920f3acc87cef | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L232-L240 |
3,102 | ivpusic/migrate | lib/migrate/migrator.rb | Migrate.Migrator.exec_migration | def exec_migration(migration, is_up)
migration_dir = self.migration_dir(migration)
result = @lang.exec_migration(migration_dir, is_up)
if @lang.ext != "sql"
puts result
end
Log.info("Updating current version number...")
version = migration["version"]
is_up ? @db.log_up(version) : @db.log_down(version)
end | ruby | def exec_migration(migration, is_up)
migration_dir = self.migration_dir(migration)
result = @lang.exec_migration(migration_dir, is_up)
if @lang.ext != "sql"
puts result
end
Log.info("Updating current version number...")
version = migration["version"]
is_up ? @db.log_up(version) : @db.log_down(version)
end | [
"def",
"exec_migration",
"(",
"migration",
",",
"is_up",
")",
"migration_dir",
"=",
"self",
".",
"migration_dir",
"(",
"migration",
")",
"result",
"=",
"@lang",
".",
"exec_migration",
"(",
"migration_dir",
",",
"is_up",
")",
"if",
"@lang",
".",
"ext",
"!=",
"\"sql\"",
"puts",
"result",
"end",
"Log",
".",
"info",
"(",
"\"Updating current version number...\"",
")",
"version",
"=",
"migration",
"[",
"\"version\"",
"]",
"is_up",
"?",
"@db",
".",
"log_up",
"(",
"version",
")",
":",
"@db",
".",
"log_down",
"(",
"version",
")",
"end"
] | will execute single migration by running up or down script | [
"will",
"execute",
"single",
"migration",
"by",
"running",
"up",
"or",
"down",
"script"
] | 2673115509e42c436e09857451d4a1c335e1089d | https://github.com/ivpusic/migrate/blob/2673115509e42c436e09857451d4a1c335e1089d/lib/migrate/migrator.rb#L79-L89 |
3,103 | ivpusic/migrate | lib/migrate/migrator.rb | Migrate.Migrator.exec_migrations | def exec_migrations(is_up=true)
Log.info("Executing migrations...")
migrations = yield @db.current_version
if migrations.count == 0
Log.warn("Migrations not found")
return
end
migrations.each do |migration|
self.exec_migration(migration, is_up)
end
Log.success("Migrations executed. Current version: #{@db.current_version}")
end | ruby | def exec_migrations(is_up=true)
Log.info("Executing migrations...")
migrations = yield @db.current_version
if migrations.count == 0
Log.warn("Migrations not found")
return
end
migrations.each do |migration|
self.exec_migration(migration, is_up)
end
Log.success("Migrations executed. Current version: #{@db.current_version}")
end | [
"def",
"exec_migrations",
"(",
"is_up",
"=",
"true",
")",
"Log",
".",
"info",
"(",
"\"Executing migrations...\"",
")",
"migrations",
"=",
"yield",
"@db",
".",
"current_version",
"if",
"migrations",
".",
"count",
"==",
"0",
"Log",
".",
"warn",
"(",
"\"Migrations not found\"",
")",
"return",
"end",
"migrations",
".",
"each",
"do",
"|",
"migration",
"|",
"self",
".",
"exec_migration",
"(",
"migration",
",",
"is_up",
")",
"end",
"Log",
".",
"success",
"(",
"\"Migrations executed. Current version: #{@db.current_version}\"",
")",
"end"
] | will execute range of migrations | [
"will",
"execute",
"range",
"of",
"migrations"
] | 2673115509e42c436e09857451d4a1c335e1089d | https://github.com/ivpusic/migrate/blob/2673115509e42c436e09857451d4a1c335e1089d/lib/migrate/migrator.rb#L92-L105 |
3,104 | rrrene/sparkr | lib/sparkr/cli.rb | Sparkr.CLI.run | def run(*args)
if args.empty? || (args.size == 1 && %w(-h --help).include?(args.first))
puts help
else
sparkline = Sparkline.new(args.map(&:to_f))
puts sparkline.to_s
end
end | ruby | def run(*args)
if args.empty? || (args.size == 1 && %w(-h --help).include?(args.first))
puts help
else
sparkline = Sparkline.new(args.map(&:to_f))
puts sparkline.to_s
end
end | [
"def",
"run",
"(",
"*",
"args",
")",
"if",
"args",
".",
"empty?",
"||",
"(",
"args",
".",
"size",
"==",
"1",
"&&",
"%w(",
"-h",
"--help",
")",
".",
"include?",
"(",
"args",
".",
"first",
")",
")",
"puts",
"help",
"else",
"sparkline",
"=",
"Sparkline",
".",
"new",
"(",
"args",
".",
"map",
"(",
":to_f",
")",
")",
"puts",
"sparkline",
".",
"to_s",
"end",
"end"
] | Runs sparkr with the given +args+
@return [void] | [
"Runs",
"sparkr",
"with",
"the",
"given",
"+",
"args",
"+"
] | 2329d965ae421dfbc4743dd728884f2da501a107 | https://github.com/rrrene/sparkr/blob/2329d965ae421dfbc4743dd728884f2da501a107/lib/sparkr/cli.rb#L17-L24 |
3,105 | opentox/lazar | lib/compound.rb | OpenTox.Compound.fingerprint | def fingerprint type=DEFAULT_FINGERPRINT
unless fingerprints[type]
return [] unless self.smiles
#http://openbabel.org/docs/dev/FileFormats/MolPrint2D_format.html#molprint2d-format
if type == "MP2D"
fp = obconversion(smiles,"smi","mpd").strip.split("\t")
name = fp.shift # remove Title
fingerprints[type] = fp.uniq # no fingerprint counts
#http://openbabel.org/docs/dev/FileFormats/Multilevel_Neighborhoods_of_Atoms_(MNA).html
elsif type== "MNA"
level = 2 # TODO: level as parameter, evaluate level 1, see paper
fp = obconversion(smiles,"smi","mna","xL\"#{level}\"").split("\n")
fp.shift # remove Title
fingerprints[type] = fp
else # standard fingerprints
fp = OpenBabel::OBFingerprint.find_fingerprint(type)
obmol = OpenBabel::OBMol.new
obconversion = OpenBabel::OBConversion.new
obconversion.set_in_format "smi"
obconversion.read_string obmol, self.smiles
result = OpenBabel::VectorUnsignedInt.new
fp.get_fingerprint(obmol,result)
# TODO: %ignore *::DescribeBits @ line 163 openbabel/scripts/openbabel-ruby.i
#p OpenBabel::OBFingerprint.describe_bits(result)
# convert result to a list of the bits that are set
# from openbabel/scripts/python/pybel.py line 830
# see also http://openbabel.org/docs/dev/UseTheLibrary/Python_Pybel.html#fingerprints
result = result.to_a
bitsperint = OpenBabel::OBFingerprint.getbitsperint()
bits_set = []
start = 1
result.each do |x|
i = start
while x > 0 do
bits_set << i if (x % 2) == 1
x >>= 1
i += 1
end
start += bitsperint
end
fingerprints[type] = bits_set
end
save
end
fingerprints[type]
end | ruby | def fingerprint type=DEFAULT_FINGERPRINT
unless fingerprints[type]
return [] unless self.smiles
#http://openbabel.org/docs/dev/FileFormats/MolPrint2D_format.html#molprint2d-format
if type == "MP2D"
fp = obconversion(smiles,"smi","mpd").strip.split("\t")
name = fp.shift # remove Title
fingerprints[type] = fp.uniq # no fingerprint counts
#http://openbabel.org/docs/dev/FileFormats/Multilevel_Neighborhoods_of_Atoms_(MNA).html
elsif type== "MNA"
level = 2 # TODO: level as parameter, evaluate level 1, see paper
fp = obconversion(smiles,"smi","mna","xL\"#{level}\"").split("\n")
fp.shift # remove Title
fingerprints[type] = fp
else # standard fingerprints
fp = OpenBabel::OBFingerprint.find_fingerprint(type)
obmol = OpenBabel::OBMol.new
obconversion = OpenBabel::OBConversion.new
obconversion.set_in_format "smi"
obconversion.read_string obmol, self.smiles
result = OpenBabel::VectorUnsignedInt.new
fp.get_fingerprint(obmol,result)
# TODO: %ignore *::DescribeBits @ line 163 openbabel/scripts/openbabel-ruby.i
#p OpenBabel::OBFingerprint.describe_bits(result)
# convert result to a list of the bits that are set
# from openbabel/scripts/python/pybel.py line 830
# see also http://openbabel.org/docs/dev/UseTheLibrary/Python_Pybel.html#fingerprints
result = result.to_a
bitsperint = OpenBabel::OBFingerprint.getbitsperint()
bits_set = []
start = 1
result.each do |x|
i = start
while x > 0 do
bits_set << i if (x % 2) == 1
x >>= 1
i += 1
end
start += bitsperint
end
fingerprints[type] = bits_set
end
save
end
fingerprints[type]
end | [
"def",
"fingerprint",
"type",
"=",
"DEFAULT_FINGERPRINT",
"unless",
"fingerprints",
"[",
"type",
"]",
"return",
"[",
"]",
"unless",
"self",
".",
"smiles",
"#http://openbabel.org/docs/dev/FileFormats/MolPrint2D_format.html#molprint2d-format",
"if",
"type",
"==",
"\"MP2D\"",
"fp",
"=",
"obconversion",
"(",
"smiles",
",",
"\"smi\"",
",",
"\"mpd\"",
")",
".",
"strip",
".",
"split",
"(",
"\"\\t\"",
")",
"name",
"=",
"fp",
".",
"shift",
"# remove Title",
"fingerprints",
"[",
"type",
"]",
"=",
"fp",
".",
"uniq",
"# no fingerprint counts",
"#http://openbabel.org/docs/dev/FileFormats/Multilevel_Neighborhoods_of_Atoms_(MNA).html",
"elsif",
"type",
"==",
"\"MNA\"",
"level",
"=",
"2",
"# TODO: level as parameter, evaluate level 1, see paper",
"fp",
"=",
"obconversion",
"(",
"smiles",
",",
"\"smi\"",
",",
"\"mna\"",
",",
"\"xL\\\"#{level}\\\"\"",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"fp",
".",
"shift",
"# remove Title",
"fingerprints",
"[",
"type",
"]",
"=",
"fp",
"else",
"# standard fingerprints",
"fp",
"=",
"OpenBabel",
"::",
"OBFingerprint",
".",
"find_fingerprint",
"(",
"type",
")",
"obmol",
"=",
"OpenBabel",
"::",
"OBMol",
".",
"new",
"obconversion",
"=",
"OpenBabel",
"::",
"OBConversion",
".",
"new",
"obconversion",
".",
"set_in_format",
"\"smi\"",
"obconversion",
".",
"read_string",
"obmol",
",",
"self",
".",
"smiles",
"result",
"=",
"OpenBabel",
"::",
"VectorUnsignedInt",
".",
"new",
"fp",
".",
"get_fingerprint",
"(",
"obmol",
",",
"result",
")",
"# TODO: %ignore *::DescribeBits @ line 163 openbabel/scripts/openbabel-ruby.i",
"#p OpenBabel::OBFingerprint.describe_bits(result)",
"# convert result to a list of the bits that are set",
"# from openbabel/scripts/python/pybel.py line 830",
"# see also http://openbabel.org/docs/dev/UseTheLibrary/Python_Pybel.html#fingerprints",
"result",
"=",
"result",
".",
"to_a",
"bitsperint",
"=",
"OpenBabel",
"::",
"OBFingerprint",
".",
"getbitsperint",
"(",
")",
"bits_set",
"=",
"[",
"]",
"start",
"=",
"1",
"result",
".",
"each",
"do",
"|",
"x",
"|",
"i",
"=",
"start",
"while",
"x",
">",
"0",
"do",
"bits_set",
"<<",
"i",
"if",
"(",
"x",
"%",
"2",
")",
"==",
"1",
"x",
">>=",
"1",
"i",
"+=",
"1",
"end",
"start",
"+=",
"bitsperint",
"end",
"fingerprints",
"[",
"type",
"]",
"=",
"bits_set",
"end",
"save",
"end",
"fingerprints",
"[",
"type",
"]",
"end"
] | Create chemical fingerprint
@param [String] fingerprint type
@return [Array<String>] | [
"Create",
"chemical",
"fingerprint"
] | 1ee7de09c969e16fd11522d22179224e694b0161 | https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/compound.rb#L35-L80 |
3,106 | opentox/lazar | lib/compound.rb | OpenTox.Compound.smarts_match | def smarts_match smarts, count=false
obconversion = OpenBabel::OBConversion.new
obmol = OpenBabel::OBMol.new
obconversion.set_in_format('smi')
obconversion.read_string(obmol,self.smiles)
smarts_pattern = OpenBabel::OBSmartsPattern.new
smarts.collect do |sma|
smarts_pattern.init(sma.smarts)
if smarts_pattern.match(obmol)
count ? value = smarts_pattern.get_map_list.to_a.size : value = 1
else
value = 0
end
value
end
end | ruby | def smarts_match smarts, count=false
obconversion = OpenBabel::OBConversion.new
obmol = OpenBabel::OBMol.new
obconversion.set_in_format('smi')
obconversion.read_string(obmol,self.smiles)
smarts_pattern = OpenBabel::OBSmartsPattern.new
smarts.collect do |sma|
smarts_pattern.init(sma.smarts)
if smarts_pattern.match(obmol)
count ? value = smarts_pattern.get_map_list.to_a.size : value = 1
else
value = 0
end
value
end
end | [
"def",
"smarts_match",
"smarts",
",",
"count",
"=",
"false",
"obconversion",
"=",
"OpenBabel",
"::",
"OBConversion",
".",
"new",
"obmol",
"=",
"OpenBabel",
"::",
"OBMol",
".",
"new",
"obconversion",
".",
"set_in_format",
"(",
"'smi'",
")",
"obconversion",
".",
"read_string",
"(",
"obmol",
",",
"self",
".",
"smiles",
")",
"smarts_pattern",
"=",
"OpenBabel",
"::",
"OBSmartsPattern",
".",
"new",
"smarts",
".",
"collect",
"do",
"|",
"sma",
"|",
"smarts_pattern",
".",
"init",
"(",
"sma",
".",
"smarts",
")",
"if",
"smarts_pattern",
".",
"match",
"(",
"obmol",
")",
"count",
"?",
"value",
"=",
"smarts_pattern",
".",
"get_map_list",
".",
"to_a",
".",
"size",
":",
"value",
"=",
"1",
"else",
"value",
"=",
"0",
"end",
"value",
"end",
"end"
] | Match a SMARTS substructure
@param [String] smarts
@param [TrueClass,FalseClass] count matches or return true/false
@return [TrueClass,FalseClass,Fixnum] | [
"Match",
"a",
"SMARTS",
"substructure"
] | 1ee7de09c969e16fd11522d22179224e694b0161 | https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/compound.rb#L110-L125 |
3,107 | opentox/lazar | lib/compound.rb | OpenTox.Compound.svg | def svg
if self.svg_id.nil?
svg = obconversion(smiles,"smi","svg")
file = Mongo::Grid::File.new(svg, :filename => "#{id}.svg", :content_type => "image/svg")
update(:svg_id => $gridfs.insert_one(file))
end
$gridfs.find_one(_id: self.svg_id).data
end | ruby | def svg
if self.svg_id.nil?
svg = obconversion(smiles,"smi","svg")
file = Mongo::Grid::File.new(svg, :filename => "#{id}.svg", :content_type => "image/svg")
update(:svg_id => $gridfs.insert_one(file))
end
$gridfs.find_one(_id: self.svg_id).data
end | [
"def",
"svg",
"if",
"self",
".",
"svg_id",
".",
"nil?",
"svg",
"=",
"obconversion",
"(",
"smiles",
",",
"\"smi\"",
",",
"\"svg\"",
")",
"file",
"=",
"Mongo",
"::",
"Grid",
"::",
"File",
".",
"new",
"(",
"svg",
",",
":filename",
"=>",
"\"#{id}.svg\"",
",",
":content_type",
"=>",
"\"image/svg\"",
")",
"update",
"(",
":svg_id",
"=>",
"$gridfs",
".",
"insert_one",
"(",
"file",
")",
")",
"end",
"$gridfs",
".",
"find_one",
"(",
"_id",
":",
"self",
".",
"svg_id",
")",
".",
"data",
"end"
] | Get SVG image
@return [image/svg] Image data | [
"Get",
"SVG",
"image"
] | 1ee7de09c969e16fd11522d22179224e694b0161 | https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/compound.rb#L214-L221 |
3,108 | opentox/lazar | lib/compound.rb | OpenTox.Compound.png | def png
if self.png_id.nil?
png = obconversion(smiles,"smi","_png2")
file = Mongo::Grid::File.new(Base64.encode64(png), :filename => "#{id}.png", :content_type => "image/png")
update(:png_id => $gridfs.insert_one(file))
end
Base64.decode64($gridfs.find_one(_id: self.png_id).data)
end | ruby | def png
if self.png_id.nil?
png = obconversion(smiles,"smi","_png2")
file = Mongo::Grid::File.new(Base64.encode64(png), :filename => "#{id}.png", :content_type => "image/png")
update(:png_id => $gridfs.insert_one(file))
end
Base64.decode64($gridfs.find_one(_id: self.png_id).data)
end | [
"def",
"png",
"if",
"self",
".",
"png_id",
".",
"nil?",
"png",
"=",
"obconversion",
"(",
"smiles",
",",
"\"smi\"",
",",
"\"_png2\"",
")",
"file",
"=",
"Mongo",
"::",
"Grid",
"::",
"File",
".",
"new",
"(",
"Base64",
".",
"encode64",
"(",
"png",
")",
",",
":filename",
"=>",
"\"#{id}.png\"",
",",
":content_type",
"=>",
"\"image/png\"",
")",
"update",
"(",
":png_id",
"=>",
"$gridfs",
".",
"insert_one",
"(",
"file",
")",
")",
"end",
"Base64",
".",
"decode64",
"(",
"$gridfs",
".",
"find_one",
"(",
"_id",
":",
"self",
".",
"png_id",
")",
".",
"data",
")",
"end"
] | Get png image
@example
image = compound.png
@return [image/png] Image data | [
"Get",
"png",
"image"
] | 1ee7de09c969e16fd11522d22179224e694b0161 | https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/compound.rb#L227-L234 |
3,109 | brasten/scruffy | lib/scruffy/layers/average.rb | Scruffy::Layers.Average.generate_coordinates | def generate_coordinates(options = {})
key_layer = layers.find { |layer| layer.relevant_data? }
options[:point_distance] = width / (key_layer.points.size - 1).to_f
coords = []
#TODO this will likely break with the new hash model
key_layer.points.each_with_index do |layer, idx|
sum, objects = points.inject([0, 0]) do |arr, elem|
if elem.relevant_data?
arr[0] += elem.points[idx]
arr[1] += 1
end
arr
end
average = sum / objects.to_f
x_coord = options[:point_distance] * idx
relative_percent = ((average == min_value) ? 0 : ((average - min_value) / (max_value - min_value).to_f))
y_coord = (height - (height * relative_percent))
coords << [x_coord, y_coord].join(',')
end
return coords
end | ruby | def generate_coordinates(options = {})
key_layer = layers.find { |layer| layer.relevant_data? }
options[:point_distance] = width / (key_layer.points.size - 1).to_f
coords = []
#TODO this will likely break with the new hash model
key_layer.points.each_with_index do |layer, idx|
sum, objects = points.inject([0, 0]) do |arr, elem|
if elem.relevant_data?
arr[0] += elem.points[idx]
arr[1] += 1
end
arr
end
average = sum / objects.to_f
x_coord = options[:point_distance] * idx
relative_percent = ((average == min_value) ? 0 : ((average - min_value) / (max_value - min_value).to_f))
y_coord = (height - (height * relative_percent))
coords << [x_coord, y_coord].join(',')
end
return coords
end | [
"def",
"generate_coordinates",
"(",
"options",
"=",
"{",
"}",
")",
"key_layer",
"=",
"layers",
".",
"find",
"{",
"|",
"layer",
"|",
"layer",
".",
"relevant_data?",
"}",
"options",
"[",
":point_distance",
"]",
"=",
"width",
"/",
"(",
"key_layer",
".",
"points",
".",
"size",
"-",
"1",
")",
".",
"to_f",
"coords",
"=",
"[",
"]",
"#TODO this will likely break with the new hash model",
"key_layer",
".",
"points",
".",
"each_with_index",
"do",
"|",
"layer",
",",
"idx",
"|",
"sum",
",",
"objects",
"=",
"points",
".",
"inject",
"(",
"[",
"0",
",",
"0",
"]",
")",
"do",
"|",
"arr",
",",
"elem",
"|",
"if",
"elem",
".",
"relevant_data?",
"arr",
"[",
"0",
"]",
"+=",
"elem",
".",
"points",
"[",
"idx",
"]",
"arr",
"[",
"1",
"]",
"+=",
"1",
"end",
"arr",
"end",
"average",
"=",
"sum",
"/",
"objects",
".",
"to_f",
"x_coord",
"=",
"options",
"[",
":point_distance",
"]",
"*",
"idx",
"relative_percent",
"=",
"(",
"(",
"average",
"==",
"min_value",
")",
"?",
"0",
":",
"(",
"(",
"average",
"-",
"min_value",
")",
"/",
"(",
"max_value",
"-",
"min_value",
")",
".",
"to_f",
")",
")",
"y_coord",
"=",
"(",
"height",
"-",
"(",
"height",
"*",
"relative_percent",
")",
")",
"coords",
"<<",
"[",
"x_coord",
",",
"y_coord",
"]",
".",
"join",
"(",
"','",
")",
"end",
"return",
"coords",
"end"
] | Override default generate_coordinates method to iterate through the layers and
generate coordinates based on the average data points. | [
"Override",
"default",
"generate_coordinates",
"method",
"to",
"iterate",
"through",
"the",
"layers",
"and",
"generate",
"coordinates",
"based",
"on",
"the",
"average",
"data",
"points",
"."
] | 4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e | https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/average.rb#L36-L64 |
3,110 | social-snippet/social-snippet | lib/social_snippet/repository/repository_manager.rb | SocialSnippet::Repository.RepositoryManager.resolve_snippet_path | def resolve_snippet_path(context, tag)
if tag.has_repo?
pkg = find_package_by_tag(tag)
pkg.snippet_path tag.path
else
new_context = context.clone
new_context.dirname + "/" + tag.filename
end
end | ruby | def resolve_snippet_path(context, tag)
if tag.has_repo?
pkg = find_package_by_tag(tag)
pkg.snippet_path tag.path
else
new_context = context.clone
new_context.dirname + "/" + tag.filename
end
end | [
"def",
"resolve_snippet_path",
"(",
"context",
",",
"tag",
")",
"if",
"tag",
".",
"has_repo?",
"pkg",
"=",
"find_package_by_tag",
"(",
"tag",
")",
"pkg",
".",
"snippet_path",
"tag",
".",
"path",
"else",
"new_context",
"=",
"context",
".",
"clone",
"new_context",
".",
"dirname",
"+",
"\"/\"",
"+",
"tag",
".",
"filename",
"end",
"end"
] | Resolve snippet path by context and tag
@param context [::SocialSnippet::Context] The context of snippet
@param tag [::SocialSnippet::Tag] The tag of snippet | [
"Resolve",
"snippet",
"path",
"by",
"context",
"and",
"tag"
] | 46ae25b3e8ced2c8b5b4923ed9e1a019c9835367 | https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/repository/repository_manager.rb#L26-L34 |
3,111 | social-snippet/social-snippet | lib/social_snippet/repository/repository_manager.rb | SocialSnippet::Repository.RepositoryManager.find_package_by_tag | def find_package_by_tag(tag)
if tag.has_ref?
find_package(tag.repo, tag.ref)
else
find_package(tag.repo)
end
end | ruby | def find_package_by_tag(tag)
if tag.has_ref?
find_package(tag.repo, tag.ref)
else
find_package(tag.repo)
end
end | [
"def",
"find_package_by_tag",
"(",
"tag",
")",
"if",
"tag",
".",
"has_ref?",
"find_package",
"(",
"tag",
".",
"repo",
",",
"tag",
".",
"ref",
")",
"else",
"find_package",
"(",
"tag",
".",
"repo",
")",
"end",
"end"
] | Find repository by tag
@param tag [::SocialSnippet::Tag] The tag of repository | [
"Find",
"repository",
"by",
"tag"
] | 46ae25b3e8ced2c8b5b4923ed9e1a019c9835367 | https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/repository/repository_manager.rb#L39-L45 |
3,112 | social-snippet/social-snippet | lib/social_snippet/repository/repository_manager.rb | SocialSnippet::Repository.RepositoryManager.find_package | def find_package(name, ref = nil)
repo = find_repository(name)
ref ||= repo.latest_package_version || repo.current_ref
raise "invalid references" unless repo.has_ref?(ref)
Models::Package.find_by(
:repo_name => name,
:rev_hash => repo.rev_hash[ref],
)
end | ruby | def find_package(name, ref = nil)
repo = find_repository(name)
ref ||= repo.latest_package_version || repo.current_ref
raise "invalid references" unless repo.has_ref?(ref)
Models::Package.find_by(
:repo_name => name,
:rev_hash => repo.rev_hash[ref],
)
end | [
"def",
"find_package",
"(",
"name",
",",
"ref",
"=",
"nil",
")",
"repo",
"=",
"find_repository",
"(",
"name",
")",
"ref",
"||=",
"repo",
".",
"latest_package_version",
"||",
"repo",
".",
"current_ref",
"raise",
"\"invalid references\"",
"unless",
"repo",
".",
"has_ref?",
"(",
"ref",
")",
"Models",
"::",
"Package",
".",
"find_by",
"(",
":repo_name",
"=>",
"name",
",",
":rev_hash",
"=>",
"repo",
".",
"rev_hash",
"[",
"ref",
"]",
",",
")",
"end"
] | Find repository by repo name
@param name [String] The name of repository | [
"Find",
"repository",
"by",
"repo",
"name"
] | 46ae25b3e8ced2c8b5b4923ed9e1a019c9835367 | https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/repository/repository_manager.rb#L50-L58 |
3,113 | drish/hyperb | lib/hyperb/images/images.rb | Hyperb.Images.remove_image | def remove_image(params = {})
raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name')
path = '/images/' + params[:name]
query = {}
query[:force] = true if params.key?(:force)
res = JSON.parse(Hyperb::Request.new(self, path, query, 'delete').perform)
downcase_symbolize(res)
end | ruby | def remove_image(params = {})
raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name')
path = '/images/' + params[:name]
query = {}
query[:force] = true if params.key?(:force)
res = JSON.parse(Hyperb::Request.new(self, path, query, 'delete').perform)
downcase_symbolize(res)
end | [
"def",
"remove_image",
"(",
"params",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"'Invalid arguments.'",
"unless",
"check_arguments",
"(",
"params",
",",
"'name'",
")",
"path",
"=",
"'/images/'",
"+",
"params",
"[",
":name",
"]",
"query",
"=",
"{",
"}",
"query",
"[",
":force",
"]",
"=",
"true",
"if",
"params",
".",
"key?",
"(",
":force",
")",
"res",
"=",
"JSON",
".",
"parse",
"(",
"Hyperb",
"::",
"Request",
".",
"new",
"(",
"self",
",",
"path",
",",
"query",
",",
"'delete'",
")",
".",
"perform",
")",
"downcase_symbolize",
"(",
"res",
")",
"end"
] | remove an image
@see https://docs.hyper.sh/Reference/API/2016-04-04%20[Ver.%201.23]/Image/remove.html
@raise [Hyperb::Error::Unauthorized] raised when credentials are not valid.
@raise [Hyperb::Error::NotFound] raised when tag is not found.
@raise [Hyperb::Error::Conflict] raised when the image will only be removed with force.
@raise [Hyperb::Error::InternalServerError] server error.
@return [Array] array of downcase symbolized json response.
@param params [Hash] A customizable set of params.
@option params [String] :name image name to be removed
@option params [Boolean] :force force image to be removed | [
"remove",
"an",
"image"
] | 637de68dc304d8d07470a771f499e33f227955f4 | https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/images/images.rb#L80-L87 |
3,114 | drish/hyperb | lib/hyperb/images/images.rb | Hyperb.Images.inspect_image | def inspect_image(params = {})
raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name')
path = '/images/' + params[:name] + '/json'
res = JSON.parse(Hyperb::Request.new(self, path, {}, 'get').perform)
downcase_symbolize(res)
end | ruby | def inspect_image(params = {})
raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name')
path = '/images/' + params[:name] + '/json'
res = JSON.parse(Hyperb::Request.new(self, path, {}, 'get').perform)
downcase_symbolize(res)
end | [
"def",
"inspect_image",
"(",
"params",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"'Invalid arguments.'",
"unless",
"check_arguments",
"(",
"params",
",",
"'name'",
")",
"path",
"=",
"'/images/'",
"+",
"params",
"[",
":name",
"]",
"+",
"'/json'",
"res",
"=",
"JSON",
".",
"parse",
"(",
"Hyperb",
"::",
"Request",
".",
"new",
"(",
"self",
",",
"path",
",",
"{",
"}",
",",
"'get'",
")",
".",
"perform",
")",
"downcase_symbolize",
"(",
"res",
")",
"end"
] | inspect an image
@see https://docs.hyper.sh/Reference/API/2016-04-04%20[Ver.%201.23]/Image/inspect.html
@raise [Hyperb::Error::Unauthorized] raised when credentials are not valid.
@raise [Hyperb::Error::NotFound] raised when tag is not found.
@raise [Hyperb::Error::InternalServerError] server error on hyper side.
@return [Hash] downcased symbolized `inspect` json response.
@param params [Hash] A customizable set of params.
@option params [String] :name image name to be removed | [
"inspect",
"an",
"image"
] | 637de68dc304d8d07470a771f499e33f227955f4 | https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/images/images.rb#L101-L106 |
3,115 | mwunsch/redwood | lib/redwood/node.rb | Redwood.Node.add_child | def add_child(name)
child = self.class.new(name, self)
yield child if block_given?
children << child
child
end | ruby | def add_child(name)
child = self.class.new(name, self)
yield child if block_given?
children << child
child
end | [
"def",
"add_child",
"(",
"name",
")",
"child",
"=",
"self",
".",
"class",
".",
"new",
"(",
"name",
",",
"self",
")",
"yield",
"child",
"if",
"block_given?",
"children",
"<<",
"child",
"child",
"end"
] | Creates a child, adds it to children, and returns the child | [
"Creates",
"a",
"child",
"adds",
"it",
"to",
"children",
"and",
"returns",
"the",
"child"
] | 6f3f980d8d84fd9a90aac30d92c3fb7ffcae1055 | https://github.com/mwunsch/redwood/blob/6f3f980d8d84fd9a90aac30d92c3fb7ffcae1055/lib/redwood/node.rb#L16-L21 |
3,116 | mwunsch/redwood | lib/redwood/node.rb | Redwood.Node.[] | def [](key)
selected_child = children.select {|child| child.name == key }
selected_child.size.eql?(1) ? selected_child.first : selected_child
end | ruby | def [](key)
selected_child = children.select {|child| child.name == key }
selected_child.size.eql?(1) ? selected_child.first : selected_child
end | [
"def",
"[]",
"(",
"key",
")",
"selected_child",
"=",
"children",
".",
"select",
"{",
"|",
"child",
"|",
"child",
".",
"name",
"==",
"key",
"}",
"selected_child",
".",
"size",
".",
"eql?",
"(",
"1",
")",
"?",
"selected_child",
".",
"first",
":",
"selected_child",
"end"
] | Lookup a child node by its name | [
"Lookup",
"a",
"child",
"node",
"by",
"its",
"name"
] | 6f3f980d8d84fd9a90aac30d92c3fb7ffcae1055 | https://github.com/mwunsch/redwood/blob/6f3f980d8d84fd9a90aac30d92c3fb7ffcae1055/lib/redwood/node.rb#L29-L32 |
3,117 | fabiokr/manageable | app/controllers/manageable/application_controller.rb | Manageable.ApplicationController.respond_with_with_storage | def respond_with_with_storage(*args, &block)
@responded_with = args.last.is_a?(Hash) ? args - [args.last] : args
respond_with_without_storage(*args, &block)
end | ruby | def respond_with_with_storage(*args, &block)
@responded_with = args.last.is_a?(Hash) ? args - [args.last] : args
respond_with_without_storage(*args, &block)
end | [
"def",
"respond_with_with_storage",
"(",
"*",
"args",
",",
"&",
"block",
")",
"@responded_with",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
"-",
"[",
"args",
".",
"last",
"]",
":",
"args",
"respond_with_without_storage",
"(",
"args",
",",
"block",
")",
"end"
] | Custom respond_with wich stores resources for later use | [
"Custom",
"respond_with",
"wich",
"stores",
"resources",
"for",
"later",
"use"
] | 9db47dea0e2e73e164923de23be20109fe1cf35f | https://github.com/fabiokr/manageable/blob/9db47dea0e2e73e164923de23be20109fe1cf35f/app/controllers/manageable/application_controller.rb#L50-L53 |
3,118 | drish/hyperb | lib/hyperb/containers/host_config.rb | Hyperb.HostConfig.fmt | def fmt
formated = {}
attrs.each_key do |key|
formated[camelize(key)] = attrs[key]
end
formated
end | ruby | def fmt
formated = {}
attrs.each_key do |key|
formated[camelize(key)] = attrs[key]
end
formated
end | [
"def",
"fmt",
"formated",
"=",
"{",
"}",
"attrs",
".",
"each_key",
"do",
"|",
"key",
"|",
"formated",
"[",
"camelize",
"(",
"key",
")",
"]",
"=",
"attrs",
"[",
"key",
"]",
"end",
"formated",
"end"
] | returns a hash containing formated host config data
@returns [Hash] | [
"returns",
"a",
"hash",
"containing",
"formated",
"host",
"config",
"data"
] | 637de68dc304d8d07470a771f499e33f227955f4 | https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/containers/host_config.rb#L23-L29 |
3,119 | ekylibre/beardley | lib/beardley/report.rb | Beardley.Report.to_pdf | def to_pdf(*args)
options = extract_options!(args)
datasource = args[0]
_JasperPrint = Rjb.import('net.sf.jasperreports.engine.JasperPrint')
_JasperExportManager = Rjb.import('net.sf.jasperreports.engine.JasperExportManager')
_JasperExportManager._invoke('exportReportToPdf', 'Lnet.sf.jasperreports.engine.JasperPrint;', prepare(datasource))
end | ruby | def to_pdf(*args)
options = extract_options!(args)
datasource = args[0]
_JasperPrint = Rjb.import('net.sf.jasperreports.engine.JasperPrint')
_JasperExportManager = Rjb.import('net.sf.jasperreports.engine.JasperExportManager')
_JasperExportManager._invoke('exportReportToPdf', 'Lnet.sf.jasperreports.engine.JasperPrint;', prepare(datasource))
end | [
"def",
"to_pdf",
"(",
"*",
"args",
")",
"options",
"=",
"extract_options!",
"(",
"args",
")",
"datasource",
"=",
"args",
"[",
"0",
"]",
"_JasperPrint",
"=",
"Rjb",
".",
"import",
"(",
"'net.sf.jasperreports.engine.JasperPrint'",
")",
"_JasperExportManager",
"=",
"Rjb",
".",
"import",
"(",
"'net.sf.jasperreports.engine.JasperExportManager'",
")",
"_JasperExportManager",
".",
"_invoke",
"(",
"'exportReportToPdf'",
",",
"'Lnet.sf.jasperreports.engine.JasperPrint;'",
",",
"prepare",
"(",
"datasource",
")",
")",
"end"
] | Constructor for a report generator
Export report to PDF with given datasource | [
"Constructor",
"for",
"a",
"report",
"generator",
"Export",
"report",
"to",
"PDF",
"with",
"given",
"datasource"
] | 7483991cb2a670a1d977a4868f204ad66c0be243 | https://github.com/ekylibre/beardley/blob/7483991cb2a670a1d977a4868f204ad66c0be243/lib/beardley/report.rb#L56-L62 |
3,120 | ekylibre/beardley | lib/beardley/report.rb | Beardley.Report.to_file | def to_file(format, *args)
options = extract_options!(args)
datasource = args[0]
path = options[:path] || File.join(Dir.tmpdir, "beardley_#{Time.now.to_i.to_s(36)}_#{rand(100_000_000_000).to_s(36)}.#{format}")
if format == :pdf
_JasperPrint = Rjb.import('net.sf.jasperreports.engine.JasperPrint')
_JasperExportManager = Rjb.import('net.sf.jasperreports.engine.JasperExportManager')
_JasperExportManager._invoke('exportReportToPdfFile', 'Lnet.sf.jasperreports.engine.JasperPrint;Ljava.lang.String;', prepare(datasource), Rjb.import('java.lang.String').new(path.to_s))
elsif Beardley.exporters[format]
exporter = Beardley.with_warnings { Rjb.import(Beardley.exporters[format]) }.new
_JRExporterParameter = Rjb.import('net.sf.jasperreports.engine.JRExporterParameter')
exporter.setParameter(_JRExporterParameter.JASPER_PRINT, prepare(datasource))
exporter.setParameter(_JRExporterParameter.OUTPUT_FILE_NAME, path.to_s)
exporter.exportReport
else
raise "Invalid export format: #{format.inspect}"
end
path
end | ruby | def to_file(format, *args)
options = extract_options!(args)
datasource = args[0]
path = options[:path] || File.join(Dir.tmpdir, "beardley_#{Time.now.to_i.to_s(36)}_#{rand(100_000_000_000).to_s(36)}.#{format}")
if format == :pdf
_JasperPrint = Rjb.import('net.sf.jasperreports.engine.JasperPrint')
_JasperExportManager = Rjb.import('net.sf.jasperreports.engine.JasperExportManager')
_JasperExportManager._invoke('exportReportToPdfFile', 'Lnet.sf.jasperreports.engine.JasperPrint;Ljava.lang.String;', prepare(datasource), Rjb.import('java.lang.String').new(path.to_s))
elsif Beardley.exporters[format]
exporter = Beardley.with_warnings { Rjb.import(Beardley.exporters[format]) }.new
_JRExporterParameter = Rjb.import('net.sf.jasperreports.engine.JRExporterParameter')
exporter.setParameter(_JRExporterParameter.JASPER_PRINT, prepare(datasource))
exporter.setParameter(_JRExporterParameter.OUTPUT_FILE_NAME, path.to_s)
exporter.exportReport
else
raise "Invalid export format: #{format.inspect}"
end
path
end | [
"def",
"to_file",
"(",
"format",
",",
"*",
"args",
")",
"options",
"=",
"extract_options!",
"(",
"args",
")",
"datasource",
"=",
"args",
"[",
"0",
"]",
"path",
"=",
"options",
"[",
":path",
"]",
"||",
"File",
".",
"join",
"(",
"Dir",
".",
"tmpdir",
",",
"\"beardley_#{Time.now.to_i.to_s(36)}_#{rand(100_000_000_000).to_s(36)}.#{format}\"",
")",
"if",
"format",
"==",
":pdf",
"_JasperPrint",
"=",
"Rjb",
".",
"import",
"(",
"'net.sf.jasperreports.engine.JasperPrint'",
")",
"_JasperExportManager",
"=",
"Rjb",
".",
"import",
"(",
"'net.sf.jasperreports.engine.JasperExportManager'",
")",
"_JasperExportManager",
".",
"_invoke",
"(",
"'exportReportToPdfFile'",
",",
"'Lnet.sf.jasperreports.engine.JasperPrint;Ljava.lang.String;'",
",",
"prepare",
"(",
"datasource",
")",
",",
"Rjb",
".",
"import",
"(",
"'java.lang.String'",
")",
".",
"new",
"(",
"path",
".",
"to_s",
")",
")",
"elsif",
"Beardley",
".",
"exporters",
"[",
"format",
"]",
"exporter",
"=",
"Beardley",
".",
"with_warnings",
"{",
"Rjb",
".",
"import",
"(",
"Beardley",
".",
"exporters",
"[",
"format",
"]",
")",
"}",
".",
"new",
"_JRExporterParameter",
"=",
"Rjb",
".",
"import",
"(",
"'net.sf.jasperreports.engine.JRExporterParameter'",
")",
"exporter",
".",
"setParameter",
"(",
"_JRExporterParameter",
".",
"JASPER_PRINT",
",",
"prepare",
"(",
"datasource",
")",
")",
"exporter",
".",
"setParameter",
"(",
"_JRExporterParameter",
".",
"OUTPUT_FILE_NAME",
",",
"path",
".",
"to_s",
")",
"exporter",
".",
"exportReport",
"else",
"raise",
"\"Invalid export format: #{format.inspect}\"",
"end",
"path",
"end"
] | Generic method to export to some format like ODT and DOCX as file in the given place | [
"Generic",
"method",
"to",
"export",
"to",
"some",
"format",
"like",
"ODT",
"and",
"DOCX",
"as",
"file",
"in",
"the",
"given",
"place"
] | 7483991cb2a670a1d977a4868f204ad66c0be243 | https://github.com/ekylibre/beardley/blob/7483991cb2a670a1d977a4868f204ad66c0be243/lib/beardley/report.rb#L90-L108 |
3,121 | ekylibre/beardley | lib/beardley/report.rb | Beardley.Report.to | def to(format, *args)
options = extract_options!(args)
datasource = args[0]
file = Tempfile.new("to_#{format}")
exporter = Beardley.with_warnings { Rjb.import(Beardley.exporters[format]) }.new
_JRExporterParameter = Rjb.import('net.sf.jasperreports.engine.JRExporterParameter')
exporter.setParameter(_JRExporterParameter.JASPER_PRINT, prepare(datasource))
exporter.setParameter(_JRExporterParameter.OUTPUT_FILE_NAME, file.path.to_s)
exporter.exportReport
file.rewind
report = file.read
file.close(true)
report
end | ruby | def to(format, *args)
options = extract_options!(args)
datasource = args[0]
file = Tempfile.new("to_#{format}")
exporter = Beardley.with_warnings { Rjb.import(Beardley.exporters[format]) }.new
_JRExporterParameter = Rjb.import('net.sf.jasperreports.engine.JRExporterParameter')
exporter.setParameter(_JRExporterParameter.JASPER_PRINT, prepare(datasource))
exporter.setParameter(_JRExporterParameter.OUTPUT_FILE_NAME, file.path.to_s)
exporter.exportReport
file.rewind
report = file.read
file.close(true)
report
end | [
"def",
"to",
"(",
"format",
",",
"*",
"args",
")",
"options",
"=",
"extract_options!",
"(",
"args",
")",
"datasource",
"=",
"args",
"[",
"0",
"]",
"file",
"=",
"Tempfile",
".",
"new",
"(",
"\"to_#{format}\"",
")",
"exporter",
"=",
"Beardley",
".",
"with_warnings",
"{",
"Rjb",
".",
"import",
"(",
"Beardley",
".",
"exporters",
"[",
"format",
"]",
")",
"}",
".",
"new",
"_JRExporterParameter",
"=",
"Rjb",
".",
"import",
"(",
"'net.sf.jasperreports.engine.JRExporterParameter'",
")",
"exporter",
".",
"setParameter",
"(",
"_JRExporterParameter",
".",
"JASPER_PRINT",
",",
"prepare",
"(",
"datasource",
")",
")",
"exporter",
".",
"setParameter",
"(",
"_JRExporterParameter",
".",
"OUTPUT_FILE_NAME",
",",
"file",
".",
"path",
".",
"to_s",
")",
"exporter",
".",
"exportReport",
"file",
".",
"rewind",
"report",
"=",
"file",
".",
"read",
"file",
".",
"close",
"(",
"true",
")",
"report",
"end"
] | Generic method to export to some format like ODT and DOCX | [
"Generic",
"method",
"to",
"export",
"to",
"some",
"format",
"like",
"ODT",
"and",
"DOCX"
] | 7483991cb2a670a1d977a4868f204ad66c0be243 | https://github.com/ekylibre/beardley/blob/7483991cb2a670a1d977a4868f204ad66c0be243/lib/beardley/report.rb#L123-L136 |
3,122 | ekylibre/beardley | lib/beardley/report.rb | Beardley.Report.prepare | def prepare(datasource = nil)
# Compile it, if needed
if @source_file && ((!@object_file.exist? && @source_file.exist?) || (@source_file.exist? && @source_file.mtime > @object_file.mtime))
_JasperCompileManager = Rjb.import('net.sf.jasperreports.engine.JasperCompileManager')
_JasperCompileManager.compileReportToFile(@source_file.to_s, @object_file.to_s)
end
load_datasource(datasource)
end | ruby | def prepare(datasource = nil)
# Compile it, if needed
if @source_file && ((!@object_file.exist? && @source_file.exist?) || (@source_file.exist? && @source_file.mtime > @object_file.mtime))
_JasperCompileManager = Rjb.import('net.sf.jasperreports.engine.JasperCompileManager')
_JasperCompileManager.compileReportToFile(@source_file.to_s, @object_file.to_s)
end
load_datasource(datasource)
end | [
"def",
"prepare",
"(",
"datasource",
"=",
"nil",
")",
"# Compile it, if needed",
"if",
"@source_file",
"&&",
"(",
"(",
"!",
"@object_file",
".",
"exist?",
"&&",
"@source_file",
".",
"exist?",
")",
"||",
"(",
"@source_file",
".",
"exist?",
"&&",
"@source_file",
".",
"mtime",
">",
"@object_file",
".",
"mtime",
")",
")",
"_JasperCompileManager",
"=",
"Rjb",
".",
"import",
"(",
"'net.sf.jasperreports.engine.JasperCompileManager'",
")",
"_JasperCompileManager",
".",
"compileReportToFile",
"(",
"@source_file",
".",
"to_s",
",",
"@object_file",
".",
"to_s",
")",
"end",
"load_datasource",
"(",
"datasource",
")",
"end"
] | Create object file if not exist and load datasource | [
"Create",
"object",
"file",
"if",
"not",
"exist",
"and",
"load",
"datasource"
] | 7483991cb2a670a1d977a4868f204ad66c0be243 | https://github.com/ekylibre/beardley/blob/7483991cb2a670a1d977a4868f204ad66c0be243/lib/beardley/report.rb#L144-L151 |
3,123 | ekylibre/beardley | lib/beardley/report.rb | Beardley.Report.prepare_params | def prepare_params
_HashMap = Rjb.import('java.util.HashMap')
_JavaString = Rjb.import('java.lang.String')
# Converting default report params to java HashMap
params = _HashMap.new
Beardley.config[:report_params].each do |k, v|
params.put(k, v)
end
# Convert the ruby parameters' hash to a java HashMap, but keeps it as
# default when they already represent a JRB entity.
# Pay attention that, for now, all other parameters are converted to string!
@parameters.each do |key, value|
params.put(_JavaString.new(key.to_s), parameter_value_of(value))
end
params
end | ruby | def prepare_params
_HashMap = Rjb.import('java.util.HashMap')
_JavaString = Rjb.import('java.lang.String')
# Converting default report params to java HashMap
params = _HashMap.new
Beardley.config[:report_params].each do |k, v|
params.put(k, v)
end
# Convert the ruby parameters' hash to a java HashMap, but keeps it as
# default when they already represent a JRB entity.
# Pay attention that, for now, all other parameters are converted to string!
@parameters.each do |key, value|
params.put(_JavaString.new(key.to_s), parameter_value_of(value))
end
params
end | [
"def",
"prepare_params",
"_HashMap",
"=",
"Rjb",
".",
"import",
"(",
"'java.util.HashMap'",
")",
"_JavaString",
"=",
"Rjb",
".",
"import",
"(",
"'java.lang.String'",
")",
"# Converting default report params to java HashMap",
"params",
"=",
"_HashMap",
".",
"new",
"Beardley",
".",
"config",
"[",
":report_params",
"]",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"params",
".",
"put",
"(",
"k",
",",
"v",
")",
"end",
"# Convert the ruby parameters' hash to a java HashMap, but keeps it as",
"# default when they already represent a JRB entity.",
"# Pay attention that, for now, all other parameters are converted to string!",
"@parameters",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"params",
".",
"put",
"(",
"_JavaString",
".",
"new",
"(",
"key",
".",
"to_s",
")",
",",
"parameter_value_of",
"(",
"value",
")",
")",
"end",
"params",
"end"
] | Build the default parameters Hash for printing | [
"Build",
"the",
"default",
"parameters",
"Hash",
"for",
"printing"
] | 7483991cb2a670a1d977a4868f204ad66c0be243 | https://github.com/ekylibre/beardley/blob/7483991cb2a670a1d977a4868f204ad66c0be243/lib/beardley/report.rb#L154-L172 |
3,124 | ekylibre/beardley | lib/beardley/report.rb | Beardley.Report.load_datasource | def load_datasource(datasource = nil)
jasper_params = prepare_params
# Parse and load XML as datasource
if datasource
_InputSource = Rjb.import('org.xml.sax.InputSource')
_StringReader = Rjb.import('java.io.StringReader')
_JRXmlUtils = Rjb.import('net.sf.jasperreports.engine.util.JRXmlUtils')
_JRXPathQueryExecuterFactory = Beardley.with_warnings { Rjb.import('net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory') }
input_source = _InputSource.new
input_source.setCharacterStream(_StringReader.new(datasource.to_s))
data_document = Beardley.with_warnings do
_JRXmlUtils._invoke('parse', 'Lorg.xml.sax.InputSource;', input_source)
end
jasper_params.put(_JRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT, data_document)
end
# Build JasperPrint
fill_report(jasper_params, datasource)
end | ruby | def load_datasource(datasource = nil)
jasper_params = prepare_params
# Parse and load XML as datasource
if datasource
_InputSource = Rjb.import('org.xml.sax.InputSource')
_StringReader = Rjb.import('java.io.StringReader')
_JRXmlUtils = Rjb.import('net.sf.jasperreports.engine.util.JRXmlUtils')
_JRXPathQueryExecuterFactory = Beardley.with_warnings { Rjb.import('net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory') }
input_source = _InputSource.new
input_source.setCharacterStream(_StringReader.new(datasource.to_s))
data_document = Beardley.with_warnings do
_JRXmlUtils._invoke('parse', 'Lorg.xml.sax.InputSource;', input_source)
end
jasper_params.put(_JRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT, data_document)
end
# Build JasperPrint
fill_report(jasper_params, datasource)
end | [
"def",
"load_datasource",
"(",
"datasource",
"=",
"nil",
")",
"jasper_params",
"=",
"prepare_params",
"# Parse and load XML as datasource",
"if",
"datasource",
"_InputSource",
"=",
"Rjb",
".",
"import",
"(",
"'org.xml.sax.InputSource'",
")",
"_StringReader",
"=",
"Rjb",
".",
"import",
"(",
"'java.io.StringReader'",
")",
"_JRXmlUtils",
"=",
"Rjb",
".",
"import",
"(",
"'net.sf.jasperreports.engine.util.JRXmlUtils'",
")",
"_JRXPathQueryExecuterFactory",
"=",
"Beardley",
".",
"with_warnings",
"{",
"Rjb",
".",
"import",
"(",
"'net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory'",
")",
"}",
"input_source",
"=",
"_InputSource",
".",
"new",
"input_source",
".",
"setCharacterStream",
"(",
"_StringReader",
".",
"new",
"(",
"datasource",
".",
"to_s",
")",
")",
"data_document",
"=",
"Beardley",
".",
"with_warnings",
"do",
"_JRXmlUtils",
".",
"_invoke",
"(",
"'parse'",
",",
"'Lorg.xml.sax.InputSource;'",
",",
"input_source",
")",
"end",
"jasper_params",
".",
"put",
"(",
"_JRXPathQueryExecuterFactory",
".",
"PARAMETER_XML_DATA_DOCUMENT",
",",
"data_document",
")",
"end",
"# Build JasperPrint",
"fill_report",
"(",
"jasper_params",
",",
"datasource",
")",
"end"
] | Load parseable XML datasource with java component | [
"Load",
"parseable",
"XML",
"datasource",
"with",
"java",
"component"
] | 7483991cb2a670a1d977a4868f204ad66c0be243 | https://github.com/ekylibre/beardley/blob/7483991cb2a670a1d977a4868f204ad66c0be243/lib/beardley/report.rb#L175-L194 |
3,125 | ekylibre/beardley | lib/beardley/report.rb | Beardley.Report.fill_report | def fill_report(params, datasource = nil)
_JasperFillManager = Rjb.import('net.sf.jasperreports.engine.JasperFillManager')
if datasource
return _JasperFillManager.fillReport(@object_file.to_s, params)
else
_JREmptyDataSource = Rjb.import('net.sf.jasperreports.engine.JREmptyDataSource')
return _JasperFillManager.fillReport(@object_file.to_s, params, _JREmptyDataSource.new)
end
end | ruby | def fill_report(params, datasource = nil)
_JasperFillManager = Rjb.import('net.sf.jasperreports.engine.JasperFillManager')
if datasource
return _JasperFillManager.fillReport(@object_file.to_s, params)
else
_JREmptyDataSource = Rjb.import('net.sf.jasperreports.engine.JREmptyDataSource')
return _JasperFillManager.fillReport(@object_file.to_s, params, _JREmptyDataSource.new)
end
end | [
"def",
"fill_report",
"(",
"params",
",",
"datasource",
"=",
"nil",
")",
"_JasperFillManager",
"=",
"Rjb",
".",
"import",
"(",
"'net.sf.jasperreports.engine.JasperFillManager'",
")",
"if",
"datasource",
"return",
"_JasperFillManager",
".",
"fillReport",
"(",
"@object_file",
".",
"to_s",
",",
"params",
")",
"else",
"_JREmptyDataSource",
"=",
"Rjb",
".",
"import",
"(",
"'net.sf.jasperreports.engine.JREmptyDataSource'",
")",
"return",
"_JasperFillManager",
".",
"fillReport",
"(",
"@object_file",
".",
"to_s",
",",
"params",
",",
"_JREmptyDataSource",
".",
"new",
")",
"end",
"end"
] | Fill the report with valid method depending on datasource | [
"Fill",
"the",
"report",
"with",
"valid",
"method",
"depending",
"on",
"datasource"
] | 7483991cb2a670a1d977a4868f204ad66c0be243 | https://github.com/ekylibre/beardley/blob/7483991cb2a670a1d977a4868f204ad66c0be243/lib/beardley/report.rb#L197-L205 |
3,126 | localmed/outbox | lib/outbox/message_fields.rb | Outbox.MessageFields.fields | def fields(new_fields = nil)
if new_fields.nil?
fields = {}
self.class.fields.each do |field|
fields[field] = public_send(field)
end
fields
else
self.fields = new_fields
end
end | ruby | def fields(new_fields = nil)
if new_fields.nil?
fields = {}
self.class.fields.each do |field|
fields[field] = public_send(field)
end
fields
else
self.fields = new_fields
end
end | [
"def",
"fields",
"(",
"new_fields",
"=",
"nil",
")",
"if",
"new_fields",
".",
"nil?",
"fields",
"=",
"{",
"}",
"self",
".",
"class",
".",
"fields",
".",
"each",
"do",
"|",
"field",
"|",
"fields",
"[",
"field",
"]",
"=",
"public_send",
"(",
"field",
")",
"end",
"fields",
"else",
"self",
".",
"fields",
"=",
"new_fields",
"end",
"end"
] | Returns a hash of the defined fields.
class SomeMessageType < Outbox::Messages::Base
fields :to, :from
end
message = SomeMessageType.new to: 'Bob'
message.from 'John'
message.fields #=> { to: 'Bob', from: 'John' }
Also allows you to set fields if you pass in a hash.
message.fields to: 'Bob', from: 'Sally'
message.fields #=> { to: 'Bob', from: 'Sally' } | [
"Returns",
"a",
"hash",
"of",
"the",
"defined",
"fields",
"."
] | 4c7bd2129df7d2bbb49e464699afed9eb8396a5f | https://github.com/localmed/outbox/blob/4c7bd2129df7d2bbb49e464699afed9eb8396a5f/lib/outbox/message_fields.rb#L175-L185 |
3,127 | localmed/outbox | lib/outbox/message_fields.rb | Outbox.MessageFields.fields= | def fields=(new_fields)
new_fields.each do |field, value|
public_send(field, value) if respond_to?(field)
end
end | ruby | def fields=(new_fields)
new_fields.each do |field, value|
public_send(field, value) if respond_to?(field)
end
end | [
"def",
"fields",
"=",
"(",
"new_fields",
")",
"new_fields",
".",
"each",
"do",
"|",
"field",
",",
"value",
"|",
"public_send",
"(",
"field",
",",
"value",
")",
"if",
"respond_to?",
"(",
"field",
")",
"end",
"end"
] | Assigns the values of the given hash.
message.to = 'Bob'
message.fields = { from: 'Sally' }
message.fields #=> { to: 'Bob', from: 'Sally' } | [
"Assigns",
"the",
"values",
"of",
"the",
"given",
"hash",
"."
] | 4c7bd2129df7d2bbb49e464699afed9eb8396a5f | https://github.com/localmed/outbox/blob/4c7bd2129df7d2bbb49e464699afed9eb8396a5f/lib/outbox/message_fields.rb#L192-L196 |
3,128 | localmed/outbox | lib/outbox/message_fields.rb | Outbox.MessageFields.validate_fields | def validate_fields
self.class.required_fields.each do |field|
value = public_send(field)
if value.nil? || value.respond_to?(:empty?) && value.empty?
raise Outbox::MissingRequiredFieldError, "Missing required field: #{field}"
end
end
end | ruby | def validate_fields
self.class.required_fields.each do |field|
value = public_send(field)
if value.nil? || value.respond_to?(:empty?) && value.empty?
raise Outbox::MissingRequiredFieldError, "Missing required field: #{field}"
end
end
end | [
"def",
"validate_fields",
"self",
".",
"class",
".",
"required_fields",
".",
"each",
"do",
"|",
"field",
"|",
"value",
"=",
"public_send",
"(",
"field",
")",
"if",
"value",
".",
"nil?",
"||",
"value",
".",
"respond_to?",
"(",
":empty?",
")",
"&&",
"value",
".",
"empty?",
"raise",
"Outbox",
"::",
"MissingRequiredFieldError",
",",
"\"Missing required field: #{field}\"",
"end",
"end",
"end"
] | Checks the current values of the fields and raises errors for any
validation issues. | [
"Checks",
"the",
"current",
"values",
"of",
"the",
"fields",
"and",
"raises",
"errors",
"for",
"any",
"validation",
"issues",
"."
] | 4c7bd2129df7d2bbb49e464699afed9eb8396a5f | https://github.com/localmed/outbox/blob/4c7bd2129df7d2bbb49e464699afed9eb8396a5f/lib/outbox/message_fields.rb#L200-L207 |
3,129 | cknadler/git-feats | lib/git-feats/serializer.rb | GitFeats.Serializer.serialize | def serialize(path, data)
# Make a path to the data file if one doesn't already exist
mkpath_to path
File.open(path, "w") do |f|
f.puts data.to_json
end
end | ruby | def serialize(path, data)
# Make a path to the data file if one doesn't already exist
mkpath_to path
File.open(path, "w") do |f|
f.puts data.to_json
end
end | [
"def",
"serialize",
"(",
"path",
",",
"data",
")",
"# Make a path to the data file if one doesn't already exist",
"mkpath_to",
"path",
"File",
".",
"open",
"(",
"path",
",",
"\"w\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"puts",
"data",
".",
"to_json",
"end",
"end"
] | serialize a ruby object to a file in json
path - file path
data - data to be serialized
Returns nothing | [
"serialize",
"a",
"ruby",
"object",
"to",
"a",
"file",
"in",
"json"
] | a2425c2c5998b0c5f817d8a80efc8c2bd053786e | https://github.com/cknadler/git-feats/blob/a2425c2c5998b0c5f817d8a80efc8c2bd053786e/lib/git-feats/serializer.rb#L15-L22 |
3,130 | cknadler/git-feats | lib/git-feats/serializer.rb | GitFeats.Serializer.unserialize | def unserialize(path)
if File.exists?(path) && !File.zero?(path)
begin
return JSON.parse(IO.binread(path))
rescue JSON::ParserError => e
puts e
end
end
end | ruby | def unserialize(path)
if File.exists?(path) && !File.zero?(path)
begin
return JSON.parse(IO.binread(path))
rescue JSON::ParserError => e
puts e
end
end
end | [
"def",
"unserialize",
"(",
"path",
")",
"if",
"File",
".",
"exists?",
"(",
"path",
")",
"&&",
"!",
"File",
".",
"zero?",
"(",
"path",
")",
"begin",
"return",
"JSON",
".",
"parse",
"(",
"IO",
".",
"binread",
"(",
"path",
")",
")",
"rescue",
"JSON",
"::",
"ParserError",
"=>",
"e",
"puts",
"e",
"end",
"end",
"end"
] | unserialize a json file to a ruby object
path - file path
Returns a ruby object or nil | [
"unserialize",
"a",
"json",
"file",
"to",
"a",
"ruby",
"object"
] | a2425c2c5998b0c5f817d8a80efc8c2bd053786e | https://github.com/cknadler/git-feats/blob/a2425c2c5998b0c5f817d8a80efc8c2bd053786e/lib/git-feats/serializer.rb#L29-L37 |
3,131 | norman/phonology | lib/phonology/orthography.rb | Phonology.OrthographyTranslator.translate | def translate(string)
@string = string
@max = array.length
SoundSequence.new(array.each_index.map do |index|
@index = index
instance_eval(&@rules)
end.flatten.compact)
ensure
@max = 0
@string = nil
@array = nil
@index = nil
@last_sound = nil
end | ruby | def translate(string)
@string = string
@max = array.length
SoundSequence.new(array.each_index.map do |index|
@index = index
instance_eval(&@rules)
end.flatten.compact)
ensure
@max = 0
@string = nil
@array = nil
@index = nil
@last_sound = nil
end | [
"def",
"translate",
"(",
"string",
")",
"@string",
"=",
"string",
"@max",
"=",
"array",
".",
"length",
"SoundSequence",
".",
"new",
"(",
"array",
".",
"each_index",
".",
"map",
"do",
"|",
"index",
"|",
"@index",
"=",
"index",
"instance_eval",
"(",
"@rules",
")",
"end",
".",
"flatten",
".",
"compact",
")",
"ensure",
"@max",
"=",
"0",
"@string",
"=",
"nil",
"@array",
"=",
"nil",
"@index",
"=",
"nil",
"@last_sound",
"=",
"nil",
"end"
] | Translate orthorgraphy to IPA | [
"Translate",
"orthorgraphy",
"to",
"IPA"
] | 910207237aecbcd8e1a464a9148d9b3fd4d1f3e4 | https://github.com/norman/phonology/blob/910207237aecbcd8e1a464a9148d9b3fd4d1f3e4/lib/phonology/orthography.rb#L95-L108 |
3,132 | tomasc/semantic_date_time_tags | lib/semantic_date_time_tags/view_helpers.rb | SemanticDateTimeTags.ViewHelpers.semantic_date_time_tag | def semantic_date_time_tag(date_time, options = {})
SemanticDateTimeTags::Tag::DateTime.new(date_time, options).to_html
end | ruby | def semantic_date_time_tag(date_time, options = {})
SemanticDateTimeTags::Tag::DateTime.new(date_time, options).to_html
end | [
"def",
"semantic_date_time_tag",
"(",
"date_time",
",",
"options",
"=",
"{",
"}",
")",
"SemanticDateTimeTags",
"::",
"Tag",
"::",
"DateTime",
".",
"new",
"(",
"date_time",
",",
"options",
")",
".",
"to_html",
"end"
] | accepts only datetime | [
"accepts",
"only",
"datetime"
] | 5748521591720bb6c3b87659b016d01775fd08eb | https://github.com/tomasc/semantic_date_time_tags/blob/5748521591720bb6c3b87659b016d01775fd08eb/lib/semantic_date_time_tags/view_helpers.rb#L24-L26 |
3,133 | tomasc/semantic_date_time_tags | lib/semantic_date_time_tags/view_helpers.rb | SemanticDateTimeTags.ViewHelpers.semantic_time_tag | def semantic_time_tag(time, options = {})
SemanticDateTimeTags::Tag::Time.new(time, options).to_html
end | ruby | def semantic_time_tag(time, options = {})
SemanticDateTimeTags::Tag::Time.new(time, options).to_html
end | [
"def",
"semantic_time_tag",
"(",
"time",
",",
"options",
"=",
"{",
"}",
")",
"SemanticDateTimeTags",
"::",
"Tag",
"::",
"Time",
".",
"new",
"(",
"time",
",",
"options",
")",
".",
"to_html",
"end"
] | accepts datetime and time | [
"accepts",
"datetime",
"and",
"time"
] | 5748521591720bb6c3b87659b016d01775fd08eb | https://github.com/tomasc/semantic_date_time_tags/blob/5748521591720bb6c3b87659b016d01775fd08eb/lib/semantic_date_time_tags/view_helpers.rb#L34-L36 |
3,134 | wr0ngway/lumber | lib/lumber/inheritance_registry.rb | Lumber.InheritanceRegistry.register_inheritance_handler | def register_inheritance_handler
synchronize do
return if defined?(Object.inherited_with_lumber_registry)
Object.class_eval do
class << self
def inherited_with_lumber_registry(subclass)
inherited_without_lumber_registry(subclass)
# Add a logger to 'subclass' if it is directly in the registry
# No need to check full inheritance chain LoggerSupport handles it
# Also prevent rails from subsequently overriding our logger when rails
# is loaded after registering logger inheritance
if Lumber::InheritanceRegistry[subclass.name]
subclass.send(:include, Lumber.logger_concern)
end
end
alias_method_chain :inherited, :lumber_registry
end
end
end
end | ruby | def register_inheritance_handler
synchronize do
return if defined?(Object.inherited_with_lumber_registry)
Object.class_eval do
class << self
def inherited_with_lumber_registry(subclass)
inherited_without_lumber_registry(subclass)
# Add a logger to 'subclass' if it is directly in the registry
# No need to check full inheritance chain LoggerSupport handles it
# Also prevent rails from subsequently overriding our logger when rails
# is loaded after registering logger inheritance
if Lumber::InheritanceRegistry[subclass.name]
subclass.send(:include, Lumber.logger_concern)
end
end
alias_method_chain :inherited, :lumber_registry
end
end
end
end | [
"def",
"register_inheritance_handler",
"synchronize",
"do",
"return",
"if",
"defined?",
"(",
"Object",
".",
"inherited_with_lumber_registry",
")",
"Object",
".",
"class_eval",
"do",
"class",
"<<",
"self",
"def",
"inherited_with_lumber_registry",
"(",
"subclass",
")",
"inherited_without_lumber_registry",
"(",
"subclass",
")",
"# Add a logger to 'subclass' if it is directly in the registry",
"# No need to check full inheritance chain LoggerSupport handles it",
"# Also prevent rails from subsequently overriding our logger when rails",
"# is loaded after registering logger inheritance",
"if",
"Lumber",
"::",
"InheritanceRegistry",
"[",
"subclass",
".",
"name",
"]",
"subclass",
".",
"send",
"(",
":include",
",",
"Lumber",
".",
"logger_concern",
")",
"end",
"end",
"alias_method_chain",
":inherited",
",",
":lumber_registry",
"end",
"end",
"end",
"end"
] | Adds a inheritance handler to Object so we can add loggers for registered classes | [
"Adds",
"a",
"inheritance",
"handler",
"to",
"Object",
"so",
"we",
"can",
"add",
"loggers",
"for",
"registered",
"classes"
] | 6a483ea44f496d4e98f5698590be59941b58fe9b | https://github.com/wr0ngway/lumber/blob/6a483ea44f496d4e98f5698590be59941b58fe9b/lib/lumber/inheritance_registry.rb#L52-L80 |
3,135 | bbtfr/index_for | lib/index_for/helper.rb | IndexFor.Helper.index_for | def index_for objects, html_options = {}, &block
html_options = html_options.dup
objects = fetch_objects objects, html_options
tag = html_options[:table_tag] || IndexFor.table_tag
klass = html_options[:klass] || objects.try(:klass) || objects.first.class
html_options[:id] ||= index_for_id(klass)
html_options[:class] = index_for_class(klass, html_options)
head = index_for_head(klass.new, html_options, &block)
body = index_for_body(objects, html_options, &block)
content = head + body
content_tag(tag, content, html_options)
end | ruby | def index_for objects, html_options = {}, &block
html_options = html_options.dup
objects = fetch_objects objects, html_options
tag = html_options[:table_tag] || IndexFor.table_tag
klass = html_options[:klass] || objects.try(:klass) || objects.first.class
html_options[:id] ||= index_for_id(klass)
html_options[:class] = index_for_class(klass, html_options)
head = index_for_head(klass.new, html_options, &block)
body = index_for_body(objects, html_options, &block)
content = head + body
content_tag(tag, content, html_options)
end | [
"def",
"index_for",
"objects",
",",
"html_options",
"=",
"{",
"}",
",",
"&",
"block",
"html_options",
"=",
"html_options",
".",
"dup",
"objects",
"=",
"fetch_objects",
"objects",
",",
"html_options",
"tag",
"=",
"html_options",
"[",
":table_tag",
"]",
"||",
"IndexFor",
".",
"table_tag",
"klass",
"=",
"html_options",
"[",
":klass",
"]",
"||",
"objects",
".",
"try",
"(",
":klass",
")",
"||",
"objects",
".",
"first",
".",
"class",
"html_options",
"[",
":id",
"]",
"||=",
"index_for_id",
"(",
"klass",
")",
"html_options",
"[",
":class",
"]",
"=",
"index_for_class",
"(",
"klass",
",",
"html_options",
")",
"head",
"=",
"index_for_head",
"(",
"klass",
".",
"new",
",",
"html_options",
",",
"block",
")",
"body",
"=",
"index_for_body",
"(",
"objects",
",",
"html_options",
",",
"block",
")",
"content",
"=",
"head",
"+",
"body",
"content_tag",
"(",
"tag",
",",
"content",
",",
"html_options",
")",
"end"
] | Creates a table around the objects and yields a builder.
Example:
index_for @users do |t|
t.attribute :name
t.attribute :email
end | [
"Creates",
"a",
"table",
"around",
"the",
"objects",
"and",
"yields",
"a",
"builder",
"."
] | cc615ce56e661b0592cc3bd7a9af3ac28b51b44f | https://github.com/bbtfr/index_for/blob/cc615ce56e661b0592cc3bd7a9af3ac28b51b44f/lib/index_for/helper.rb#L14-L30 |
3,136 | bbtfr/index_for | lib/index_for/helper.rb | IndexFor.Helper.index_for_actions | def index_for_actions object, *action_names, &block
html_options = action_names.extract_options!
action_names = [:show, :edit, :destroy] if action_names == [:all]
builder = html_options[:action_builder] || IndexFor::ActionBuilder
builder = builder.new(object, html_options, self)
content = capture(builder) do |a|
action_names.map do |action_name|
a.action_link action_name
end.join.html_safe
end
content += capture(builder, &block) if block
content
end | ruby | def index_for_actions object, *action_names, &block
html_options = action_names.extract_options!
action_names = [:show, :edit, :destroy] if action_names == [:all]
builder = html_options[:action_builder] || IndexFor::ActionBuilder
builder = builder.new(object, html_options, self)
content = capture(builder) do |a|
action_names.map do |action_name|
a.action_link action_name
end.join.html_safe
end
content += capture(builder, &block) if block
content
end | [
"def",
"index_for_actions",
"object",
",",
"*",
"action_names",
",",
"&",
"block",
"html_options",
"=",
"action_names",
".",
"extract_options!",
"action_names",
"=",
"[",
":show",
",",
":edit",
",",
":destroy",
"]",
"if",
"action_names",
"==",
"[",
":all",
"]",
"builder",
"=",
"html_options",
"[",
":action_builder",
"]",
"||",
"IndexFor",
"::",
"ActionBuilder",
"builder",
"=",
"builder",
".",
"new",
"(",
"object",
",",
"html_options",
",",
"self",
")",
"content",
"=",
"capture",
"(",
"builder",
")",
"do",
"|",
"a",
"|",
"action_names",
".",
"map",
"do",
"|",
"action_name",
"|",
"a",
".",
"action_link",
"action_name",
"end",
".",
"join",
".",
"html_safe",
"end",
"content",
"+=",
"capture",
"(",
"builder",
",",
"block",
")",
"if",
"block",
"content",
"end"
] | Create action links and yields a builder.
Example:
index_for_actions @user do |a|
a.action_link :show
a.action_link :edit
end
index_for_actions @user, :show, :edit | [
"Create",
"action",
"links",
"and",
"yields",
"a",
"builder",
"."
] | cc615ce56e661b0592cc3bd7a9af3ac28b51b44f | https://github.com/bbtfr/index_for/blob/cc615ce56e661b0592cc3bd7a9af3ac28b51b44f/lib/index_for/helper.rb#L60-L76 |
3,137 | bbtfr/index_for | lib/index_for/helper.rb | IndexFor.Helper.show_for | def show_for object, html_options = {}, &block
html_options = html_options.dup
tag = html_options[:list_tag] || IndexFor.list_tag
html_options[:id] ||= show_for_id(object)
html_options[:class] = show_for_class(object, html_options)
builder = html_options[:builder] || IndexFor::ListColumnBuilder
content = capture(builder.new(object, html_options, self), &block)
content_tag(tag, content, html_options)
end | ruby | def show_for object, html_options = {}, &block
html_options = html_options.dup
tag = html_options[:list_tag] || IndexFor.list_tag
html_options[:id] ||= show_for_id(object)
html_options[:class] = show_for_class(object, html_options)
builder = html_options[:builder] || IndexFor::ListColumnBuilder
content = capture(builder.new(object, html_options, self), &block)
content_tag(tag, content, html_options)
end | [
"def",
"show_for",
"object",
",",
"html_options",
"=",
"{",
"}",
",",
"&",
"block",
"html_options",
"=",
"html_options",
".",
"dup",
"tag",
"=",
"html_options",
"[",
":list_tag",
"]",
"||",
"IndexFor",
".",
"list_tag",
"html_options",
"[",
":id",
"]",
"||=",
"show_for_id",
"(",
"object",
")",
"html_options",
"[",
":class",
"]",
"=",
"show_for_class",
"(",
"object",
",",
"html_options",
")",
"builder",
"=",
"html_options",
"[",
":builder",
"]",
"||",
"IndexFor",
"::",
"ListColumnBuilder",
"content",
"=",
"capture",
"(",
"builder",
".",
"new",
"(",
"object",
",",
"html_options",
",",
"self",
")",
",",
"block",
")",
"content_tag",
"(",
"tag",
",",
"content",
",",
"html_options",
")",
"end"
] | Creates a desc list around the object and yields a builder.
Example:
show_for @user do |l|
l.attribute :name
l.attribute :email
end | [
"Creates",
"a",
"desc",
"list",
"around",
"the",
"object",
"and",
"yields",
"a",
"builder",
"."
] | cc615ce56e661b0592cc3bd7a9af3ac28b51b44f | https://github.com/bbtfr/index_for/blob/cc615ce56e661b0592cc3bd7a9af3ac28b51b44f/lib/index_for/helper.rb#L87-L99 |
3,138 | BrightcoveOS/Ruby-MAPI-Wrapper | lib/brightcove-api.rb | Brightcove.API.post | def post(api_method, parameters = {})
parameters.merge!({"token" => @token})
body = {}
body.merge!({:method => api_method})
body.merge!({:params => parameters})
self.class.post(@write_api_url, {:body => {:json => JSON.generate(body)}})
end | ruby | def post(api_method, parameters = {})
parameters.merge!({"token" => @token})
body = {}
body.merge!({:method => api_method})
body.merge!({:params => parameters})
self.class.post(@write_api_url, {:body => {:json => JSON.generate(body)}})
end | [
"def",
"post",
"(",
"api_method",
",",
"parameters",
"=",
"{",
"}",
")",
"parameters",
".",
"merge!",
"(",
"{",
"\"token\"",
"=>",
"@token",
"}",
")",
"body",
"=",
"{",
"}",
"body",
".",
"merge!",
"(",
"{",
":method",
"=>",
"api_method",
"}",
")",
"body",
".",
"merge!",
"(",
"{",
":params",
"=>",
"parameters",
"}",
")",
"self",
".",
"class",
".",
"post",
"(",
"@write_api_url",
",",
"{",
":body",
"=>",
"{",
":json",
"=>",
"JSON",
".",
"generate",
"(",
"body",
")",
"}",
"}",
")",
"end"
] | Make an HTTP POST call to the Brightcove API for a particular API method.
@param api_method [String] Brightcove API method.
@param parameters [Hash] Optional hash containing parameter names and values. | [
"Make",
"an",
"HTTP",
"POST",
"call",
"to",
"the",
"Brightcove",
"API",
"for",
"a",
"particular",
"API",
"method",
"."
] | babde5c12ef08b8908d460f04aa156c1905205b8 | https://github.com/BrightcoveOS/Ruby-MAPI-Wrapper/blob/babde5c12ef08b8908d460f04aa156c1905205b8/lib/brightcove-api.rb#L84-L92 |
3,139 | tecfoundary/hicube | app/controllers/hicube/contents_controller.rb | Hicube.ContentsController.load_resource | def load_resource
@page = Hicube::Page.unscoped.find(params[:page_id])
@content = @page.content.find_or_create_by(name: params[:id])
end | ruby | def load_resource
@page = Hicube::Page.unscoped.find(params[:page_id])
@content = @page.content.find_or_create_by(name: params[:id])
end | [
"def",
"load_resource",
"@page",
"=",
"Hicube",
"::",
"Page",
".",
"unscoped",
".",
"find",
"(",
"params",
"[",
":page_id",
"]",
")",
"@content",
"=",
"@page",
".",
"content",
".",
"find_or_create_by",
"(",
"name",
":",
"params",
"[",
":id",
"]",
")",
"end"
] | Nested attributes are currently not handled in basecontroller | [
"Nested",
"attributes",
"are",
"currently",
"not",
"handled",
"in",
"basecontroller"
] | 57e0e6bd2d6400dd6c7027deaeffbd95a175bbfe | https://github.com/tecfoundary/hicube/blob/57e0e6bd2d6400dd6c7027deaeffbd95a175bbfe/app/controllers/hicube/contents_controller.rb#L43-L46 |
3,140 | czarneckid/hipchat-api | lib/hipchat-api.rb | HipChat.API.rooms_create | def rooms_create(name, owner_user_id, privacy = 'public', topic = '', guest_access = 0)
self.class.post(hipchat_api_url_for('rooms/create'), :body => {:auth_token => @token, :name => name, :owner_user_id => owner_user_id,
:topic => topic, :privacy => privacy, :guest_access => guest_access})
end | ruby | def rooms_create(name, owner_user_id, privacy = 'public', topic = '', guest_access = 0)
self.class.post(hipchat_api_url_for('rooms/create'), :body => {:auth_token => @token, :name => name, :owner_user_id => owner_user_id,
:topic => topic, :privacy => privacy, :guest_access => guest_access})
end | [
"def",
"rooms_create",
"(",
"name",
",",
"owner_user_id",
",",
"privacy",
"=",
"'public'",
",",
"topic",
"=",
"''",
",",
"guest_access",
"=",
"0",
")",
"self",
".",
"class",
".",
"post",
"(",
"hipchat_api_url_for",
"(",
"'rooms/create'",
")",
",",
":body",
"=>",
"{",
":auth_token",
"=>",
"@token",
",",
":name",
"=>",
"name",
",",
":owner_user_id",
"=>",
"owner_user_id",
",",
":topic",
"=>",
"topic",
",",
":privacy",
"=>",
"privacy",
",",
":guest_access",
"=>",
"guest_access",
"}",
")",
"end"
] | Creates a new room.
@param name [String] Name of the room.
@param owner_user_id [int] User ID of the room's owner.
@param privacy [String, 'public'] Privacy setting for room.
@param topic [String, ''] Room topic.
@param guest_access [int, 0] Whether or not to enable guest access for this room. 0 = false, 1 = true. (default: 0).
@see https://www.hipchat.com/docs/api/method/rooms/create | [
"Creates",
"a",
"new",
"room",
"."
] | 195b921e7c615433977927d3ad6f5a9cdb9b308f | https://github.com/czarneckid/hipchat-api/blob/195b921e7c615433977927d3ad6f5a9cdb9b308f/lib/hipchat-api.rb#L69-L72 |
3,141 | czarneckid/hipchat-api | lib/hipchat-api.rb | HipChat.API.rooms_message | def rooms_message(room_id, from, message, notify = 0, color = 'yellow', message_format = 'html')
self.class.post(hipchat_api_url_for('rooms/message'), :body => {:auth_token => @token, :room_id => room_id, :from => from,
:message => message, :notify => notify, :color => color, :message_format => message_format})
end | ruby | def rooms_message(room_id, from, message, notify = 0, color = 'yellow', message_format = 'html')
self.class.post(hipchat_api_url_for('rooms/message'), :body => {:auth_token => @token, :room_id => room_id, :from => from,
:message => message, :notify => notify, :color => color, :message_format => message_format})
end | [
"def",
"rooms_message",
"(",
"room_id",
",",
"from",
",",
"message",
",",
"notify",
"=",
"0",
",",
"color",
"=",
"'yellow'",
",",
"message_format",
"=",
"'html'",
")",
"self",
".",
"class",
".",
"post",
"(",
"hipchat_api_url_for",
"(",
"'rooms/message'",
")",
",",
":body",
"=>",
"{",
":auth_token",
"=>",
"@token",
",",
":room_id",
"=>",
"room_id",
",",
":from",
"=>",
"from",
",",
":message",
"=>",
"message",
",",
":notify",
"=>",
"notify",
",",
":color",
"=>",
"color",
",",
":message_format",
"=>",
"message_format",
"}",
")",
"end"
] | Send a message to a room.
@param room_id [int] ID of the room.
@param from [String] Name the message will appear be sent from. Must be less than 15 characters long. May contain letters, numbers, -, _, and spaces.
@param message [String] The message body. Must be valid XHTML. HTML entities must be escaped (e.g.: & instead of &). May contain basic tags: a, b, i, strong, em, br, img, pre, code. 5000 characters max.
@param notify [int] Boolean flag of whether or not this message should trigger a notification for people in the room (based on their individual notification preferences). 0 = false, 1 = true. (default: 0)
@param color [String] Background color for message. One of "yellow", "red", "green", "purple", or "random". (default: yellow)
@param message_format [String] Determines how the message is treated by HipChat's server and rendered inside HipChat applications. One of "html" or "text". (default: html)
@see https://www.hipchat.com/docs/api/method/rooms/message | [
"Send",
"a",
"message",
"to",
"a",
"room",
"."
] | 195b921e7c615433977927d3ad6f5a9cdb9b308f | https://github.com/czarneckid/hipchat-api/blob/195b921e7c615433977927d3ad6f5a9cdb9b308f/lib/hipchat-api.rb#L111-L114 |
3,142 | czarneckid/hipchat-api | lib/hipchat-api.rb | HipChat.API.users_create | def users_create(email, name, title, is_group_admin = 0, password = nil, timezone = 'UTC')
self.class.post(hipchat_api_url_for('users/create'), :body => {:auth_token => @token, :email => email, :name => name, :title => title,
:is_group_admin => is_group_admin, :password => password, :timezone => timezone}.reject{|key, value| value.nil?})
end | ruby | def users_create(email, name, title, is_group_admin = 0, password = nil, timezone = 'UTC')
self.class.post(hipchat_api_url_for('users/create'), :body => {:auth_token => @token, :email => email, :name => name, :title => title,
:is_group_admin => is_group_admin, :password => password, :timezone => timezone}.reject{|key, value| value.nil?})
end | [
"def",
"users_create",
"(",
"email",
",",
"name",
",",
"title",
",",
"is_group_admin",
"=",
"0",
",",
"password",
"=",
"nil",
",",
"timezone",
"=",
"'UTC'",
")",
"self",
".",
"class",
".",
"post",
"(",
"hipchat_api_url_for",
"(",
"'users/create'",
")",
",",
":body",
"=>",
"{",
":auth_token",
"=>",
"@token",
",",
":email",
"=>",
"email",
",",
":name",
"=>",
"name",
",",
":title",
"=>",
"title",
",",
":is_group_admin",
"=>",
"is_group_admin",
",",
":password",
"=>",
"password",
",",
":timezone",
"=>",
"timezone",
"}",
".",
"reject",
"{",
"|",
"key",
",",
"value",
"|",
"value",
".",
"nil?",
"}",
")",
"end"
] | Create a new user in your group.
@param email [String] User's email.
@param name [String] User's full name.
@param title [String] User's title.
@param is_group_admin [int] Whether or not this user is an admin. 0 = false, 1 = true. (default: 0)
@param password [String, nil] User's password. If not provided, a randomly generated password will be returned.
@param timezone [String, 'UTC'] User's timezone. Must be a PHP supported timezone. (default: UTC)
@see https://www.hipchat.com/docs/api/method/users/create | [
"Create",
"a",
"new",
"user",
"in",
"your",
"group",
"."
] | 195b921e7c615433977927d3ad6f5a9cdb9b308f | https://github.com/czarneckid/hipchat-api/blob/195b921e7c615433977927d3ad6f5a9cdb9b308f/lib/hipchat-api.rb#L146-L149 |
3,143 | luikore/markascend | lib/markascend/popular_company_macros.rb | Markascend.Macro.parse_video | def parse_video
# standard
unless /\A\s*(?<width>\d+)x(?<height>\d+)\s+(?<url>.+)\z/ =~ content
env.warn 'can not parse \video content, should be "#{WIDTH}x#{HEIGHT} #{URL}"'
return
end
case url
when /youtu\.?be/
# NOTE merging them into one regexp fails (because longest match?)
unless id = url[/(?<=watch\?v=)\w+/] || url[/(?<=embed\/)\w+/] || url[/(?<=youtu\.be\/)\w+/]
env.warn 'can not parse youtube id'
return
end
%Q|<iframe width="#{width}" height="#{height}" src="https://www.youtube-nocookie.com/embed/#{id}?rel=0" frameborder="0" allowfullscreen></iframe>|
when /vimeo/
unless id = url[/(?<=vimeo\.com\/)\w+/]
env.warn 'can not parse vimeo id, should use link like this "http://vimeo.com/#{DIGITS}"'
return
end
%Q|<iframe width="#{width}" height="#{height}" src="https://player.vimeo.com/video/#{id}" frameborder="0" allowFullScreen></iframe>|
when /sm/
unless id = url[/\bsm\d+/]
env.warn 'can not find "sm#{DIGITS}" from link'
return
end
%Q|<script src="https://ext.nicovideo.jp/thumb_watch/#{id}?w=#{width}&h=#{height}"></script>"|
else
env.warn 'failed to parse video link, currently only youtube, vimeo and niconico are supported'
return
end
end | ruby | def parse_video
# standard
unless /\A\s*(?<width>\d+)x(?<height>\d+)\s+(?<url>.+)\z/ =~ content
env.warn 'can not parse \video content, should be "#{WIDTH}x#{HEIGHT} #{URL}"'
return
end
case url
when /youtu\.?be/
# NOTE merging them into one regexp fails (because longest match?)
unless id = url[/(?<=watch\?v=)\w+/] || url[/(?<=embed\/)\w+/] || url[/(?<=youtu\.be\/)\w+/]
env.warn 'can not parse youtube id'
return
end
%Q|<iframe width="#{width}" height="#{height}" src="https://www.youtube-nocookie.com/embed/#{id}?rel=0" frameborder="0" allowfullscreen></iframe>|
when /vimeo/
unless id = url[/(?<=vimeo\.com\/)\w+/]
env.warn 'can not parse vimeo id, should use link like this "http://vimeo.com/#{DIGITS}"'
return
end
%Q|<iframe width="#{width}" height="#{height}" src="https://player.vimeo.com/video/#{id}" frameborder="0" allowFullScreen></iframe>|
when /sm/
unless id = url[/\bsm\d+/]
env.warn 'can not find "sm#{DIGITS}" from link'
return
end
%Q|<script src="https://ext.nicovideo.jp/thumb_watch/#{id}?w=#{width}&h=#{height}"></script>"|
else
env.warn 'failed to parse video link, currently only youtube, vimeo and niconico are supported'
return
end
end | [
"def",
"parse_video",
"# standard",
"unless",
"/",
"\\A",
"\\s",
"\\d",
"\\d",
"\\s",
"\\z",
"/",
"=~",
"content",
"env",
".",
"warn",
"'can not parse \\video content, should be \"#{WIDTH}x#{HEIGHT} #{URL}\"'",
"return",
"end",
"case",
"url",
"when",
"/",
"\\.",
"/",
"# NOTE merging them into one regexp fails (because longest match?)",
"unless",
"id",
"=",
"url",
"[",
"/",
"\\?",
"\\w",
"/",
"]",
"||",
"url",
"[",
"/",
"\\/",
"\\w",
"/",
"]",
"||",
"url",
"[",
"/",
"\\.",
"\\/",
"\\w",
"/",
"]",
"env",
".",
"warn",
"'can not parse youtube id'",
"return",
"end",
"%Q|<iframe width=\"#{width}\" height=\"#{height}\" src=\"https://www.youtube-nocookie.com/embed/#{id}?rel=0\" frameborder=\"0\" allowfullscreen></iframe>|",
"when",
"/",
"/",
"unless",
"id",
"=",
"url",
"[",
"/",
"\\.",
"\\/",
"\\w",
"/",
"]",
"env",
".",
"warn",
"'can not parse vimeo id, should use link like this \"http://vimeo.com/#{DIGITS}\"'",
"return",
"end",
"%Q|<iframe width=\"#{width}\" height=\"#{height}\" src=\"https://player.vimeo.com/video/#{id}\" frameborder=\"0\" allowFullScreen></iframe>|",
"when",
"/",
"/",
"unless",
"id",
"=",
"url",
"[",
"/",
"\\b",
"\\d",
"/",
"]",
"env",
".",
"warn",
"'can not find \"sm#{DIGITS}\" from link'",
"return",
"end",
"%Q|<script src=\"https://ext.nicovideo.jp/thumb_watch/#{id}?w=#{width}&h=#{height}\"></script>\"|",
"else",
"env",
".",
"warn",
"'failed to parse video link, currently only youtube, vimeo and niconico are supported'",
"return",
"end",
"end"
] | embed video, calculates embed iframe by urls from various simple formats, but not accept iframe code | [
"embed",
"video",
"calculates",
"embed",
"iframe",
"by",
"urls",
"from",
"various",
"simple",
"formats",
"but",
"not",
"accept",
"iframe",
"code"
] | 58a7d9c18bf764dba537f7b4bf52ac550bbccb50 | https://github.com/luikore/markascend/blob/58a7d9c18bf764dba537f7b4bf52ac550bbccb50/lib/markascend/popular_company_macros.rb#L54-L85 |
3,144 | flajann2/k-tree | lib/k-tree/k-tree.rb | KTree.KTree.create_tree | def create_tree(vupper, vlower, &block)
@root = Node.new(vupper, vlower, @depth)
@root.create_children &block
end | ruby | def create_tree(vupper, vlower, &block)
@root = Node.new(vupper, vlower, @depth)
@root.create_children &block
end | [
"def",
"create_tree",
"(",
"vupper",
",",
"vlower",
",",
"&",
"block",
")",
"@root",
"=",
"Node",
".",
"new",
"(",
"vupper",
",",
"vlower",
",",
"@depth",
")",
"@root",
".",
"create_children",
"block",
"end"
] | The block is passed node itself as parent and the vector midpoints of
its children to be.
The block sets is own refob, and returns either true, in which case
all the children are created, or it returns false, in which case none
of the children will be created, in effect, marking itself as a leaf
node. | [
"The",
"block",
"is",
"passed",
"node",
"itself",
"as",
"parent",
"and",
"the",
"vector",
"midpoints",
"of",
"its",
"children",
"to",
"be",
"."
] | 16a96dcfd38705160cc21ed892d44bb23ba59ebb | https://github.com/flajann2/k-tree/blob/16a96dcfd38705160cc21ed892d44bb23ba59ebb/lib/k-tree/k-tree.rb#L84-L87 |
3,145 | rberger/asi_bod | lib/asi_bod/asi.rb | AsiBod.Asi.array_data_to_hash | def array_data_to_hash(array_data)
array_data.each_with_object({}) do |node, memo|
memo[node['Address'].to_i] = clean_node(node)
end
end | ruby | def array_data_to_hash(array_data)
array_data.each_with_object({}) do |node, memo|
memo[node['Address'].to_i] = clean_node(node)
end
end | [
"def",
"array_data_to_hash",
"(",
"array_data",
")",
"array_data",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"node",
",",
"memo",
"|",
"memo",
"[",
"node",
"[",
"'Address'",
"]",
".",
"to_i",
"]",
"=",
"clean_node",
"(",
"node",
")",
"end",
"end"
] | Asi.new reads in the source file for the ASIObjectDictionary and creates
an internal Hash
@param params [Hash]
Convert the array of hashes to a hash with the address as primary key | [
"Asi",
".",
"new",
"reads",
"in",
"the",
"source",
"file",
"for",
"the",
"ASIObjectDictionary",
"and",
"creates",
"an",
"internal",
"Hash"
] | 7aa6c86f996bf856f83d84bb6f0a22dbe257f925 | https://github.com/rberger/asi_bod/blob/7aa6c86f996bf856f83d84bb6f0a22dbe257f925/lib/asi_bod/asi.rb#L29-L33 |
3,146 | wr0ngway/lumber | lib/lumber/level_util.rb | Lumber.LevelUtil.start_monitor | def start_monitor(interval=10)
t = MonitorThread.new do
loop do
break if Thread.current.should_exit
begin
activate_levels
rescue => e
$stderr.puts "Failure activating log levels: #{e}"
end
sleep interval
end
end
at_exit { t.should_exit = true }
t
end | ruby | def start_monitor(interval=10)
t = MonitorThread.new do
loop do
break if Thread.current.should_exit
begin
activate_levels
rescue => e
$stderr.puts "Failure activating log levels: #{e}"
end
sleep interval
end
end
at_exit { t.should_exit = true }
t
end | [
"def",
"start_monitor",
"(",
"interval",
"=",
"10",
")",
"t",
"=",
"MonitorThread",
".",
"new",
"do",
"loop",
"do",
"break",
"if",
"Thread",
".",
"current",
".",
"should_exit",
"begin",
"activate_levels",
"rescue",
"=>",
"e",
"$stderr",
".",
"puts",
"\"Failure activating log levels: #{e}\"",
"end",
"sleep",
"interval",
"end",
"end",
"at_exit",
"{",
"t",
".",
"should_exit",
"=",
"true",
"}",
"t",
"end"
] | Convenience method for starting a thread to watch for changes in log
levels and apply them. You don't need to use this if you are manually
calling activate levels at all your entry points.
@param [Integer] How long to sleep between checks
@return [Thread] The monitor thread | [
"Convenience",
"method",
"for",
"starting",
"a",
"thread",
"to",
"watch",
"for",
"changes",
"in",
"log",
"levels",
"and",
"apply",
"them",
".",
"You",
"don",
"t",
"need",
"to",
"use",
"this",
"if",
"you",
"are",
"manually",
"calling",
"activate",
"levels",
"at",
"all",
"your",
"entry",
"points",
"."
] | 6a483ea44f496d4e98f5698590be59941b58fe9b | https://github.com/wr0ngway/lumber/blob/6a483ea44f496d4e98f5698590be59941b58fe9b/lib/lumber/level_util.rb#L82-L99 |
3,147 | wr0ngway/lumber | lib/lumber/level_util.rb | Lumber.LevelUtil.backup_levels | def backup_levels(loggers)
synchronize do
loggers.each do |name|
outputter = Log4r::Outputter[name]
if outputter
@original_outputter_levels[name] ||= outputter.level
else
logger = Lumber.find_or_create_logger(name)
# only store the old level if we haven't overriden it's logger yet
@original_levels[name] ||= logger.level
end
end
end
end | ruby | def backup_levels(loggers)
synchronize do
loggers.each do |name|
outputter = Log4r::Outputter[name]
if outputter
@original_outputter_levels[name] ||= outputter.level
else
logger = Lumber.find_or_create_logger(name)
# only store the old level if we haven't overriden it's logger yet
@original_levels[name] ||= logger.level
end
end
end
end | [
"def",
"backup_levels",
"(",
"loggers",
")",
"synchronize",
"do",
"loggers",
".",
"each",
"do",
"|",
"name",
"|",
"outputter",
"=",
"Log4r",
"::",
"Outputter",
"[",
"name",
"]",
"if",
"outputter",
"@original_outputter_levels",
"[",
"name",
"]",
"||=",
"outputter",
".",
"level",
"else",
"logger",
"=",
"Lumber",
".",
"find_or_create_logger",
"(",
"name",
")",
"# only store the old level if we haven't overriden it's logger yet",
"@original_levels",
"[",
"name",
"]",
"||=",
"logger",
".",
"level",
"end",
"end",
"end",
"end"
] | Backs up original values of logger levels before we overwrite them
This is better in local memory since we shouldn't reset loggers that we haven't set
@param [Enumerable<String>] The logger names to backup | [
"Backs",
"up",
"original",
"values",
"of",
"logger",
"levels",
"before",
"we",
"overwrite",
"them",
"This",
"is",
"better",
"in",
"local",
"memory",
"since",
"we",
"shouldn",
"t",
"reset",
"loggers",
"that",
"we",
"haven",
"t",
"set"
] | 6a483ea44f496d4e98f5698590be59941b58fe9b | https://github.com/wr0ngway/lumber/blob/6a483ea44f496d4e98f5698590be59941b58fe9b/lib/lumber/level_util.rb#L109-L122 |
3,148 | wr0ngway/lumber | lib/lumber/level_util.rb | Lumber.LevelUtil.restore_levels | def restore_levels
synchronize do
@original_outputter_levels.each do |name, level|
outputter = Log4r::Outputter[name]
outputter.level = level if outputter.level != level
end
@original_outputter_levels.clear
@original_levels.each do |name, level|
logger = Lumber.find_or_create_logger(name)
logger.level = level if logger.level != level
end
@original_levels.clear
end
end | ruby | def restore_levels
synchronize do
@original_outputter_levels.each do |name, level|
outputter = Log4r::Outputter[name]
outputter.level = level if outputter.level != level
end
@original_outputter_levels.clear
@original_levels.each do |name, level|
logger = Lumber.find_or_create_logger(name)
logger.level = level if logger.level != level
end
@original_levels.clear
end
end | [
"def",
"restore_levels",
"synchronize",
"do",
"@original_outputter_levels",
".",
"each",
"do",
"|",
"name",
",",
"level",
"|",
"outputter",
"=",
"Log4r",
"::",
"Outputter",
"[",
"name",
"]",
"outputter",
".",
"level",
"=",
"level",
"if",
"outputter",
".",
"level",
"!=",
"level",
"end",
"@original_outputter_levels",
".",
"clear",
"@original_levels",
".",
"each",
"do",
"|",
"name",
",",
"level",
"|",
"logger",
"=",
"Lumber",
".",
"find_or_create_logger",
"(",
"name",
")",
"logger",
".",
"level",
"=",
"level",
"if",
"logger",
".",
"level",
"!=",
"level",
"end",
"@original_levels",
".",
"clear",
"end",
"end"
] | Restores original values of logger levels after expiration | [
"Restores",
"original",
"values",
"of",
"logger",
"levels",
"after",
"expiration"
] | 6a483ea44f496d4e98f5698590be59941b58fe9b | https://github.com/wr0ngway/lumber/blob/6a483ea44f496d4e98f5698590be59941b58fe9b/lib/lumber/level_util.rb#L125-L139 |
3,149 | weenhanceit/gaapi | lib/gaapi/row.rb | GAAPI.Row.method_missing | def method_missing(method, *args)
if (i = dimension_method_names.find_index(method))
define_singleton_method(method) do
dimensions[i]
end
send(method)
elsif (i = metric_method_names.find_index(method))
define_singleton_method(method) do
convert_metric(i)
end
send(method)
else
super
end
end | ruby | def method_missing(method, *args)
if (i = dimension_method_names.find_index(method))
define_singleton_method(method) do
dimensions[i]
end
send(method)
elsif (i = metric_method_names.find_index(method))
define_singleton_method(method) do
convert_metric(i)
end
send(method)
else
super
end
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
")",
"if",
"(",
"i",
"=",
"dimension_method_names",
".",
"find_index",
"(",
"method",
")",
")",
"define_singleton_method",
"(",
"method",
")",
"do",
"dimensions",
"[",
"i",
"]",
"end",
"send",
"(",
"method",
")",
"elsif",
"(",
"i",
"=",
"metric_method_names",
".",
"find_index",
"(",
"method",
")",
")",
"define_singleton_method",
"(",
"method",
")",
"do",
"convert_metric",
"(",
"i",
")",
"end",
"send",
"(",
"method",
")",
"else",
"super",
"end",
"end"
] | Define and call methods to return the value of the dimensions and metrics
in the report.
@!macro method_missing | [
"Define",
"and",
"call",
"methods",
"to",
"return",
"the",
"value",
"of",
"the",
"dimensions",
"and",
"metrics",
"in",
"the",
"report",
"."
] | 20d25bd06b2e0cccc86ca1ea1baaac6be045355a | https://github.com/weenhanceit/gaapi/blob/20d25bd06b2e0cccc86ca1ea1baaac6be045355a/lib/gaapi/row.rb#L37-L51 |
3,150 | weenhanceit/gaapi | lib/gaapi/row.rb | GAAPI.Row.convert_metric | def convert_metric(i)
case report.metric_type(i)
when "INTEGER"
# INTEGER Integer metric.
metrics[i].to_i
when "FLOAT", "PERCENT"
# FLOAT Float metric.
# PERCENT Percentage metric.
metrics[i].to_f
when "CURRENCY"
# CURRENCY Currency metric.
# TODO: Do this better.
metrics[i].to_f
when "TIME"
# Google documentation claims to following:
# TIME Time metric in HH:MM:SS format.
# It also says it's seconds, and that's what I see in real results.
# So comment out the following:
# (metrics[i][0..1].to_i +
# metrics[i][3..4].to_i * 60 +
# metrics[i][6..7].to_i * 24 * 60)
# Simply make it a float.
metrics[i].to_f
else
# METRIC_TYPE_UNSPECIFIED Metric type is unspecified.
metric[i]
end
end | ruby | def convert_metric(i)
case report.metric_type(i)
when "INTEGER"
# INTEGER Integer metric.
metrics[i].to_i
when "FLOAT", "PERCENT"
# FLOAT Float metric.
# PERCENT Percentage metric.
metrics[i].to_f
when "CURRENCY"
# CURRENCY Currency metric.
# TODO: Do this better.
metrics[i].to_f
when "TIME"
# Google documentation claims to following:
# TIME Time metric in HH:MM:SS format.
# It also says it's seconds, and that's what I see in real results.
# So comment out the following:
# (metrics[i][0..1].to_i +
# metrics[i][3..4].to_i * 60 +
# metrics[i][6..7].to_i * 24 * 60)
# Simply make it a float.
metrics[i].to_f
else
# METRIC_TYPE_UNSPECIFIED Metric type is unspecified.
metric[i]
end
end | [
"def",
"convert_metric",
"(",
"i",
")",
"case",
"report",
".",
"metric_type",
"(",
"i",
")",
"when",
"\"INTEGER\"",
"# INTEGER Integer metric.",
"metrics",
"[",
"i",
"]",
".",
"to_i",
"when",
"\"FLOAT\"",
",",
"\"PERCENT\"",
"# FLOAT Float metric.",
"# PERCENT Percentage metric.",
"metrics",
"[",
"i",
"]",
".",
"to_f",
"when",
"\"CURRENCY\"",
"# CURRENCY Currency metric.",
"# TODO: Do this better.",
"metrics",
"[",
"i",
"]",
".",
"to_f",
"when",
"\"TIME\"",
"# Google documentation claims to following:",
"# TIME Time metric in HH:MM:SS format.",
"# It also says it's seconds, and that's what I see in real results.",
"# So comment out the following:",
"# (metrics[i][0..1].to_i +",
"# metrics[i][3..4].to_i * 60 +",
"# metrics[i][6..7].to_i * 24 * 60)",
"# Simply make it a float.",
"metrics",
"[",
"i",
"]",
".",
"to_f",
"else",
"# METRIC_TYPE_UNSPECIFIED Metric type is unspecified.",
"metric",
"[",
"i",
"]",
"end",
"end"
] | Convert metric to the right type. | [
"Convert",
"metric",
"to",
"the",
"right",
"type",
"."
] | 20d25bd06b2e0cccc86ca1ea1baaac6be045355a | https://github.com/weenhanceit/gaapi/blob/20d25bd06b2e0cccc86ca1ea1baaac6be045355a/lib/gaapi/row.rb#L87-L114 |
3,151 | PeterCamilleri/mini_term | lib/mini_term/common/mapper.rb | MiniTerm.Mapper.[]= | def []=(indexes, value)
indexes = [indexes] unless indexes.is_a?(Range)
indexes.each do |index|
process_non_terminals(index)
if @map.has_key?(index)
fail MiniTermKME, "Duplicate entry #{index.inspect}"
end
@map[index] = [value, index]
end
end | ruby | def []=(indexes, value)
indexes = [indexes] unless indexes.is_a?(Range)
indexes.each do |index|
process_non_terminals(index)
if @map.has_key?(index)
fail MiniTermKME, "Duplicate entry #{index.inspect}"
end
@map[index] = [value, index]
end
end | [
"def",
"[]=",
"(",
"indexes",
",",
"value",
")",
"indexes",
"=",
"[",
"indexes",
"]",
"unless",
"indexes",
".",
"is_a?",
"(",
"Range",
")",
"indexes",
".",
"each",
"do",
"|",
"index",
"|",
"process_non_terminals",
"(",
"index",
")",
"if",
"@map",
".",
"has_key?",
"(",
"index",
")",
"fail",
"MiniTermKME",
",",
"\"Duplicate entry #{index.inspect}\"",
"end",
"@map",
"[",
"index",
"]",
"=",
"[",
"value",
",",
"index",
"]",
"end",
"end"
] | Set up the keystroke mapper.
Add a map entry | [
"Set",
"up",
"the",
"keystroke",
"mapper",
".",
"Add",
"a",
"map",
"entry"
] | 71c179e82d3a353144d7e100ee0df89c2d71fac8 | https://github.com/PeterCamilleri/mini_term/blob/71c179e82d3a353144d7e100ee0df89c2d71fac8/lib/mini_term/common/mapper.rb#L16-L28 |
3,152 | PeterCamilleri/mini_term | lib/mini_term/common/mapper.rb | MiniTerm.Mapper.process_non_terminals | def process_non_terminals(index)
seq = ""
index.chop.chars.each do |char|
seq << char
if @map.has_key?(seq) && @map[seq]
fail MiniTermKME, "Ambiguous entry #{index.inspect}"
end
@map[seq] = false
end
end | ruby | def process_non_terminals(index)
seq = ""
index.chop.chars.each do |char|
seq << char
if @map.has_key?(seq) && @map[seq]
fail MiniTermKME, "Ambiguous entry #{index.inspect}"
end
@map[seq] = false
end
end | [
"def",
"process_non_terminals",
"(",
"index",
")",
"seq",
"=",
"\"\"",
"index",
".",
"chop",
".",
"chars",
".",
"each",
"do",
"|",
"char",
"|",
"seq",
"<<",
"char",
"if",
"@map",
".",
"has_key?",
"(",
"seq",
")",
"&&",
"@map",
"[",
"seq",
"]",
"fail",
"MiniTermKME",
",",
"\"Ambiguous entry #{index.inspect}\"",
"end",
"@map",
"[",
"seq",
"]",
"=",
"false",
"end",
"end"
] | Handle the preamble characters in the command sequence. | [
"Handle",
"the",
"preamble",
"characters",
"in",
"the",
"command",
"sequence",
"."
] | 71c179e82d3a353144d7e100ee0df89c2d71fac8 | https://github.com/PeterCamilleri/mini_term/blob/71c179e82d3a353144d7e100ee0df89c2d71fac8/lib/mini_term/common/mapper.rb#L31-L43 |
3,153 | Bweeb/malcolm | lib/malcolm/request/soap_builder.rb | Malcolm.SOAPBuilder.wrap | def wrap(data)
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\"><env:Body>".tap do |soap_envelope|
unless data.blank?
soap_envelope << (data.is_a?(Hash) ? Gyoku.xml(data) : data)
end
soap_envelope << "</env:Body></env:Envelope>"
end
end | ruby | def wrap(data)
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\"><env:Body>".tap do |soap_envelope|
unless data.blank?
soap_envelope << (data.is_a?(Hash) ? Gyoku.xml(data) : data)
end
soap_envelope << "</env:Body></env:Envelope>"
end
end | [
"def",
"wrap",
"(",
"data",
")",
"\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><env:Envelope xmlns:env=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\"><env:Body>\"",
".",
"tap",
"do",
"|",
"soap_envelope",
"|",
"unless",
"data",
".",
"blank?",
"soap_envelope",
"<<",
"(",
"data",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"Gyoku",
".",
"xml",
"(",
"data",
")",
":",
"data",
")",
"end",
"soap_envelope",
"<<",
"\"</env:Body></env:Envelope>\"",
"end",
"end"
] | Builds an XML document around request data | [
"Builds",
"an",
"XML",
"document",
"around",
"request",
"data"
] | 8a6253ec72a6c15a25fb765d4fceb4d0ede165e7 | https://github.com/Bweeb/malcolm/blob/8a6253ec72a6c15a25fb765d4fceb4d0ede165e7/lib/malcolm/request/soap_builder.rb#L14-L21 |
3,154 | dfhoughton/list_matcher | lib/list_matcher.rb | List.Matcher.bud | def bud(opts={})
opts = {
atomic: @atomic,
backtracking: @backtracking,
bound: @_bound,
strip: @strip,
case_insensitive: @case_insensitive,
multiline: @multiline,
not_extended: @not_extended,
normalize_whitespace: @normalize_whitespace,
symbols: @symbols,
name: @name,
vet: @vet && opts[:symbols]
}.merge opts
self.class.new(**opts)
end | ruby | def bud(opts={})
opts = {
atomic: @atomic,
backtracking: @backtracking,
bound: @_bound,
strip: @strip,
case_insensitive: @case_insensitive,
multiline: @multiline,
not_extended: @not_extended,
normalize_whitespace: @normalize_whitespace,
symbols: @symbols,
name: @name,
vet: @vet && opts[:symbols]
}.merge opts
self.class.new(**opts)
end | [
"def",
"bud",
"(",
"opts",
"=",
"{",
"}",
")",
"opts",
"=",
"{",
"atomic",
":",
"@atomic",
",",
"backtracking",
":",
"@backtracking",
",",
"bound",
":",
"@_bound",
",",
"strip",
":",
"@strip",
",",
"case_insensitive",
":",
"@case_insensitive",
",",
"multiline",
":",
"@multiline",
",",
"not_extended",
":",
"@not_extended",
",",
"normalize_whitespace",
":",
"@normalize_whitespace",
",",
"symbols",
":",
"@symbols",
",",
"name",
":",
"@name",
",",
"vet",
":",
"@vet",
"&&",
"opts",
"[",
":symbols",
"]",
"}",
".",
"merge",
"opts",
"self",
".",
"class",
".",
"new",
"(",
"**",
"opts",
")",
"end"
] | returns a new pattern matcher differing from the original only in the options specified | [
"returns",
"a",
"new",
"pattern",
"matcher",
"differing",
"from",
"the",
"original",
"only",
"in",
"the",
"options",
"specified"
] | cbc2368251e8a69ac99aea84fbd64034c1ff7c88 | https://github.com/dfhoughton/list_matcher/blob/cbc2368251e8a69ac99aea84fbd64034c1ff7c88/lib/list_matcher.rb#L126-L141 |
3,155 | dfhoughton/list_matcher | lib/list_matcher.rb | List.Matcher.pattern | def pattern( list, opts={} )
return '(?!)' unless list.any?
return bud(opts).pattern list unless opts.empty?
list = list.compact.map(&:to_s).select{ |s| s.length > 0 }
list.map!(&:strip).select!{ |s| s.length > 0 } if strip
list.map!{ |s| s.gsub %r/\s++/, ' ' } if normalize_whitespace
return nil if list.empty?
specializer = Special.new self, @symbols, list
list = specializer.normalize
root = tree list, specializer
root.root = true
root.flatten
rx = root.convert
if m = modifiers
rx = "(?#{m}:#{rx})"
grouped = true
end
if name
rx = "(?<#{name}>#{rx})"
grouped = true
end
return rx if grouped && backtracking
if atomic && !root.atomic?
wrap rx
else
rx
end
end | ruby | def pattern( list, opts={} )
return '(?!)' unless list.any?
return bud(opts).pattern list unless opts.empty?
list = list.compact.map(&:to_s).select{ |s| s.length > 0 }
list.map!(&:strip).select!{ |s| s.length > 0 } if strip
list.map!{ |s| s.gsub %r/\s++/, ' ' } if normalize_whitespace
return nil if list.empty?
specializer = Special.new self, @symbols, list
list = specializer.normalize
root = tree list, specializer
root.root = true
root.flatten
rx = root.convert
if m = modifiers
rx = "(?#{m}:#{rx})"
grouped = true
end
if name
rx = "(?<#{name}>#{rx})"
grouped = true
end
return rx if grouped && backtracking
if atomic && !root.atomic?
wrap rx
else
rx
end
end | [
"def",
"pattern",
"(",
"list",
",",
"opts",
"=",
"{",
"}",
")",
"return",
"'(?!)'",
"unless",
"list",
".",
"any?",
"return",
"bud",
"(",
"opts",
")",
".",
"pattern",
"list",
"unless",
"opts",
".",
"empty?",
"list",
"=",
"list",
".",
"compact",
".",
"map",
"(",
":to_s",
")",
".",
"select",
"{",
"|",
"s",
"|",
"s",
".",
"length",
">",
"0",
"}",
"list",
".",
"map!",
"(",
":strip",
")",
".",
"select!",
"{",
"|",
"s",
"|",
"s",
".",
"length",
">",
"0",
"}",
"if",
"strip",
"list",
".",
"map!",
"{",
"|",
"s",
"|",
"s",
".",
"gsub",
"%r/",
"\\s",
"/",
",",
"' '",
"}",
"if",
"normalize_whitespace",
"return",
"nil",
"if",
"list",
".",
"empty?",
"specializer",
"=",
"Special",
".",
"new",
"self",
",",
"@symbols",
",",
"list",
"list",
"=",
"specializer",
".",
"normalize",
"root",
"=",
"tree",
"list",
",",
"specializer",
"root",
".",
"root",
"=",
"true",
"root",
".",
"flatten",
"rx",
"=",
"root",
".",
"convert",
"if",
"m",
"=",
"modifiers",
"rx",
"=",
"\"(?#{m}:#{rx})\"",
"grouped",
"=",
"true",
"end",
"if",
"name",
"rx",
"=",
"\"(?<#{name}>#{rx})\"",
"grouped",
"=",
"true",
"end",
"return",
"rx",
"if",
"grouped",
"&&",
"backtracking",
"if",
"atomic",
"&&",
"!",
"root",
".",
"atomic?",
"wrap",
"rx",
"else",
"rx",
"end",
"end"
] | converst list into a string representing a regex pattern suitable for inclusion in a larger regex | [
"converst",
"list",
"into",
"a",
"string",
"representing",
"a",
"regex",
"pattern",
"suitable",
"for",
"inclusion",
"in",
"a",
"larger",
"regex"
] | cbc2368251e8a69ac99aea84fbd64034c1ff7c88 | https://github.com/dfhoughton/list_matcher/blob/cbc2368251e8a69ac99aea84fbd64034c1ff7c88/lib/list_matcher.rb#L144-L172 |
3,156 | MustWin/missinglink | app/models/missinglink/survey_question.rb | Missinglink.SurveyQuestion.possible_responses | def possible_responses(search_other = false)
{}.tap do |hash|
survey_response_answers.each do |sra|
sa_row = (sra.row_survey_answer_id ? SurveyAnswer.find(sra.row_survey_answer_id) : nil)
sa_col = (sra.col_survey_answer_id ? SurveyAnswer.find(sra.col_survey_answer_id) : nil)
sa_col_choice = (sra.col_choice_survey_answer_id ? SurveyAnswer.find(sra.col_choice_survey_answer_id) : nil)
case answer_strategy
when "first_survey_response_answer_text"
hash[sra.text] = sra.id unless (sra.text.nil? || hash[sra.text])
when "answer_row_for_subquestion"
other_text = (sra.text.nil? ? nil : "#{ (sa_row.try(:text) || "Other") }: #{ sra.text }")
hash[other_text] = sra.id unless (other_text.nil? || hash[other_text])
when "answer_row_for_response"
other_text = ((!search_other || sra.text.nil?) ? nil : "#{ (sa_row.try(:text) || "Other") }: #{ sra.text }")
hash[sa_row.text] = sra.id unless (sa_row.nil? || hash[sa_row.text])
hash[other_text] = sra.id unless (other_text.nil? || hash[other_text])
when "answer_row_and_column_for_response"
main_text = "#{ sa_row.try(:text) }: #{ sa_col.try(:text) }"
other_text = ((!search_other || sra.text.nil? || !sa_row.nil?) ? nil : "Other: #{ sra.text }")
hash[main_text] = sra.id unless (sa_row.nil? || sa_col.nil? || hash[main_text])
hash[other_text] = sra.id unless (other_text.nil? || hash[other_text])
when "answer_row_column_choice_for_response"
main_text = "#{ sa_row.try(:text) }, #{ sa_col.try(:text) }: #{ sa_col_choice.try(:text) }"
other_text = ((!search_other || sra.text.nil? || !sa_row.nil?) ? nil : "Other: #{ sra.text }")
hash[main_text] = sra.id unless (sa_row.nil? || sa_col.nil? || sa_col_choice.nil? || hash[main_text])
hash[other_text] = sra.id unless (other_text.nil? || hash[other_text])
end
end
end
end | ruby | def possible_responses(search_other = false)
{}.tap do |hash|
survey_response_answers.each do |sra|
sa_row = (sra.row_survey_answer_id ? SurveyAnswer.find(sra.row_survey_answer_id) : nil)
sa_col = (sra.col_survey_answer_id ? SurveyAnswer.find(sra.col_survey_answer_id) : nil)
sa_col_choice = (sra.col_choice_survey_answer_id ? SurveyAnswer.find(sra.col_choice_survey_answer_id) : nil)
case answer_strategy
when "first_survey_response_answer_text"
hash[sra.text] = sra.id unless (sra.text.nil? || hash[sra.text])
when "answer_row_for_subquestion"
other_text = (sra.text.nil? ? nil : "#{ (sa_row.try(:text) || "Other") }: #{ sra.text }")
hash[other_text] = sra.id unless (other_text.nil? || hash[other_text])
when "answer_row_for_response"
other_text = ((!search_other || sra.text.nil?) ? nil : "#{ (sa_row.try(:text) || "Other") }: #{ sra.text }")
hash[sa_row.text] = sra.id unless (sa_row.nil? || hash[sa_row.text])
hash[other_text] = sra.id unless (other_text.nil? || hash[other_text])
when "answer_row_and_column_for_response"
main_text = "#{ sa_row.try(:text) }: #{ sa_col.try(:text) }"
other_text = ((!search_other || sra.text.nil? || !sa_row.nil?) ? nil : "Other: #{ sra.text }")
hash[main_text] = sra.id unless (sa_row.nil? || sa_col.nil? || hash[main_text])
hash[other_text] = sra.id unless (other_text.nil? || hash[other_text])
when "answer_row_column_choice_for_response"
main_text = "#{ sa_row.try(:text) }, #{ sa_col.try(:text) }: #{ sa_col_choice.try(:text) }"
other_text = ((!search_other || sra.text.nil? || !sa_row.nil?) ? nil : "Other: #{ sra.text }")
hash[main_text] = sra.id unless (sa_row.nil? || sa_col.nil? || sa_col_choice.nil? || hash[main_text])
hash[other_text] = sra.id unless (other_text.nil? || hash[other_text])
end
end
end
end | [
"def",
"possible_responses",
"(",
"search_other",
"=",
"false",
")",
"{",
"}",
".",
"tap",
"do",
"|",
"hash",
"|",
"survey_response_answers",
".",
"each",
"do",
"|",
"sra",
"|",
"sa_row",
"=",
"(",
"sra",
".",
"row_survey_answer_id",
"?",
"SurveyAnswer",
".",
"find",
"(",
"sra",
".",
"row_survey_answer_id",
")",
":",
"nil",
")",
"sa_col",
"=",
"(",
"sra",
".",
"col_survey_answer_id",
"?",
"SurveyAnswer",
".",
"find",
"(",
"sra",
".",
"col_survey_answer_id",
")",
":",
"nil",
")",
"sa_col_choice",
"=",
"(",
"sra",
".",
"col_choice_survey_answer_id",
"?",
"SurveyAnswer",
".",
"find",
"(",
"sra",
".",
"col_choice_survey_answer_id",
")",
":",
"nil",
")",
"case",
"answer_strategy",
"when",
"\"first_survey_response_answer_text\"",
"hash",
"[",
"sra",
".",
"text",
"]",
"=",
"sra",
".",
"id",
"unless",
"(",
"sra",
".",
"text",
".",
"nil?",
"||",
"hash",
"[",
"sra",
".",
"text",
"]",
")",
"when",
"\"answer_row_for_subquestion\"",
"other_text",
"=",
"(",
"sra",
".",
"text",
".",
"nil?",
"?",
"nil",
":",
"\"#{ (sa_row.try(:text) || \"Other\") }: #{ sra.text }\"",
")",
"hash",
"[",
"other_text",
"]",
"=",
"sra",
".",
"id",
"unless",
"(",
"other_text",
".",
"nil?",
"||",
"hash",
"[",
"other_text",
"]",
")",
"when",
"\"answer_row_for_response\"",
"other_text",
"=",
"(",
"(",
"!",
"search_other",
"||",
"sra",
".",
"text",
".",
"nil?",
")",
"?",
"nil",
":",
"\"#{ (sa_row.try(:text) || \"Other\") }: #{ sra.text }\"",
")",
"hash",
"[",
"sa_row",
".",
"text",
"]",
"=",
"sra",
".",
"id",
"unless",
"(",
"sa_row",
".",
"nil?",
"||",
"hash",
"[",
"sa_row",
".",
"text",
"]",
")",
"hash",
"[",
"other_text",
"]",
"=",
"sra",
".",
"id",
"unless",
"(",
"other_text",
".",
"nil?",
"||",
"hash",
"[",
"other_text",
"]",
")",
"when",
"\"answer_row_and_column_for_response\"",
"main_text",
"=",
"\"#{ sa_row.try(:text) }: #{ sa_col.try(:text) }\"",
"other_text",
"=",
"(",
"(",
"!",
"search_other",
"||",
"sra",
".",
"text",
".",
"nil?",
"||",
"!",
"sa_row",
".",
"nil?",
")",
"?",
"nil",
":",
"\"Other: #{ sra.text }\"",
")",
"hash",
"[",
"main_text",
"]",
"=",
"sra",
".",
"id",
"unless",
"(",
"sa_row",
".",
"nil?",
"||",
"sa_col",
".",
"nil?",
"||",
"hash",
"[",
"main_text",
"]",
")",
"hash",
"[",
"other_text",
"]",
"=",
"sra",
".",
"id",
"unless",
"(",
"other_text",
".",
"nil?",
"||",
"hash",
"[",
"other_text",
"]",
")",
"when",
"\"answer_row_column_choice_for_response\"",
"main_text",
"=",
"\"#{ sa_row.try(:text) }, #{ sa_col.try(:text) }: #{ sa_col_choice.try(:text) }\"",
"other_text",
"=",
"(",
"(",
"!",
"search_other",
"||",
"sra",
".",
"text",
".",
"nil?",
"||",
"!",
"sa_row",
".",
"nil?",
")",
"?",
"nil",
":",
"\"Other: #{ sra.text }\"",
")",
"hash",
"[",
"main_text",
"]",
"=",
"sra",
".",
"id",
"unless",
"(",
"sa_row",
".",
"nil?",
"||",
"sa_col",
".",
"nil?",
"||",
"sa_col_choice",
".",
"nil?",
"||",
"hash",
"[",
"main_text",
"]",
")",
"hash",
"[",
"other_text",
"]",
"=",
"sra",
".",
"id",
"unless",
"(",
"other_text",
".",
"nil?",
"||",
"hash",
"[",
"other_text",
"]",
")",
"end",
"end",
"end",
"end"
] | for reference, when searching, listing all possible responses is
logical, but it is impossible to track all survey response answers
that match the desired answer. therefore, we only track one
example, and later find all similar response answers based on the
question strategy | [
"for",
"reference",
"when",
"searching",
"listing",
"all",
"possible",
"responses",
"is",
"logical",
"but",
"it",
"is",
"impossible",
"to",
"track",
"all",
"survey",
"response",
"answers",
"that",
"match",
"the",
"desired",
"answer",
".",
"therefore",
"we",
"only",
"track",
"one",
"example",
"and",
"later",
"find",
"all",
"similar",
"response",
"answers",
"based",
"on",
"the",
"question",
"strategy"
] | 732f362cc802a73946a36aa5b469957e6487f48a | https://github.com/MustWin/missinglink/blob/732f362cc802a73946a36aa5b469957e6487f48a/app/models/missinglink/survey_question.rb#L41-L71 |
3,157 | SquareSquash/uploader | lib/squash/uploader.rb | Squash.Uploader.http_post | def http_post(url, headers, bodies)
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == 'https')
http.open_timeout = options[:open_timeout]
http.read_timeout = options[:read_timeout]
http.verify_mode = OpenSSL::SSL::VERIFY_NONE if options[:skip_verification]
http.start do |session|
bodies.each do |body|
request = Net::HTTP::Post.new(uri.request_uri)
headers.each { |k, v| request.add_field k, v }
request.body = body
response = session.request(request)
if options[:success].none? { |cl|
if cl.kind_of?(Class)
response.kind_of?(cl)
elsif cl.kind_of?(Fixnum) || cl.kind_of?(String)
response.code.to_i == cl.to_i
else
raise ArgumentError, "Unknown :success value #{cl}"
end
}
raise "Unexpected response from Squash host: #{response.code}"
end
end
end
end | ruby | def http_post(url, headers, bodies)
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == 'https')
http.open_timeout = options[:open_timeout]
http.read_timeout = options[:read_timeout]
http.verify_mode = OpenSSL::SSL::VERIFY_NONE if options[:skip_verification]
http.start do |session|
bodies.each do |body|
request = Net::HTTP::Post.new(uri.request_uri)
headers.each { |k, v| request.add_field k, v }
request.body = body
response = session.request(request)
if options[:success].none? { |cl|
if cl.kind_of?(Class)
response.kind_of?(cl)
elsif cl.kind_of?(Fixnum) || cl.kind_of?(String)
response.code.to_i == cl.to_i
else
raise ArgumentError, "Unknown :success value #{cl}"
end
}
raise "Unexpected response from Squash host: #{response.code}"
end
end
end
end | [
"def",
"http_post",
"(",
"url",
",",
"headers",
",",
"bodies",
")",
"uri",
"=",
"URI",
".",
"parse",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"http",
".",
"use_ssl",
"=",
"(",
"uri",
".",
"scheme",
"==",
"'https'",
")",
"http",
".",
"open_timeout",
"=",
"options",
"[",
":open_timeout",
"]",
"http",
".",
"read_timeout",
"=",
"options",
"[",
":read_timeout",
"]",
"http",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_NONE",
"if",
"options",
"[",
":skip_verification",
"]",
"http",
".",
"start",
"do",
"|",
"session",
"|",
"bodies",
".",
"each",
"do",
"|",
"body",
"|",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"request_uri",
")",
"headers",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"request",
".",
"add_field",
"k",
",",
"v",
"}",
"request",
".",
"body",
"=",
"body",
"response",
"=",
"session",
".",
"request",
"(",
"request",
")",
"if",
"options",
"[",
":success",
"]",
".",
"none?",
"{",
"|",
"cl",
"|",
"if",
"cl",
".",
"kind_of?",
"(",
"Class",
")",
"response",
".",
"kind_of?",
"(",
"cl",
")",
"elsif",
"cl",
".",
"kind_of?",
"(",
"Fixnum",
")",
"||",
"cl",
".",
"kind_of?",
"(",
"String",
")",
"response",
".",
"code",
".",
"to_i",
"==",
"cl",
".",
"to_i",
"else",
"raise",
"ArgumentError",
",",
"\"Unknown :success value #{cl}\"",
"end",
"}",
"raise",
"\"Unexpected response from Squash host: #{response.code}\"",
"end",
"end",
"end",
"end"
] | Override this method to use your favorite HTTP library. This method receives
an array of bodies. It is intended that each element of the array be
transmitted as a separate POST request, _not_ that the bodies be
concatenated and sent as one request.
A response of code found in the `:success` option is considered successful.
@param [String] url The URL to POST to.
@param [Hash<String, String>] headers The request headers.
@param [Array<String>] bodies The bodies of each request to POST.
@raise [StandardError] If a response other than 2xx or 422 is returned. | [
"Override",
"this",
"method",
"to",
"use",
"your",
"favorite",
"HTTP",
"library",
".",
"This",
"method",
"receives",
"an",
"array",
"of",
"bodies",
".",
"It",
"is",
"intended",
"that",
"each",
"element",
"of",
"the",
"array",
"be",
"transmitted",
"as",
"a",
"separate",
"POST",
"request",
"_not_",
"that",
"the",
"bodies",
"be",
"concatenated",
"and",
"sent",
"as",
"one",
"request",
"."
] | 6a0aa2b5ca6298492fcf11b7b07458e2cadb5c92 | https://github.com/SquareSquash/uploader/blob/6a0aa2b5ca6298492fcf11b7b07458e2cadb5c92/lib/squash/uploader.rb#L88-L116 |
3,158 | rtjoseph11/modernizer | lib/modernizer.rb | Modernize.Modernizer.translate | def translate(context, hash)
# makes sure that the context is a hash
raise ArgumentError.new('did not pass a hash for the context') unless context.is_a?(Hash)
raise ArgumentError.new('cannot provide include hash in context') if context[:hash]
# create the context instance for instance variables
struct = StructContext.new(context, hash)
# instantiate MapMethods to perform translations and define lambda
# for how to tranlate a field
#
translate = lambda { |t|
MapMethods.send(t[:name], struct, t[:field], t[:block])
}
# determine the version of the incoming hash
#
struct_version = struct.instance_exec(&@migrations.version)
raise StandardError.new('calculated version is not valid') unless Gem::Version.correct?(struct_version)
# gets a list of the potential versions
#
migration_versions = @migrations.translations.keys
migration_versions.delete(:first)
migration_versions.delete(:last)
# get the first and last translations
#
firsts = @migrations.translations[:first]
lasts = @migrations.translations[:last]
# sorts the versions
#
migration_versions.sort! do |x,y|
Gem::Version.new(x) <=> Gem::Version.new(y)
end
# reverse order if descending was specified
#
migration_versions = @migrations.order == :descending ? migration_versions.reverse : migration_versions
# run the first translations if they exist
#
firsts.each(&translate) if firsts
# determine the first version to run translations
#
first_index = @migrations.order == :ascending ? migration_versions.find_index(struct_version) : nil
last_index = @migrations.order == :descending ? migration_versions.find_index(struct_version) : nil
# run all subsequent version translations
#
migration_versions.each_with_index do |version, index|
next unless !first_index || index >= first_index
next unless !last_index || index <= last_index
@migrations.translations[version].each(&translate)
end
# run the first translations if they exist
#
lasts.each(&translate) if lasts
# return hash
#
struct.hash
end | ruby | def translate(context, hash)
# makes sure that the context is a hash
raise ArgumentError.new('did not pass a hash for the context') unless context.is_a?(Hash)
raise ArgumentError.new('cannot provide include hash in context') if context[:hash]
# create the context instance for instance variables
struct = StructContext.new(context, hash)
# instantiate MapMethods to perform translations and define lambda
# for how to tranlate a field
#
translate = lambda { |t|
MapMethods.send(t[:name], struct, t[:field], t[:block])
}
# determine the version of the incoming hash
#
struct_version = struct.instance_exec(&@migrations.version)
raise StandardError.new('calculated version is not valid') unless Gem::Version.correct?(struct_version)
# gets a list of the potential versions
#
migration_versions = @migrations.translations.keys
migration_versions.delete(:first)
migration_versions.delete(:last)
# get the first and last translations
#
firsts = @migrations.translations[:first]
lasts = @migrations.translations[:last]
# sorts the versions
#
migration_versions.sort! do |x,y|
Gem::Version.new(x) <=> Gem::Version.new(y)
end
# reverse order if descending was specified
#
migration_versions = @migrations.order == :descending ? migration_versions.reverse : migration_versions
# run the first translations if they exist
#
firsts.each(&translate) if firsts
# determine the first version to run translations
#
first_index = @migrations.order == :ascending ? migration_versions.find_index(struct_version) : nil
last_index = @migrations.order == :descending ? migration_versions.find_index(struct_version) : nil
# run all subsequent version translations
#
migration_versions.each_with_index do |version, index|
next unless !first_index || index >= first_index
next unless !last_index || index <= last_index
@migrations.translations[version].each(&translate)
end
# run the first translations if they exist
#
lasts.each(&translate) if lasts
# return hash
#
struct.hash
end | [
"def",
"translate",
"(",
"context",
",",
"hash",
")",
"# makes sure that the context is a hash",
"raise",
"ArgumentError",
".",
"new",
"(",
"'did not pass a hash for the context'",
")",
"unless",
"context",
".",
"is_a?",
"(",
"Hash",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"'cannot provide include hash in context'",
")",
"if",
"context",
"[",
":hash",
"]",
"# create the context instance for instance variables",
"struct",
"=",
"StructContext",
".",
"new",
"(",
"context",
",",
"hash",
")",
"# instantiate MapMethods to perform translations and define lambda",
"# for how to tranlate a field",
"#",
"translate",
"=",
"lambda",
"{",
"|",
"t",
"|",
"MapMethods",
".",
"send",
"(",
"t",
"[",
":name",
"]",
",",
"struct",
",",
"t",
"[",
":field",
"]",
",",
"t",
"[",
":block",
"]",
")",
"}",
"# determine the version of the incoming hash",
"#",
"struct_version",
"=",
"struct",
".",
"instance_exec",
"(",
"@migrations",
".",
"version",
")",
"raise",
"StandardError",
".",
"new",
"(",
"'calculated version is not valid'",
")",
"unless",
"Gem",
"::",
"Version",
".",
"correct?",
"(",
"struct_version",
")",
"# gets a list of the potential versions ",
"#",
"migration_versions",
"=",
"@migrations",
".",
"translations",
".",
"keys",
"migration_versions",
".",
"delete",
"(",
":first",
")",
"migration_versions",
".",
"delete",
"(",
":last",
")",
"# get the first and last translations",
"#",
"firsts",
"=",
"@migrations",
".",
"translations",
"[",
":first",
"]",
"lasts",
"=",
"@migrations",
".",
"translations",
"[",
":last",
"]",
"# sorts the versions",
"#",
"migration_versions",
".",
"sort!",
"do",
"|",
"x",
",",
"y",
"|",
"Gem",
"::",
"Version",
".",
"new",
"(",
"x",
")",
"<=>",
"Gem",
"::",
"Version",
".",
"new",
"(",
"y",
")",
"end",
"# reverse order if descending was specified",
"#",
"migration_versions",
"=",
"@migrations",
".",
"order",
"==",
":descending",
"?",
"migration_versions",
".",
"reverse",
":",
"migration_versions",
"# run the first translations if they exist",
"#",
"firsts",
".",
"each",
"(",
"translate",
")",
"if",
"firsts",
"# determine the first version to run translations",
"#",
"first_index",
"=",
"@migrations",
".",
"order",
"==",
":ascending",
"?",
"migration_versions",
".",
"find_index",
"(",
"struct_version",
")",
":",
"nil",
"last_index",
"=",
"@migrations",
".",
"order",
"==",
":descending",
"?",
"migration_versions",
".",
"find_index",
"(",
"struct_version",
")",
":",
"nil",
"# run all subsequent version translations",
"#",
"migration_versions",
".",
"each_with_index",
"do",
"|",
"version",
",",
"index",
"|",
"next",
"unless",
"!",
"first_index",
"||",
"index",
">=",
"first_index",
"next",
"unless",
"!",
"last_index",
"||",
"index",
"<=",
"last_index",
"@migrations",
".",
"translations",
"[",
"version",
"]",
".",
"each",
"(",
"translate",
")",
"end",
"# run the first translations if they exist",
"#",
"lasts",
".",
"each",
"(",
"translate",
")",
"if",
"lasts",
"# return hash",
"#",
"struct",
".",
"hash",
"end"
] | Generates the set of migrations by parsing the passed in block
Translates a hash based on defined migrations
with a given context and returns the hash.
This will modify whatever gets passed in. | [
"Generates",
"the",
"set",
"of",
"migrations",
"by",
"parsing",
"the",
"passed",
"in",
"block"
] | 5700b61815731f41146248d7e3fe8eca0e647ef3 | https://github.com/rtjoseph11/modernizer/blob/5700b61815731f41146248d7e3fe8eca0e647ef3/lib/modernizer.rb#L20-L85 |
3,159 | stvvan/hoiio-ruby | lib/hoiio-ruby/util/request_util.rb | Hoiio.RequestUtil.check_nil_or_empty | def check_nil_or_empty(required_param_names=[], params)
required_param_names.each { |p|
if params[p].nil? || params[p].empty?
raise Hoiio::RequestError.new "Param " << p << " is missing"
end
}
end | ruby | def check_nil_or_empty(required_param_names=[], params)
required_param_names.each { |p|
if params[p].nil? || params[p].empty?
raise Hoiio::RequestError.new "Param " << p << " is missing"
end
}
end | [
"def",
"check_nil_or_empty",
"(",
"required_param_names",
"=",
"[",
"]",
",",
"params",
")",
"required_param_names",
".",
"each",
"{",
"|",
"p",
"|",
"if",
"params",
"[",
"p",
"]",
".",
"nil?",
"||",
"params",
"[",
"p",
"]",
".",
"empty?",
"raise",
"Hoiio",
"::",
"RequestError",
".",
"new",
"\"Param \"",
"<<",
"p",
"<<",
"\" is missing\"",
"end",
"}",
"end"
] | Utility methods
Check if any required parameter is missing in params hash
@param required_param_names array of names of required parameters that need to be checked
@param params hash of params that will be used to check the presence of each required_param_name
@return Hoiio::InputError if a required param is missing | [
"Utility",
"methods",
"Check",
"if",
"any",
"required",
"parameter",
"is",
"missing",
"in",
"params",
"hash"
] | 7f6840b94c5f61c221619ca069bc008d502dd339 | https://github.com/stvvan/hoiio-ruby/blob/7f6840b94c5f61c221619ca069bc008d502dd339/lib/hoiio-ruby/util/request_util.rb#L35-L41 |
3,160 | stvvan/hoiio-ruby | lib/hoiio-ruby/util/request_util.rb | Hoiio.RequestUtil.check_for_mutual_exclusivity | def check_for_mutual_exclusivity(required_param_names=[], params)
i = 0
required_param_names.each { |p|
if !params[p].nil? && !params[p].empty?
i += 1
end
}
if i == 0
raise Hoiio::RequestError.new "All required params are missing"
elsif i > 1
raise Hoiio::RequestError.new "More than 1 required, mutually exclusive param are present."
end
end | ruby | def check_for_mutual_exclusivity(required_param_names=[], params)
i = 0
required_param_names.each { |p|
if !params[p].nil? && !params[p].empty?
i += 1
end
}
if i == 0
raise Hoiio::RequestError.new "All required params are missing"
elsif i > 1
raise Hoiio::RequestError.new "More than 1 required, mutually exclusive param are present."
end
end | [
"def",
"check_for_mutual_exclusivity",
"(",
"required_param_names",
"=",
"[",
"]",
",",
"params",
")",
"i",
"=",
"0",
"required_param_names",
".",
"each",
"{",
"|",
"p",
"|",
"if",
"!",
"params",
"[",
"p",
"]",
".",
"nil?",
"&&",
"!",
"params",
"[",
"p",
"]",
".",
"empty?",
"i",
"+=",
"1",
"end",
"}",
"if",
"i",
"==",
"0",
"raise",
"Hoiio",
"::",
"RequestError",
".",
"new",
"\"All required params are missing\"",
"elsif",
"i",
">",
"1",
"raise",
"Hoiio",
"::",
"RequestError",
".",
"new",
"\"More than 1 required, mutually exclusive param are present.\"",
"end",
"end"
] | Check that only 1 required parameter is needed for specific API calls
@param required_param_names array of names of required parameters that need to be checked
@param params hash of params that will be used to check the presence of each required_param_name
@return Hoiio::InputError if a required param is missing or if all required params are present | [
"Check",
"that",
"only",
"1",
"required",
"parameter",
"is",
"needed",
"for",
"specific",
"API",
"calls"
] | 7f6840b94c5f61c221619ca069bc008d502dd339 | https://github.com/stvvan/hoiio-ruby/blob/7f6840b94c5f61c221619ca069bc008d502dd339/lib/hoiio-ruby/util/request_util.rb#L49-L62 |
3,161 | dennisvandehoef/easy-html-creator | lib/generator/haml_generator.rb | Generator.Context.render_partial | def render_partial(file_name)
# The "default" version of the partial.
file_to_render = "#{@input_folder}/partials/#{file_name.to_s}.haml"
if @scope
# Look for a partial prefixed with the current "scope" (which is just the name of the
# primary template being rendered).
scope_file = "#{@input_folder}/partials/#{@scope.to_s}_#{file_name.to_s}.haml"
# Use it if it's there.
file_to_render = scope_file if File.exists? scope_file
end
# If we found a matching partial (either the scoped one or the default), render it now.
if File.exists? file_to_render
partial = Haml::Engine.new(File.read(file_to_render), @options)
partial.render self
else
nil
end
rescue Exception => e
raise $!, "#{$!} PARTIAL::#{file_name} ", $!.backtrace
end | ruby | def render_partial(file_name)
# The "default" version of the partial.
file_to_render = "#{@input_folder}/partials/#{file_name.to_s}.haml"
if @scope
# Look for a partial prefixed with the current "scope" (which is just the name of the
# primary template being rendered).
scope_file = "#{@input_folder}/partials/#{@scope.to_s}_#{file_name.to_s}.haml"
# Use it if it's there.
file_to_render = scope_file if File.exists? scope_file
end
# If we found a matching partial (either the scoped one or the default), render it now.
if File.exists? file_to_render
partial = Haml::Engine.new(File.read(file_to_render), @options)
partial.render self
else
nil
end
rescue Exception => e
raise $!, "#{$!} PARTIAL::#{file_name} ", $!.backtrace
end | [
"def",
"render_partial",
"(",
"file_name",
")",
"# The \"default\" version of the partial.",
"file_to_render",
"=",
"\"#{@input_folder}/partials/#{file_name.to_s}.haml\"",
"if",
"@scope",
"# Look for a partial prefixed with the current \"scope\" (which is just the name of the",
"# primary template being rendered).",
"scope_file",
"=",
"\"#{@input_folder}/partials/#{@scope.to_s}_#{file_name.to_s}.haml\"",
"# Use it if it's there.",
"file_to_render",
"=",
"scope_file",
"if",
"File",
".",
"exists?",
"scope_file",
"end",
"# If we found a matching partial (either the scoped one or the default), render it now.",
"if",
"File",
".",
"exists?",
"file_to_render",
"partial",
"=",
"Haml",
"::",
"Engine",
".",
"new",
"(",
"File",
".",
"read",
"(",
"file_to_render",
")",
",",
"@options",
")",
"partial",
".",
"render",
"self",
"else",
"nil",
"end",
"rescue",
"Exception",
"=>",
"e",
"raise",
"$!",
",",
"\"#{$!} PARTIAL::#{file_name} \"",
",",
"$!",
".",
"backtrace",
"end"
] | This function is no different from the "copyright_year" function above. It just uses some
conventions to render another template file when it's called. | [
"This",
"function",
"is",
"no",
"different",
"from",
"the",
"copyright_year",
"function",
"above",
".",
"It",
"just",
"uses",
"some",
"conventions",
"to",
"render",
"another",
"template",
"file",
"when",
"it",
"s",
"called",
"."
] | 54f1e5f2898e6411a0a944359fa959ff2c57cc44 | https://github.com/dennisvandehoef/easy-html-creator/blob/54f1e5f2898e6411a0a944359fa959ff2c57cc44/lib/generator/haml_generator.rb#L89-L108 |
3,162 | henkm/shake-the-counter | lib/shake_the_counter/client.rb | ShakeTheCounter.Client.access_token | def access_token
@access_token ||= ShakeTheCounter::Authentication.renew_access_token(client_id: id, client_secret: secret, refresh_token: refresh_token)["access_token"]
end | ruby | def access_token
@access_token ||= ShakeTheCounter::Authentication.renew_access_token(client_id: id, client_secret: secret, refresh_token: refresh_token)["access_token"]
end | [
"def",
"access_token",
"@access_token",
"||=",
"ShakeTheCounter",
"::",
"Authentication",
".",
"renew_access_token",
"(",
"client_id",
":",
"id",
",",
"client_secret",
":",
"secret",
",",
"refresh_token",
":",
"refresh_token",
")",
"[",
"\"access_token\"",
"]",
"end"
] | Retrieves a new authentication token to use for this client
or reuse the same one from memory. | [
"Retrieves",
"a",
"new",
"authentication",
"token",
"to",
"use",
"for",
"this",
"client",
"or",
"reuse",
"the",
"same",
"one",
"from",
"memory",
"."
] | 094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e | https://github.com/henkm/shake-the-counter/blob/094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e/lib/shake_the_counter/client.rb#L48-L50 |
3,163 | henkm/shake-the-counter | lib/shake_the_counter/client.rb | ShakeTheCounter.Client.call | def call(path, http_method: :get, body: {}, header: {})
# add bearer token to header
header[:authorization] = "Bearer #{access_token}"
return ShakeTheCounter::API.call(path, http_method: http_method, body: body, header: header)
end | ruby | def call(path, http_method: :get, body: {}, header: {})
# add bearer token to header
header[:authorization] = "Bearer #{access_token}"
return ShakeTheCounter::API.call(path, http_method: http_method, body: body, header: header)
end | [
"def",
"call",
"(",
"path",
",",
"http_method",
":",
":get",
",",
"body",
":",
"{",
"}",
",",
"header",
":",
"{",
"}",
")",
"# add bearer token to header",
"header",
"[",
":authorization",
"]",
"=",
"\"Bearer #{access_token}\"",
"return",
"ShakeTheCounter",
"::",
"API",
".",
"call",
"(",
"path",
",",
"http_method",
":",
"http_method",
",",
"body",
":",
"body",
",",
"header",
":",
"header",
")",
"end"
] | Make an API with access_token | [
"Make",
"an",
"API",
"with",
"access_token"
] | 094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e | https://github.com/henkm/shake-the-counter/blob/094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e/lib/shake_the_counter/client.rb#L56-L60 |
3,164 | henkm/shake-the-counter | lib/shake_the_counter/client.rb | ShakeTheCounter.Client.start_payment | def start_payment(reservation_key)
path = "reservation/#{reservation_key}/payment"
result = call(path, http_method: :post)
if result.code.to_i == 200
return true
else
raise ShakeTheCounterError.new "Payment failed"
end
end | ruby | def start_payment(reservation_key)
path = "reservation/#{reservation_key}/payment"
result = call(path, http_method: :post)
if result.code.to_i == 200
return true
else
raise ShakeTheCounterError.new "Payment failed"
end
end | [
"def",
"start_payment",
"(",
"reservation_key",
")",
"path",
"=",
"\"reservation/#{reservation_key}/payment\"",
"result",
"=",
"call",
"(",
"path",
",",
"http_method",
":",
":post",
")",
"if",
"result",
".",
"code",
".",
"to_i",
"==",
"200",
"return",
"true",
"else",
"raise",
"ShakeTheCounterError",
".",
"new",
"\"Payment failed\"",
"end",
"end"
] | Send a message to STC that a payment
has started.
@return String status | [
"Send",
"a",
"message",
"to",
"STC",
"that",
"a",
"payment",
"has",
"started",
"."
] | 094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e | https://github.com/henkm/shake-the-counter/blob/094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e/lib/shake_the_counter/client.rb#L96-L104 |
3,165 | psusmars/MyJohnDeere-RubyGem | lib/myjohndeere/api_support_item.rb | MyJohnDeere.APISupportItem.to_hash | def to_hash()
ret_hash = {}
self.class.json_attributes.each do |attrib|
ret_hash[attrib] = self.send(attrib.to_s.underscore)
end
return ret_hash
end | ruby | def to_hash()
ret_hash = {}
self.class.json_attributes.each do |attrib|
ret_hash[attrib] = self.send(attrib.to_s.underscore)
end
return ret_hash
end | [
"def",
"to_hash",
"(",
")",
"ret_hash",
"=",
"{",
"}",
"self",
".",
"class",
".",
"json_attributes",
".",
"each",
"do",
"|",
"attrib",
"|",
"ret_hash",
"[",
"attrib",
"]",
"=",
"self",
".",
"send",
"(",
"attrib",
".",
"to_s",
".",
"underscore",
")",
"end",
"return",
"ret_hash",
"end"
] | see attributes_to_pull_from_json for the order if creating yourself | [
"see",
"attributes_to_pull_from_json",
"for",
"the",
"order",
"if",
"creating",
"yourself"
] | 0af129dc55f3a93eb61a0cb08a1af550289f4a7e | https://github.com/psusmars/MyJohnDeere-RubyGem/blob/0af129dc55f3a93eb61a0cb08a1af550289f4a7e/lib/myjohndeere/api_support_item.rb#L19-L25 |
3,166 | akerl/userinput | lib/userinput/prompt.rb | UserInput.Prompt.ask | def ask
@fd.print full_message
disable_echo if @secret
input = _ask
return input if valid(input)
check_counter
ask
ensure
enable_echo if @secret
end | ruby | def ask
@fd.print full_message
disable_echo if @secret
input = _ask
return input if valid(input)
check_counter
ask
ensure
enable_echo if @secret
end | [
"def",
"ask",
"@fd",
".",
"print",
"full_message",
"disable_echo",
"if",
"@secret",
"input",
"=",
"_ask",
"return",
"input",
"if",
"valid",
"(",
"input",
")",
"check_counter",
"ask",
"ensure",
"enable_echo",
"if",
"@secret",
"end"
] | Build new prompt object and set defaults
Request user input | [
"Build",
"new",
"prompt",
"object",
"and",
"set",
"defaults"
] | 098d4ac91e91dd6f3f062b45027ef6d10c43476f | https://github.com/akerl/userinput/blob/098d4ac91e91dd6f3f062b45027ef6d10c43476f/lib/userinput/prompt.rb#L21-L32 |
3,167 | akerl/userinput | lib/userinput/prompt.rb | UserInput.Prompt.valid | def valid(input)
return true unless @validation
_, method = VALIDATIONS.find { |klass, _| @validation.is_a? klass }
return @validation.send(method, input) if method
raise "Supported validation type not provided #{@validation.class}"
end | ruby | def valid(input)
return true unless @validation
_, method = VALIDATIONS.find { |klass, _| @validation.is_a? klass }
return @validation.send(method, input) if method
raise "Supported validation type not provided #{@validation.class}"
end | [
"def",
"valid",
"(",
"input",
")",
"return",
"true",
"unless",
"@validation",
"_",
",",
"method",
"=",
"VALIDATIONS",
".",
"find",
"{",
"|",
"klass",
",",
"_",
"|",
"@validation",
".",
"is_a?",
"klass",
"}",
"return",
"@validation",
".",
"send",
"(",
"method",
",",
"input",
")",
"if",
"method",
"raise",
"\"Supported validation type not provided #{@validation.class}\"",
"end"
] | Validate user input | [
"Validate",
"user",
"input"
] | 098d4ac91e91dd6f3f062b45027ef6d10c43476f | https://github.com/akerl/userinput/blob/098d4ac91e91dd6f3f062b45027ef6d10c43476f/lib/userinput/prompt.rb#L47-L52 |
3,168 | akerl/userinput | lib/userinput/prompt.rb | UserInput.Prompt._ask | def _ask
input = STDIN.gets.chomp
input = @default if input.empty? && @default
@fd.puts if @secret
input
end | ruby | def _ask
input = STDIN.gets.chomp
input = @default if input.empty? && @default
@fd.puts if @secret
input
end | [
"def",
"_ask",
"input",
"=",
"STDIN",
".",
"gets",
".",
"chomp",
"input",
"=",
"@default",
"if",
"input",
".",
"empty?",
"&&",
"@default",
"@fd",
".",
"puts",
"if",
"@secret",
"input",
"end"
] | Parse user input | [
"Parse",
"user",
"input"
] | 098d4ac91e91dd6f3f062b45027ef6d10c43476f | https://github.com/akerl/userinput/blob/098d4ac91e91dd6f3f062b45027ef6d10c43476f/lib/userinput/prompt.rb#L56-L61 |
3,169 | drish/hyperb | lib/hyperb/utils.rb | Hyperb.Utils.check_arguments | def check_arguments(params, *args)
contains = true
args.each do |arg|
contains = false unless params.key? arg.to_sym
end
contains
end | ruby | def check_arguments(params, *args)
contains = true
args.each do |arg|
contains = false unless params.key? arg.to_sym
end
contains
end | [
"def",
"check_arguments",
"(",
"params",
",",
"*",
"args",
")",
"contains",
"=",
"true",
"args",
".",
"each",
"do",
"|",
"arg",
"|",
"contains",
"=",
"false",
"unless",
"params",
".",
"key?",
"arg",
".",
"to_sym",
"end",
"contains",
"end"
] | checks if all args are keys into the hash
@return [Boolean]
@param params [Hash] hash to check.
@option *args [String] array of strings to check against the hash | [
"checks",
"if",
"all",
"args",
"are",
"keys",
"into",
"the",
"hash"
] | 637de68dc304d8d07470a771f499e33f227955f4 | https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/utils.rb#L16-L22 |
3,170 | drish/hyperb | lib/hyperb/utils.rb | Hyperb.Utils.prepare_json | def prepare_json(params = {})
json = {}
params.each do |key, value|
value = prepare_json(value) if value.is_a?(Hash)
json[camelize(key)] = value
end
json
end | ruby | def prepare_json(params = {})
json = {}
params.each do |key, value|
value = prepare_json(value) if value.is_a?(Hash)
json[camelize(key)] = value
end
json
end | [
"def",
"prepare_json",
"(",
"params",
"=",
"{",
"}",
")",
"json",
"=",
"{",
"}",
"params",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"value",
"=",
"prepare_json",
"(",
"value",
")",
"if",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"json",
"[",
"camelize",
"(",
"key",
")",
"]",
"=",
"value",
"end",
"json",
"end"
] | prepares all json payloads before sending to hyper
input: { foo_bar: 'test' }
output: {'FooBar': 'test' } | [
"prepares",
"all",
"json",
"payloads",
"before",
"sending",
"to",
"hyper"
] | 637de68dc304d8d07470a771f499e33f227955f4 | https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/utils.rb#L49-L56 |
3,171 | void-main/tily.rb | lib/tily/utils/tile_system.rb | Tily.TileSystem.each_tile | def each_tile level
size = tile_size level
(0...size).each do |y|
(0...size).each do |x|
yield(x, y) if block_given?
end
end
end | ruby | def each_tile level
size = tile_size level
(0...size).each do |y|
(0...size).each do |x|
yield(x, y) if block_given?
end
end
end | [
"def",
"each_tile",
"level",
"size",
"=",
"tile_size",
"level",
"(",
"0",
"...",
"size",
")",
".",
"each",
"do",
"|",
"y",
"|",
"(",
"0",
"...",
"size",
")",
".",
"each",
"do",
"|",
"x",
"|",
"yield",
"(",
"x",
",",
"y",
")",
"if",
"block_given?",
"end",
"end",
"end"
] | Builds the "x, y" pairs, and returns these pairs in block | [
"Builds",
"the",
"x",
"y",
"pairs",
"and",
"returns",
"these",
"pairs",
"in",
"block"
] | 5ff21e172ef0d62eaea59573aa429522080ae326 | https://github.com/void-main/tily.rb/blob/5ff21e172ef0d62eaea59573aa429522080ae326/lib/tily/utils/tile_system.rb#L77-L84 |
3,172 | void-main/tily.rb | lib/tily/utils/tile_system.rb | Tily.TileSystem.each_tile_with_index | def each_tile_with_index level
idx = 0
size = tile_size level
(0...size).each do |y|
(0...size).each do |x|
yield(x, y, idx) if block_given?
idx += 1
end
end
end | ruby | def each_tile_with_index level
idx = 0
size = tile_size level
(0...size).each do |y|
(0...size).each do |x|
yield(x, y, idx) if block_given?
idx += 1
end
end
end | [
"def",
"each_tile_with_index",
"level",
"idx",
"=",
"0",
"size",
"=",
"tile_size",
"level",
"(",
"0",
"...",
"size",
")",
".",
"each",
"do",
"|",
"y",
"|",
"(",
"0",
"...",
"size",
")",
".",
"each",
"do",
"|",
"x",
"|",
"yield",
"(",
"x",
",",
"y",
",",
"idx",
")",
"if",
"block_given?",
"idx",
"+=",
"1",
"end",
"end",
"end"
] | Builds the "x, y, index" pairs, and returns these pairs in block | [
"Builds",
"the",
"x",
"y",
"index",
"pairs",
"and",
"returns",
"these",
"pairs",
"in",
"block"
] | 5ff21e172ef0d62eaea59573aa429522080ae326 | https://github.com/void-main/tily.rb/blob/5ff21e172ef0d62eaea59573aa429522080ae326/lib/tily/utils/tile_system.rb#L87-L96 |
3,173 | experteer/simple_po_parser | lib/simple_po_parser/parser.rb | SimplePoParser.Parser.parse | def parse(message)
@result = {}
@scanner = StringScanner.new(message.strip)
begin
lines
rescue ParserError => pe
error_msg = "SimplePoParser::ParserError"
error_msg += pe.message
error_msg += "\nParseing result before error: '#{@result}'"
error_msg += "\nSimplePoParser filtered backtrace: SimplePoParser::ParserError"
backtrace = "#{pe.backtrace.select{|i| i =~ /lib\/simple_po_parser/}.join("\n\tfrom ")}"
raise ParserError, error_msg, backtrace
end
@result
end | ruby | def parse(message)
@result = {}
@scanner = StringScanner.new(message.strip)
begin
lines
rescue ParserError => pe
error_msg = "SimplePoParser::ParserError"
error_msg += pe.message
error_msg += "\nParseing result before error: '#{@result}'"
error_msg += "\nSimplePoParser filtered backtrace: SimplePoParser::ParserError"
backtrace = "#{pe.backtrace.select{|i| i =~ /lib\/simple_po_parser/}.join("\n\tfrom ")}"
raise ParserError, error_msg, backtrace
end
@result
end | [
"def",
"parse",
"(",
"message",
")",
"@result",
"=",
"{",
"}",
"@scanner",
"=",
"StringScanner",
".",
"new",
"(",
"message",
".",
"strip",
")",
"begin",
"lines",
"rescue",
"ParserError",
"=>",
"pe",
"error_msg",
"=",
"\"SimplePoParser::ParserError\"",
"error_msg",
"+=",
"pe",
".",
"message",
"error_msg",
"+=",
"\"\\nParseing result before error: '#{@result}'\"",
"error_msg",
"+=",
"\"\\nSimplePoParser filtered backtrace: SimplePoParser::ParserError\"",
"backtrace",
"=",
"\"#{pe.backtrace.select{|i| i =~ /lib\\/simple_po_parser/}.join(\"\\n\\tfrom \")}\"",
"raise",
"ParserError",
",",
"error_msg",
",",
"backtrace",
"end",
"@result",
"end"
] | parse a single message of the PO format.
@param message a single PO message in String format without leading or trailing whitespace
@return [Hash] parsed PO message information in Hash format | [
"parse",
"a",
"single",
"message",
"of",
"the",
"PO",
"format",
"."
] | b0ab9f76a12273b13869fd7f44231253d116ee8a | https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L21-L35 |
3,174 | experteer/simple_po_parser | lib/simple_po_parser/parser.rb | SimplePoParser.Parser.msgctxt | def msgctxt
begin
if @scanner.scan(/msgctxt/)
skip_whitespace
text = message_line
add_result(:msgctxt, text)
message_multiline(:msgctxt) if text.empty?
end
msgid
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in msgctxt\n" + pe.message, pe.backtrace
end
end | ruby | def msgctxt
begin
if @scanner.scan(/msgctxt/)
skip_whitespace
text = message_line
add_result(:msgctxt, text)
message_multiline(:msgctxt) if text.empty?
end
msgid
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in msgctxt\n" + pe.message, pe.backtrace
end
end | [
"def",
"msgctxt",
"begin",
"if",
"@scanner",
".",
"scan",
"(",
"/",
"/",
")",
"skip_whitespace",
"text",
"=",
"message_line",
"add_result",
"(",
":msgctxt",
",",
"text",
")",
"message_multiline",
"(",
":msgctxt",
")",
"if",
"text",
".",
"empty?",
"end",
"msgid",
"rescue",
"PoSyntaxError",
"=>",
"pe",
"raise",
"PoSyntaxError",
",",
"\"Syntax error in msgctxt\\n\"",
"+",
"pe",
".",
"message",
",",
"pe",
".",
"backtrace",
"end",
"end"
] | matches the msgctxt line and will continue to check for msgid afterwards
msgctxt is optional | [
"matches",
"the",
"msgctxt",
"line",
"and",
"will",
"continue",
"to",
"check",
"for",
"msgid",
"afterwards"
] | b0ab9f76a12273b13869fd7f44231253d116ee8a | https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L106-L118 |
3,175 | experteer/simple_po_parser | lib/simple_po_parser/parser.rb | SimplePoParser.Parser.msgid | def msgid
begin
if @scanner.scan(/msgid/)
skip_whitespace
text = message_line
add_result(:msgid, text)
message_multiline(:msgid) if text.empty?
if msgid_plural
msgstr_plural
else
msgstr
end
else
err_msg = "Message without msgid is not allowed."
err_msg += "The Line started unexpectedly with #{@scanner.peek(10).inspect}."
raise PoSyntaxError, err_msg
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in msgid\n" + pe.message, pe.backtrace
end
end | ruby | def msgid
begin
if @scanner.scan(/msgid/)
skip_whitespace
text = message_line
add_result(:msgid, text)
message_multiline(:msgid) if text.empty?
if msgid_plural
msgstr_plural
else
msgstr
end
else
err_msg = "Message without msgid is not allowed."
err_msg += "The Line started unexpectedly with #{@scanner.peek(10).inspect}."
raise PoSyntaxError, err_msg
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in msgid\n" + pe.message, pe.backtrace
end
end | [
"def",
"msgid",
"begin",
"if",
"@scanner",
".",
"scan",
"(",
"/",
"/",
")",
"skip_whitespace",
"text",
"=",
"message_line",
"add_result",
"(",
":msgid",
",",
"text",
")",
"message_multiline",
"(",
":msgid",
")",
"if",
"text",
".",
"empty?",
"if",
"msgid_plural",
"msgstr_plural",
"else",
"msgstr",
"end",
"else",
"err_msg",
"=",
"\"Message without msgid is not allowed.\"",
"err_msg",
"+=",
"\"The Line started unexpectedly with #{@scanner.peek(10).inspect}.\"",
"raise",
"PoSyntaxError",
",",
"err_msg",
"end",
"rescue",
"PoSyntaxError",
"=>",
"pe",
"raise",
"PoSyntaxError",
",",
"\"Syntax error in msgid\\n\"",
"+",
"pe",
".",
"message",
",",
"pe",
".",
"backtrace",
"end",
"end"
] | matches the msgid line. Will check for optional msgid_plural.
Will advance to msgstr or msgstr_plural based on msgid_plural
msgid is required | [
"matches",
"the",
"msgid",
"line",
".",
"Will",
"check",
"for",
"optional",
"msgid_plural",
".",
"Will",
"advance",
"to",
"msgstr",
"or",
"msgstr_plural",
"based",
"on",
"msgid_plural"
] | b0ab9f76a12273b13869fd7f44231253d116ee8a | https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L124-L145 |
3,176 | experteer/simple_po_parser | lib/simple_po_parser/parser.rb | SimplePoParser.Parser.msgid_plural | def msgid_plural
begin
if @scanner.scan(/msgid_plural/)
skip_whitespace
text = message_line
add_result(:msgid_plural, text)
message_multiline(:msgid_plural) if text.empty?
true
else
false
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in msgid\n" + pe.message, pe.backtrace
end
end | ruby | def msgid_plural
begin
if @scanner.scan(/msgid_plural/)
skip_whitespace
text = message_line
add_result(:msgid_plural, text)
message_multiline(:msgid_plural) if text.empty?
true
else
false
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in msgid\n" + pe.message, pe.backtrace
end
end | [
"def",
"msgid_plural",
"begin",
"if",
"@scanner",
".",
"scan",
"(",
"/",
"/",
")",
"skip_whitespace",
"text",
"=",
"message_line",
"add_result",
"(",
":msgid_plural",
",",
"text",
")",
"message_multiline",
"(",
":msgid_plural",
")",
"if",
"text",
".",
"empty?",
"true",
"else",
"false",
"end",
"rescue",
"PoSyntaxError",
"=>",
"pe",
"raise",
"PoSyntaxError",
",",
"\"Syntax error in msgid\\n\"",
"+",
"pe",
".",
"message",
",",
"pe",
".",
"backtrace",
"end",
"end"
] | matches the msgid_plural line.
msgid_plural is optional
@return [boolean] true if msgid_plural is present, false otherwise | [
"matches",
"the",
"msgid_plural",
"line",
"."
] | b0ab9f76a12273b13869fd7f44231253d116ee8a | https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L152-L166 |
3,177 | experteer/simple_po_parser | lib/simple_po_parser/parser.rb | SimplePoParser.Parser.msgstr | def msgstr
begin
if @scanner.scan(/msgstr/)
skip_whitespace
text = message_line
add_result(:msgstr, text)
message_multiline(:msgstr) if text.empty?
skip_whitespace
raise PoSyntaxError, "Unexpected content after expected message end #{@scanner.peek(10).inspect}" unless @scanner.eos?
else
raise PoSyntaxError, "Singular message without msgstr is not allowed. Line started unexpectedly with #{@scanner.peek(10).inspect}."
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in msgstr\n" + pe.message, pe.backtrace
end
end | ruby | def msgstr
begin
if @scanner.scan(/msgstr/)
skip_whitespace
text = message_line
add_result(:msgstr, text)
message_multiline(:msgstr) if text.empty?
skip_whitespace
raise PoSyntaxError, "Unexpected content after expected message end #{@scanner.peek(10).inspect}" unless @scanner.eos?
else
raise PoSyntaxError, "Singular message without msgstr is not allowed. Line started unexpectedly with #{@scanner.peek(10).inspect}."
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in msgstr\n" + pe.message, pe.backtrace
end
end | [
"def",
"msgstr",
"begin",
"if",
"@scanner",
".",
"scan",
"(",
"/",
"/",
")",
"skip_whitespace",
"text",
"=",
"message_line",
"add_result",
"(",
":msgstr",
",",
"text",
")",
"message_multiline",
"(",
":msgstr",
")",
"if",
"text",
".",
"empty?",
"skip_whitespace",
"raise",
"PoSyntaxError",
",",
"\"Unexpected content after expected message end #{@scanner.peek(10).inspect}\"",
"unless",
"@scanner",
".",
"eos?",
"else",
"raise",
"PoSyntaxError",
",",
"\"Singular message without msgstr is not allowed. Line started unexpectedly with #{@scanner.peek(10).inspect}.\"",
"end",
"rescue",
"PoSyntaxError",
"=>",
"pe",
"raise",
"PoSyntaxError",
",",
"\"Syntax error in msgstr\\n\"",
"+",
"pe",
".",
"message",
",",
"pe",
".",
"backtrace",
"end",
"end"
] | parses the msgstr singular line
msgstr is required in singular translations | [
"parses",
"the",
"msgstr",
"singular",
"line"
] | b0ab9f76a12273b13869fd7f44231253d116ee8a | https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L171-L186 |
3,178 | experteer/simple_po_parser | lib/simple_po_parser/parser.rb | SimplePoParser.Parser.msgstr_plural | def msgstr_plural(num = 0)
begin
msgstr_key = @scanner.scan(/msgstr\[\d\]/) # matches 'msgstr[0]' to 'msgstr[9]'
if msgstr_key
# msgstr plurals must come in 0-based index in order
msgstr_num = msgstr_key.match(/\d/)[0].to_i
raise PoSyntaxError, "Bad 'msgstr[index]' index." if msgstr_num != num
skip_whitespace
text = message_line
add_result(msgstr_key, text)
message_multiline(msgstr_key) if text.empty?
msgstr_plural(num+1)
elsif num == 0 # and msgstr_key was false
raise PoSyntaxError, "Plural message without msgstr[0] is not allowed. Line started unexpectedly with #{@scanner.peek(10).inspect}."
else
raise PoSyntaxError, "End of message was expected, but line started unexpectedly with #{@scanner.peek(10).inspect}" unless @scanner.eos?
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in msgstr_plural\n" + pe.message, pe.backtrace
end
end | ruby | def msgstr_plural(num = 0)
begin
msgstr_key = @scanner.scan(/msgstr\[\d\]/) # matches 'msgstr[0]' to 'msgstr[9]'
if msgstr_key
# msgstr plurals must come in 0-based index in order
msgstr_num = msgstr_key.match(/\d/)[0].to_i
raise PoSyntaxError, "Bad 'msgstr[index]' index." if msgstr_num != num
skip_whitespace
text = message_line
add_result(msgstr_key, text)
message_multiline(msgstr_key) if text.empty?
msgstr_plural(num+1)
elsif num == 0 # and msgstr_key was false
raise PoSyntaxError, "Plural message without msgstr[0] is not allowed. Line started unexpectedly with #{@scanner.peek(10).inspect}."
else
raise PoSyntaxError, "End of message was expected, but line started unexpectedly with #{@scanner.peek(10).inspect}" unless @scanner.eos?
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in msgstr_plural\n" + pe.message, pe.backtrace
end
end | [
"def",
"msgstr_plural",
"(",
"num",
"=",
"0",
")",
"begin",
"msgstr_key",
"=",
"@scanner",
".",
"scan",
"(",
"/",
"\\[",
"\\d",
"\\]",
"/",
")",
"# matches 'msgstr[0]' to 'msgstr[9]'",
"if",
"msgstr_key",
"# msgstr plurals must come in 0-based index in order",
"msgstr_num",
"=",
"msgstr_key",
".",
"match",
"(",
"/",
"\\d",
"/",
")",
"[",
"0",
"]",
".",
"to_i",
"raise",
"PoSyntaxError",
",",
"\"Bad 'msgstr[index]' index.\"",
"if",
"msgstr_num",
"!=",
"num",
"skip_whitespace",
"text",
"=",
"message_line",
"add_result",
"(",
"msgstr_key",
",",
"text",
")",
"message_multiline",
"(",
"msgstr_key",
")",
"if",
"text",
".",
"empty?",
"msgstr_plural",
"(",
"num",
"+",
"1",
")",
"elsif",
"num",
"==",
"0",
"# and msgstr_key was false",
"raise",
"PoSyntaxError",
",",
"\"Plural message without msgstr[0] is not allowed. Line started unexpectedly with #{@scanner.peek(10).inspect}.\"",
"else",
"raise",
"PoSyntaxError",
",",
"\"End of message was expected, but line started unexpectedly with #{@scanner.peek(10).inspect}\"",
"unless",
"@scanner",
".",
"eos?",
"end",
"rescue",
"PoSyntaxError",
"=>",
"pe",
"raise",
"PoSyntaxError",
",",
"\"Syntax error in msgstr_plural\\n\"",
"+",
"pe",
".",
"message",
",",
"pe",
".",
"backtrace",
"end",
"end"
] | parses the msgstr plural lines
msgstr plural lines are used when there is msgid_plural.
They have the format msgstr[N] where N is incremental number starting from zero representing
the plural number as specified in the headers "Plural-Forms" entry. Most languages, like the
English language only have two plural forms (singular and plural),
but there are languages with more plurals | [
"parses",
"the",
"msgstr",
"plural",
"lines"
] | b0ab9f76a12273b13869fd7f44231253d116ee8a | https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L195-L215 |
3,179 | experteer/simple_po_parser | lib/simple_po_parser/parser.rb | SimplePoParser.Parser.previous_comments | def previous_comments
begin
# next part must be msgctxt, msgid or msgid_plural
if @scanner.scan(/msg/)
if @scanner.scan(/id/)
if @scanner.scan(/_plural/)
key = :previous_msgid_plural
else
key = :previous_msgid
end
elsif @scanner.scan(/ctxt/)
key = :previous_msgctxt
else
raise PoSyntaxError, "Previous comment type #{("msg" + @scanner.peek(10)).inspect} unknown."
end
skip_whitespace
text = message_line
add_result(key, text)
previous_multiline(key) if text.empty?
else
raise PoSyntaxError, "Previous comments must start with '#| msg'. #{@scanner.peek(10).inspect} unknown."
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in previous_comments\n" + pe.message, pe.backtrace
end
end | ruby | def previous_comments
begin
# next part must be msgctxt, msgid or msgid_plural
if @scanner.scan(/msg/)
if @scanner.scan(/id/)
if @scanner.scan(/_plural/)
key = :previous_msgid_plural
else
key = :previous_msgid
end
elsif @scanner.scan(/ctxt/)
key = :previous_msgctxt
else
raise PoSyntaxError, "Previous comment type #{("msg" + @scanner.peek(10)).inspect} unknown."
end
skip_whitespace
text = message_line
add_result(key, text)
previous_multiline(key) if text.empty?
else
raise PoSyntaxError, "Previous comments must start with '#| msg'. #{@scanner.peek(10).inspect} unknown."
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in previous_comments\n" + pe.message, pe.backtrace
end
end | [
"def",
"previous_comments",
"begin",
"# next part must be msgctxt, msgid or msgid_plural",
"if",
"@scanner",
".",
"scan",
"(",
"/",
"/",
")",
"if",
"@scanner",
".",
"scan",
"(",
"/",
"/",
")",
"if",
"@scanner",
".",
"scan",
"(",
"/",
"/",
")",
"key",
"=",
":previous_msgid_plural",
"else",
"key",
"=",
":previous_msgid",
"end",
"elsif",
"@scanner",
".",
"scan",
"(",
"/",
"/",
")",
"key",
"=",
":previous_msgctxt",
"else",
"raise",
"PoSyntaxError",
",",
"\"Previous comment type #{(\"msg\" + @scanner.peek(10)).inspect} unknown.\"",
"end",
"skip_whitespace",
"text",
"=",
"message_line",
"add_result",
"(",
"key",
",",
"text",
")",
"previous_multiline",
"(",
"key",
")",
"if",
"text",
".",
"empty?",
"else",
"raise",
"PoSyntaxError",
",",
"\"Previous comments must start with '#| msg'. #{@scanner.peek(10).inspect} unknown.\"",
"end",
"rescue",
"PoSyntaxError",
"=>",
"pe",
"raise",
"PoSyntaxError",
",",
"\"Syntax error in previous_comments\\n\"",
"+",
"pe",
".",
"message",
",",
"pe",
".",
"backtrace",
"end",
"end"
] | parses previous comments, which provide additional information on fuzzy matching
previous comments are:
* #| msgctxt
* #| msgid
* #| msgid_plural | [
"parses",
"previous",
"comments",
"which",
"provide",
"additional",
"information",
"on",
"fuzzy",
"matching"
] | b0ab9f76a12273b13869fd7f44231253d116ee8a | https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L223-L248 |
3,180 | experteer/simple_po_parser | lib/simple_po_parser/parser.rb | SimplePoParser.Parser.previous_multiline | def previous_multiline(key)
begin
# scan multilines until no further multiline is hit
# /#\|\p{Blank}"/ needs to catch the double quote to ensure it hits a previous
# multiline and not another line type.
if @scanner.scan(/#\|\p{Blank}*"/)
@scanner.pos = @scanner.pos - 1 # go one character back, so we can reuse the "message line" method
add_result(key, message_line)
previous_multiline(key) # go on until we no longer hit a multiline line
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in previous_multiline\n" + pe.message, pe.backtrace
end
end | ruby | def previous_multiline(key)
begin
# scan multilines until no further multiline is hit
# /#\|\p{Blank}"/ needs to catch the double quote to ensure it hits a previous
# multiline and not another line type.
if @scanner.scan(/#\|\p{Blank}*"/)
@scanner.pos = @scanner.pos - 1 # go one character back, so we can reuse the "message line" method
add_result(key, message_line)
previous_multiline(key) # go on until we no longer hit a multiline line
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in previous_multiline\n" + pe.message, pe.backtrace
end
end | [
"def",
"previous_multiline",
"(",
"key",
")",
"begin",
"# scan multilines until no further multiline is hit",
"# /#\\|\\p{Blank}\"/ needs to catch the double quote to ensure it hits a previous",
"# multiline and not another line type.",
"if",
"@scanner",
".",
"scan",
"(",
"/",
"\\|",
"\\p",
"/",
")",
"@scanner",
".",
"pos",
"=",
"@scanner",
".",
"pos",
"-",
"1",
"# go one character back, so we can reuse the \"message line\" method",
"add_result",
"(",
"key",
",",
"message_line",
")",
"previous_multiline",
"(",
"key",
")",
"# go on until we no longer hit a multiline line",
"end",
"rescue",
"PoSyntaxError",
"=>",
"pe",
"raise",
"PoSyntaxError",
",",
"\"Syntax error in previous_multiline\\n\"",
"+",
"pe",
".",
"message",
",",
"pe",
".",
"backtrace",
"end",
"end"
] | parses the multiline messages of the previous comment lines | [
"parses",
"the",
"multiline",
"messages",
"of",
"the",
"previous",
"comment",
"lines"
] | b0ab9f76a12273b13869fd7f44231253d116ee8a | https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L251-L264 |
3,181 | experteer/simple_po_parser | lib/simple_po_parser/parser.rb | SimplePoParser.Parser.message_multiline | def message_multiline(key)
begin
skip_whitespace
if @scanner.check(/"/)
add_result(key, message_line)
message_multiline(key)
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in message_multiline with key '#{key}'\n" + pe.message, pe.backtrace
end
end | ruby | def message_multiline(key)
begin
skip_whitespace
if @scanner.check(/"/)
add_result(key, message_line)
message_multiline(key)
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in message_multiline with key '#{key}'\n" + pe.message, pe.backtrace
end
end | [
"def",
"message_multiline",
"(",
"key",
")",
"begin",
"skip_whitespace",
"if",
"@scanner",
".",
"check",
"(",
"/",
"/",
")",
"add_result",
"(",
"key",
",",
"message_line",
")",
"message_multiline",
"(",
"key",
")",
"end",
"rescue",
"PoSyntaxError",
"=>",
"pe",
"raise",
"PoSyntaxError",
",",
"\"Syntax error in message_multiline with key '#{key}'\\n\"",
"+",
"pe",
".",
"message",
",",
"pe",
".",
"backtrace",
"end",
"end"
] | parses a multiline message
multiline messages are indicated by an empty content as first line and the next line
starting with the double quote character | [
"parses",
"a",
"multiline",
"message"
] | b0ab9f76a12273b13869fd7f44231253d116ee8a | https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L270-L280 |
3,182 | experteer/simple_po_parser | lib/simple_po_parser/parser.rb | SimplePoParser.Parser.message_line | def message_line
begin
if @scanner.getch == '"'
text = message_text
unless @scanner.getch == '"'
err_msg = "The message text '#{text}' must be finished with the double quote character '\"'."
raise PoSyntaxError, err_msg
end
skip_whitespace
unless end_of_line
err_msg = "There should be only whitespace until the end of line"
err_msg += " after the double quote character of a message text."
raise PoSyntaxError.new(err_msg)
end
text
else
@scanner.pos = @scanner.pos - 1
err_msg = "A message text needs to start with the double quote character '\"',"
err_msg += " but this was found: #{@scanner.peek(10).inspect}"
raise PoSyntaxError, err_msg
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in message_line\n" + pe.message, pe.backtrace
end
end | ruby | def message_line
begin
if @scanner.getch == '"'
text = message_text
unless @scanner.getch == '"'
err_msg = "The message text '#{text}' must be finished with the double quote character '\"'."
raise PoSyntaxError, err_msg
end
skip_whitespace
unless end_of_line
err_msg = "There should be only whitespace until the end of line"
err_msg += " after the double quote character of a message text."
raise PoSyntaxError.new(err_msg)
end
text
else
@scanner.pos = @scanner.pos - 1
err_msg = "A message text needs to start with the double quote character '\"',"
err_msg += " but this was found: #{@scanner.peek(10).inspect}"
raise PoSyntaxError, err_msg
end
rescue PoSyntaxError => pe
raise PoSyntaxError, "Syntax error in message_line\n" + pe.message, pe.backtrace
end
end | [
"def",
"message_line",
"begin",
"if",
"@scanner",
".",
"getch",
"==",
"'\"'",
"text",
"=",
"message_text",
"unless",
"@scanner",
".",
"getch",
"==",
"'\"'",
"err_msg",
"=",
"\"The message text '#{text}' must be finished with the double quote character '\\\"'.\"",
"raise",
"PoSyntaxError",
",",
"err_msg",
"end",
"skip_whitespace",
"unless",
"end_of_line",
"err_msg",
"=",
"\"There should be only whitespace until the end of line\"",
"err_msg",
"+=",
"\" after the double quote character of a message text.\"",
"raise",
"PoSyntaxError",
".",
"new",
"(",
"err_msg",
")",
"end",
"text",
"else",
"@scanner",
".",
"pos",
"=",
"@scanner",
".",
"pos",
"-",
"1",
"err_msg",
"=",
"\"A message text needs to start with the double quote character '\\\"',\"",
"err_msg",
"+=",
"\" but this was found: #{@scanner.peek(10).inspect}\"",
"raise",
"PoSyntaxError",
",",
"err_msg",
"end",
"rescue",
"PoSyntaxError",
"=>",
"pe",
"raise",
"PoSyntaxError",
",",
"\"Syntax error in message_line\\n\"",
"+",
"pe",
".",
"message",
",",
"pe",
".",
"backtrace",
"end",
"end"
] | identifies a message line and returns it's text or raises an error
@return [String] message_text | [
"identifies",
"a",
"message",
"line",
"and",
"returns",
"it",
"s",
"text",
"or",
"raises",
"an",
"error"
] | b0ab9f76a12273b13869fd7f44231253d116ee8a | https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L285-L309 |
3,183 | experteer/simple_po_parser | lib/simple_po_parser/parser.rb | SimplePoParser.Parser.add_result | def add_result(key, text)
if @result[key]
if @result[key].is_a? Array
@result[key].push(text)
else
@result[key] = [@result[key], text]
end
else
@result[key] = text
end
end | ruby | def add_result(key, text)
if @result[key]
if @result[key].is_a? Array
@result[key].push(text)
else
@result[key] = [@result[key], text]
end
else
@result[key] = text
end
end | [
"def",
"add_result",
"(",
"key",
",",
"text",
")",
"if",
"@result",
"[",
"key",
"]",
"if",
"@result",
"[",
"key",
"]",
".",
"is_a?",
"Array",
"@result",
"[",
"key",
"]",
".",
"push",
"(",
"text",
")",
"else",
"@result",
"[",
"key",
"]",
"=",
"[",
"@result",
"[",
"key",
"]",
",",
"text",
"]",
"end",
"else",
"@result",
"[",
"key",
"]",
"=",
"text",
"end",
"end"
] | adds text to the given key in results
creates an array if the given key already has a result | [
"adds",
"text",
"to",
"the",
"given",
"key",
"in",
"results",
"creates",
"an",
"array",
"if",
"the",
"given",
"key",
"already",
"has",
"a",
"result"
] | b0ab9f76a12273b13869fd7f44231253d116ee8a | https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L364-L374 |
3,184 | social-snippet/social-snippet | lib/social_snippet/resolvers/base_resolver.rb | SocialSnippet.Resolvers::BaseResolver.resolve_tag_repo_ref! | def resolve_tag_repo_ref!(tag)
return unless tag.has_repo?
repo = core.repo_manager.find_repository(tag.repo)
# set latest version
if tag.has_ref? === false
if repo.has_package_versions?
tag.set_ref repo.latest_package_version
else
tag.set_ref repo.current_ref
end
else
unless repo.has_ref?(tag.ref)
new_ref = repo.latest_version(tag.ref)
raise "error" if new_ref.nil?
tag.set_ref new_ref
end
end
end | ruby | def resolve_tag_repo_ref!(tag)
return unless tag.has_repo?
repo = core.repo_manager.find_repository(tag.repo)
# set latest version
if tag.has_ref? === false
if repo.has_package_versions?
tag.set_ref repo.latest_package_version
else
tag.set_ref repo.current_ref
end
else
unless repo.has_ref?(tag.ref)
new_ref = repo.latest_version(tag.ref)
raise "error" if new_ref.nil?
tag.set_ref new_ref
end
end
end | [
"def",
"resolve_tag_repo_ref!",
"(",
"tag",
")",
"return",
"unless",
"tag",
".",
"has_repo?",
"repo",
"=",
"core",
".",
"repo_manager",
".",
"find_repository",
"(",
"tag",
".",
"repo",
")",
"# set latest version",
"if",
"tag",
".",
"has_ref?",
"===",
"false",
"if",
"repo",
".",
"has_package_versions?",
"tag",
".",
"set_ref",
"repo",
".",
"latest_package_version",
"else",
"tag",
".",
"set_ref",
"repo",
".",
"current_ref",
"end",
"else",
"unless",
"repo",
".",
"has_ref?",
"(",
"tag",
".",
"ref",
")",
"new_ref",
"=",
"repo",
".",
"latest_version",
"(",
"tag",
".",
"ref",
")",
"raise",
"\"error\"",
"if",
"new_ref",
".",
"nil?",
"tag",
".",
"set_ref",
"new_ref",
"end",
"end",
"end"
] | Resolve tag's ref | [
"Resolve",
"tag",
"s",
"ref"
] | 46ae25b3e8ced2c8b5b4923ed9e1a019c9835367 | https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/resolvers/base_resolver.rb#L77-L94 |
3,185 | featureflow/featureflow-ruby-sdk | lib/featureflow/events_client.rb | Featureflow.EventsClient.register_features | def register_features(with_features)
Thread.new do
features = []
features = with_features.each do | feature |
features.push(key: feature[:key],
variants: feature[:variants],
failoverVariant: feature[:failover_variant])
end
send_event 'Register Features', :put, '/api/sdk/v1/register', features
end
end | ruby | def register_features(with_features)
Thread.new do
features = []
features = with_features.each do | feature |
features.push(key: feature[:key],
variants: feature[:variants],
failoverVariant: feature[:failover_variant])
end
send_event 'Register Features', :put, '/api/sdk/v1/register', features
end
end | [
"def",
"register_features",
"(",
"with_features",
")",
"Thread",
".",
"new",
"do",
"features",
"=",
"[",
"]",
"features",
"=",
"with_features",
".",
"each",
"do",
"|",
"feature",
"|",
"features",
".",
"push",
"(",
"key",
":",
"feature",
"[",
":key",
"]",
",",
"variants",
":",
"feature",
"[",
":variants",
"]",
",",
"failoverVariant",
":",
"feature",
"[",
":failover_variant",
"]",
")",
"end",
"send_event",
"'Register Features'",
",",
":put",
",",
"'/api/sdk/v1/register'",
",",
"features",
"end",
"end"
] | register features are not queued and go straight out | [
"register",
"features",
"are",
"not",
"queued",
"and",
"go",
"straight",
"out"
] | ec3c1304a62b66711f633753fad4c21137460a03 | https://github.com/featureflow/featureflow-ruby-sdk/blob/ec3c1304a62b66711f633753fad4c21137460a03/lib/featureflow/events_client.rb#L29-L39 |
3,186 | gareth/ruby_hid_api | lib/hid_api/device_info.rb | HidApi.DeviceInfo.each | def each
return enum_for(:each) unless block_given?
pointer = self
loop do
break if pointer.null?
yield pointer
pointer = pointer.next
end
end | ruby | def each
return enum_for(:each) unless block_given?
pointer = self
loop do
break if pointer.null?
yield pointer
pointer = pointer.next
end
end | [
"def",
"each",
"return",
"enum_for",
"(",
":each",
")",
"unless",
"block_given?",
"pointer",
"=",
"self",
"loop",
"do",
"break",
"if",
"pointer",
".",
"null?",
"yield",
"pointer",
"pointer",
"=",
"pointer",
".",
"next",
"end",
"end"
] | Exposes the linked list structure in an Enumerable-compatible format | [
"Exposes",
"the",
"linked",
"list",
"structure",
"in",
"an",
"Enumerable",
"-",
"compatible",
"format"
] | dff5eb6e649f50e634b7a3acc83dc4828e514fe6 | https://github.com/gareth/ruby_hid_api/blob/dff5eb6e649f50e634b7a3acc83dc4828e514fe6/lib/hid_api/device_info.rb#L44-L53 |
3,187 | probedock/probedock-cucumber-ruby | lib/probe_dock_cucumber/formatter.rb | ProbeDockCucumber.Formatter.comment_line | def comment_line(comment)
# Take care of annotation only if matched
if comment.match(ProbeDockProbe::Annotation::ANNOTATION_REGEXP)
# If the feature already started, the annotations are for scenarios
if @current_feature_started
@annotation = ProbeDockProbe::Annotation.new(comment)
else
@feature_annotation = ProbeDockProbe::Annotation.new(comment)
end
end
end | ruby | def comment_line(comment)
# Take care of annotation only if matched
if comment.match(ProbeDockProbe::Annotation::ANNOTATION_REGEXP)
# If the feature already started, the annotations are for scenarios
if @current_feature_started
@annotation = ProbeDockProbe::Annotation.new(comment)
else
@feature_annotation = ProbeDockProbe::Annotation.new(comment)
end
end
end | [
"def",
"comment_line",
"(",
"comment",
")",
"# Take care of annotation only if matched",
"if",
"comment",
".",
"match",
"(",
"ProbeDockProbe",
"::",
"Annotation",
"::",
"ANNOTATION_REGEXP",
")",
"# If the feature already started, the annotations are for scenarios",
"if",
"@current_feature_started",
"@annotation",
"=",
"ProbeDockProbe",
"::",
"Annotation",
".",
"new",
"(",
"comment",
")",
"else",
"@feature_annotation",
"=",
"ProbeDockProbe",
"::",
"Annotation",
".",
"new",
"(",
"comment",
")",
"end",
"end",
"end"
] | Called for each comment line | [
"Called",
"for",
"each",
"comment",
"line"
] | 9554da1a565c354b50994d0bfd567915adc3c108 | https://github.com/probedock/probedock-cucumber-ruby/blob/9554da1a565c354b50994d0bfd567915adc3c108/lib/probe_dock_cucumber/formatter.rb#L100-L110 |
3,188 | smileart/network_utils | lib/network_utils/url_info.rb | NetworkUtils.UrlInfo.is? | def is?(type)
return false if type.to_s.empty?
expected_types = Array.wrap(type).map(&:to_s)
content_type && expected_types.select do |t|
content_type.select { |ct| ct.start_with?(t) }
end.any?
end | ruby | def is?(type)
return false if type.to_s.empty?
expected_types = Array.wrap(type).map(&:to_s)
content_type && expected_types.select do |t|
content_type.select { |ct| ct.start_with?(t) }
end.any?
end | [
"def",
"is?",
"(",
"type",
")",
"return",
"false",
"if",
"type",
".",
"to_s",
".",
"empty?",
"expected_types",
"=",
"Array",
".",
"wrap",
"(",
"type",
")",
".",
"map",
"(",
":to_s",
")",
"content_type",
"&&",
"expected_types",
".",
"select",
"do",
"|",
"t",
"|",
"content_type",
".",
"select",
"{",
"|",
"ct",
"|",
"ct",
".",
"start_with?",
"(",
"t",
")",
"}",
"end",
".",
"any?",
"end"
] | Initialise a UrlInfo for a particular URL
@param [String] url the URL you want to get info about
@param [Integer] request_timeout Max time to wait for headers from the server
Check the Content-Type of the resource
@param [String, Symbol, Array] type the prefix (before "/") or full Content-Type content
@return [Boolean] true if Content-Type matches something from the types list | [
"Initialise",
"a",
"UrlInfo",
"for",
"a",
"particular",
"URL"
] | 3a4a8b58f9898d9bacf168ed45721db2e52abf9b | https://github.com/smileart/network_utils/blob/3a4a8b58f9898d9bacf168ed45721db2e52abf9b/lib/network_utils/url_info.rb#L32-L39 |
3,189 | raskhadafi/vesr | lib/vesr/prawn/esr_recipe.rb | Prawn.EsrRecipe.esr9_format_account_id | def esr9_format_account_id(account_id)
(pre, main, post) = account_id.split('-')
sprintf('%02i%06i%1i', pre.to_i, main.to_i, post.to_i)
end | ruby | def esr9_format_account_id(account_id)
(pre, main, post) = account_id.split('-')
sprintf('%02i%06i%1i', pre.to_i, main.to_i, post.to_i)
end | [
"def",
"esr9_format_account_id",
"(",
"account_id",
")",
"(",
"pre",
",",
"main",
",",
"post",
")",
"=",
"account_id",
".",
"split",
"(",
"'-'",
")",
"sprintf",
"(",
"'%02i%06i%1i'",
",",
"pre",
".",
"to_i",
",",
"main",
".",
"to_i",
",",
"post",
".",
"to_i",
")",
"end"
] | Formats an account number for ESR
Account numbers for ESR should have the following format:
XXYYYYYYZ, where the number of digits is fixed. We support
providing the number in the format XX-YYYY-Z which is more
common in written communication. | [
"Formats",
"an",
"account",
"number",
"for",
"ESR"
] | 303d250355ef725bd5b384f9390949620652a3e2 | https://github.com/raskhadafi/vesr/blob/303d250355ef725bd5b384f9390949620652a3e2/lib/vesr/prawn/esr_recipe.rb#L143-L147 |
3,190 | IUBLibTech/ldap_groups_lookup | lib/ldap_groups_lookup/configuration.rb | LDAPGroupsLookup.Configuration.config | def config
if @config.nil?
if defined? Rails
configure(Rails.root.join('config', 'ldap_groups_lookup.yml').to_s)
else
configure(File.join(__dir__, '..', '..', 'config', 'ldap_groups_lookup.yml').to_s)
end
end
@config
end | ruby | def config
if @config.nil?
if defined? Rails
configure(Rails.root.join('config', 'ldap_groups_lookup.yml').to_s)
else
configure(File.join(__dir__, '..', '..', 'config', 'ldap_groups_lookup.yml').to_s)
end
end
@config
end | [
"def",
"config",
"if",
"@config",
".",
"nil?",
"if",
"defined?",
"Rails",
"configure",
"(",
"Rails",
".",
"root",
".",
"join",
"(",
"'config'",
",",
"'ldap_groups_lookup.yml'",
")",
".",
"to_s",
")",
"else",
"configure",
"(",
"File",
".",
"join",
"(",
"__dir__",
",",
"'..'",
",",
"'..'",
",",
"'config'",
",",
"'ldap_groups_lookup.yml'",
")",
".",
"to_s",
")",
"end",
"end",
"@config",
"end"
] | Loads LDAP host and authentication configuration | [
"Loads",
"LDAP",
"host",
"and",
"authentication",
"configuration"
] | 430ff8e1dd084fdc7113fbfe85b6422900b39184 | https://github.com/IUBLibTech/ldap_groups_lookup/blob/430ff8e1dd084fdc7113fbfe85b6422900b39184/lib/ldap_groups_lookup/configuration.rb#L19-L28 |
3,191 | desktoppr/cached_counts | lib/cached_counts/cache.rb | CachedCounts.Cache.clear | def clear
invalid_keys = all_keys.select { |key| key.include?(@scope.table_name.downcase) }
invalid_keys.each { |key| Rails.cache.delete(key) }
Rails.cache.write(list_key, all_keys - invalid_keys)
end | ruby | def clear
invalid_keys = all_keys.select { |key| key.include?(@scope.table_name.downcase) }
invalid_keys.each { |key| Rails.cache.delete(key) }
Rails.cache.write(list_key, all_keys - invalid_keys)
end | [
"def",
"clear",
"invalid_keys",
"=",
"all_keys",
".",
"select",
"{",
"|",
"key",
"|",
"key",
".",
"include?",
"(",
"@scope",
".",
"table_name",
".",
"downcase",
")",
"}",
"invalid_keys",
".",
"each",
"{",
"|",
"key",
"|",
"Rails",
".",
"cache",
".",
"delete",
"(",
"key",
")",
"}",
"Rails",
".",
"cache",
".",
"write",
"(",
"list_key",
",",
"all_keys",
"-",
"invalid_keys",
")",
"end"
] | Clear out any count caches which have SQL that includes the scopes table | [
"Clear",
"out",
"any",
"count",
"caches",
"which",
"have",
"SQL",
"that",
"includes",
"the",
"scopes",
"table"
] | e859d1b4b0751a9dd76d3d213d79004c1efa0bc2 | https://github.com/desktoppr/cached_counts/blob/e859d1b4b0751a9dd76d3d213d79004c1efa0bc2/lib/cached_counts/cache.rb#L14-L19 |
3,192 | tbpgr/qiita_scouter | lib/qiita_scouter_core.rb | QiitaScouter.Core.analyze | def analyze(target_user)
user = read_user(target_user)
articles = read_articles(target_user)
calc_power_levels(user, articles)
end | ruby | def analyze(target_user)
user = read_user(target_user)
articles = read_articles(target_user)
calc_power_levels(user, articles)
end | [
"def",
"analyze",
"(",
"target_user",
")",
"user",
"=",
"read_user",
"(",
"target_user",
")",
"articles",
"=",
"read_articles",
"(",
"target_user",
")",
"calc_power_levels",
"(",
"user",
",",
"articles",
")",
"end"
] | Generate QiitaScouter markdown file. | [
"Generate",
"QiitaScouter",
"markdown",
"file",
"."
] | 55a0504d292dabb27c8c75be2669c48adcfc2cbe | https://github.com/tbpgr/qiita_scouter/blob/55a0504d292dabb27c8c75be2669c48adcfc2cbe/lib/qiita_scouter_core.rb#L13-L17 |
3,193 | JavonDavis/parallel_appium | lib/parallel_appium/ios.rb | ParallelAppium.IOS.simulator_information | def simulator_information
re = /\([0-9]+\.[0-9](\.[0-9])?\) \[[0-9A-Z-]+\]/m
# Filter out simulator info for iPhone platform version and udid
@simulators.select { |simulator_data| simulator_data.include?('iPhone') && !simulator_data.include?('Apple Watch') }
.map { |simulator_data| simulator_data.match(re).to_s.tr('()[]', '').split }[0, ENV['THREADS'].to_i]
end | ruby | def simulator_information
re = /\([0-9]+\.[0-9](\.[0-9])?\) \[[0-9A-Z-]+\]/m
# Filter out simulator info for iPhone platform version and udid
@simulators.select { |simulator_data| simulator_data.include?('iPhone') && !simulator_data.include?('Apple Watch') }
.map { |simulator_data| simulator_data.match(re).to_s.tr('()[]', '').split }[0, ENV['THREADS'].to_i]
end | [
"def",
"simulator_information",
"re",
"=",
"/",
"\\(",
"\\.",
"\\.",
"\\)",
"\\[",
"\\]",
"/m",
"# Filter out simulator info for iPhone platform version and udid",
"@simulators",
".",
"select",
"{",
"|",
"simulator_data",
"|",
"simulator_data",
".",
"include?",
"(",
"'iPhone'",
")",
"&&",
"!",
"simulator_data",
".",
"include?",
"(",
"'Apple Watch'",
")",
"}",
".",
"map",
"{",
"|",
"simulator_data",
"|",
"simulator_data",
".",
"match",
"(",
"re",
")",
".",
"to_s",
".",
"tr",
"(",
"'()[]'",
",",
"''",
")",
".",
"split",
"}",
"[",
"0",
",",
"ENV",
"[",
"'THREADS'",
"]",
".",
"to_i",
"]",
"end"
] | Filter simulator data | [
"Filter",
"simulator",
"data"
] | 2e92bf6f4cf6142909080f471dda196ee12c41ea | https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium/ios.rb#L11-L17 |
3,194 | mpalmer/frankenstein | lib/frankenstein/request.rb | Frankenstein.Request.measure | def measure(labels = {})
start_time = Time.now
unless block_given?
raise NoBlockError,
"No block passed to #{self.class}#measure"
end
@requests.increment(labels, 1)
@mutex.synchronize { @current.set(labels, (@current.get(labels) || 0) + 1) }
res_labels = labels.dup
begin
yield(res_labels).tap do
elapsed_time = Time.now - start_time
@durations.observe(res_labels, elapsed_time)
end
rescue Exception => ex
@exceptions.increment(labels.merge(class: ex.class.to_s), 1)
raise
ensure
@mutex.synchronize { @current.set(labels, @current.get(labels) - 1) }
end
end | ruby | def measure(labels = {})
start_time = Time.now
unless block_given?
raise NoBlockError,
"No block passed to #{self.class}#measure"
end
@requests.increment(labels, 1)
@mutex.synchronize { @current.set(labels, (@current.get(labels) || 0) + 1) }
res_labels = labels.dup
begin
yield(res_labels).tap do
elapsed_time = Time.now - start_time
@durations.observe(res_labels, elapsed_time)
end
rescue Exception => ex
@exceptions.increment(labels.merge(class: ex.class.to_s), 1)
raise
ensure
@mutex.synchronize { @current.set(labels, @current.get(labels) - 1) }
end
end | [
"def",
"measure",
"(",
"labels",
"=",
"{",
"}",
")",
"start_time",
"=",
"Time",
".",
"now",
"unless",
"block_given?",
"raise",
"NoBlockError",
",",
"\"No block passed to #{self.class}#measure\"",
"end",
"@requests",
".",
"increment",
"(",
"labels",
",",
"1",
")",
"@mutex",
".",
"synchronize",
"{",
"@current",
".",
"set",
"(",
"labels",
",",
"(",
"@current",
".",
"get",
"(",
"labels",
")",
"||",
"0",
")",
"+",
"1",
")",
"}",
"res_labels",
"=",
"labels",
".",
"dup",
"begin",
"yield",
"(",
"res_labels",
")",
".",
"tap",
"do",
"elapsed_time",
"=",
"Time",
".",
"now",
"-",
"start_time",
"@durations",
".",
"observe",
"(",
"res_labels",
",",
"elapsed_time",
")",
"end",
"rescue",
"Exception",
"=>",
"ex",
"@exceptions",
".",
"increment",
"(",
"labels",
".",
"merge",
"(",
"class",
":",
"ex",
".",
"class",
".",
"to_s",
")",
",",
"1",
")",
"raise",
"ensure",
"@mutex",
".",
"synchronize",
"{",
"@current",
".",
"set",
"(",
"labels",
",",
"@current",
".",
"get",
"(",
"labels",
")",
"-",
"1",
")",
"}",
"end",
"end"
] | Create a new request instrumentation package.
A "request", for the purposes of this discussion, is a distinct
interaction with an external system, typically either the receipt of some
sort of communication from another system which needs a response by this
system (the one being instrumented), or else the communication to another
system from this one for which we are expecting an answer. Each instance
of this class should be used to instrument all requests of a particular
type.
For each instance of this class, the following metrics will be created:
* `<prefix>_requests_total` -- a counter indicating the total number
of requests started (initiated or received by the system). Labels on
this metric are taken from the label set passed to #measure.
* `<prefix>_request_duration_seconds` -- a histogram for the response
times of successful responses (that is, where no exception was raised).
You can get the count of total successful responses from
`<prefix>_request_duration_seconds_count`. Labels on this metric
are taken from the labels set generated during the measured run (as
generated by manipulating the hash yielded to your block).
* `<prefix>_exceptions_total` -- a count of the number of exceptions
raised during processing. A label, `class`, indicates the class of
the exception raised. Labels on this metric are taken from the
label set passed to #measure, along with a special label `class`
to indicate the class of the exception raised.
* `<prefix>_in_progress_count` -- a gauge indicating how many requests
are currently in progress as at the time of the scrape. Labels on this
metric are taken from the label set passed to #measure.
@param prefix [#to_s] the string that will be prepended to all of the
Prometheus metric names generated for this instrumentation. The prefix
you choose should include both the application name (typically the
first word) as well as a unique identifier for the request type itself.
Multiple words should be underscore separated.
@param outgoing [Boolean] whether this Request instance is collecting
data on incoming requests or outgoing requests (the default, as usually
there is one incoming request handler, but there can easily be several
outgoing request types). It is only used to customise the metric
description text for the metrics, so it's not crucially important.
@param description [#to_s] a short explanation of what this is measuring.
It should be a singular and indefinite noun phrase, to maximise the
chances that it will fit neatly into the generated description text.
@param registry [Prometheus::Client::Registry] the client registry in
which all the metrics will be created. The default will put all the
metrics in the Prometheus Client's default registry, which may or may
not be what you're up for. If you're using Frankenstein::Server, you
want `stats_server.registry`.
Instrument an instance of the request.
Each time a particular external communication occurs, it should be
wrapped by a call to this method. Request-related statistics (that
the request has been made or received) are updated before the passed
block is executed, and then after the block completes,
response-related statistics (duration or exception) are recorded. The
number of currently-in-progress instances of the request are also kept
track of.
@param labels [Hash] a set of labels that can help to differentiate
different sorts of requests. These labels are applied to the
`<prefix>_requests_total` and `<prefix>_in_progress_count` metrics, as
well as the `<prefix>_exceptions_total` metric, if an exception is
raised.
Don't get too fancy with this label set -- it's unusual that this is
actually useful in practice. However it is provided for those unusual
cases where it isn't a bad idea. Your go-to solution should be to
label the `<prefix>_request_duration_seconds` metric (by modifying the
hash yielded to the block you pass to #measure), rather than using
this parameter with wild abandon.
Serious talk time: I've been there. It seems like a great idea at
first, to differentiate requests with lots of labels, but it usually
just ends up turning into a giant mess. Primarily, due to the way that
Prometheus deals with label sets, if you *ever* use a label on *any* of
your requests, you need to set the same label to some value on *all* of
your requests. So, unless you can say with certainty that every
request you receive will logically have some meaningful value for a
given label, you shouldn't use it.
**NOTE**: the labelset you specify here will be the default labelset
applied to the `<prefix>_request_duration_seconds` metric. If you need
to remove a label from the response, use `labels.replace` or
`labels.delete` to remove the key.
@yield [Hash] the labels that will be applied to the
`<Prefix>_request_duration_seconds` metric.
In order for your label set to be applied, you must *mutate the
hash that is yielded*, rather than overwriting it. That means,
for example, that the following code **will not work**:
req_stats.measure do |labels|
labels = {foo: 'bar', baz: 'wombat'}
...
Instead, you need to either set each key one by one, or use the
handy-dandy Hash#replace method, like this:
req_stats.measure do |labels|
labels.replace(foo: 'bar', baz: 'wombat')
...
If your labels are not being applied to your response histogram,
check for any assignment to the yielded variable. It's *really* easy
to do by mistake.
**NOTE WELL**: The Prometheus specification (assuming it exists)
apparently requires that all of the instances of a given metric
have the same set of labels. If you fail to do this, an exception
will be raised by Prometheus after the block is executed.
@raise [Prometheus::Request::NoBlockError] if you didn't pass a block to
call. There's nothing to instrument!
@raise [Prometheus::Client::LabelSetValidator::LabelSetError] if you
violate any written or unwritten rules about how Prometheus label
sets should be constructed.
@raise [Exception] any exception raised by the executed block will
be re-raised by this method after statistics collection is
complete.
@return [Object] whatever was returned by the block passed. | [
"Create",
"a",
"new",
"request",
"instrumentation",
"package",
"."
] | 1bbd9835233d0672af020da405ea1b29d55d105e | https://github.com/mpalmer/frankenstein/blob/1bbd9835233d0672af020da405ea1b29d55d105e/lib/frankenstein/request.rb#L165-L189 |
3,195 | mpalmer/frankenstein | lib/frankenstein/collected_metric.rb | Frankenstein.CollectedMetric.values | def values
begin
@collector.call(self).tap do |results|
unless results.is_a?(Hash)
@logger.error(progname) { "Collector proc did not return a hash, got #{results.inspect}" }
@errors_metric.increment(class: "NotAHashError")
return {}
end
results.keys.each { |labelset| @validator.validate(labelset) }
end
rescue StandardError => ex
@logger.error(progname) { (["Exception in collection: #{ex.message} (#{ex.class})"] + ex.backtrace).join("\n ") }
@errors_metric.increment(class: ex.class.to_s)
{}
end
end | ruby | def values
begin
@collector.call(self).tap do |results|
unless results.is_a?(Hash)
@logger.error(progname) { "Collector proc did not return a hash, got #{results.inspect}" }
@errors_metric.increment(class: "NotAHashError")
return {}
end
results.keys.each { |labelset| @validator.validate(labelset) }
end
rescue StandardError => ex
@logger.error(progname) { (["Exception in collection: #{ex.message} (#{ex.class})"] + ex.backtrace).join("\n ") }
@errors_metric.increment(class: ex.class.to_s)
{}
end
end | [
"def",
"values",
"begin",
"@collector",
".",
"call",
"(",
"self",
")",
".",
"tap",
"do",
"|",
"results",
"|",
"unless",
"results",
".",
"is_a?",
"(",
"Hash",
")",
"@logger",
".",
"error",
"(",
"progname",
")",
"{",
"\"Collector proc did not return a hash, got #{results.inspect}\"",
"}",
"@errors_metric",
".",
"increment",
"(",
"class",
":",
"\"NotAHashError\"",
")",
"return",
"{",
"}",
"end",
"results",
".",
"keys",
".",
"each",
"{",
"|",
"labelset",
"|",
"@validator",
".",
"validate",
"(",
"labelset",
")",
"}",
"end",
"rescue",
"StandardError",
"=>",
"ex",
"@logger",
".",
"error",
"(",
"progname",
")",
"{",
"(",
"[",
"\"Exception in collection: #{ex.message} (#{ex.class})\"",
"]",
"+",
"ex",
".",
"backtrace",
")",
".",
"join",
"(",
"\"\\n \"",
")",
"}",
"@errors_metric",
".",
"increment",
"(",
"class",
":",
"ex",
".",
"class",
".",
"to_s",
")",
"{",
"}",
"end",
"end"
] | Retrieve a complete set of labels and values for the metric. | [
"Retrieve",
"a",
"complete",
"set",
"of",
"labels",
"and",
"values",
"for",
"the",
"metric",
"."
] | 1bbd9835233d0672af020da405ea1b29d55d105e | https://github.com/mpalmer/frankenstein/blob/1bbd9835233d0672af020da405ea1b29d55d105e/lib/frankenstein/collected_metric.rb#L121-L137 |
3,196 | mpalmer/frankenstein | lib/frankenstein/collected_metric.rb | Frankenstein.CollectedMetric.validate_type | def validate_type(type)
unless %i{gauge counter histogram summary}.include?(type)
raise ArgumentError, "type must be one of :gauge, :counter, :histogram, or :summary (got #{type.inspect})"
end
end | ruby | def validate_type(type)
unless %i{gauge counter histogram summary}.include?(type)
raise ArgumentError, "type must be one of :gauge, :counter, :histogram, or :summary (got #{type.inspect})"
end
end | [
"def",
"validate_type",
"(",
"type",
")",
"unless",
"%i{",
"gauge",
"counter",
"histogram",
"summary",
"}",
".",
"include?",
"(",
"type",
")",
"raise",
"ArgumentError",
",",
"\"type must be one of :gauge, :counter, :histogram, or :summary (got #{type.inspect})\"",
"end",
"end"
] | Make sure that the type we were passed is one Prometheus is known to accept. | [
"Make",
"sure",
"that",
"the",
"type",
"we",
"were",
"passed",
"is",
"one",
"Prometheus",
"is",
"known",
"to",
"accept",
"."
] | 1bbd9835233d0672af020da405ea1b29d55d105e | https://github.com/mpalmer/frankenstein/blob/1bbd9835233d0672af020da405ea1b29d55d105e/lib/frankenstein/collected_metric.rb#L143-L147 |
3,197 | raygao/asf-soap-adapter | lib/salesforce/chatter_feed.rb | Salesforce.ChatterFeed.search_chatter_feeds | def search_chatter_feeds(object_type, query_string, binding, limit=100)
return get_all_chatter_feeds_with_attachments(nil, object_type, binding, 'no-attachment-for-search', limit, false, query_string)
end | ruby | def search_chatter_feeds(object_type, query_string, binding, limit=100)
return get_all_chatter_feeds_with_attachments(nil, object_type, binding, 'no-attachment-for-search', limit, false, query_string)
end | [
"def",
"search_chatter_feeds",
"(",
"object_type",
",",
"query_string",
",",
"binding",
",",
"limit",
"=",
"100",
")",
"return",
"get_all_chatter_feeds_with_attachments",
"(",
"nil",
",",
"object_type",
",",
"binding",
",",
"'no-attachment-for-search'",
",",
"limit",
",",
"false",
",",
"query_string",
")",
"end"
] | find all chatter feeds based on object_type, query_string, and given binding | [
"find",
"all",
"chatter",
"feeds",
"based",
"on",
"object_type",
"query_string",
"and",
"given",
"binding"
] | ab96dc48d60a6410d620cafe68ae7add012dc9d4 | https://github.com/raygao/asf-soap-adapter/blob/ab96dc48d60a6410d620cafe68ae7add012dc9d4/lib/salesforce/chatter_feed.rb#L66-L68 |
3,198 | norman/phonology | lib/phonology/inventory.rb | Phonology.Inventory.with | def with(*features)
pos, neg = mangle_args(*features)
self.class.new(Hash[@sets.select do |key, val|
!key.intersection(pos).empty?
end]).without_any(neg)
end | ruby | def with(*features)
pos, neg = mangle_args(*features)
self.class.new(Hash[@sets.select do |key, val|
!key.intersection(pos).empty?
end]).without_any(neg)
end | [
"def",
"with",
"(",
"*",
"features",
")",
"pos",
",",
"neg",
"=",
"mangle_args",
"(",
"features",
")",
"self",
".",
"class",
".",
"new",
"(",
"Hash",
"[",
"@sets",
".",
"select",
"do",
"|",
"key",
",",
"val",
"|",
"!",
"key",
".",
"intersection",
"(",
"pos",
")",
".",
"empty?",
"end",
"]",
")",
".",
"without_any",
"(",
"neg",
")",
"end"
] | Return an instance of Sounds whose sets include any of the given
features. | [
"Return",
"an",
"instance",
"of",
"Sounds",
"whose",
"sets",
"include",
"any",
"of",
"the",
"given",
"features",
"."
] | 910207237aecbcd8e1a464a9148d9b3fd4d1f3e4 | https://github.com/norman/phonology/blob/910207237aecbcd8e1a464a9148d9b3fd4d1f3e4/lib/phonology/inventory.rb#L48-L53 |
3,199 | norman/phonology | lib/phonology/inventory.rb | Phonology.Inventory.with_all | def with_all(*features)
pos, neg = mangle_args(*features)
self.class.new(Hash[@sets.select do |key, val|
pos.subset?(key)
end]).without_any(neg)
end | ruby | def with_all(*features)
pos, neg = mangle_args(*features)
self.class.new(Hash[@sets.select do |key, val|
pos.subset?(key)
end]).without_any(neg)
end | [
"def",
"with_all",
"(",
"*",
"features",
")",
"pos",
",",
"neg",
"=",
"mangle_args",
"(",
"features",
")",
"self",
".",
"class",
".",
"new",
"(",
"Hash",
"[",
"@sets",
".",
"select",
"do",
"|",
"key",
",",
"val",
"|",
"pos",
".",
"subset?",
"(",
"key",
")",
"end",
"]",
")",
".",
"without_any",
"(",
"neg",
")",
"end"
] | Return feature sets that include all of the given features | [
"Return",
"feature",
"sets",
"that",
"include",
"all",
"of",
"the",
"given",
"features"
] | 910207237aecbcd8e1a464a9148d9b3fd4d1f3e4 | https://github.com/norman/phonology/blob/910207237aecbcd8e1a464a9148d9b3fd4d1f3e4/lib/phonology/inventory.rb#L56-L61 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.