repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
mguymon/naether | src/main/ruby/naether/runtime.rb | Naether.Runtime.load_dependencies_to_classpath | def load_dependencies_to_classpath
jars = dependencies_classpath.split(File::PATH_SEPARATOR)
Naether::Java.load_jars(jars)
jars
end | ruby | def load_dependencies_to_classpath
jars = dependencies_classpath.split(File::PATH_SEPARATOR)
Naether::Java.load_jars(jars)
jars
end | [
"def",
"load_dependencies_to_classpath",
"jars",
"=",
"dependencies_classpath",
".",
"split",
"(",
"File",
"::",
"PATH_SEPARATOR",
")",
"Naether",
"::",
"Java",
".",
"load_jars",
"(",
"jars",
")",
"jars",
"end"
]
| Load dependencies to Classpath
@return [Array] of loaded jars | [
"Load",
"dependencies",
"to",
"Classpath"
]
| 218d8fd36c0b8b6e16d66e5715975570b4560ec4 | https://github.com/mguymon/naether/blob/218d8fd36c0b8b6e16d66e5715975570b4560ec4/src/main/ruby/naether/runtime.rb#L278-L283 | train |
mguymon/naether | src/main/ruby/naether/runtime.rb | Naether.Runtime.to_local_paths | def to_local_paths( notations )
if Naether.platform == 'java'
Naether::Java.convert_to_ruby_array(
Naether::Java.exec_static_method(
'com.tobedevoured.naether.util.Notation',
'getLocalPaths',
[local_repo_path, notations ],
['java.lang.String', 'java.util.List'] ) )
else
paths = Naether::Java.exec_static_method(
'com.tobedevoured.naether.util.Notation',
'getLocalPaths',
[local_repo_path, Naether::Java.convert_to_java_list(notations) ],
['java.lang.String', 'java.util.List'] )
Naether::Java.convert_to_ruby_array( paths, true )
end
end | ruby | def to_local_paths( notations )
if Naether.platform == 'java'
Naether::Java.convert_to_ruby_array(
Naether::Java.exec_static_method(
'com.tobedevoured.naether.util.Notation',
'getLocalPaths',
[local_repo_path, notations ],
['java.lang.String', 'java.util.List'] ) )
else
paths = Naether::Java.exec_static_method(
'com.tobedevoured.naether.util.Notation',
'getLocalPaths',
[local_repo_path, Naether::Java.convert_to_java_list(notations) ],
['java.lang.String', 'java.util.List'] )
Naether::Java.convert_to_ruby_array( paths, true )
end
end | [
"def",
"to_local_paths",
"(",
"notations",
")",
"if",
"Naether",
".",
"platform",
"==",
"'java'",
"Naether",
"::",
"Java",
".",
"convert_to_ruby_array",
"(",
"Naether",
"::",
"Java",
".",
"exec_static_method",
"(",
"'com.tobedevoured.naether.util.Notation'",
",",
"'getLocalPaths'",
",",
"[",
"local_repo_path",
",",
"notations",
"]",
",",
"[",
"'java.lang.String'",
",",
"'java.util.List'",
"]",
")",
")",
"else",
"paths",
"=",
"Naether",
"::",
"Java",
".",
"exec_static_method",
"(",
"'com.tobedevoured.naether.util.Notation'",
",",
"'getLocalPaths'",
",",
"[",
"local_repo_path",
",",
"Naether",
"::",
"Java",
".",
"convert_to_java_list",
"(",
"notations",
")",
"]",
",",
"[",
"'java.lang.String'",
",",
"'java.util.List'",
"]",
")",
"Naether",
"::",
"Java",
".",
"convert_to_ruby_array",
"(",
"paths",
",",
"true",
")",
"end",
"end"
]
| Convert notations to local paths of artifacts
@param [Array<String>] notations
@return [Array<String>] of paths to artifacts
@see https://github.com/mguymon/naether/wiki/Notations | [
"Convert",
"notations",
"to",
"local",
"paths",
"of",
"artifacts"
]
| 218d8fd36c0b8b6e16d66e5715975570b4560ec4 | https://github.com/mguymon/naether/blob/218d8fd36c0b8b6e16d66e5715975570b4560ec4/src/main/ruby/naether/runtime.rb#L308-L325 | train |
mguymon/naether | src/main/ruby/naether/runtime.rb | Naether.Runtime.deploy_artifact | def deploy_artifact( notation, file_path, url, opts = {} )
artifact = Naether::Java.create( "com.tobedevoured.naether.deploy.DeployArtifact" )
artifact.setRemoteRepo( url )
artifact.setNotation( notation )
artifact.setFilePath( file_path )
if opts[:pom_path]
artifact.setPomPath( opts[:pom_path] )
end
if opts[:username] || opts[:pub_key]
artifact.setAuth(opts[:username], opts[:password], opts[:pub_key], opts[:pub_key_passphrase] )
end
if Naether.platform == 'java'
@resolver.deployArtifact(artifact)
else
@resolver._invoke( 'deployArtifact', 'Lcom.tobedevoured.naether.deploy.DeployArtifact;', artifact )
end
end | ruby | def deploy_artifact( notation, file_path, url, opts = {} )
artifact = Naether::Java.create( "com.tobedevoured.naether.deploy.DeployArtifact" )
artifact.setRemoteRepo( url )
artifact.setNotation( notation )
artifact.setFilePath( file_path )
if opts[:pom_path]
artifact.setPomPath( opts[:pom_path] )
end
if opts[:username] || opts[:pub_key]
artifact.setAuth(opts[:username], opts[:password], opts[:pub_key], opts[:pub_key_passphrase] )
end
if Naether.platform == 'java'
@resolver.deployArtifact(artifact)
else
@resolver._invoke( 'deployArtifact', 'Lcom.tobedevoured.naether.deploy.DeployArtifact;', artifact )
end
end | [
"def",
"deploy_artifact",
"(",
"notation",
",",
"file_path",
",",
"url",
",",
"opts",
"=",
"{",
"}",
")",
"artifact",
"=",
"Naether",
"::",
"Java",
".",
"create",
"(",
"\"com.tobedevoured.naether.deploy.DeployArtifact\"",
")",
"artifact",
".",
"setRemoteRepo",
"(",
"url",
")",
"artifact",
".",
"setNotation",
"(",
"notation",
")",
"artifact",
".",
"setFilePath",
"(",
"file_path",
")",
"if",
"opts",
"[",
":pom_path",
"]",
"artifact",
".",
"setPomPath",
"(",
"opts",
"[",
":pom_path",
"]",
")",
"end",
"if",
"opts",
"[",
":username",
"]",
"||",
"opts",
"[",
":pub_key",
"]",
"artifact",
".",
"setAuth",
"(",
"opts",
"[",
":username",
"]",
",",
"opts",
"[",
":password",
"]",
",",
"opts",
"[",
":pub_key",
"]",
",",
"opts",
"[",
":pub_key_passphrase",
"]",
")",
"end",
"if",
"Naether",
".",
"platform",
"==",
"'java'",
"@resolver",
".",
"deployArtifact",
"(",
"artifact",
")",
"else",
"@resolver",
".",
"_invoke",
"(",
"'deployArtifact'",
",",
"'Lcom.tobedevoured.naether.deploy.DeployArtifact;'",
",",
"artifact",
")",
"end",
"end"
]
| Deploy artifact to remote repo url
@param [String] notation
@param [String] file_path to artifact to deploy
@param [String] url to deploy to
@param [Hash] opts
@option opts [String] :pom_path path to pom.xml
@option opts [String] :username for optional auth
@option opts [String] :password for optional auth
@option opts [String] :pub_key for optional auth
@option opts [String] :pub_key_passphrase for optional auth | [
"Deploy",
"artifact",
"to",
"remote",
"repo",
"url"
]
| 218d8fd36c0b8b6e16d66e5715975570b4560ec4 | https://github.com/mguymon/naether/blob/218d8fd36c0b8b6e16d66e5715975570b4560ec4/src/main/ruby/naether/runtime.rb#L364-L382 | train |
south37/rucc | lib/rucc/parser.rb | Rucc.Parser.read_int_sval | def read_int_sval(s)
s = s.downcase
if s.match(/^[+-]?0x/)
return s.to_i(16)
end
if s.match(/^[+-]?0b/)
return s.to_i(2)
end
if s.match(/^[+-]?0/)
return s.to_i(8)
end
s.to_i(10)
end | ruby | def read_int_sval(s)
s = s.downcase
if s.match(/^[+-]?0x/)
return s.to_i(16)
end
if s.match(/^[+-]?0b/)
return s.to_i(2)
end
if s.match(/^[+-]?0/)
return s.to_i(8)
end
s.to_i(10)
end | [
"def",
"read_int_sval",
"(",
"s",
")",
"s",
"=",
"s",
".",
"downcase",
"if",
"s",
".",
"match",
"(",
"/",
"/",
")",
"return",
"s",
".",
"to_i",
"(",
"16",
")",
"end",
"if",
"s",
".",
"match",
"(",
"/",
"/",
")",
"return",
"s",
".",
"to_i",
"(",
"2",
")",
"end",
"if",
"s",
".",
"match",
"(",
"/",
"/",
")",
"return",
"s",
".",
"to_i",
"(",
"8",
")",
"end",
"s",
".",
"to_i",
"(",
"10",
")",
"end"
]
| Max of long
@param [s]
@return [Integer] | [
"Max",
"of",
"long"
]
| 11743d10eb2fcf0834b4f4a34bb5b8a109b32558 | https://github.com/south37/rucc/blob/11743d10eb2fcf0834b4f4a34bb5b8a109b32558/lib/rucc/parser.rb#L299-L311 | train |
BookingSync/synced | lib/synced/attributes_as_hash.rb | Synced.AttributesAsHash.synced_attributes_as_hash | def synced_attributes_as_hash(attributes)
return attributes if attributes.is_a?(Hash)
Hash[Array.wrap(attributes).map { |name| [name, name] }]
end | ruby | def synced_attributes_as_hash(attributes)
return attributes if attributes.is_a?(Hash)
Hash[Array.wrap(attributes).map { |name| [name, name] }]
end | [
"def",
"synced_attributes_as_hash",
"(",
"attributes",
")",
"return",
"attributes",
"if",
"attributes",
".",
"is_a?",
"(",
"Hash",
")",
"Hash",
"[",
"Array",
".",
"wrap",
"(",
"attributes",
")",
".",
"map",
"{",
"|",
"name",
"|",
"[",
"name",
",",
"name",
"]",
"}",
"]",
"end"
]
| On a Hash returns the same Hash
On an Array returns a Hash with identical corresponding keys and values
Used for mapping local - remote attributes | [
"On",
"a",
"Hash",
"returns",
"the",
"same",
"Hash",
"On",
"an",
"Array",
"returns",
"a",
"Hash",
"with",
"identical",
"corresponding",
"keys",
"and",
"values",
"Used",
"for",
"mapping",
"local",
"-",
"remote",
"attributes"
]
| 4a79eee67497c7b7954b0a8dd6ac832fa06c112b | https://github.com/BookingSync/synced/blob/4a79eee67497c7b7954b0a8dd6ac832fa06c112b/lib/synced/attributes_as_hash.rb#L6-L9 | train |
south37/rucc | lib/rucc/engine.rb | Rucc.Engine.read_from_string | def read_from_string(buf)
@lexer.stream_stash([FileIO.new(StringIO.new(buf), "-")])
parse.each do |toplevel_ast|
@gen.emit_toplevel(toplevel_ast)
end
@lexer.stream_unstash
end | ruby | def read_from_string(buf)
@lexer.stream_stash([FileIO.new(StringIO.new(buf), "-")])
parse.each do |toplevel_ast|
@gen.emit_toplevel(toplevel_ast)
end
@lexer.stream_unstash
end | [
"def",
"read_from_string",
"(",
"buf",
")",
"@lexer",
".",
"stream_stash",
"(",
"[",
"FileIO",
".",
"new",
"(",
"StringIO",
".",
"new",
"(",
"buf",
")",
",",
"\"-\"",
")",
"]",
")",
"parse",
".",
"each",
"do",
"|",
"toplevel_ast",
"|",
"@gen",
".",
"emit_toplevel",
"(",
"toplevel_ast",
")",
"end",
"@lexer",
".",
"stream_unstash",
"end"
]
| Reads from a string as if the string is a content of input file.
Convenient for evaluating small string snippet contaiing preprocessor macros.
@param [String] buf | [
"Reads",
"from",
"a",
"string",
"as",
"if",
"the",
"string",
"is",
"a",
"content",
"of",
"input",
"file",
".",
"Convenient",
"for",
"evaluating",
"small",
"string",
"snippet",
"contaiing",
"preprocessor",
"macros",
"."
]
| 11743d10eb2fcf0834b4f4a34bb5b8a109b32558 | https://github.com/south37/rucc/blob/11743d10eb2fcf0834b4f4a34bb5b8a109b32558/lib/rucc/engine.rb#L130-L136 | train |
infinitetoken/barcodes | lib/barcodes/exec.rb | Barcodes.Exec.run | def run
begin
unless self.symbology.nil?
unless self.options[:ascii]
Barcodes::Renderer::Pdf.new(Barcodes.create(self.symbology, self.options)).render(self.target)
else
Barcodes::Renderer::Ascii.new(Barcodes.create(self.symbology, self.options)).render(self.target)
end
end
rescue Exception => e
puts e.message
end
end | ruby | def run
begin
unless self.symbology.nil?
unless self.options[:ascii]
Barcodes::Renderer::Pdf.new(Barcodes.create(self.symbology, self.options)).render(self.target)
else
Barcodes::Renderer::Ascii.new(Barcodes.create(self.symbology, self.options)).render(self.target)
end
end
rescue Exception => e
puts e.message
end
end | [
"def",
"run",
"begin",
"unless",
"self",
".",
"symbology",
".",
"nil?",
"unless",
"self",
".",
"options",
"[",
":ascii",
"]",
"Barcodes",
"::",
"Renderer",
"::",
"Pdf",
".",
"new",
"(",
"Barcodes",
".",
"create",
"(",
"self",
".",
"symbology",
",",
"self",
".",
"options",
")",
")",
".",
"render",
"(",
"self",
".",
"target",
")",
"else",
"Barcodes",
"::",
"Renderer",
"::",
"Ascii",
".",
"new",
"(",
"Barcodes",
".",
"create",
"(",
"self",
".",
"symbology",
",",
"self",
".",
"options",
")",
")",
".",
"render",
"(",
"self",
".",
"target",
")",
"end",
"end",
"rescue",
"Exception",
"=>",
"e",
"puts",
"e",
".",
"message",
"end",
"end"
]
| Creates a new instance with given command line arguments and options
Runs the command and renders barcode | [
"Creates",
"a",
"new",
"instance",
"with",
"given",
"command",
"line",
"arguments",
"and",
"options",
"Runs",
"the",
"command",
"and",
"renders",
"barcode"
]
| 76a0bda4f5afca246ef040ea96f92044366efc39 | https://github.com/infinitetoken/barcodes/blob/76a0bda4f5afca246ef040ea96f92044366efc39/lib/barcodes/exec.rb#L42-L54 | train |
infinitetoken/barcodes | lib/barcodes/exec.rb | Barcodes.Exec._init_parser | def _init_parser
@parser ||= OptionParser.new do |opts|
opts.banner = "Usage: barcodes [OPTIONS] symbology target"
opts.separator ""
opts.on('-D', '--data [DATA]', 'The barcode data to encode (0123456789)') { |v| @options[:data] = v ||= '0123456789' }
opts.on('-s', '--start_character [START_CHARACTER]', 'The barcode start character if applicable') { |v| @options[:start_character] = v ||= '' }
opts.on('-e', '--stop_character [STOP_CHARACTER]', 'The barcode stop character if applicable') { |v| @options[:stop_character] = v ||= '' }
opts.on('-W', '--bar_width [BAR_WIDTH]', 'The barcode bar width in mils (20)') { |v| @options[:bar_width] = v.to_i ||= 20 }
opts.on('-H', '--bar_height [BAR_HEIGHT]', 'The barcode bar height in mils (1000)') { |v| @options[:bar_height] = v.to_i ||= 1000 }
opts.on('-c', '--caption_height [CAPTION_HEIGHT]', 'The barcode caption height in mils (180)') { |v| @options[:caption_height] = v.to_i ||= 180 }
opts.on('-p', '--caption_size [CAPTION_SIZE]', 'The caption font size in mils (167)') { |v| @options[:font_size] = v.to_f ||= 167 }
opts.on('-A', '--alpha [ALPHA]', 'The barcode transparency (1.0)') { |v| @options[:alpha] = v.to_f ||= 1.0 }
opts.on('-O', '--color [COLOR]', 'The barcode color in hex (000000)') { |v| @options[:color] = v ||= '000000' }
opts.on('-a', '--captioned', 'Render barcode caption (true)') { |v| @options[:captioned] = v ||= true }
opts.on('-i', '--ascii', 'Render barcode as ASCII string (false)') { |v| @options[:ascii] = v ||= false }
opts.on('-v', '--version') { puts self._version; exit }
opts.on('-h', '--help') { puts opts; exit }
opts.separator ""
end
end | ruby | def _init_parser
@parser ||= OptionParser.new do |opts|
opts.banner = "Usage: barcodes [OPTIONS] symbology target"
opts.separator ""
opts.on('-D', '--data [DATA]', 'The barcode data to encode (0123456789)') { |v| @options[:data] = v ||= '0123456789' }
opts.on('-s', '--start_character [START_CHARACTER]', 'The barcode start character if applicable') { |v| @options[:start_character] = v ||= '' }
opts.on('-e', '--stop_character [STOP_CHARACTER]', 'The barcode stop character if applicable') { |v| @options[:stop_character] = v ||= '' }
opts.on('-W', '--bar_width [BAR_WIDTH]', 'The barcode bar width in mils (20)') { |v| @options[:bar_width] = v.to_i ||= 20 }
opts.on('-H', '--bar_height [BAR_HEIGHT]', 'The barcode bar height in mils (1000)') { |v| @options[:bar_height] = v.to_i ||= 1000 }
opts.on('-c', '--caption_height [CAPTION_HEIGHT]', 'The barcode caption height in mils (180)') { |v| @options[:caption_height] = v.to_i ||= 180 }
opts.on('-p', '--caption_size [CAPTION_SIZE]', 'The caption font size in mils (167)') { |v| @options[:font_size] = v.to_f ||= 167 }
opts.on('-A', '--alpha [ALPHA]', 'The barcode transparency (1.0)') { |v| @options[:alpha] = v.to_f ||= 1.0 }
opts.on('-O', '--color [COLOR]', 'The barcode color in hex (000000)') { |v| @options[:color] = v ||= '000000' }
opts.on('-a', '--captioned', 'Render barcode caption (true)') { |v| @options[:captioned] = v ||= true }
opts.on('-i', '--ascii', 'Render barcode as ASCII string (false)') { |v| @options[:ascii] = v ||= false }
opts.on('-v', '--version') { puts self._version; exit }
opts.on('-h', '--help') { puts opts; exit }
opts.separator ""
end
end | [
"def",
"_init_parser",
"@parser",
"||=",
"OptionParser",
".",
"new",
"do",
"|",
"opts",
"|",
"opts",
".",
"banner",
"=",
"\"Usage: barcodes [OPTIONS] symbology target\"",
"opts",
".",
"separator",
"\"\"",
"opts",
".",
"on",
"(",
"'-D'",
",",
"'--data [DATA]'",
",",
"'The barcode data to encode (0123456789)'",
")",
"{",
"|",
"v",
"|",
"@options",
"[",
":data",
"]",
"=",
"v",
"||=",
"'0123456789'",
"}",
"opts",
".",
"on",
"(",
"'-s'",
",",
"'--start_character [START_CHARACTER]'",
",",
"'The barcode start character if applicable'",
")",
"{",
"|",
"v",
"|",
"@options",
"[",
":start_character",
"]",
"=",
"v",
"||=",
"''",
"}",
"opts",
".",
"on",
"(",
"'-e'",
",",
"'--stop_character [STOP_CHARACTER]'",
",",
"'The barcode stop character if applicable'",
")",
"{",
"|",
"v",
"|",
"@options",
"[",
":stop_character",
"]",
"=",
"v",
"||=",
"''",
"}",
"opts",
".",
"on",
"(",
"'-W'",
",",
"'--bar_width [BAR_WIDTH]'",
",",
"'The barcode bar width in mils (20)'",
")",
"{",
"|",
"v",
"|",
"@options",
"[",
":bar_width",
"]",
"=",
"v",
".",
"to_i",
"||=",
"20",
"}",
"opts",
".",
"on",
"(",
"'-H'",
",",
"'--bar_height [BAR_HEIGHT]'",
",",
"'The barcode bar height in mils (1000)'",
")",
"{",
"|",
"v",
"|",
"@options",
"[",
":bar_height",
"]",
"=",
"v",
".",
"to_i",
"||=",
"1000",
"}",
"opts",
".",
"on",
"(",
"'-c'",
",",
"'--caption_height [CAPTION_HEIGHT]'",
",",
"'The barcode caption height in mils (180)'",
")",
"{",
"|",
"v",
"|",
"@options",
"[",
":caption_height",
"]",
"=",
"v",
".",
"to_i",
"||=",
"180",
"}",
"opts",
".",
"on",
"(",
"'-p'",
",",
"'--caption_size [CAPTION_SIZE]'",
",",
"'The caption font size in mils (167)'",
")",
"{",
"|",
"v",
"|",
"@options",
"[",
":font_size",
"]",
"=",
"v",
".",
"to_f",
"||=",
"167",
"}",
"opts",
".",
"on",
"(",
"'-A'",
",",
"'--alpha [ALPHA]'",
",",
"'The barcode transparency (1.0)'",
")",
"{",
"|",
"v",
"|",
"@options",
"[",
":alpha",
"]",
"=",
"v",
".",
"to_f",
"||=",
"1.0",
"}",
"opts",
".",
"on",
"(",
"'-O'",
",",
"'--color [COLOR]'",
",",
"'The barcode color in hex (000000)'",
")",
"{",
"|",
"v",
"|",
"@options",
"[",
":color",
"]",
"=",
"v",
"||=",
"'000000'",
"}",
"opts",
".",
"on",
"(",
"'-a'",
",",
"'--captioned'",
",",
"'Render barcode caption (true)'",
")",
"{",
"|",
"v",
"|",
"@options",
"[",
":captioned",
"]",
"=",
"v",
"||=",
"true",
"}",
"opts",
".",
"on",
"(",
"'-i'",
",",
"'--ascii'",
",",
"'Render barcode as ASCII string (false)'",
")",
"{",
"|",
"v",
"|",
"@options",
"[",
":ascii",
"]",
"=",
"v",
"||=",
"false",
"}",
"opts",
".",
"on",
"(",
"'-v'",
",",
"'--version'",
")",
"{",
"puts",
"self",
".",
"_version",
";",
"exit",
"}",
"opts",
".",
"on",
"(",
"'-h'",
",",
"'--help'",
")",
"{",
"puts",
"opts",
";",
"exit",
"}",
"opts",
".",
"separator",
"\"\"",
"end",
"end"
]
| Initializes the option parser instance | [
"Initializes",
"the",
"option",
"parser",
"instance"
]
| 76a0bda4f5afca246ef040ea96f92044366efc39 | https://github.com/infinitetoken/barcodes/blob/76a0bda4f5afca246ef040ea96f92044366efc39/lib/barcodes/exec.rb#L59-L78 | train |
infinitetoken/barcodes | lib/barcodes/exec.rb | Barcodes.Exec._parse! | def _parse!
begin
self.parser.parse!(self.argv)
rescue
puts self.parser.help
exit 1
end
@symbology = self.argv.shift
@target = self.argv.shift
end | ruby | def _parse!
begin
self.parser.parse!(self.argv)
rescue
puts self.parser.help
exit 1
end
@symbology = self.argv.shift
@target = self.argv.shift
end | [
"def",
"_parse!",
"begin",
"self",
".",
"parser",
".",
"parse!",
"(",
"self",
".",
"argv",
")",
"rescue",
"puts",
"self",
".",
"parser",
".",
"help",
"exit",
"1",
"end",
"@symbology",
"=",
"self",
".",
"argv",
".",
"shift",
"@target",
"=",
"self",
".",
"argv",
".",
"shift",
"end"
]
| Parses the command line arguments | [
"Parses",
"the",
"command",
"line",
"arguments"
]
| 76a0bda4f5afca246ef040ea96f92044366efc39 | https://github.com/infinitetoken/barcodes/blob/76a0bda4f5afca246ef040ea96f92044366efc39/lib/barcodes/exec.rb#L81-L92 | train |
ruby-ore/ore | lib/ore/cli.rb | Ore.CLI.list | def list
print_template = lambda { |path|
puts " #{File.basename(path)}"
}
say "Builtin templates:", :green
Config.builtin_templates(&print_template)
say "Installed templates:", :green
Config.installed_templates(&print_template)
end | ruby | def list
print_template = lambda { |path|
puts " #{File.basename(path)}"
}
say "Builtin templates:", :green
Config.builtin_templates(&print_template)
say "Installed templates:", :green
Config.installed_templates(&print_template)
end | [
"def",
"list",
"print_template",
"=",
"lambda",
"{",
"|",
"path",
"|",
"puts",
"\" #{File.basename(path)}\"",
"}",
"say",
"\"Builtin templates:\"",
",",
":green",
"Config",
".",
"builtin_templates",
"(",
"&",
"print_template",
")",
"say",
"\"Installed templates:\"",
",",
":green",
"Config",
".",
"installed_templates",
"(",
"&",
"print_template",
")",
"end"
]
| Lists builtin and installed templates. | [
"Lists",
"builtin",
"and",
"installed",
"templates",
"."
]
| 585c98027771fd118041e90bb38295983d67166c | https://github.com/ruby-ore/ore/blob/585c98027771fd118041e90bb38295983d67166c/lib/ore/cli.rb#L24-L34 | train |
ruby-ore/ore | lib/ore/cli.rb | Ore.CLI.remove | def remove(name)
name = File.basename(name)
path = File.join(Config::TEMPLATES_DIR,name)
unless File.exists?(path)
say "Unknown template: #{name}", :red
exit -1
end
FileUtils.rm_rf(path)
end | ruby | def remove(name)
name = File.basename(name)
path = File.join(Config::TEMPLATES_DIR,name)
unless File.exists?(path)
say "Unknown template: #{name}", :red
exit -1
end
FileUtils.rm_rf(path)
end | [
"def",
"remove",
"(",
"name",
")",
"name",
"=",
"File",
".",
"basename",
"(",
"name",
")",
"path",
"=",
"File",
".",
"join",
"(",
"Config",
"::",
"TEMPLATES_DIR",
",",
"name",
")",
"unless",
"File",
".",
"exists?",
"(",
"path",
")",
"say",
"\"Unknown template: #{name}\"",
",",
":red",
"exit",
"-",
"1",
"end",
"FileUtils",
".",
"rm_rf",
"(",
"path",
")",
"end"
]
| Removes a previously installed template.
@param [String] name
The name of the template to remove. | [
"Removes",
"a",
"previously",
"installed",
"template",
"."
]
| 585c98027771fd118041e90bb38295983d67166c | https://github.com/ruby-ore/ore/blob/585c98027771fd118041e90bb38295983d67166c/lib/ore/cli.rb#L82-L92 | train |
ruby-ore/ore | lib/ore/generator.rb | Ore.Generator.generate | def generate
self.destination_root = path
enable_templates!
initialize_variables!
extend Template::Helpers::MARKUP.fetch(@markup)
unless options.quiet?
say "Generating #{self.destination_root}", :green
end
generate_directories!
generate_files!
initialize_scm!
end | ruby | def generate
self.destination_root = path
enable_templates!
initialize_variables!
extend Template::Helpers::MARKUP.fetch(@markup)
unless options.quiet?
say "Generating #{self.destination_root}", :green
end
generate_directories!
generate_files!
initialize_scm!
end | [
"def",
"generate",
"self",
".",
"destination_root",
"=",
"path",
"enable_templates!",
"initialize_variables!",
"extend",
"Template",
"::",
"Helpers",
"::",
"MARKUP",
".",
"fetch",
"(",
"@markup",
")",
"unless",
"options",
".",
"quiet?",
"say",
"\"Generating #{self.destination_root}\"",
",",
":green",
"end",
"generate_directories!",
"generate_files!",
"initialize_scm!",
"end"
]
| Generates a new project. | [
"Generates",
"a",
"new",
"project",
"."
]
| 585c98027771fd118041e90bb38295983d67166c | https://github.com/ruby-ore/ore/blob/585c98027771fd118041e90bb38295983d67166c/lib/ore/generator.rb#L90-L105 | train |
ruby-ore/ore | lib/ore/generator.rb | Ore.Generator.enable_template | def enable_template(name)
name = name.to_sym
return false if @enabled_templates.include?(name)
unless (template_dir = Template.templates[name])
say "Unknown template #{name}", :red
exit -1
end
new_template = Template::Directory.new(template_dir)
# mark the template as enabled
@enabled_templates << name
# enable any other templates
new_template.enable.each do |sub_template|
enable_template(sub_template)
end
# append the new template to the end of the list,
# to override previously loaded templates
@templates << new_template
# add the template directory to the source-paths
self.source_paths << new_template.path
return true
end | ruby | def enable_template(name)
name = name.to_sym
return false if @enabled_templates.include?(name)
unless (template_dir = Template.templates[name])
say "Unknown template #{name}", :red
exit -1
end
new_template = Template::Directory.new(template_dir)
# mark the template as enabled
@enabled_templates << name
# enable any other templates
new_template.enable.each do |sub_template|
enable_template(sub_template)
end
# append the new template to the end of the list,
# to override previously loaded templates
@templates << new_template
# add the template directory to the source-paths
self.source_paths << new_template.path
return true
end | [
"def",
"enable_template",
"(",
"name",
")",
"name",
"=",
"name",
".",
"to_sym",
"return",
"false",
"if",
"@enabled_templates",
".",
"include?",
"(",
"name",
")",
"unless",
"(",
"template_dir",
"=",
"Template",
".",
"templates",
"[",
"name",
"]",
")",
"say",
"\"Unknown template #{name}\"",
",",
":red",
"exit",
"-",
"1",
"end",
"new_template",
"=",
"Template",
"::",
"Directory",
".",
"new",
"(",
"template_dir",
")",
"@enabled_templates",
"<<",
"name",
"new_template",
".",
"enable",
".",
"each",
"do",
"|",
"sub_template",
"|",
"enable_template",
"(",
"sub_template",
")",
"end",
"@templates",
"<<",
"new_template",
"self",
".",
"source_paths",
"<<",
"new_template",
".",
"path",
"return",
"true",
"end"
]
| Enables a template, adding it to the generator.
@param [Symbol, String] name
The name of the template to add.
@since 0.4.0 | [
"Enables",
"a",
"template",
"adding",
"it",
"to",
"the",
"generator",
"."
]
| 585c98027771fd118041e90bb38295983d67166c | https://github.com/ruby-ore/ore/blob/585c98027771fd118041e90bb38295983d67166c/lib/ore/generator.rb#L117-L144 | train |
ruby-ore/ore | lib/ore/generator.rb | Ore.Generator.disable_template | def disable_template(name)
name = name.to_sym
return false if @disabled_templates.include?(name)
if (template_dir = Template.templates[name])
source_paths.delete(template_dir)
@templates.delete_if { |template| template.path == template_dir }
@enabled_templates.delete(name)
end
@disabled_templates << name
return true
end | ruby | def disable_template(name)
name = name.to_sym
return false if @disabled_templates.include?(name)
if (template_dir = Template.templates[name])
source_paths.delete(template_dir)
@templates.delete_if { |template| template.path == template_dir }
@enabled_templates.delete(name)
end
@disabled_templates << name
return true
end | [
"def",
"disable_template",
"(",
"name",
")",
"name",
"=",
"name",
".",
"to_sym",
"return",
"false",
"if",
"@disabled_templates",
".",
"include?",
"(",
"name",
")",
"if",
"(",
"template_dir",
"=",
"Template",
".",
"templates",
"[",
"name",
"]",
")",
"source_paths",
".",
"delete",
"(",
"template_dir",
")",
"@templates",
".",
"delete_if",
"{",
"|",
"template",
"|",
"template",
".",
"path",
"==",
"template_dir",
"}",
"@enabled_templates",
".",
"delete",
"(",
"name",
")",
"end",
"@disabled_templates",
"<<",
"name",
"return",
"true",
"end"
]
| Disables a template in the generator.
@param [Symbol, String] name
The name of the template.
@since 0.4.0 | [
"Disables",
"a",
"template",
"in",
"the",
"generator",
"."
]
| 585c98027771fd118041e90bb38295983d67166c | https://github.com/ruby-ore/ore/blob/585c98027771fd118041e90bb38295983d67166c/lib/ore/generator.rb#L154-L168 | train |
ruby-ore/ore | lib/ore/generator.rb | Ore.Generator.enable_templates! | def enable_templates!
@templates = []
@enabled_templates = Set[]
@disabled_templates = Set[]
enable_template :gem
# enable the default templates first
Options::DEFAULT_TEMPLATES.each do |name|
if (Template.template?(name) && options[name])
enable_template(name)
end
end
# enable the templates specified by option
options.each do |name,value|
if (Template.template?(name) && value)
enable_template(name)
end
end
# enable any additionally specified templates
options.templates.each { |name| enable_template(name) }
# disable any previously enabled templates
@templates.reverse_each do |template|
template.disable.each { |name| disable_template(name) }
end
end | ruby | def enable_templates!
@templates = []
@enabled_templates = Set[]
@disabled_templates = Set[]
enable_template :gem
# enable the default templates first
Options::DEFAULT_TEMPLATES.each do |name|
if (Template.template?(name) && options[name])
enable_template(name)
end
end
# enable the templates specified by option
options.each do |name,value|
if (Template.template?(name) && value)
enable_template(name)
end
end
# enable any additionally specified templates
options.templates.each { |name| enable_template(name) }
# disable any previously enabled templates
@templates.reverse_each do |template|
template.disable.each { |name| disable_template(name) }
end
end | [
"def",
"enable_templates!",
"@templates",
"=",
"[",
"]",
"@enabled_templates",
"=",
"Set",
"[",
"]",
"@disabled_templates",
"=",
"Set",
"[",
"]",
"enable_template",
":gem",
"Options",
"::",
"DEFAULT_TEMPLATES",
".",
"each",
"do",
"|",
"name",
"|",
"if",
"(",
"Template",
".",
"template?",
"(",
"name",
")",
"&&",
"options",
"[",
"name",
"]",
")",
"enable_template",
"(",
"name",
")",
"end",
"end",
"options",
".",
"each",
"do",
"|",
"name",
",",
"value",
"|",
"if",
"(",
"Template",
".",
"template?",
"(",
"name",
")",
"&&",
"value",
")",
"enable_template",
"(",
"name",
")",
"end",
"end",
"options",
".",
"templates",
".",
"each",
"{",
"|",
"name",
"|",
"enable_template",
"(",
"name",
")",
"}",
"@templates",
".",
"reverse_each",
"do",
"|",
"template",
"|",
"template",
".",
"disable",
".",
"each",
"{",
"|",
"name",
"|",
"disable_template",
"(",
"name",
")",
"}",
"end",
"end"
]
| Enables templates. | [
"Enables",
"templates",
"."
]
| 585c98027771fd118041e90bb38295983d67166c | https://github.com/ruby-ore/ore/blob/585c98027771fd118041e90bb38295983d67166c/lib/ore/generator.rb#L173-L201 | train |
ruby-ore/ore | lib/ore/generator.rb | Ore.Generator.initialize_variables! | def initialize_variables!
@root = destination_root
@project_dir = File.basename(@root)
@name = (options.name || @project_dir)
@scm = if File.directory?(File.join(@root,'.git')) then :git
elsif File.directory?(File.join(@root,'.hg')) then :hg
elsif File.directory?(File.join(@root,'.svn')) then :svn
elsif options.hg? then :hg
elsif options.git? then :git
end
case @scm
when :git
@scm_user = `git config user.name`.chomp
@scm_email = `git config user.email`.chomp
@github_user = `git config github.user`.chomp
when :hg
user_email = `hg showconfig ui.username`.chomp
user_email.scan(/([^<]+)\s+<([^>]+)>/) do |(user,email)|
@scm_user, @scm_email = user, email
end
end
@modules = modules_of(@name)
@module_depth = @modules.length
@module = @modules.last
@namespace = options.namespace || namespace_of(@name)
@namespace_dirs = namespace_dirs_of(@name)
@namespace_path = namespace_path_of(@name)
@namespace_dir = @namespace_dirs.last
@version = options.version
@summary = options.summary
@description = options.description
@authors = if options.author || options.author
[*options.author, *options.authors]
else
[@scm_user || ENV['USERNAME'] || ENV['USER'].capitalize]
end
@author = @authors.first
@email = (options.email || @scm_email)
@safe_email = @email.sub('@',' at ') if @email
@homepage = if options.homepage
options.homepage
elsif !(@github_user.nil? || @github_user.empty?)
"https://github.com/#{@github_user}/#{@name}#readme"
else
"https://rubygems.org/gems/#{@name}"
end
@uri = URI(@homepage)
@bug_tracker = case @uri.host
when 'github.com'
"https://#{@uri.host}#{@uri.path}/issues"
end
@markup = if options.markdown? then :markdown
elsif options.textile? then :textile
elsif options.markup? then options.markup.to_sym
end
@markup_ext = Template::Markup::EXT.fetch(@markup) do
say "Unknown markup: #{@markup}", :red
exit -1
end
@date = Date.today
@year = @date.year
@month = @date.month
@day = @date.day
@ignore = SortedSet[]
@dependencies = {}
@development_dependencies = {}
@templates.each do |template|
@ignore.merge(template.ignore)
@dependencies.merge!(template.dependencies)
@development_dependencies.merge!(template.development_dependencies)
template.variables.each do |name,value|
instance_variable_set("@#{name}",value)
end
end
@generated_dirs = {}
@generated_files = {}
end | ruby | def initialize_variables!
@root = destination_root
@project_dir = File.basename(@root)
@name = (options.name || @project_dir)
@scm = if File.directory?(File.join(@root,'.git')) then :git
elsif File.directory?(File.join(@root,'.hg')) then :hg
elsif File.directory?(File.join(@root,'.svn')) then :svn
elsif options.hg? then :hg
elsif options.git? then :git
end
case @scm
when :git
@scm_user = `git config user.name`.chomp
@scm_email = `git config user.email`.chomp
@github_user = `git config github.user`.chomp
when :hg
user_email = `hg showconfig ui.username`.chomp
user_email.scan(/([^<]+)\s+<([^>]+)>/) do |(user,email)|
@scm_user, @scm_email = user, email
end
end
@modules = modules_of(@name)
@module_depth = @modules.length
@module = @modules.last
@namespace = options.namespace || namespace_of(@name)
@namespace_dirs = namespace_dirs_of(@name)
@namespace_path = namespace_path_of(@name)
@namespace_dir = @namespace_dirs.last
@version = options.version
@summary = options.summary
@description = options.description
@authors = if options.author || options.author
[*options.author, *options.authors]
else
[@scm_user || ENV['USERNAME'] || ENV['USER'].capitalize]
end
@author = @authors.first
@email = (options.email || @scm_email)
@safe_email = @email.sub('@',' at ') if @email
@homepage = if options.homepage
options.homepage
elsif !(@github_user.nil? || @github_user.empty?)
"https://github.com/#{@github_user}/#{@name}#readme"
else
"https://rubygems.org/gems/#{@name}"
end
@uri = URI(@homepage)
@bug_tracker = case @uri.host
when 'github.com'
"https://#{@uri.host}#{@uri.path}/issues"
end
@markup = if options.markdown? then :markdown
elsif options.textile? then :textile
elsif options.markup? then options.markup.to_sym
end
@markup_ext = Template::Markup::EXT.fetch(@markup) do
say "Unknown markup: #{@markup}", :red
exit -1
end
@date = Date.today
@year = @date.year
@month = @date.month
@day = @date.day
@ignore = SortedSet[]
@dependencies = {}
@development_dependencies = {}
@templates.each do |template|
@ignore.merge(template.ignore)
@dependencies.merge!(template.dependencies)
@development_dependencies.merge!(template.development_dependencies)
template.variables.each do |name,value|
instance_variable_set("@#{name}",value)
end
end
@generated_dirs = {}
@generated_files = {}
end | [
"def",
"initialize_variables!",
"@root",
"=",
"destination_root",
"@project_dir",
"=",
"File",
".",
"basename",
"(",
"@root",
")",
"@name",
"=",
"(",
"options",
".",
"name",
"||",
"@project_dir",
")",
"@scm",
"=",
"if",
"File",
".",
"directory?",
"(",
"File",
".",
"join",
"(",
"@root",
",",
"'.git'",
")",
")",
"then",
":git",
"elsif",
"File",
".",
"directory?",
"(",
"File",
".",
"join",
"(",
"@root",
",",
"'.hg'",
")",
")",
"then",
":hg",
"elsif",
"File",
".",
"directory?",
"(",
"File",
".",
"join",
"(",
"@root",
",",
"'.svn'",
")",
")",
"then",
":svn",
"elsif",
"options",
".",
"hg?",
"then",
":hg",
"elsif",
"options",
".",
"git?",
"then",
":git",
"end",
"case",
"@scm",
"when",
":git",
"@scm_user",
"=",
"`",
"`",
".",
"chomp",
"@scm_email",
"=",
"`",
"`",
".",
"chomp",
"@github_user",
"=",
"`",
"`",
".",
"chomp",
"when",
":hg",
"user_email",
"=",
"`",
"`",
".",
"chomp",
"user_email",
".",
"scan",
"(",
"/",
"\\s",
"/",
")",
"do",
"|",
"(",
"user",
",",
"email",
")",
"|",
"@scm_user",
",",
"@scm_email",
"=",
"user",
",",
"email",
"end",
"end",
"@modules",
"=",
"modules_of",
"(",
"@name",
")",
"@module_depth",
"=",
"@modules",
".",
"length",
"@module",
"=",
"@modules",
".",
"last",
"@namespace",
"=",
"options",
".",
"namespace",
"||",
"namespace_of",
"(",
"@name",
")",
"@namespace_dirs",
"=",
"namespace_dirs_of",
"(",
"@name",
")",
"@namespace_path",
"=",
"namespace_path_of",
"(",
"@name",
")",
"@namespace_dir",
"=",
"@namespace_dirs",
".",
"last",
"@version",
"=",
"options",
".",
"version",
"@summary",
"=",
"options",
".",
"summary",
"@description",
"=",
"options",
".",
"description",
"@authors",
"=",
"if",
"options",
".",
"author",
"||",
"options",
".",
"author",
"[",
"*",
"options",
".",
"author",
",",
"*",
"options",
".",
"authors",
"]",
"else",
"[",
"@scm_user",
"||",
"ENV",
"[",
"'USERNAME'",
"]",
"||",
"ENV",
"[",
"'USER'",
"]",
".",
"capitalize",
"]",
"end",
"@author",
"=",
"@authors",
".",
"first",
"@email",
"=",
"(",
"options",
".",
"email",
"||",
"@scm_email",
")",
"@safe_email",
"=",
"@email",
".",
"sub",
"(",
"'@'",
",",
"' at '",
")",
"if",
"@email",
"@homepage",
"=",
"if",
"options",
".",
"homepage",
"options",
".",
"homepage",
"elsif",
"!",
"(",
"@github_user",
".",
"nil?",
"||",
"@github_user",
".",
"empty?",
")",
"\"https://github.com/#{@github_user}/#{@name}#readme\"",
"else",
"\"https://rubygems.org/gems/#{@name}\"",
"end",
"@uri",
"=",
"URI",
"(",
"@homepage",
")",
"@bug_tracker",
"=",
"case",
"@uri",
".",
"host",
"when",
"'github.com'",
"\"https://#{@uri.host}#{@uri.path}/issues\"",
"end",
"@markup",
"=",
"if",
"options",
".",
"markdown?",
"then",
":markdown",
"elsif",
"options",
".",
"textile?",
"then",
":textile",
"elsif",
"options",
".",
"markup?",
"then",
"options",
".",
"markup",
".",
"to_sym",
"end",
"@markup_ext",
"=",
"Template",
"::",
"Markup",
"::",
"EXT",
".",
"fetch",
"(",
"@markup",
")",
"do",
"say",
"\"Unknown markup: #{@markup}\"",
",",
":red",
"exit",
"-",
"1",
"end",
"@date",
"=",
"Date",
".",
"today",
"@year",
"=",
"@date",
".",
"year",
"@month",
"=",
"@date",
".",
"month",
"@day",
"=",
"@date",
".",
"day",
"@ignore",
"=",
"SortedSet",
"[",
"]",
"@dependencies",
"=",
"{",
"}",
"@development_dependencies",
"=",
"{",
"}",
"@templates",
".",
"each",
"do",
"|",
"template",
"|",
"@ignore",
".",
"merge",
"(",
"template",
".",
"ignore",
")",
"@dependencies",
".",
"merge!",
"(",
"template",
".",
"dependencies",
")",
"@development_dependencies",
".",
"merge!",
"(",
"template",
".",
"development_dependencies",
")",
"template",
".",
"variables",
".",
"each",
"do",
"|",
"name",
",",
"value",
"|",
"instance_variable_set",
"(",
"\"@#{name}\"",
",",
"value",
")",
"end",
"end",
"@generated_dirs",
"=",
"{",
"}",
"@generated_files",
"=",
"{",
"}",
"end"
]
| Initializes variables for the templates. | [
"Initializes",
"variables",
"for",
"the",
"templates",
"."
]
| 585c98027771fd118041e90bb38295983d67166c | https://github.com/ruby-ore/ore/blob/585c98027771fd118041e90bb38295983d67166c/lib/ore/generator.rb#L206-L299 | train |
ruby-ore/ore | lib/ore/generator.rb | Ore.Generator.generate_files! | def generate_files!
# iterate through the templates in reverse, so files in the templates
# loaded last override the previously templates.
@templates.reverse_each do |template|
# copy in the static files first
template.each_file(@markup) do |dest,file|
generate_file dest, file
end
# then render the templates
template.each_template(@markup) do |dest,file|
generate_file dest, file, template: true
end
end
@generated_files.each_value do |path|
dir = path.split(File::SEPARATOR,2).first
if dir == 'bin'
chmod path, 0755
end
end
end | ruby | def generate_files!
# iterate through the templates in reverse, so files in the templates
# loaded last override the previously templates.
@templates.reverse_each do |template|
# copy in the static files first
template.each_file(@markup) do |dest,file|
generate_file dest, file
end
# then render the templates
template.each_template(@markup) do |dest,file|
generate_file dest, file, template: true
end
end
@generated_files.each_value do |path|
dir = path.split(File::SEPARATOR,2).first
if dir == 'bin'
chmod path, 0755
end
end
end | [
"def",
"generate_files!",
"@templates",
".",
"reverse_each",
"do",
"|",
"template",
"|",
"template",
".",
"each_file",
"(",
"@markup",
")",
"do",
"|",
"dest",
",",
"file",
"|",
"generate_file",
"dest",
",",
"file",
"end",
"template",
".",
"each_template",
"(",
"@markup",
")",
"do",
"|",
"dest",
",",
"file",
"|",
"generate_file",
"dest",
",",
"file",
",",
"template",
":",
"true",
"end",
"end",
"@generated_files",
".",
"each_value",
"do",
"|",
"path",
"|",
"dir",
"=",
"path",
".",
"split",
"(",
"File",
"::",
"SEPARATOR",
",",
"2",
")",
".",
"first",
"if",
"dir",
"==",
"'bin'",
"chmod",
"path",
",",
"0755",
"end",
"end",
"end"
]
| Copies static files and renders templates in the template directories. | [
"Copies",
"static",
"files",
"and",
"renders",
"templates",
"in",
"the",
"template",
"directories",
"."
]
| 585c98027771fd118041e90bb38295983d67166c | https://github.com/ruby-ore/ore/blob/585c98027771fd118041e90bb38295983d67166c/lib/ore/generator.rb#L315-L337 | train |
ruby-ore/ore | lib/ore/generator.rb | Ore.Generator.initialize_scm! | def initialize_scm!
in_root do
case @scm
when :git
unless File.directory?('.git')
run 'git init'
run 'git add .'
run 'git commit -m "Initial commit."'
end
when :hg
unless File.directory?('.hg')
run 'hg init'
run 'hg add .'
run 'hg commit -m "Initial commit."'
end
when :svn
@ignore.each do |pattern|
run "svn propset svn:ignore #{pattern.dump}"
end
run 'svn add .'
run 'svn commit -m "Initial commit."'
end
end
end | ruby | def initialize_scm!
in_root do
case @scm
when :git
unless File.directory?('.git')
run 'git init'
run 'git add .'
run 'git commit -m "Initial commit."'
end
when :hg
unless File.directory?('.hg')
run 'hg init'
run 'hg add .'
run 'hg commit -m "Initial commit."'
end
when :svn
@ignore.each do |pattern|
run "svn propset svn:ignore #{pattern.dump}"
end
run 'svn add .'
run 'svn commit -m "Initial commit."'
end
end
end | [
"def",
"initialize_scm!",
"in_root",
"do",
"case",
"@scm",
"when",
":git",
"unless",
"File",
".",
"directory?",
"(",
"'.git'",
")",
"run",
"'git init'",
"run",
"'git add .'",
"run",
"'git commit -m \"Initial commit.\"'",
"end",
"when",
":hg",
"unless",
"File",
".",
"directory?",
"(",
"'.hg'",
")",
"run",
"'hg init'",
"run",
"'hg add .'",
"run",
"'hg commit -m \"Initial commit.\"'",
"end",
"when",
":svn",
"@ignore",
".",
"each",
"do",
"|",
"pattern",
"|",
"run",
"\"svn propset svn:ignore #{pattern.dump}\"",
"end",
"run",
"'svn add .'",
"run",
"'svn commit -m \"Initial commit.\"'",
"end",
"end",
"end"
]
| Initializes the project repository and commits all files.
@since 0.10.0 | [
"Initializes",
"the",
"project",
"repository",
"and",
"commits",
"all",
"files",
"."
]
| 585c98027771fd118041e90bb38295983d67166c | https://github.com/ruby-ore/ore/blob/585c98027771fd118041e90bb38295983d67166c/lib/ore/generator.rb#L344-L368 | train |
octopress/deploy | lib/octopress-deploy.rb | Octopress.Deploy.init_config | def init_config(options={})
options = options.to_symbol_keys
if !options[:method]
abort "Please provide a deployment method. e.g. #{METHODS.keys}"
end
@options = DEFAULT_OPTIONS.deep_merge(options)
write_config
check_gitignore
end | ruby | def init_config(options={})
options = options.to_symbol_keys
if !options[:method]
abort "Please provide a deployment method. e.g. #{METHODS.keys}"
end
@options = DEFAULT_OPTIONS.deep_merge(options)
write_config
check_gitignore
end | [
"def",
"init_config",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"options",
".",
"to_symbol_keys",
"if",
"!",
"options",
"[",
":method",
"]",
"abort",
"\"Please provide a deployment method. e.g. #{METHODS.keys}\"",
"end",
"@options",
"=",
"DEFAULT_OPTIONS",
".",
"deep_merge",
"(",
"options",
")",
"write_config",
"check_gitignore",
"end"
]
| Create a config file | [
"Create",
"a",
"config",
"file"
]
| 662485f5ba8f66e0cbfe4a3ee1f2844dee4c6d59 | https://github.com/octopress/deploy/blob/662485f5ba8f66e0cbfe4a3ee1f2844dee4c6d59/lib/octopress-deploy.rb#L92-L102 | train |
maetl/calyx | lib/calyx/grammar.rb | Calyx.Grammar.generate_result | def generate_result(*args)
start_symbol, rules_map = map_default_args(*args)
Result.new(@registry.evaluate(start_symbol, rules_map))
end | ruby | def generate_result(*args)
start_symbol, rules_map = map_default_args(*args)
Result.new(@registry.evaluate(start_symbol, rules_map))
end | [
"def",
"generate_result",
"(",
"*",
"args",
")",
"start_symbol",
",",
"rules_map",
"=",
"map_default_args",
"(",
"*",
"args",
")",
"Result",
".",
"new",
"(",
"@registry",
".",
"evaluate",
"(",
"start_symbol",
",",
"rules_map",
")",
")",
"end"
]
| Produces a generated result from evaluating the grammar.
@see Calyx::Result
@overload generate_result(start_symbol)
@param [Symbol] start_symbol
@overload generate_result(rules_map)
@param [Hash] rules_map
@overload generate_result(start_symbol, rules_map)
@param [Symbol] start_symbol
@param [Hash] rules_map
@return [Calyx::Result] | [
"Produces",
"a",
"generated",
"result",
"from",
"evaluating",
"the",
"grammar",
"."
]
| 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/grammar.rb#L175-L179 | train |
cloudfoundry-attic/vcap-services-base | lib/base/job/snapshot.rb | VCAP::Services::Base::AsyncJob.Snapshot.service_snapshots | def service_snapshots(service_id)
return unless service_id
res = client.hgetall(redis_key(service_id))
res.values.map{|v| Yajl::Parser.parse(v)}
end | ruby | def service_snapshots(service_id)
return unless service_id
res = client.hgetall(redis_key(service_id))
res.values.map{|v| Yajl::Parser.parse(v)}
end | [
"def",
"service_snapshots",
"(",
"service_id",
")",
"return",
"unless",
"service_id",
"res",
"=",
"client",
".",
"hgetall",
"(",
"redis_key",
"(",
"service_id",
")",
")",
"res",
".",
"values",
".",
"map",
"{",
"|",
"v",
"|",
"Yajl",
"::",
"Parser",
".",
"parse",
"(",
"v",
")",
"}",
"end"
]
| Get all snapshots related to a service instance | [
"Get",
"all",
"snapshots",
"related",
"to",
"a",
"service",
"instance"
]
| bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/job/snapshot.rb#L38-L42 | train |
cloudfoundry-attic/vcap-services-base | lib/base/job/snapshot.rb | VCAP::Services::Base::AsyncJob.Snapshot.snapshot_details | def snapshot_details(service_id, snapshot_id)
return unless service_id && snapshot_id
res = client.hget(redis_key(service_id), snapshot_id)
raise ServiceError.new(ServiceError::NOT_FOUND, "snapshot #{snapshot_id}") unless res
Yajl::Parser.parse(res)
end | ruby | def snapshot_details(service_id, snapshot_id)
return unless service_id && snapshot_id
res = client.hget(redis_key(service_id), snapshot_id)
raise ServiceError.new(ServiceError::NOT_FOUND, "snapshot #{snapshot_id}") unless res
Yajl::Parser.parse(res)
end | [
"def",
"snapshot_details",
"(",
"service_id",
",",
"snapshot_id",
")",
"return",
"unless",
"service_id",
"&&",
"snapshot_id",
"res",
"=",
"client",
".",
"hget",
"(",
"redis_key",
"(",
"service_id",
")",
",",
"snapshot_id",
")",
"raise",
"ServiceError",
".",
"new",
"(",
"ServiceError",
"::",
"NOT_FOUND",
",",
"\"snapshot #{snapshot_id}\"",
")",
"unless",
"res",
"Yajl",
"::",
"Parser",
".",
"parse",
"(",
"res",
")",
"end"
]
| Get detail information for a single snapshot | [
"Get",
"detail",
"information",
"for",
"a",
"single",
"snapshot"
]
| bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/job/snapshot.rb#L53-L58 | train |
cloudfoundry-attic/vcap-services-base | lib/base/job/snapshot.rb | VCAP::Services::Base::AsyncJob.Snapshot.filter_keys | def filter_keys(snapshot)
return unless snapshot.is_a? Hash
snapshot.select {|k,v| FILTER_KEYS.include? k.to_s}
end | ruby | def filter_keys(snapshot)
return unless snapshot.is_a? Hash
snapshot.select {|k,v| FILTER_KEYS.include? k.to_s}
end | [
"def",
"filter_keys",
"(",
"snapshot",
")",
"return",
"unless",
"snapshot",
".",
"is_a?",
"Hash",
"snapshot",
".",
"select",
"{",
"|",
"k",
",",
"v",
"|",
"FILTER_KEYS",
".",
"include?",
"k",
".",
"to_s",
"}",
"end"
]
| filter internal keys of a given snapshot object, return a new snapshot object in canonical format | [
"filter",
"internal",
"keys",
"of",
"a",
"given",
"snapshot",
"object",
"return",
"a",
"new",
"snapshot",
"object",
"in",
"canonical",
"format"
]
| bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/job/snapshot.rb#L61-L64 | train |
ruby-ore/ore | lib/ore/actions.rb | Ore.Actions.generate_dir | def generate_dir(dest)
return if @generated_dirs.has_key?(dest)
path = interpolate(dest)
empty_directory path
@generated_dirs[dest] = path
return path
end | ruby | def generate_dir(dest)
return if @generated_dirs.has_key?(dest)
path = interpolate(dest)
empty_directory path
@generated_dirs[dest] = path
return path
end | [
"def",
"generate_dir",
"(",
"dest",
")",
"return",
"if",
"@generated_dirs",
".",
"has_key?",
"(",
"dest",
")",
"path",
"=",
"interpolate",
"(",
"dest",
")",
"empty_directory",
"path",
"@generated_dirs",
"[",
"dest",
"]",
"=",
"path",
"return",
"path",
"end"
]
| Generates an empty directory.
@param [String] dest
The uninterpolated destination path.
@return [String]
The destination path of the directory.
@since 0.7.1 | [
"Generates",
"an",
"empty",
"directory",
"."
]
| 585c98027771fd118041e90bb38295983d67166c | https://github.com/ruby-ore/ore/blob/585c98027771fd118041e90bb38295983d67166c/lib/ore/actions.rb#L38-L46 | train |
ruby-ore/ore | lib/ore/actions.rb | Ore.Actions.generate_file | def generate_file(dest,file,options={})
return if @generated_files.has_key?(dest)
path = interpolate(dest)
if options[:template]
@current_template_dir = File.dirname(dest)
template file, path
@current_template_dir = nil
else
copy_file file, path
end
@generated_files[dest] = path
return path
end | ruby | def generate_file(dest,file,options={})
return if @generated_files.has_key?(dest)
path = interpolate(dest)
if options[:template]
@current_template_dir = File.dirname(dest)
template file, path
@current_template_dir = nil
else
copy_file file, path
end
@generated_files[dest] = path
return path
end | [
"def",
"generate_file",
"(",
"dest",
",",
"file",
",",
"options",
"=",
"{",
"}",
")",
"return",
"if",
"@generated_files",
".",
"has_key?",
"(",
"dest",
")",
"path",
"=",
"interpolate",
"(",
"dest",
")",
"if",
"options",
"[",
":template",
"]",
"@current_template_dir",
"=",
"File",
".",
"dirname",
"(",
"dest",
")",
"template",
"file",
",",
"path",
"@current_template_dir",
"=",
"nil",
"else",
"copy_file",
"file",
",",
"path",
"end",
"@generated_files",
"[",
"dest",
"]",
"=",
"path",
"return",
"path",
"end"
]
| Generates a file.
@param [String] dest
The uninterpolated destination path.
@param [String] file
The source file or template.
@param [Hash] options
Additional options.
@option options [Boolean] :template
Specifies that the file is a template, and should be rendered.
@return [String]
The destination path of the file.
@since 0.7.1 | [
"Generates",
"a",
"file",
"."
]
| 585c98027771fd118041e90bb38295983d67166c | https://github.com/ruby-ore/ore/blob/585c98027771fd118041e90bb38295983d67166c/lib/ore/actions.rb#L68-L83 | train |
instructure/moodle2cc | lib/moodle2cc/moodle2converter/migrator.rb | Moodle2CC::Moodle2Converter.Migrator.convert_assessments | def convert_assessments(quizzes, choices, feedbacks, questionnaires)
assessment_converter = Moodle2CC::Moodle2Converter::AssessmentConverter.new
assessments = []
assessments += quizzes.map { |quiz| assessment_converter.convert_quiz(quiz) }
assessments += choices.map { |choice| assessment_converter.convert_choice(choice) }
assessments += feedbacks.map { |feedback| assessment_converter.convert_feedback(feedback) }
assessments += questionnaires.map { |questionnaire| assessment_converter.convert_questionnaire(questionnaire) }
assessments
end | ruby | def convert_assessments(quizzes, choices, feedbacks, questionnaires)
assessment_converter = Moodle2CC::Moodle2Converter::AssessmentConverter.new
assessments = []
assessments += quizzes.map { |quiz| assessment_converter.convert_quiz(quiz) }
assessments += choices.map { |choice| assessment_converter.convert_choice(choice) }
assessments += feedbacks.map { |feedback| assessment_converter.convert_feedback(feedback) }
assessments += questionnaires.map { |questionnaire| assessment_converter.convert_questionnaire(questionnaire) }
assessments
end | [
"def",
"convert_assessments",
"(",
"quizzes",
",",
"choices",
",",
"feedbacks",
",",
"questionnaires",
")",
"assessment_converter",
"=",
"Moodle2CC",
"::",
"Moodle2Converter",
"::",
"AssessmentConverter",
".",
"new",
"assessments",
"=",
"[",
"]",
"assessments",
"+=",
"quizzes",
".",
"map",
"{",
"|",
"quiz",
"|",
"assessment_converter",
".",
"convert_quiz",
"(",
"quiz",
")",
"}",
"assessments",
"+=",
"choices",
".",
"map",
"{",
"|",
"choice",
"|",
"assessment_converter",
".",
"convert_choice",
"(",
"choice",
")",
"}",
"assessments",
"+=",
"feedbacks",
".",
"map",
"{",
"|",
"feedback",
"|",
"assessment_converter",
".",
"convert_feedback",
"(",
"feedback",
")",
"}",
"assessments",
"+=",
"questionnaires",
".",
"map",
"{",
"|",
"questionnaire",
"|",
"assessment_converter",
".",
"convert_questionnaire",
"(",
"questionnaire",
")",
"}",
"assessments",
"end"
]
| convert quizzes to assessments | [
"convert",
"quizzes",
"to",
"assessments"
]
| cdb1666a76b22e87e8853d4045e31439244cce4b | https://github.com/instructure/moodle2cc/blob/cdb1666a76b22e87e8853d4045e31439244cce4b/lib/moodle2cc/moodle2converter/migrator.rb#L114-L122 | train |
instructure/moodle2cc | lib/moodle2cc/moodle2converter/migrator.rb | Moodle2CC::Moodle2Converter.Migrator.convert_question_banks | def convert_question_banks(question_categories)
bank_converter = Moodle2CC::Moodle2Converter::QuestionBankConverter.new
question_categories.map { |category| bank_converter.convert(category) }
end | ruby | def convert_question_banks(question_categories)
bank_converter = Moodle2CC::Moodle2Converter::QuestionBankConverter.new
question_categories.map { |category| bank_converter.convert(category) }
end | [
"def",
"convert_question_banks",
"(",
"question_categories",
")",
"bank_converter",
"=",
"Moodle2CC",
"::",
"Moodle2Converter",
"::",
"QuestionBankConverter",
".",
"new",
"question_categories",
".",
"map",
"{",
"|",
"category",
"|",
"bank_converter",
".",
"convert",
"(",
"category",
")",
"}",
"end"
]
| convert question categories to question banks | [
"convert",
"question",
"categories",
"to",
"question",
"banks"
]
| cdb1666a76b22e87e8853d4045e31439244cce4b | https://github.com/instructure/moodle2cc/blob/cdb1666a76b22e87e8853d4045e31439244cce4b/lib/moodle2cc/moodle2converter/migrator.rb#L125-L128 | train |
zl4bv/packer-client | lib/packer/client.rb | Packer.Client.build | def build(template, options = {})
args = ['build', '-machine-readable']
args << '-force' if options.key?(:force)
args << "-except=#{options[:except].join(',')}" if options.key?(:except)
args << "-only=#{options[:only].join(',')}" if options.key?(:only)
args << "-parallel=#{options[:parallel]}" if options.key?(:parallel)
args << "-var-file=#{options[:var_file]}" if options.key?(:var_file)
vars = options[:vars] || {}
vars.each { |key, val| args << "-var '#{key}=#{val}'" }
args << template
Packer::Output::Build.new(
command(args, options[:live_stream]))
end | ruby | def build(template, options = {})
args = ['build', '-machine-readable']
args << '-force' if options.key?(:force)
args << "-except=#{options[:except].join(',')}" if options.key?(:except)
args << "-only=#{options[:only].join(',')}" if options.key?(:only)
args << "-parallel=#{options[:parallel]}" if options.key?(:parallel)
args << "-var-file=#{options[:var_file]}" if options.key?(:var_file)
vars = options[:vars] || {}
vars.each { |key, val| args << "-var '#{key}=#{val}'" }
args << template
Packer::Output::Build.new(
command(args, options[:live_stream]))
end | [
"def",
"build",
"(",
"template",
",",
"options",
"=",
"{",
"}",
")",
"args",
"=",
"[",
"'build'",
",",
"'-machine-readable'",
"]",
"args",
"<<",
"'-force'",
"if",
"options",
".",
"key?",
"(",
":force",
")",
"args",
"<<",
"\"-except=#{options[:except].join(',')}\"",
"if",
"options",
".",
"key?",
"(",
":except",
")",
"args",
"<<",
"\"-only=#{options[:only].join(',')}\"",
"if",
"options",
".",
"key?",
"(",
":only",
")",
"args",
"<<",
"\"-parallel=#{options[:parallel]}\"",
"if",
"options",
".",
"key?",
"(",
":parallel",
")",
"args",
"<<",
"\"-var-file=#{options[:var_file]}\"",
"if",
"options",
".",
"key?",
"(",
":var_file",
")",
"vars",
"=",
"options",
"[",
":vars",
"]",
"||",
"{",
"}",
"vars",
".",
"each",
"{",
"|",
"key",
",",
"val",
"|",
"args",
"<<",
"\"-var '#{key}=#{val}'\"",
"}",
"args",
"<<",
"template",
"Packer",
"::",
"Output",
"::",
"Build",
".",
"new",
"(",
"command",
"(",
"args",
",",
"options",
"[",
":live_stream",
"]",
")",
")",
"end"
]
| Executes +packer build+.
Will execute multiple builds in parallel as defined in the template.
The various artifacts created by the template will be outputted.
@param [String,Packer::Template] template the Packer template
@param [Hash] options
@option options [Boolean] :force force a build to continue if artifacts
exist, deletes existing artifacts
@option options [Array<String>] :except build all builds other than
these
@option options [Array<String>] :only only build the given builds by
name
@option options [Boolean] :parallel disable parallelization (on by
default)
@option options [Hash] :vars variables for templates
@option options [String] :var_file path to JSON file containing user
variables
@option options [IO] :live_stream an IO object to stream packer output to
in addition to saving output in the output object.
@return [Packer::Output::Build] | [
"Executes",
"+",
"packer",
"build",
"+",
"."
]
| e925f03572425ffeaa9901d8014b445cdea64f9f | https://github.com/zl4bv/packer-client/blob/e925f03572425ffeaa9901d8014b445cdea64f9f/lib/packer/client.rb#L32-L47 | train |
zl4bv/packer-client | lib/packer/client.rb | Packer.Client.inspect_template | def inspect_template(template)
args = ['inspect', '-machine-readable', template]
Packer::Output::Inspect.new(command(args))
end | ruby | def inspect_template(template)
args = ['inspect', '-machine-readable', template]
Packer::Output::Inspect.new(command(args))
end | [
"def",
"inspect_template",
"(",
"template",
")",
"args",
"=",
"[",
"'inspect'",
",",
"'-machine-readable'",
",",
"template",
"]",
"Packer",
"::",
"Output",
"::",
"Inspect",
".",
"new",
"(",
"command",
"(",
"args",
")",
")",
"end"
]
| Excutes +packer inspect+
Inspects a template, parsing and outputting the components a template
defines. This does not validate the contents of a template (other than
basic syntax by necessity).
@param [String,Packer::Template] template the Packer template
@return [Packer::Output::Inspect] | [
"Excutes",
"+",
"packer",
"inspect",
"+"
]
| e925f03572425ffeaa9901d8014b445cdea64f9f | https://github.com/zl4bv/packer-client/blob/e925f03572425ffeaa9901d8014b445cdea64f9f/lib/packer/client.rb#L108-L112 | train |
zl4bv/packer-client | lib/packer/client.rb | Packer.Client.push | def push(template, options = {})
args = ['push']
args << "-message=#{options[:message]}" if options.key?(:message)
args << "-name=#{options[:name]}" if options.key?(:name)
args << "-token=#{options[:token]}" if options.key?(:token)
args << "-var-file=#{options[:var_file]}" if options.key?(:var_file)
vars = options[:vars] || {}
vars.each { |key, val| args << "-var '#{key}=#{val}'" }
args << template
Packer::Output::Push.new(command(args, options[:live_stream]))
end | ruby | def push(template, options = {})
args = ['push']
args << "-message=#{options[:message]}" if options.key?(:message)
args << "-name=#{options[:name]}" if options.key?(:name)
args << "-token=#{options[:token]}" if options.key?(:token)
args << "-var-file=#{options[:var_file]}" if options.key?(:var_file)
vars = options[:vars] || {}
vars.each { |key, val| args << "-var '#{key}=#{val}'" }
args << template
Packer::Output::Push.new(command(args, options[:live_stream]))
end | [
"def",
"push",
"(",
"template",
",",
"options",
"=",
"{",
"}",
")",
"args",
"=",
"[",
"'push'",
"]",
"args",
"<<",
"\"-message=#{options[:message]}\"",
"if",
"options",
".",
"key?",
"(",
":message",
")",
"args",
"<<",
"\"-name=#{options[:name]}\"",
"if",
"options",
".",
"key?",
"(",
":name",
")",
"args",
"<<",
"\"-token=#{options[:token]}\"",
"if",
"options",
".",
"key?",
"(",
":token",
")",
"args",
"<<",
"\"-var-file=#{options[:var_file]}\"",
"if",
"options",
".",
"key?",
"(",
":var_file",
")",
"vars",
"=",
"options",
"[",
":vars",
"]",
"||",
"{",
"}",
"vars",
".",
"each",
"{",
"|",
"key",
",",
"val",
"|",
"args",
"<<",
"\"-var '#{key}=#{val}'\"",
"}",
"args",
"<<",
"template",
"Packer",
"::",
"Output",
"::",
"Push",
".",
"new",
"(",
"command",
"(",
"args",
",",
"options",
"[",
":live_stream",
"]",
")",
")",
"end"
]
| Executes +packer push+.
Push the given template and supporting files to a Packer build service
such as Atlas.
If a build configuration for the given template does not exist, it will
be created automatically. If the build configuration already exists, a
new version will be created with this template and the supporting files.
Additional configuration options (such as Atlas server URL and files to
include) may be specified in the "push" section of the Packer template.
Please see the online documentation about these configurables.
@param [String,Packer::Template] template the Packer template
@param [Hash] options
@option options [String] :message a message to identify the purpose of
changes in this Packer template much like a VCS commit message
@option options [String] :name the destination build in Atlas. This is
in a format "username/name".
@option options [String] :token the access token to use when uploading
@option options [Hash] :vars variables for templates
@option options [String] :var_file path to JSON file containing user
variables
@option options [IO] :live_stream an IO object to stream packer output to
in addition to saving output in the output object.
@return [Packer::Output::Push] | [
"Executes",
"+",
"packer",
"push",
"+",
"."
]
| e925f03572425ffeaa9901d8014b445cdea64f9f | https://github.com/zl4bv/packer-client/blob/e925f03572425ffeaa9901d8014b445cdea64f9f/lib/packer/client.rb#L140-L153 | train |
zl4bv/packer-client | lib/packer/client.rb | Packer.Client.validate | def validate(template, options = {})
args = ['validate']
args << '-syntax-only' if options.key?(:syntax_only)
args << "-except=#{options[:except].join(',')}" if options.key?(:except)
args << "-only=#{options[:only].join(',')}" if options.key?(:only)
args << "-var-file=#{options[:var_file]}" if options.key?(:var_file)
vars = options[:vars] || {}
vars.each { |key, val| args << "-var '#{key}=#{val}'" }
args << template
Packer::Output::Validate.new(command(args, options[:live_stream]))
end | ruby | def validate(template, options = {})
args = ['validate']
args << '-syntax-only' if options.key?(:syntax_only)
args << "-except=#{options[:except].join(',')}" if options.key?(:except)
args << "-only=#{options[:only].join(',')}" if options.key?(:only)
args << "-var-file=#{options[:var_file]}" if options.key?(:var_file)
vars = options[:vars] || {}
vars.each { |key, val| args << "-var '#{key}=#{val}'" }
args << template
Packer::Output::Validate.new(command(args, options[:live_stream]))
end | [
"def",
"validate",
"(",
"template",
",",
"options",
"=",
"{",
"}",
")",
"args",
"=",
"[",
"'validate'",
"]",
"args",
"<<",
"'-syntax-only'",
"if",
"options",
".",
"key?",
"(",
":syntax_only",
")",
"args",
"<<",
"\"-except=#{options[:except].join(',')}\"",
"if",
"options",
".",
"key?",
"(",
":except",
")",
"args",
"<<",
"\"-only=#{options[:only].join(',')}\"",
"if",
"options",
".",
"key?",
"(",
":only",
")",
"args",
"<<",
"\"-var-file=#{options[:var_file]}\"",
"if",
"options",
".",
"key?",
"(",
":var_file",
")",
"vars",
"=",
"options",
"[",
":vars",
"]",
"||",
"{",
"}",
"vars",
".",
"each",
"{",
"|",
"key",
",",
"val",
"|",
"args",
"<<",
"\"-var '#{key}=#{val}'\"",
"}",
"args",
"<<",
"template",
"Packer",
"::",
"Output",
"::",
"Validate",
".",
"new",
"(",
"command",
"(",
"args",
",",
"options",
"[",
":live_stream",
"]",
")",
")",
"end"
]
| Executes +packer validate+
Checks the template is valid by parsing the template and also checking
the configuration with the various builders, provisioners, etc.
If it is not valid, the errors will be shown and the command will exit
with a non-zero exit status. If it is valid, it will exist with a zero
exist status.
@param [String,Packer::Template] template the Packer template
@param [Hash] options
@option options [Boolean] :syntax_only only check syntax. Do not verify
config of the template.
@option options [Array<String>] :except validate all builds other than
these
@option options [Array<String>] :only validate only these builds
@option options [Hash] :vars variables for templates
@option options [String] :var_file path to JSON file containing user
@option options [IO] :live_stream an IO object to stream packer output to
in addition to saving output in the output object.
variables
@return [Packer::Output::Validate] | [
"Executes",
"+",
"packer",
"validate",
"+"
]
| e925f03572425ffeaa9901d8014b445cdea64f9f | https://github.com/zl4bv/packer-client/blob/e925f03572425ffeaa9901d8014b445cdea64f9f/lib/packer/client.rb#L177-L190 | train |
cloudfoundry-attic/vcap-services-base | lib/base/snapshot_v2/snapshot_client.rb | VCAP::Services::Base::SnapshotV2.SnapshotClient.update_name | def update_name(service_id, snapshot_id, name)
return unless service_id && snapshot_id && name
verify_input_name(name)
key = self.class.redis_key(service_id)
# NOTE: idealy should watch on combination of (service_id, snapshot_id)
# but current design doesn't support such fine-grained watching.
client.watch(key)
snapshot = client.hget(redis_key(service_id), snapshot_id)
return nil unless snapshot
snapshot = Yajl::Parser.parse(snapshot)
snapshot["name"] = name
res = client.multi do
save_snapshot(service_id, snapshot)
end
unless res
raise ServiceError.new(ServiceError::REDIS_CONCURRENT_UPDATE)
end
true
end | ruby | def update_name(service_id, snapshot_id, name)
return unless service_id && snapshot_id && name
verify_input_name(name)
key = self.class.redis_key(service_id)
# NOTE: idealy should watch on combination of (service_id, snapshot_id)
# but current design doesn't support such fine-grained watching.
client.watch(key)
snapshot = client.hget(redis_key(service_id), snapshot_id)
return nil unless snapshot
snapshot = Yajl::Parser.parse(snapshot)
snapshot["name"] = name
res = client.multi do
save_snapshot(service_id, snapshot)
end
unless res
raise ServiceError.new(ServiceError::REDIS_CONCURRENT_UPDATE)
end
true
end | [
"def",
"update_name",
"(",
"service_id",
",",
"snapshot_id",
",",
"name",
")",
"return",
"unless",
"service_id",
"&&",
"snapshot_id",
"&&",
"name",
"verify_input_name",
"(",
"name",
")",
"key",
"=",
"self",
".",
"class",
".",
"redis_key",
"(",
"service_id",
")",
"client",
".",
"watch",
"(",
"key",
")",
"snapshot",
"=",
"client",
".",
"hget",
"(",
"redis_key",
"(",
"service_id",
")",
",",
"snapshot_id",
")",
"return",
"nil",
"unless",
"snapshot",
"snapshot",
"=",
"Yajl",
"::",
"Parser",
".",
"parse",
"(",
"snapshot",
")",
"snapshot",
"[",
"\"name\"",
"]",
"=",
"name",
"res",
"=",
"client",
".",
"multi",
"do",
"save_snapshot",
"(",
"service_id",
",",
"snapshot",
")",
"end",
"unless",
"res",
"raise",
"ServiceError",
".",
"new",
"(",
"ServiceError",
"::",
"REDIS_CONCURRENT_UPDATE",
")",
"end",
"true",
"end"
]
| Update the name of given snapshot.
This function is not protected by redis lock so a optimistic lock
is applied to prevent concurrent update. | [
"Update",
"the",
"name",
"of",
"given",
"snapshot",
".",
"This",
"function",
"is",
"not",
"protected",
"by",
"redis",
"lock",
"so",
"a",
"optimistic",
"lock",
"is",
"applied",
"to",
"prevent",
"concurrent",
"update",
"."
]
| bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/snapshot_v2/snapshot_client.rb#L77-L99 | train |
maetl/calyx | lib/calyx/modifiers.rb | Calyx.Modifiers.transform | def transform(name, value)
if respond_to?(name)
send(name, value)
elsif value.respond_to?(name)
value.send(name)
else
value
end
end | ruby | def transform(name, value)
if respond_to?(name)
send(name, value)
elsif value.respond_to?(name)
value.send(name)
else
value
end
end | [
"def",
"transform",
"(",
"name",
",",
"value",
")",
"if",
"respond_to?",
"(",
"name",
")",
"send",
"(",
"name",
",",
"value",
")",
"elsif",
"value",
".",
"respond_to?",
"(",
"name",
")",
"value",
".",
"send",
"(",
"name",
")",
"else",
"value",
"end",
"end"
]
| Transforms an output string by delegating to the given output function.
If a registered modifier method is not found, then delegate to the given
string function.
If an invalid modifier function is given, returns the raw input string.
@param [Symbol] name
@param [String] value
@return [String] | [
"Transforms",
"an",
"output",
"string",
"by",
"delegating",
"to",
"the",
"given",
"output",
"function",
"."
]
| 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/modifiers.rb#L14-L22 | train |
norman/squirm | lib/squirm/procedure.rb | Squirm.Procedure.load | def load
query = (arguments or self).info_sql
Squirm.exec(query, [name, schema]) do |result|
validate result
set_values_from result
end
self
end | ruby | def load
query = (arguments or self).info_sql
Squirm.exec(query, [name, schema]) do |result|
validate result
set_values_from result
end
self
end | [
"def",
"load",
"query",
"=",
"(",
"arguments",
"or",
"self",
")",
".",
"info_sql",
"Squirm",
".",
"exec",
"(",
"query",
",",
"[",
"name",
",",
"schema",
"]",
")",
"do",
"|",
"result",
"|",
"validate",
"result",
"set_values_from",
"result",
"end",
"self",
"end"
]
| Loads meta info about the stored procedure.
This action is not performed in the constructor to allow instances to
be created before a database connection has been established.
@return [Squirm::Procedure] The instance | [
"Loads",
"meta",
"info",
"about",
"the",
"stored",
"procedure",
"."
]
| bbe38ebb27d0a43c5738213aab1c41bfa7e357ea | https://github.com/norman/squirm/blob/bbe38ebb27d0a43c5738213aab1c41bfa7e357ea/lib/squirm/procedure.rb#L63-L70 | train |
norman/squirm | lib/squirm/procedure.rb | Squirm.Procedure.call | def call(*args, &block)
Squirm.exec query, arguments.format(*args) do |result|
if block_given?
yield result
elsif return_type =~ /\ASETOF/
result.to_a
else
result.getvalue(0,0)
end
end
end | ruby | def call(*args, &block)
Squirm.exec query, arguments.format(*args) do |result|
if block_given?
yield result
elsif return_type =~ /\ASETOF/
result.to_a
else
result.getvalue(0,0)
end
end
end | [
"def",
"call",
"(",
"*",
"args",
",",
"&",
"block",
")",
"Squirm",
".",
"exec",
"query",
",",
"arguments",
".",
"format",
"(",
"*",
"args",
")",
"do",
"|",
"result",
"|",
"if",
"block_given?",
"yield",
"result",
"elsif",
"return_type",
"=~",
"/",
"\\A",
"/",
"result",
".",
"to_a",
"else",
"result",
".",
"getvalue",
"(",
"0",
",",
"0",
")",
"end",
"end",
"end"
]
| Invokes the procedure. | [
"Invokes",
"the",
"procedure",
"."
]
| bbe38ebb27d0a43c5738213aab1c41bfa7e357ea | https://github.com/norman/squirm/blob/bbe38ebb27d0a43c5738213aab1c41bfa7e357ea/lib/squirm/procedure.rb#L80-L90 | train |
norman/squirm | lib/squirm/procedure.rb | Squirm.Procedure.validate | def validate(result)
if result.ntuples == 0
raise NotFound
elsif result.ntuples > 1
raise TooManyChoices
end
end | ruby | def validate(result)
if result.ntuples == 0
raise NotFound
elsif result.ntuples > 1
raise TooManyChoices
end
end | [
"def",
"validate",
"(",
"result",
")",
"if",
"result",
".",
"ntuples",
"==",
"0",
"raise",
"NotFound",
"elsif",
"result",
".",
"ntuples",
">",
"1",
"raise",
"TooManyChoices",
"end",
"end"
]
| Checks the number of values returned when looking up meta info about
the procedure.
@see #load
@see #info_sql | [
"Checks",
"the",
"number",
"of",
"values",
"returned",
"when",
"looking",
"up",
"meta",
"info",
"about",
"the",
"procedure",
"."
]
| bbe38ebb27d0a43c5738213aab1c41bfa7e357ea | https://github.com/norman/squirm/blob/bbe38ebb27d0a43c5738213aab1c41bfa7e357ea/lib/squirm/procedure.rb#L103-L109 | train |
m104/interpolate | lib/interpolate/base.rb | Interpolate.Points.merge! | def merge!(points = {})
# points must be a Hash
raise ArgumentError, "key points must be a Hash object" unless points.is_a? Hash
# ensure the points are all keyed Numeric-ally
points.each do |key, value|
raise ArgumentError, "found a point key that is not a Numeric object: #{key.inspect}" unless key.is_a? Numeric
end
@points.merge!(points)
normalize_data
self
end | ruby | def merge!(points = {})
# points must be a Hash
raise ArgumentError, "key points must be a Hash object" unless points.is_a? Hash
# ensure the points are all keyed Numeric-ally
points.each do |key, value|
raise ArgumentError, "found a point key that is not a Numeric object: #{key.inspect}" unless key.is_a? Numeric
end
@points.merge!(points)
normalize_data
self
end | [
"def",
"merge!",
"(",
"points",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"\"key points must be a Hash object\"",
"unless",
"points",
".",
"is_a?",
"Hash",
"points",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"raise",
"ArgumentError",
",",
"\"found a point key that is not a Numeric object: #{key.inspect}\"",
"unless",
"key",
".",
"is_a?",
"Numeric",
"end",
"@points",
".",
"merge!",
"(",
"points",
")",
"normalize_data",
"self",
"end"
]
| merges the given key points with the original points | [
"merges",
"the",
"given",
"key",
"points",
"with",
"the",
"original",
"points"
]
| 4f22c0237b7a08df94fb3f7e297a2c1d98188a16 | https://github.com/m104/interpolate/blob/4f22c0237b7a08df94fb3f7e297a2c1d98188a16/lib/interpolate/base.rb#L80-L91 | train |
m104/interpolate | lib/interpolate/base.rb | Interpolate.Points.at | def at(point, &block)
# obvious cases first
if @sorted.empty?
# no key points
return nil
elsif @sorted.size == 1
# one key point
return @sorted.first.last
end
# out-of-bounds cases next
if point <= @min_point
# lower than lowest key point
return @sorted.first.last
elsif point >= @max_point
# higher than highest key point
return @sorted.last.last
end
# binary search to find the right interpolation key point/value interval
left = 0
right = @sorted.length - 2 # highest point will be included
low_point = nil
low_value = nil
high_point = nil
high_value = nil
while left <= right
middle = (right - left) / 2 + left
(low_point, low_value) = @sorted[middle]
(high_point, high_value) = @sorted[middle + 1]
break if low_point <= point and point <= high_point
if point < low_point
right = middle - 1
else
left = middle + 1
end
end
# determine the balance ratio
span = high_point - low_point
balance = (point.to_f - low_point) / span
# choose and call the blending function
blend = block || @blend_with || DEFAULT_BLEND
blend.call(low_value, high_value, balance)
end | ruby | def at(point, &block)
# obvious cases first
if @sorted.empty?
# no key points
return nil
elsif @sorted.size == 1
# one key point
return @sorted.first.last
end
# out-of-bounds cases next
if point <= @min_point
# lower than lowest key point
return @sorted.first.last
elsif point >= @max_point
# higher than highest key point
return @sorted.last.last
end
# binary search to find the right interpolation key point/value interval
left = 0
right = @sorted.length - 2 # highest point will be included
low_point = nil
low_value = nil
high_point = nil
high_value = nil
while left <= right
middle = (right - left) / 2 + left
(low_point, low_value) = @sorted[middle]
(high_point, high_value) = @sorted[middle + 1]
break if low_point <= point and point <= high_point
if point < low_point
right = middle - 1
else
left = middle + 1
end
end
# determine the balance ratio
span = high_point - low_point
balance = (point.to_f - low_point) / span
# choose and call the blending function
blend = block || @blend_with || DEFAULT_BLEND
blend.call(low_value, high_value, balance)
end | [
"def",
"at",
"(",
"point",
",",
"&",
"block",
")",
"if",
"@sorted",
".",
"empty?",
"return",
"nil",
"elsif",
"@sorted",
".",
"size",
"==",
"1",
"return",
"@sorted",
".",
"first",
".",
"last",
"end",
"if",
"point",
"<=",
"@min_point",
"return",
"@sorted",
".",
"first",
".",
"last",
"elsif",
"point",
">=",
"@max_point",
"return",
"@sorted",
".",
"last",
".",
"last",
"end",
"left",
"=",
"0",
"right",
"=",
"@sorted",
".",
"length",
"-",
"2",
"low_point",
"=",
"nil",
"low_value",
"=",
"nil",
"high_point",
"=",
"nil",
"high_value",
"=",
"nil",
"while",
"left",
"<=",
"right",
"middle",
"=",
"(",
"right",
"-",
"left",
")",
"/",
"2",
"+",
"left",
"(",
"low_point",
",",
"low_value",
")",
"=",
"@sorted",
"[",
"middle",
"]",
"(",
"high_point",
",",
"high_value",
")",
"=",
"@sorted",
"[",
"middle",
"+",
"1",
"]",
"break",
"if",
"low_point",
"<=",
"point",
"and",
"point",
"<=",
"high_point",
"if",
"point",
"<",
"low_point",
"right",
"=",
"middle",
"-",
"1",
"else",
"left",
"=",
"middle",
"+",
"1",
"end",
"end",
"span",
"=",
"high_point",
"-",
"low_point",
"balance",
"=",
"(",
"point",
".",
"to_f",
"-",
"low_point",
")",
"/",
"span",
"blend",
"=",
"block",
"||",
"@blend_with",
"||",
"DEFAULT_BLEND",
"blend",
".",
"call",
"(",
"low_value",
",",
"high_value",
",",
"balance",
")",
"end"
]
| returns the interpolated value at the Numeric point specified, optionally
using a given block as the blending function
if no key points have been specified, the return value is +nil+
if one key point has been specified, the return value is the value
of that key point
if the given point falls outside the interpolation key range (lower than
the lowest key point or higher than the highest key point), the nearest
point value is used; in other words, no extrapolation is performed
otherwise, the interpolated value is calculated in accordance with the
first of:
* the given block
* the stored blending function, :blend_with
* a call to :interpolate on a key value object | [
"returns",
"the",
"interpolated",
"value",
"at",
"the",
"Numeric",
"point",
"specified",
"optionally",
"using",
"a",
"given",
"block",
"as",
"the",
"blending",
"function"
]
| 4f22c0237b7a08df94fb3f7e297a2c1d98188a16 | https://github.com/m104/interpolate/blob/4f22c0237b7a08df94fb3f7e297a2c1d98188a16/lib/interpolate/base.rb#L112-L161 | train |
instructure/moodle2cc | lib/moodle2cc/canvas_cc/models/question_bank.rb | Moodle2CC::CanvasCC::Models.QuestionBank.find_children_banks | def find_children_banks(all_banks, visited_banks=[])
visited_banks << self
children = []
sub_children = []
all_banks.each do |bank|
children << bank if bank.parent_id && bank.parent_id == self.original_id && !visited_banks.include?(bank)
end
children.each do |child|
sub_children += child.find_children_banks(all_banks, visited_banks)
end
return children + sub_children
end | ruby | def find_children_banks(all_banks, visited_banks=[])
visited_banks << self
children = []
sub_children = []
all_banks.each do |bank|
children << bank if bank.parent_id && bank.parent_id == self.original_id && !visited_banks.include?(bank)
end
children.each do |child|
sub_children += child.find_children_banks(all_banks, visited_banks)
end
return children + sub_children
end | [
"def",
"find_children_banks",
"(",
"all_banks",
",",
"visited_banks",
"=",
"[",
"]",
")",
"visited_banks",
"<<",
"self",
"children",
"=",
"[",
"]",
"sub_children",
"=",
"[",
"]",
"all_banks",
".",
"each",
"do",
"|",
"bank",
"|",
"children",
"<<",
"bank",
"if",
"bank",
".",
"parent_id",
"&&",
"bank",
".",
"parent_id",
"==",
"self",
".",
"original_id",
"&&",
"!",
"visited_banks",
".",
"include?",
"(",
"bank",
")",
"end",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"sub_children",
"+=",
"child",
".",
"find_children_banks",
"(",
"all_banks",
",",
"visited_banks",
")",
"end",
"return",
"children",
"+",
"sub_children",
"end"
]
| recursively find all banks that belong to this one | [
"recursively",
"find",
"all",
"banks",
"that",
"belong",
"to",
"this",
"one"
]
| cdb1666a76b22e87e8853d4045e31439244cce4b | https://github.com/instructure/moodle2cc/blob/cdb1666a76b22e87e8853d4045e31439244cce4b/lib/moodle2cc/canvas_cc/models/question_bank.rb#L29-L40 | train |
ruby-ore/ore | lib/ore/naming.rb | Ore.Naming.module_of | def module_of(word)
if COMMON_NAMESPACES.has_key?(word)
COMMON_NAMESPACES[word]
elsif COMMON_ABBREVIATIONS.has_key?(word)
COMMON_ABBREVIATIONS[word]
else
word.capitalize
end
end | ruby | def module_of(word)
if COMMON_NAMESPACES.has_key?(word)
COMMON_NAMESPACES[word]
elsif COMMON_ABBREVIATIONS.has_key?(word)
COMMON_ABBREVIATIONS[word]
else
word.capitalize
end
end | [
"def",
"module_of",
"(",
"word",
")",
"if",
"COMMON_NAMESPACES",
".",
"has_key?",
"(",
"word",
")",
"COMMON_NAMESPACES",
"[",
"word",
"]",
"elsif",
"COMMON_ABBREVIATIONS",
".",
"has_key?",
"(",
"word",
")",
"COMMON_ABBREVIATIONS",
"[",
"word",
"]",
"else",
"word",
".",
"capitalize",
"end",
"end"
]
| Guesses the module name for a word within a project name.
@param [String] word
The word within a project name.
@return [String]
The module name.
@since 0.1.1 | [
"Guesses",
"the",
"module",
"name",
"for",
"a",
"word",
"within",
"a",
"project",
"name",
"."
]
| 585c98027771fd118041e90bb38295983d67166c | https://github.com/ruby-ore/ore/blob/585c98027771fd118041e90bb38295983d67166c/lib/ore/naming.rb#L74-L82 | train |
ruby-ore/ore | lib/ore/naming.rb | Ore.Naming.modules_of | def modules_of(name)
names_in(name).map do |words|
words.split('_').map { |word| module_of(word) }.join
end
end | ruby | def modules_of(name)
names_in(name).map do |words|
words.split('_').map { |word| module_of(word) }.join
end
end | [
"def",
"modules_of",
"(",
"name",
")",
"names_in",
"(",
"name",
")",
".",
"map",
"do",
"|",
"words",
"|",
"words",
".",
"split",
"(",
"'_'",
")",
".",
"map",
"{",
"|",
"word",
"|",
"module_of",
"(",
"word",
")",
"}",
".",
"join",
"end",
"end"
]
| Guesses the module names from a project name.
@param [String] name
The name of the project.
@return [Array<String>]
The module names for a project. | [
"Guesses",
"the",
"module",
"names",
"from",
"a",
"project",
"name",
"."
]
| 585c98027771fd118041e90bb38295983d67166c | https://github.com/ruby-ore/ore/blob/585c98027771fd118041e90bb38295983d67166c/lib/ore/naming.rb#L93-L97 | train |
janosrusiczki/japr | lib/japr/pipeline.rb | JAPR.Pipeline.convert | def convert
@assets.each do |asset|
# Convert asset multiple times if more than one converter is found
finished = false
while finished == false
# Find a converter to use
klass = JAPR::Converter.klass(asset.filename)
# Convert asset if converter is found
if klass.nil?
finished = true
else
convert_asset(klass, asset)
end
end
end
end | ruby | def convert
@assets.each do |asset|
# Convert asset multiple times if more than one converter is found
finished = false
while finished == false
# Find a converter to use
klass = JAPR::Converter.klass(asset.filename)
# Convert asset if converter is found
if klass.nil?
finished = true
else
convert_asset(klass, asset)
end
end
end
end | [
"def",
"convert",
"@assets",
".",
"each",
"do",
"|",
"asset",
"|",
"finished",
"=",
"false",
"while",
"finished",
"==",
"false",
"klass",
"=",
"JAPR",
"::",
"Converter",
".",
"klass",
"(",
"asset",
".",
"filename",
")",
"if",
"klass",
".",
"nil?",
"finished",
"=",
"true",
"else",
"convert_asset",
"(",
"klass",
",",
"asset",
")",
"end",
"end",
"end",
"end"
]
| Convert assets based on the file extension if converter is defined | [
"Convert",
"assets",
"based",
"on",
"the",
"file",
"extension",
"if",
"converter",
"is",
"defined"
]
| fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee | https://github.com/janosrusiczki/japr/blob/fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee/lib/japr/pipeline.rb#L129-L145 | train |
janosrusiczki/japr | lib/japr/pipeline.rb | JAPR.Pipeline.bundle | def bundle
content = @assets.map(&:content).join("\n")
hash = JAPR::Pipeline.hash(@source, @manifest, @options)
@assets = [JAPR::Asset.new(content, "#{@prefix}-#{hash}#{@type}")]
end | ruby | def bundle
content = @assets.map(&:content).join("\n")
hash = JAPR::Pipeline.hash(@source, @manifest, @options)
@assets = [JAPR::Asset.new(content, "#{@prefix}-#{hash}#{@type}")]
end | [
"def",
"bundle",
"content",
"=",
"@assets",
".",
"map",
"(",
"&",
":content",
")",
".",
"join",
"(",
"\"\\n\"",
")",
"hash",
"=",
"JAPR",
"::",
"Pipeline",
".",
"hash",
"(",
"@source",
",",
"@manifest",
",",
"@options",
")",
"@assets",
"=",
"[",
"JAPR",
"::",
"Asset",
".",
"new",
"(",
"content",
",",
"\"#{@prefix}-#{hash}#{@type}\"",
")",
"]",
"end"
]
| Bundle multiple assets into a single asset | [
"Bundle",
"multiple",
"assets",
"into",
"a",
"single",
"asset"
]
| fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee | https://github.com/janosrusiczki/japr/blob/fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee/lib/japr/pipeline.rb#L167-L172 | train |
janosrusiczki/japr | lib/japr/pipeline.rb | JAPR.Pipeline.write_asset_file | def write_asset_file(directory, asset)
FileUtils.mkpath(directory) unless File.directory?(directory)
begin
# Save file to disk
File.open(File.join(directory, asset.filename), 'w') do |file|
file.write(asset.content)
end
rescue StandardError => se
puts "Asset Pipeline: Failed to save '#{asset.filename}' to " \
"disk: #{se.message}"
raise se
end
end | ruby | def write_asset_file(directory, asset)
FileUtils.mkpath(directory) unless File.directory?(directory)
begin
# Save file to disk
File.open(File.join(directory, asset.filename), 'w') do |file|
file.write(asset.content)
end
rescue StandardError => se
puts "Asset Pipeline: Failed to save '#{asset.filename}' to " \
"disk: #{se.message}"
raise se
end
end | [
"def",
"write_asset_file",
"(",
"directory",
",",
"asset",
")",
"FileUtils",
".",
"mkpath",
"(",
"directory",
")",
"unless",
"File",
".",
"directory?",
"(",
"directory",
")",
"begin",
"File",
".",
"open",
"(",
"File",
".",
"join",
"(",
"directory",
",",
"asset",
".",
"filename",
")",
",",
"'w'",
")",
"do",
"|",
"file",
"|",
"file",
".",
"write",
"(",
"asset",
".",
"content",
")",
"end",
"rescue",
"StandardError",
"=>",
"se",
"puts",
"\"Asset Pipeline: Failed to save '#{asset.filename}' to \"",
"\"disk: #{se.message}\"",
"raise",
"se",
"end",
"end"
]
| Write asset file to disk | [
"Write",
"asset",
"file",
"to",
"disk"
]
| fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee | https://github.com/janosrusiczki/japr/blob/fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee/lib/japr/pipeline.rb#L220-L232 | train |
janosrusiczki/japr | lib/japr/pipeline.rb | JAPR.Pipeline.markup | def markup
# Use display_path if defined, otherwise use output_path in url
display_path = @options['display_path'] || @options['output_path']
@html = @assets.map do |asset|
klass = JAPR::Template.klass(asset.filename)
html = klass.new(display_path, asset.filename).html unless klass.nil?
html
end.join
end | ruby | def markup
# Use display_path if defined, otherwise use output_path in url
display_path = @options['display_path'] || @options['output_path']
@html = @assets.map do |asset|
klass = JAPR::Template.klass(asset.filename)
html = klass.new(display_path, asset.filename).html unless klass.nil?
html
end.join
end | [
"def",
"markup",
"display_path",
"=",
"@options",
"[",
"'display_path'",
"]",
"||",
"@options",
"[",
"'output_path'",
"]",
"@html",
"=",
"@assets",
".",
"map",
"do",
"|",
"asset",
"|",
"klass",
"=",
"JAPR",
"::",
"Template",
".",
"klass",
"(",
"asset",
".",
"filename",
")",
"html",
"=",
"klass",
".",
"new",
"(",
"display_path",
",",
"asset",
".",
"filename",
")",
".",
"html",
"unless",
"klass",
".",
"nil?",
"html",
"end",
".",
"join",
"end"
]
| Generate html markup pointing to assets | [
"Generate",
"html",
"markup",
"pointing",
"to",
"assets"
]
| fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee | https://github.com/janosrusiczki/japr/blob/fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee/lib/japr/pipeline.rb#L235-L245 | train |
mycolorway/SeventeenMon | lib/seventeen_mon/ip.rb | SeventeenMon.IP.four_number | def four_number
@four_number ||= begin
fn = ip.split(".").map(&:to_i)
raise "ip is no valid" if fn.length != 4 || fn.any?{ |d| d < 0 || d > 255}
fn
end
end | ruby | def four_number
@four_number ||= begin
fn = ip.split(".").map(&:to_i)
raise "ip is no valid" if fn.length != 4 || fn.any?{ |d| d < 0 || d > 255}
fn
end
end | [
"def",
"four_number",
"@four_number",
"||=",
"begin",
"fn",
"=",
"ip",
".",
"split",
"(",
"\".\"",
")",
".",
"map",
"(",
"&",
":to_i",
")",
"raise",
"\"ip is no valid\"",
"if",
"fn",
".",
"length",
"!=",
"4",
"||",
"fn",
".",
"any?",
"{",
"|",
"d",
"|",
"d",
"<",
"0",
"||",
"d",
">",
"255",
"}",
"fn",
"end",
"end"
]
| Initialize IP object
== parameters:
params::
Might contain address(hostname) and protocol, or just IP
== Returns:
self | [
"Initialize",
"IP",
"object"
]
| 152e90efa4cb267dea013f31cbca24d9278185ed | https://github.com/mycolorway/SeventeenMon/blob/152e90efa4cb267dea013f31cbca24d9278185ed/lib/seventeen_mon/ip.rb#L19-L25 | train |
instructure/moodle2cc | lib/moodle2cc/cc/assignment.rb | Moodle2CC::CC.Assignment.build_meta_fields | def build_meta_fields(mod)
fields = {}
%w{mod_type assignment_type}.each do |key|
fields[key] = mod.send(key) if mod.respond_to?(key)
end
if mod.grade_item
Moodle2CC::Moodle::GradeItem::PROPERTIES.each do |key|
fields[key] = mod.grade_item.send(key) if mod.grade_item.respond_to?(key)
end
end
fields
end | ruby | def build_meta_fields(mod)
fields = {}
%w{mod_type assignment_type}.each do |key|
fields[key] = mod.send(key) if mod.respond_to?(key)
end
if mod.grade_item
Moodle2CC::Moodle::GradeItem::PROPERTIES.each do |key|
fields[key] = mod.grade_item.send(key) if mod.grade_item.respond_to?(key)
end
end
fields
end | [
"def",
"build_meta_fields",
"(",
"mod",
")",
"fields",
"=",
"{",
"}",
"%w{",
"mod_type",
"assignment_type",
"}",
".",
"each",
"do",
"|",
"key",
"|",
"fields",
"[",
"key",
"]",
"=",
"mod",
".",
"send",
"(",
"key",
")",
"if",
"mod",
".",
"respond_to?",
"(",
"key",
")",
"end",
"if",
"mod",
".",
"grade_item",
"Moodle2CC",
"::",
"Moodle",
"::",
"GradeItem",
"::",
"PROPERTIES",
".",
"each",
"do",
"|",
"key",
"|",
"fields",
"[",
"key",
"]",
"=",
"mod",
".",
"grade_item",
".",
"send",
"(",
"key",
")",
"if",
"mod",
".",
"grade_item",
".",
"respond_to?",
"(",
"key",
")",
"end",
"end",
"fields",
"end"
]
| Common Cartridge doesn't have anywhere to put assignment meta data like this
So add them as HTML meta fields in the HTML file | [
"Common",
"Cartridge",
"doesn",
"t",
"have",
"anywhere",
"to",
"put",
"assignment",
"meta",
"data",
"like",
"this",
"So",
"add",
"them",
"as",
"HTML",
"meta",
"fields",
"in",
"the",
"HTML",
"file"
]
| cdb1666a76b22e87e8853d4045e31439244cce4b | https://github.com/instructure/moodle2cc/blob/cdb1666a76b22e87e8853d4045e31439244cce4b/lib/moodle2cc/cc/assignment.rb#L18-L30 | train |
norman/squirm | lib/squirm/core.rb | Squirm.Core.connect | def connect(options = {})
return @pool = options[:pool] if options[:pool]
options = options.dup
timeout = options.delete(:timeout) || 5
pool_size = options.delete(:pool_size) || 1
@pool = Squirm::Pool.new(timeout)
pool_size.times do
conn = PGconn.open(options)
yield conn if block_given?
@pool.checkin conn
end
end | ruby | def connect(options = {})
return @pool = options[:pool] if options[:pool]
options = options.dup
timeout = options.delete(:timeout) || 5
pool_size = options.delete(:pool_size) || 1
@pool = Squirm::Pool.new(timeout)
pool_size.times do
conn = PGconn.open(options)
yield conn if block_given?
@pool.checkin conn
end
end | [
"def",
"connect",
"(",
"options",
"=",
"{",
"}",
")",
"return",
"@pool",
"=",
"options",
"[",
":pool",
"]",
"if",
"options",
"[",
":pool",
"]",
"options",
"=",
"options",
".",
"dup",
"timeout",
"=",
"options",
".",
"delete",
"(",
":timeout",
")",
"||",
"5",
"pool_size",
"=",
"options",
".",
"delete",
"(",
":pool_size",
")",
"||",
"1",
"@pool",
"=",
"Squirm",
"::",
"Pool",
".",
"new",
"(",
"timeout",
")",
"pool_size",
".",
"times",
"do",
"conn",
"=",
"PGconn",
".",
"open",
"(",
"options",
")",
"yield",
"conn",
"if",
"block_given?",
"@pool",
".",
"checkin",
"conn",
"end",
"end"
]
| Establishes a connection pool.
@param [Hash] options The connection options
@option options [String] :pool Use the given pool rather than Squirm's.
@option options [Fixnum] :timeout The pool timeout.
@option options [Fixnum] :pool_size The pool size. | [
"Establishes",
"a",
"connection",
"pool",
"."
]
| bbe38ebb27d0a43c5738213aab1c41bfa7e357ea | https://github.com/norman/squirm/blob/bbe38ebb27d0a43c5738213aab1c41bfa7e357ea/lib/squirm/core.rb#L16-L27 | train |
norman/squirm | lib/squirm/core.rb | Squirm.Core.exec | def exec(*args, &block)
if current = Thread.current[:squirm_connection]
current.exec(*args, &block)
else
use {|conn| conn.exec(*args, &block)}
end
end | ruby | def exec(*args, &block)
if current = Thread.current[:squirm_connection]
current.exec(*args, &block)
else
use {|conn| conn.exec(*args, &block)}
end
end | [
"def",
"exec",
"(",
"*",
"args",
",",
"&",
"block",
")",
"if",
"current",
"=",
"Thread",
".",
"current",
"[",
":squirm_connection",
"]",
"current",
".",
"exec",
"(",
"*",
"args",
",",
"&",
"block",
")",
"else",
"use",
"{",
"|",
"conn",
"|",
"conn",
".",
"exec",
"(",
"*",
"args",
",",
"&",
"block",
")",
"}",
"end",
"end"
]
| Executes the query and passes the result to the block you specify. | [
"Executes",
"the",
"query",
"and",
"passes",
"the",
"result",
"to",
"the",
"block",
"you",
"specify",
"."
]
| bbe38ebb27d0a43c5738213aab1c41bfa7e357ea | https://github.com/norman/squirm/blob/bbe38ebb27d0a43c5738213aab1c41bfa7e357ea/lib/squirm/core.rb#L37-L43 | train |
norman/squirm | lib/squirm/core.rb | Squirm.Core.use | def use(conn = nil)
conn_given = !!conn
conn = conn_given ? conn : @pool.checkout
begin
yield Thread.current[:squirm_connection] = conn
ensure
Thread.current[:squirm_connection] = nil
@pool.checkin conn unless conn_given
end
end | ruby | def use(conn = nil)
conn_given = !!conn
conn = conn_given ? conn : @pool.checkout
begin
yield Thread.current[:squirm_connection] = conn
ensure
Thread.current[:squirm_connection] = nil
@pool.checkin conn unless conn_given
end
end | [
"def",
"use",
"(",
"conn",
"=",
"nil",
")",
"conn_given",
"=",
"!",
"!",
"conn",
"conn",
"=",
"conn_given",
"?",
"conn",
":",
"@pool",
".",
"checkout",
"begin",
"yield",
"Thread",
".",
"current",
"[",
":squirm_connection",
"]",
"=",
"conn",
"ensure",
"Thread",
".",
"current",
"[",
":squirm_connection",
"]",
"=",
"nil",
"@pool",
".",
"checkin",
"conn",
"unless",
"conn_given",
"end",
"end"
]
| Uses a connection for all database access inside the given block. If no
connection is given, then one will be checked out from the pool for use
inside the block, and then checked back in when the method returns. | [
"Uses",
"a",
"connection",
"for",
"all",
"database",
"access",
"inside",
"the",
"given",
"block",
".",
"If",
"no",
"connection",
"is",
"given",
"then",
"one",
"will",
"be",
"checked",
"out",
"from",
"the",
"pool",
"for",
"use",
"inside",
"the",
"block",
"and",
"then",
"checked",
"back",
"in",
"when",
"the",
"method",
"returns",
"."
]
| bbe38ebb27d0a43c5738213aab1c41bfa7e357ea | https://github.com/norman/squirm/blob/bbe38ebb27d0a43c5738213aab1c41bfa7e357ea/lib/squirm/core.rb#L72-L81 | train |
cloudfoundry-attic/vcap-services-base | lib/base/job/package.rb | VCAP::Services::Base::AsyncJob.Package.manifest= | def manifest=(hash)
return unless hash
raise "Input should be Hash" unless hash.is_a? Hash
@manifest.merge! VCAP.symbolize_keys(hash)
end | ruby | def manifest=(hash)
return unless hash
raise "Input should be Hash" unless hash.is_a? Hash
@manifest.merge! VCAP.symbolize_keys(hash)
end | [
"def",
"manifest",
"=",
"(",
"hash",
")",
"return",
"unless",
"hash",
"raise",
"\"Input should be Hash\"",
"unless",
"hash",
".",
"is_a?",
"Hash",
"@manifest",
".",
"merge!",
"VCAP",
".",
"symbolize_keys",
"(",
"hash",
")",
"end"
]
| add +hash+ to manifest file. | [
"add",
"+",
"hash",
"+",
"to",
"manifest",
"file",
"."
]
| bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/job/package.rb#L42-L46 | train |
cloudfoundry-attic/vcap-services-base | lib/base/job/package.rb | VCAP::Services::Base::AsyncJob.Package.pack | def pack(force=nil)
if File.exists? @zipfile
if force
File.delete @zipfile
else
raise "File #{@zipfile} already exists."
end
end
dirname = File.dirname(@zipfile)
raise "Dir #{dirname} is not exists." unless File.exists? dirname
raise "Dir #{dirname} is not writable." unless File.writable? dirname
Zip::ZipFile.open(@zipfile, Zip::ZipFile::CREATE) do |zf|
# manifest file
zf.get_output_stream(MANIFEST_FILE) {|o| o << Yajl::Encoder.encode(@manifest)}
@files.each do |f, path|
zf.add("#{CONTENT_FOLDER}/#{f}", path)
end
end
begin
File.chmod(@filemode, @zipfile)
rescue => e
raise "Fail to change the mode of #{@zipfile} to #{@filemode.to_s(8)}: #{e}"
end
end | ruby | def pack(force=nil)
if File.exists? @zipfile
if force
File.delete @zipfile
else
raise "File #{@zipfile} already exists."
end
end
dirname = File.dirname(@zipfile)
raise "Dir #{dirname} is not exists." unless File.exists? dirname
raise "Dir #{dirname} is not writable." unless File.writable? dirname
Zip::ZipFile.open(@zipfile, Zip::ZipFile::CREATE) do |zf|
# manifest file
zf.get_output_stream(MANIFEST_FILE) {|o| o << Yajl::Encoder.encode(@manifest)}
@files.each do |f, path|
zf.add("#{CONTENT_FOLDER}/#{f}", path)
end
end
begin
File.chmod(@filemode, @zipfile)
rescue => e
raise "Fail to change the mode of #{@zipfile} to #{@filemode.to_s(8)}: #{e}"
end
end | [
"def",
"pack",
"(",
"force",
"=",
"nil",
")",
"if",
"File",
".",
"exists?",
"@zipfile",
"if",
"force",
"File",
".",
"delete",
"@zipfile",
"else",
"raise",
"\"File #{@zipfile} already exists.\"",
"end",
"end",
"dirname",
"=",
"File",
".",
"dirname",
"(",
"@zipfile",
")",
"raise",
"\"Dir #{dirname} is not exists.\"",
"unless",
"File",
".",
"exists?",
"dirname",
"raise",
"\"Dir #{dirname} is not writable.\"",
"unless",
"File",
".",
"writable?",
"dirname",
"Zip",
"::",
"ZipFile",
".",
"open",
"(",
"@zipfile",
",",
"Zip",
"::",
"ZipFile",
"::",
"CREATE",
")",
"do",
"|",
"zf",
"|",
"zf",
".",
"get_output_stream",
"(",
"MANIFEST_FILE",
")",
"{",
"|",
"o",
"|",
"o",
"<<",
"Yajl",
"::",
"Encoder",
".",
"encode",
"(",
"@manifest",
")",
"}",
"@files",
".",
"each",
"do",
"|",
"f",
",",
"path",
"|",
"zf",
".",
"add",
"(",
"\"#{CONTENT_FOLDER}/#{f}\"",
",",
"path",
")",
"end",
"end",
"begin",
"File",
".",
"chmod",
"(",
"@filemode",
",",
"@zipfile",
")",
"rescue",
"=>",
"e",
"raise",
"\"Fail to change the mode of #{@zipfile} to #{@filemode.to_s(8)}: #{e}\"",
"end",
"end"
]
| package files and manifest in +zipfile+. If +force+ is true, we'll try to delete the target +zipfile+ if it already exists. | [
"package",
"files",
"and",
"manifest",
"in",
"+",
"zipfile",
"+",
".",
"If",
"+",
"force",
"+",
"is",
"true",
"we",
"ll",
"try",
"to",
"delete",
"the",
"target",
"+",
"zipfile",
"+",
"if",
"it",
"already",
"exists",
"."
]
| bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/job/package.rb#L49-L76 | train |
cloudfoundry-attic/vcap-services-base | lib/base/job/package.rb | VCAP::Services::Base::AsyncJob.Package.unpack | def unpack path
raise "File #{@zipfile} not exists." unless File.exists? @zipfile
raise "unpack path: #{path} not found." unless Dir.exists? path
raise "unpack path: #{path} is not writable." unless File.writable? path
files = []
Zip::ZipFile.foreach(@zipfile) do |entry|
next if entry.to_s == MANIFEST_FILE
entry_name = File.basename entry.to_s
dst_path = File.join(path, entry_name)
dirname = File.dirname(dst_path)
FileUtils.mkdir_p(dirname) unless File.exists? dirname
files << dst_path
entry.extract(dst_path)
end
files.freeze
yield files if block_given?
files
rescue => e
# auto cleanup if error raised.
files.each{|f| File.delete f if File.exists? f} if files
raise ServiceError.new(ServiceError::FILE_CORRUPTED) if e.is_a? Zlib::DataError
raise e
end | ruby | def unpack path
raise "File #{@zipfile} not exists." unless File.exists? @zipfile
raise "unpack path: #{path} not found." unless Dir.exists? path
raise "unpack path: #{path} is not writable." unless File.writable? path
files = []
Zip::ZipFile.foreach(@zipfile) do |entry|
next if entry.to_s == MANIFEST_FILE
entry_name = File.basename entry.to_s
dst_path = File.join(path, entry_name)
dirname = File.dirname(dst_path)
FileUtils.mkdir_p(dirname) unless File.exists? dirname
files << dst_path
entry.extract(dst_path)
end
files.freeze
yield files if block_given?
files
rescue => e
# auto cleanup if error raised.
files.each{|f| File.delete f if File.exists? f} if files
raise ServiceError.new(ServiceError::FILE_CORRUPTED) if e.is_a? Zlib::DataError
raise e
end | [
"def",
"unpack",
"path",
"raise",
"\"File #{@zipfile} not exists.\"",
"unless",
"File",
".",
"exists?",
"@zipfile",
"raise",
"\"unpack path: #{path} not found.\"",
"unless",
"Dir",
".",
"exists?",
"path",
"raise",
"\"unpack path: #{path} is not writable.\"",
"unless",
"File",
".",
"writable?",
"path",
"files",
"=",
"[",
"]",
"Zip",
"::",
"ZipFile",
".",
"foreach",
"(",
"@zipfile",
")",
"do",
"|",
"entry",
"|",
"next",
"if",
"entry",
".",
"to_s",
"==",
"MANIFEST_FILE",
"entry_name",
"=",
"File",
".",
"basename",
"entry",
".",
"to_s",
"dst_path",
"=",
"File",
".",
"join",
"(",
"path",
",",
"entry_name",
")",
"dirname",
"=",
"File",
".",
"dirname",
"(",
"dst_path",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"dirname",
")",
"unless",
"File",
".",
"exists?",
"dirname",
"files",
"<<",
"dst_path",
"entry",
".",
"extract",
"(",
"dst_path",
")",
"end",
"files",
".",
"freeze",
"yield",
"files",
"if",
"block_given?",
"files",
"rescue",
"=>",
"e",
"files",
".",
"each",
"{",
"|",
"f",
"|",
"File",
".",
"delete",
"f",
"if",
"File",
".",
"exists?",
"f",
"}",
"if",
"files",
"raise",
"ServiceError",
".",
"new",
"(",
"ServiceError",
"::",
"FILE_CORRUPTED",
")",
"if",
"e",
".",
"is_a?",
"Zlib",
"::",
"DataError",
"raise",
"e",
"end"
]
| unpack the content to +path+ and return extraced file list. | [
"unpack",
"the",
"content",
"to",
"+",
"path",
"+",
"and",
"return",
"extraced",
"file",
"list",
"."
]
| bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/job/package.rb#L79-L102 | train |
cloudfoundry-attic/vcap-services-base | lib/base/job/package.rb | VCAP::Services::Base::AsyncJob.Package.load_manifest | def load_manifest
zf = Zip::ZipFile.open(@zipfile)
@manifest = VCAP.symbolize_keys(Yajl::Parser.parse(zf.read(MANIFEST_FILE)))
rescue Errno::ENOENT => e
raise ServiceError.new(ServiceError::BAD_SERIALIZED_DATAFILE, "request. Missing manifest.")
end | ruby | def load_manifest
zf = Zip::ZipFile.open(@zipfile)
@manifest = VCAP.symbolize_keys(Yajl::Parser.parse(zf.read(MANIFEST_FILE)))
rescue Errno::ENOENT => e
raise ServiceError.new(ServiceError::BAD_SERIALIZED_DATAFILE, "request. Missing manifest.")
end | [
"def",
"load_manifest",
"zf",
"=",
"Zip",
"::",
"ZipFile",
".",
"open",
"(",
"@zipfile",
")",
"@manifest",
"=",
"VCAP",
".",
"symbolize_keys",
"(",
"Yajl",
"::",
"Parser",
".",
"parse",
"(",
"zf",
".",
"read",
"(",
"MANIFEST_FILE",
")",
")",
")",
"rescue",
"Errno",
"::",
"ENOENT",
"=>",
"e",
"raise",
"ServiceError",
".",
"new",
"(",
"ServiceError",
"::",
"BAD_SERIALIZED_DATAFILE",
",",
"\"request. Missing manifest.\"",
")",
"end"
]
| read manifest in a zip file | [
"read",
"manifest",
"in",
"a",
"zip",
"file"
]
| bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/job/package.rb#L105-L110 | train |
maetl/calyx | lib/calyx/registry.rb | Calyx.Registry.filter | def filter(name, callable=nil, &block)
if block_given?
transforms[name.to_sym] = block
else
transforms[name.to_sym] = callable
end
end | ruby | def filter(name, callable=nil, &block)
if block_given?
transforms[name.to_sym] = block
else
transforms[name.to_sym] = callable
end
end | [
"def",
"filter",
"(",
"name",
",",
"callable",
"=",
"nil",
",",
"&",
"block",
")",
"if",
"block_given?",
"transforms",
"[",
"name",
".",
"to_sym",
"]",
"=",
"block",
"else",
"transforms",
"[",
"name",
".",
"to_sym",
"]",
"=",
"callable",
"end",
"end"
]
| Registers the given block as a string filter.
@param [Symbol] name
@yield [String]
@yieldreturn [String] | [
"Registers",
"the",
"given",
"block",
"as",
"a",
"string",
"filter",
"."
]
| 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/registry.rb#L41-L47 | train |
maetl/calyx | lib/calyx/registry.rb | Calyx.Registry.define_rule | def define_rule(name, trace, productions)
rules[name.to_sym] = Rule.new(name.to_sym, construct_rule(productions), trace)
end | ruby | def define_rule(name, trace, productions)
rules[name.to_sym] = Rule.new(name.to_sym, construct_rule(productions), trace)
end | [
"def",
"define_rule",
"(",
"name",
",",
"trace",
",",
"productions",
")",
"rules",
"[",
"name",
".",
"to_sym",
"]",
"=",
"Rule",
".",
"new",
"(",
"name",
".",
"to_sym",
",",
"construct_rule",
"(",
"productions",
")",
",",
"trace",
")",
"end"
]
| Defines a static rule in the grammar.
@param [Symbol] name
@param [Array] productions | [
"Defines",
"a",
"static",
"rule",
"in",
"the",
"grammar",
"."
]
| 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/registry.rb#L69-L71 | train |
maetl/calyx | lib/calyx/registry.rb | Calyx.Registry.define_context_rule | def define_context_rule(name, trace, productions)
productions = [productions] unless productions.is_a?(Enumerable)
context[name.to_sym] = Rule.new(name.to_sym, construct_rule(productions), trace)
end | ruby | def define_context_rule(name, trace, productions)
productions = [productions] unless productions.is_a?(Enumerable)
context[name.to_sym] = Rule.new(name.to_sym, construct_rule(productions), trace)
end | [
"def",
"define_context_rule",
"(",
"name",
",",
"trace",
",",
"productions",
")",
"productions",
"=",
"[",
"productions",
"]",
"unless",
"productions",
".",
"is_a?",
"(",
"Enumerable",
")",
"context",
"[",
"name",
".",
"to_sym",
"]",
"=",
"Rule",
".",
"new",
"(",
"name",
".",
"to_sym",
",",
"construct_rule",
"(",
"productions",
")",
",",
"trace",
")",
"end"
]
| Defines a rule in the temporary evaluation context.
@param [Symbol] name
@param [Array] productions | [
"Defines",
"a",
"rule",
"in",
"the",
"temporary",
"evaluation",
"context",
"."
]
| 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/registry.rb#L77-L80 | train |
maetl/calyx | lib/calyx/registry.rb | Calyx.Registry.expand | def expand(symbol)
expansion = rules[symbol] || context[symbol]
if expansion.nil?
if @options.strict?
raise Errors::UndefinedRule.new(@last_expansion, symbol)
else
expansion = Production::Terminal.new('')
end
end
@last_expansion = expansion
expansion
end | ruby | def expand(symbol)
expansion = rules[symbol] || context[symbol]
if expansion.nil?
if @options.strict?
raise Errors::UndefinedRule.new(@last_expansion, symbol)
else
expansion = Production::Terminal.new('')
end
end
@last_expansion = expansion
expansion
end | [
"def",
"expand",
"(",
"symbol",
")",
"expansion",
"=",
"rules",
"[",
"symbol",
"]",
"||",
"context",
"[",
"symbol",
"]",
"if",
"expansion",
".",
"nil?",
"if",
"@options",
".",
"strict?",
"raise",
"Errors",
"::",
"UndefinedRule",
".",
"new",
"(",
"@last_expansion",
",",
"symbol",
")",
"else",
"expansion",
"=",
"Production",
"::",
"Terminal",
".",
"new",
"(",
"''",
")",
"end",
"end",
"@last_expansion",
"=",
"expansion",
"expansion",
"end"
]
| Expands the given symbol to its rule.
@param [Symbol] symbol
@return [Calyx::Rule] | [
"Expands",
"the",
"given",
"symbol",
"to",
"its",
"rule",
"."
]
| 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/registry.rb#L86-L99 | train |
maetl/calyx | lib/calyx/registry.rb | Calyx.Registry.transform | def transform(name, value)
if transforms.key?(name)
transforms[name].call(value)
else
modifiers.transform(name, value)
end
end | ruby | def transform(name, value)
if transforms.key?(name)
transforms[name].call(value)
else
modifiers.transform(name, value)
end
end | [
"def",
"transform",
"(",
"name",
",",
"value",
")",
"if",
"transforms",
".",
"key?",
"(",
"name",
")",
"transforms",
"[",
"name",
"]",
".",
"call",
"(",
"value",
")",
"else",
"modifiers",
".",
"transform",
"(",
"name",
",",
"value",
")",
"end",
"end"
]
| Applies the given modifier function to the given value to transform it.
@param [Symbol] name
@param [String] value
@return [String] | [
"Applies",
"the",
"given",
"modifier",
"function",
"to",
"the",
"given",
"value",
"to",
"transform",
"it",
"."
]
| 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/registry.rb#L106-L112 | train |
maetl/calyx | lib/calyx/registry.rb | Calyx.Registry.unique_expansion | def unique_expansion(symbol)
pending = true
uniques[symbol] = [] if uniques[symbol].nil?
while pending
if uniques[symbol].size == expand(symbol).size
uniques[symbol] = []
pending = false
end
result = expand(symbol).evaluate(@options)
unless uniques[symbol].include?(result)
uniques[symbol] << result
pending = false
end
end
result
end | ruby | def unique_expansion(symbol)
pending = true
uniques[symbol] = [] if uniques[symbol].nil?
while pending
if uniques[symbol].size == expand(symbol).size
uniques[symbol] = []
pending = false
end
result = expand(symbol).evaluate(@options)
unless uniques[symbol].include?(result)
uniques[symbol] << result
pending = false
end
end
result
end | [
"def",
"unique_expansion",
"(",
"symbol",
")",
"pending",
"=",
"true",
"uniques",
"[",
"symbol",
"]",
"=",
"[",
"]",
"if",
"uniques",
"[",
"symbol",
"]",
".",
"nil?",
"while",
"pending",
"if",
"uniques",
"[",
"symbol",
"]",
".",
"size",
"==",
"expand",
"(",
"symbol",
")",
".",
"size",
"uniques",
"[",
"symbol",
"]",
"=",
"[",
"]",
"pending",
"=",
"false",
"end",
"result",
"=",
"expand",
"(",
"symbol",
")",
".",
"evaluate",
"(",
"@options",
")",
"unless",
"uniques",
"[",
"symbol",
"]",
".",
"include?",
"(",
"result",
")",
"uniques",
"[",
"symbol",
"]",
"<<",
"result",
"pending",
"=",
"false",
"end",
"end",
"result",
"end"
]
| Expands a unique rule symbol by evaluating it and checking that it hasn't
previously been selected.
@param [Symbol] symbol | [
"Expands",
"a",
"unique",
"rule",
"symbol",
"by",
"evaluating",
"it",
"and",
"checking",
"that",
"it",
"hasn",
"t",
"previously",
"been",
"selected",
"."
]
| 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/registry.rb#L126-L145 | train |
maetl/calyx | lib/calyx/registry.rb | Calyx.Registry.evaluate | def evaluate(start_symbol=:start, rules_map={})
reset_evaluation_context
rules_map.each do |key, value|
if rules.key?(key.to_sym)
raise Errors::DuplicateRule.new(key)
end
define_context_rule(key, caller_locations.last, value)
end
[start_symbol, expand(start_symbol).evaluate(@options)]
end | ruby | def evaluate(start_symbol=:start, rules_map={})
reset_evaluation_context
rules_map.each do |key, value|
if rules.key?(key.to_sym)
raise Errors::DuplicateRule.new(key)
end
define_context_rule(key, caller_locations.last, value)
end
[start_symbol, expand(start_symbol).evaluate(@options)]
end | [
"def",
"evaluate",
"(",
"start_symbol",
"=",
":start",
",",
"rules_map",
"=",
"{",
"}",
")",
"reset_evaluation_context",
"rules_map",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"rules",
".",
"key?",
"(",
"key",
".",
"to_sym",
")",
"raise",
"Errors",
"::",
"DuplicateRule",
".",
"new",
"(",
"key",
")",
"end",
"define_context_rule",
"(",
"key",
",",
"caller_locations",
".",
"last",
",",
"value",
")",
"end",
"[",
"start_symbol",
",",
"expand",
"(",
"start_symbol",
")",
".",
"evaluate",
"(",
"@options",
")",
"]",
"end"
]
| Evaluates the grammar defined in this registry, combining it with rules
from the passed in context.
Produces a syntax tree of nested list nodes.
@param [Symbol] start_symbol
@param [Hash] rules_map
@return [Array] | [
"Evaluates",
"the",
"grammar",
"defined",
"in",
"this",
"registry",
"combining",
"it",
"with",
"rules",
"from",
"the",
"passed",
"in",
"context",
"."
]
| 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/registry.rb#L165-L177 | train |
cloudfoundry-attic/vcap-services-base | lib/base/job/lock.rb | VCAP::Services::Base::AsyncJob.Lock.make_logger | def make_logger
logger = Logger.new(STDOUT)
logger.level = Logger::ERROR
logger
end | ruby | def make_logger
logger = Logger.new(STDOUT)
logger.level = Logger::ERROR
logger
end | [
"def",
"make_logger",
"logger",
"=",
"Logger",
".",
"new",
"(",
"STDOUT",
")",
"logger",
".",
"level",
"=",
"Logger",
"::",
"ERROR",
"logger",
"end"
]
| Options for lock
name - The uuid of the lock
timeout - The time that waits to acquire the lock, default 20 seconds
expiration - Lock expires in given seconds if not refreshed, default 10 seconds
logger - The logger..
ttl - The max time that a thread can acquire the lock, default 600 seconds. Lock raise +JOB_TIMEOUT+ error once the ttl is exceeded. | [
"Options",
"for",
"lock",
"name",
"-",
"The",
"uuid",
"of",
"the",
"lock",
"timeout",
"-",
"The",
"time",
"that",
"waits",
"to",
"acquire",
"the",
"lock",
"default",
"20",
"seconds",
"expiration",
"-",
"Lock",
"expires",
"in",
"given",
"seconds",
"if",
"not",
"refreshed",
"default",
"10",
"seconds",
"logger",
"-",
"The",
"logger",
"..",
"ttl",
"-",
"The",
"max",
"time",
"that",
"a",
"thread",
"can",
"acquire",
"the",
"lock",
"default",
"600",
"seconds",
".",
"Lock",
"raise",
"+",
"JOB_TIMEOUT",
"+",
"error",
"once",
"the",
"ttl",
"is",
"exceeded",
"."
]
| bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/job/lock.rb#L33-L37 | train |
cloudfoundry-attic/vcap-services-base | lib/base/asynchronous_service_gateway.rb | VCAP::Services.AsynchronousServiceGateway.validate_incoming_request | def validate_incoming_request
unless request.media_type == Rack::Mime.mime_type('.json')
error_msg = ServiceError.new(ServiceError::INVALID_CONTENT).to_hash
logger.error("Validation failure: #{error_msg.inspect}, request media type: #{request.media_type} is not json")
abort_request(error_msg)
end
unless auth_token && (auth_token == @token)
error_msg = ServiceError.new(ServiceError::NOT_AUTHORIZED).to_hash
logger.error("Validation failure: #{error_msg.inspect}, expected token: #{@token}, specified token: #{auth_token}")
abort_request(error_msg)
end
unless @handle_fetched
error_msg = ServiceError.new(ServiceError::SERVICE_UNAVAILABLE).to_hash
logger.error("Validation failure: #{error_msg.inspect}, handles not fetched")
abort_request(error_msg)
end
end | ruby | def validate_incoming_request
unless request.media_type == Rack::Mime.mime_type('.json')
error_msg = ServiceError.new(ServiceError::INVALID_CONTENT).to_hash
logger.error("Validation failure: #{error_msg.inspect}, request media type: #{request.media_type} is not json")
abort_request(error_msg)
end
unless auth_token && (auth_token == @token)
error_msg = ServiceError.new(ServiceError::NOT_AUTHORIZED).to_hash
logger.error("Validation failure: #{error_msg.inspect}, expected token: #{@token}, specified token: #{auth_token}")
abort_request(error_msg)
end
unless @handle_fetched
error_msg = ServiceError.new(ServiceError::SERVICE_UNAVAILABLE).to_hash
logger.error("Validation failure: #{error_msg.inspect}, handles not fetched")
abort_request(error_msg)
end
end | [
"def",
"validate_incoming_request",
"unless",
"request",
".",
"media_type",
"==",
"Rack",
"::",
"Mime",
".",
"mime_type",
"(",
"'.json'",
")",
"error_msg",
"=",
"ServiceError",
".",
"new",
"(",
"ServiceError",
"::",
"INVALID_CONTENT",
")",
".",
"to_hash",
"logger",
".",
"error",
"(",
"\"Validation failure: #{error_msg.inspect}, request media type: #{request.media_type} is not json\"",
")",
"abort_request",
"(",
"error_msg",
")",
"end",
"unless",
"auth_token",
"&&",
"(",
"auth_token",
"==",
"@token",
")",
"error_msg",
"=",
"ServiceError",
".",
"new",
"(",
"ServiceError",
"::",
"NOT_AUTHORIZED",
")",
".",
"to_hash",
"logger",
".",
"error",
"(",
"\"Validation failure: #{error_msg.inspect}, expected token: #{@token}, specified token: #{auth_token}\"",
")",
"abort_request",
"(",
"error_msg",
")",
"end",
"unless",
"@handle_fetched",
"error_msg",
"=",
"ServiceError",
".",
"new",
"(",
"ServiceError",
"::",
"SERVICE_UNAVAILABLE",
")",
".",
"to_hash",
"logger",
".",
"error",
"(",
"\"Validation failure: #{error_msg.inspect}, handles not fetched\"",
")",
"abort_request",
"(",
"error_msg",
")",
"end",
"end"
]
| Validate the incoming request | [
"Validate",
"the",
"incoming",
"request"
]
| bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/asynchronous_service_gateway.rb#L113-L129 | train |
cloudfoundry-attic/vcap-services-base | lib/base/snapshot_v2/snapshot.rb | VCAP::Services::Base::SnapshotV2.BaseRollbackSnapshotJob.perform | def perform
begin
required_options :service_id, :snapshot_id
@name = options["service_id"]
@snapshot_id = options["snapshot_id"]
@logger.info("Launch job: #{self.class} for #{name}")
lock = create_lock
@snapshot_files = []
lock.lock do
# extract origin files from package
dump_path = get_dump_path(name, snapshot_id)
package_file = "#{snapshot_id}.zip"
package = Package.load(File.join(dump_path, package_file))
@manifest = package.manifest
@snapshot_files = package.unpack(dump_path)
@logger.debug("Unpack files from #{package_file}: #{@snapshot_files}")
raise "Package file doesn't contain snapshot file." if @snapshot_files.empty?
result = execute
@logger.info("Results of rollback snapshot: #{result}")
completed(Yajl::Encoder.encode({:result => :ok}))
@logger.info("Complete job: #{self.class} for #{name}")
end
rescue => e
handle_error(e)
ensure
set_status({:complete_time => Time.now.to_s})
@snapshot_files.each{|f| File.delete(f) if File.exists? f} if @snapshot_files
end
end | ruby | def perform
begin
required_options :service_id, :snapshot_id
@name = options["service_id"]
@snapshot_id = options["snapshot_id"]
@logger.info("Launch job: #{self.class} for #{name}")
lock = create_lock
@snapshot_files = []
lock.lock do
# extract origin files from package
dump_path = get_dump_path(name, snapshot_id)
package_file = "#{snapshot_id}.zip"
package = Package.load(File.join(dump_path, package_file))
@manifest = package.manifest
@snapshot_files = package.unpack(dump_path)
@logger.debug("Unpack files from #{package_file}: #{@snapshot_files}")
raise "Package file doesn't contain snapshot file." if @snapshot_files.empty?
result = execute
@logger.info("Results of rollback snapshot: #{result}")
completed(Yajl::Encoder.encode({:result => :ok}))
@logger.info("Complete job: #{self.class} for #{name}")
end
rescue => e
handle_error(e)
ensure
set_status({:complete_time => Time.now.to_s})
@snapshot_files.each{|f| File.delete(f) if File.exists? f} if @snapshot_files
end
end | [
"def",
"perform",
"begin",
"required_options",
":service_id",
",",
":snapshot_id",
"@name",
"=",
"options",
"[",
"\"service_id\"",
"]",
"@snapshot_id",
"=",
"options",
"[",
"\"snapshot_id\"",
"]",
"@logger",
".",
"info",
"(",
"\"Launch job: #{self.class} for #{name}\"",
")",
"lock",
"=",
"create_lock",
"@snapshot_files",
"=",
"[",
"]",
"lock",
".",
"lock",
"do",
"dump_path",
"=",
"get_dump_path",
"(",
"name",
",",
"snapshot_id",
")",
"package_file",
"=",
"\"#{snapshot_id}.zip\"",
"package",
"=",
"Package",
".",
"load",
"(",
"File",
".",
"join",
"(",
"dump_path",
",",
"package_file",
")",
")",
"@manifest",
"=",
"package",
".",
"manifest",
"@snapshot_files",
"=",
"package",
".",
"unpack",
"(",
"dump_path",
")",
"@logger",
".",
"debug",
"(",
"\"Unpack files from #{package_file}: #{@snapshot_files}\"",
")",
"raise",
"\"Package file doesn't contain snapshot file.\"",
"if",
"@snapshot_files",
".",
"empty?",
"result",
"=",
"execute",
"@logger",
".",
"info",
"(",
"\"Results of rollback snapshot: #{result}\"",
")",
"completed",
"(",
"Yajl",
"::",
"Encoder",
".",
"encode",
"(",
"{",
":result",
"=>",
":ok",
"}",
")",
")",
"@logger",
".",
"info",
"(",
"\"Complete job: #{self.class} for #{name}\"",
")",
"end",
"rescue",
"=>",
"e",
"handle_error",
"(",
"e",
")",
"ensure",
"set_status",
"(",
"{",
":complete_time",
"=>",
"Time",
".",
"now",
".",
"to_s",
"}",
")",
"@snapshot_files",
".",
"each",
"{",
"|",
"f",
"|",
"File",
".",
"delete",
"(",
"f",
")",
"if",
"File",
".",
"exists?",
"f",
"}",
"if",
"@snapshot_files",
"end",
"end"
]
| workflow template
Subclass implement execute method which returns true for a successful rollback | [
"workflow",
"template",
"Subclass",
"implement",
"execute",
"method",
"which",
"returns",
"true",
"for",
"a",
"successful",
"rollback"
]
| bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/snapshot_v2/snapshot.rb#L193-L225 | train |
cloudfoundry-attic/vcap-services-base | lib/base/simple_aop.rb | Before.ClassMethods.enhance_method | def enhance_method(method, callbacks)
_method = (PREFIX + method.to_s).to_sym
alias_method _method, method
self.send(:define_method, method) do |*args, &blk|
[callbacks, _method].flatten.each do |callback|
break unless self.send(callback, *args, &blk)
end
end
end | ruby | def enhance_method(method, callbacks)
_method = (PREFIX + method.to_s).to_sym
alias_method _method, method
self.send(:define_method, method) do |*args, &blk|
[callbacks, _method].flatten.each do |callback|
break unless self.send(callback, *args, &blk)
end
end
end | [
"def",
"enhance_method",
"(",
"method",
",",
"callbacks",
")",
"_method",
"=",
"(",
"PREFIX",
"+",
"method",
".",
"to_s",
")",
".",
"to_sym",
"alias_method",
"_method",
",",
"method",
"self",
".",
"send",
"(",
":define_method",
",",
"method",
")",
"do",
"|",
"*",
"args",
",",
"&",
"blk",
"|",
"[",
"callbacks",
",",
"_method",
"]",
".",
"flatten",
".",
"each",
"do",
"|",
"callback",
"|",
"break",
"unless",
"self",
".",
"send",
"(",
"callback",
",",
"*",
"args",
",",
"&",
"blk",
")",
"end",
"end",
"end"
]
| enhance single method with callbacks | [
"enhance",
"single",
"method",
"with",
"callbacks"
]
| bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/simple_aop.rb#L52-L61 | train |
instructure/moodle2cc | lib/moodle2cc/moodle2converter/questionnaire_converter.rb | Moodle2CC::Moodle2Converter.QuestionnaireConverter.convert_rating_question | def convert_rating_question(moodle_question, canvas_question)
choices = create_rating_choices(moodle_question)
canvas_question.responses = []
moodle_question.choices.each_with_index do |answer, answer_idx|
response = {:id => "response#{answer_idx + 1}", :choices => []}
# add dropdown to the question text
canvas_question.material = canvas_question.material.to_s + "<p>#{answer[:content]} [#{response[:id]}]</p>"
choices.each_with_index do |choice, choice_idx|
response[:choices] << {:id => "#{moodle_question.id}_choice_#{answer_idx}_#{choice_idx}", :text => choice}
end
canvas_question.responses << response
end
end | ruby | def convert_rating_question(moodle_question, canvas_question)
choices = create_rating_choices(moodle_question)
canvas_question.responses = []
moodle_question.choices.each_with_index do |answer, answer_idx|
response = {:id => "response#{answer_idx + 1}", :choices => []}
# add dropdown to the question text
canvas_question.material = canvas_question.material.to_s + "<p>#{answer[:content]} [#{response[:id]}]</p>"
choices.each_with_index do |choice, choice_idx|
response[:choices] << {:id => "#{moodle_question.id}_choice_#{answer_idx}_#{choice_idx}", :text => choice}
end
canvas_question.responses << response
end
end | [
"def",
"convert_rating_question",
"(",
"moodle_question",
",",
"canvas_question",
")",
"choices",
"=",
"create_rating_choices",
"(",
"moodle_question",
")",
"canvas_question",
".",
"responses",
"=",
"[",
"]",
"moodle_question",
".",
"choices",
".",
"each_with_index",
"do",
"|",
"answer",
",",
"answer_idx",
"|",
"response",
"=",
"{",
":id",
"=>",
"\"response#{answer_idx + 1}\"",
",",
":choices",
"=>",
"[",
"]",
"}",
"canvas_question",
".",
"material",
"=",
"canvas_question",
".",
"material",
".",
"to_s",
"+",
"\"<p>#{answer[:content]} [#{response[:id]}]</p>\"",
"choices",
".",
"each_with_index",
"do",
"|",
"choice",
",",
"choice_idx",
"|",
"response",
"[",
":choices",
"]",
"<<",
"{",
":id",
"=>",
"\"#{moodle_question.id}_choice_#{answer_idx}_#{choice_idx}\"",
",",
":text",
"=>",
"choice",
"}",
"end",
"canvas_question",
".",
"responses",
"<<",
"response",
"end",
"end"
]
| For l..x rating questions | [
"For",
"l",
"..",
"x",
"rating",
"questions"
]
| cdb1666a76b22e87e8853d4045e31439244cce4b | https://github.com/instructure/moodle2cc/blob/cdb1666a76b22e87e8853d4045e31439244cce4b/lib/moodle2cc/moodle2converter/questionnaire_converter.rb#L72-L88 | train |
greysteil/spot-gps | lib/spot-gps/paginator.rb | SPOT.Paginator.enumerator | def enumerator
Enumerator.new do |yielder|
response = get_initial_response
loop do
items = response.records
# If there are no records, we're done
break if items.empty?
# Otherwise, iterate through the records...
items.each { |item| yielder << item }
# ...and fetch the next page
@params ||= {}
@params[:page] ||= 1
@params[:page] += 1
response = @service.list(**@params)
end
end.lazy
end | ruby | def enumerator
Enumerator.new do |yielder|
response = get_initial_response
loop do
items = response.records
# If there are no records, we're done
break if items.empty?
# Otherwise, iterate through the records...
items.each { |item| yielder << item }
# ...and fetch the next page
@params ||= {}
@params[:page] ||= 1
@params[:page] += 1
response = @service.list(**@params)
end
end.lazy
end | [
"def",
"enumerator",
"Enumerator",
".",
"new",
"do",
"|",
"yielder",
"|",
"response",
"=",
"get_initial_response",
"loop",
"do",
"items",
"=",
"response",
".",
"records",
"break",
"if",
"items",
".",
"empty?",
"items",
".",
"each",
"{",
"|",
"item",
"|",
"yielder",
"<<",
"item",
"}",
"@params",
"||=",
"{",
"}",
"@params",
"[",
":page",
"]",
"||=",
"1",
"@params",
"[",
":page",
"]",
"+=",
"1",
"response",
"=",
"@service",
".",
"list",
"(",
"**",
"@params",
")",
"end",
"end",
".",
"lazy",
"end"
]
| Get a lazy enumerable for listing data from the API | [
"Get",
"a",
"lazy",
"enumerable",
"for",
"listing",
"data",
"from",
"the",
"API"
]
| 808367da20dd9976f06cf281324566e25d6a3b35 | https://github.com/greysteil/spot-gps/blob/808367da20dd9976f06cf281324566e25d6a3b35/lib/spot-gps/paginator.rb#L10-L31 | train |
kristianmandrup/troles | lib/troles/common/api/write.rb | Troles::Common::Api.Write.static_role! | def static_role! role_name
raise ArgumentError, "Take a single role name, was: #{role_name}" if !role_name || !role_name.kind_of_label?
troles_config.add_valid_roles role_name
if set_roles role_name
define_method :static_roles? do
true
end
end
end | ruby | def static_role! role_name
raise ArgumentError, "Take a single role name, was: #{role_name}" if !role_name || !role_name.kind_of_label?
troles_config.add_valid_roles role_name
if set_roles role_name
define_method :static_roles? do
true
end
end
end | [
"def",
"static_role!",
"role_name",
"raise",
"ArgumentError",
",",
"\"Take a single role name, was: #{role_name}\"",
"if",
"!",
"role_name",
"||",
"!",
"role_name",
".",
"kind_of_label?",
"troles_config",
".",
"add_valid_roles",
"role_name",
"if",
"set_roles",
"role_name",
"define_method",
":static_roles?",
"do",
"true",
"end",
"end",
"end"
]
| Do we need a static_roles! method? I think so! | [
"Do",
"we",
"need",
"a",
"static_roles!",
"method?",
"I",
"think",
"so!"
]
| c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/troles/common/api/write.rb#L9-L17 | train |
kristianmandrup/troles | lib/troles/common/api/write.rb | Troles::Common::Api.Write.set_roles | def set_roles *roles
roles_to_set = make_valid_roles(*roles).flat_uniq
return false if !roles_to_set || roles_to_set.empty?
store.set_roles(roles_to_set)
end | ruby | def set_roles *roles
roles_to_set = make_valid_roles(*roles).flat_uniq
return false if !roles_to_set || roles_to_set.empty?
store.set_roles(roles_to_set)
end | [
"def",
"set_roles",
"*",
"roles",
"roles_to_set",
"=",
"make_valid_roles",
"(",
"*",
"roles",
")",
".",
"flat_uniq",
"return",
"false",
"if",
"!",
"roles_to_set",
"||",
"roles_to_set",
".",
"empty?",
"store",
".",
"set_roles",
"(",
"roles_to_set",
")",
"end"
]
| Sets new roles for the subject
@param [Array<Symbol>] list of role names
@return [true, false, Error] true if set ok, false if any roles were invalid, Error on some error | [
"Sets",
"new",
"roles",
"for",
"the",
"subject"
]
| c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/troles/common/api/write.rb#L51-L55 | train |
arashm/PoParser | lib/poparser/entry.rb | PoParser.Entry.untranslated? | def untranslated?
return false if obsolete? || fuzzy?
return @msgstr.map(&:str).join.empty? if @msgstr.is_a? Array
@msgstr.nil? || @msgstr.str.empty?
end | ruby | def untranslated?
return false if obsolete? || fuzzy?
return @msgstr.map(&:str).join.empty? if @msgstr.is_a? Array
@msgstr.nil? || @msgstr.str.empty?
end | [
"def",
"untranslated?",
"return",
"false",
"if",
"obsolete?",
"||",
"fuzzy?",
"return",
"@msgstr",
".",
"map",
"(",
"&",
":str",
")",
".",
"join",
".",
"empty?",
"if",
"@msgstr",
".",
"is_a?",
"Array",
"@msgstr",
".",
"nil?",
"||",
"@msgstr",
".",
"str",
".",
"empty?",
"end"
]
| Checks if the entry is untraslated
@return [Boolean] | [
"Checks",
"if",
"the",
"entry",
"is",
"untraslated"
]
| e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/entry.rb#L30-L35 | train |
arashm/PoParser | lib/poparser/entry.rb | PoParser.Entry.to_h | def to_h
instance_variables.each_with_object({}) do |label, hash|
object = instance_variable_get(label)
# If it's a plural msgstr
if object.is_a?(Array)
object.each do |entry|
hash[entry.type] = entry.to_s unless entry.nil?
end
else
hash[object.type] = object.to_s unless object.nil?
end
end
end | ruby | def to_h
instance_variables.each_with_object({}) do |label, hash|
object = instance_variable_get(label)
# If it's a plural msgstr
if object.is_a?(Array)
object.each do |entry|
hash[entry.type] = entry.to_s unless entry.nil?
end
else
hash[object.type] = object.to_s unless object.nil?
end
end
end | [
"def",
"to_h",
"instance_variables",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"label",
",",
"hash",
"|",
"object",
"=",
"instance_variable_get",
"(",
"label",
")",
"if",
"object",
".",
"is_a?",
"(",
"Array",
")",
"object",
".",
"each",
"do",
"|",
"entry",
"|",
"hash",
"[",
"entry",
".",
"type",
"]",
"=",
"entry",
".",
"to_s",
"unless",
"entry",
".",
"nil?",
"end",
"else",
"hash",
"[",
"object",
".",
"type",
"]",
"=",
"object",
".",
"to_s",
"unless",
"object",
".",
"nil?",
"end",
"end",
"end"
]
| Convert entry to a hash key value
@return [Hash] | [
"Convert",
"entry",
"to",
"a",
"hash",
"key",
"value"
]
| e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/entry.rb#L82-L94 | train |
arashm/PoParser | lib/poparser/entry.rb | PoParser.Entry.to_s | def to_s
LABELS.each_with_object([]) do |label, arr|
object = instance_variable_get("@#{label}".to_sym)
# If it's a plural msgstr
if object.is_a?(Array)
arr.push(*object.map { |entry| entry.to_s(true) }.compact)
else
arr << object.to_s(true) unless object.nil?
end
end.join
end | ruby | def to_s
LABELS.each_with_object([]) do |label, arr|
object = instance_variable_get("@#{label}".to_sym)
# If it's a plural msgstr
if object.is_a?(Array)
arr.push(*object.map { |entry| entry.to_s(true) }.compact)
else
arr << object.to_s(true) unless object.nil?
end
end.join
end | [
"def",
"to_s",
"LABELS",
".",
"each_with_object",
"(",
"[",
"]",
")",
"do",
"|",
"label",
",",
"arr",
"|",
"object",
"=",
"instance_variable_get",
"(",
"\"@#{label}\"",
".",
"to_sym",
")",
"if",
"object",
".",
"is_a?",
"(",
"Array",
")",
"arr",
".",
"push",
"(",
"*",
"object",
".",
"map",
"{",
"|",
"entry",
"|",
"entry",
".",
"to_s",
"(",
"true",
")",
"}",
".",
"compact",
")",
"else",
"arr",
"<<",
"object",
".",
"to_s",
"(",
"true",
")",
"unless",
"object",
".",
"nil?",
"end",
"end",
".",
"join",
"end"
]
| Convert entry to a string
@return [String] | [
"Convert",
"entry",
"to",
"a",
"string"
]
| e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/entry.rb#L99-L109 | train |
OnlinetoursGit/qiwi-pay | lib/qiwi-pay/payment_operation.rb | QiwiPay.PaymentOperation.params_hash | def params_hash
%i[opcode].push(*ATTRIBUTES)
.map { |a| [a, send(a).to_s] }
.to_h
.reject { |_k, v| v.nil? || v.empty? }
end | ruby | def params_hash
%i[opcode].push(*ATTRIBUTES)
.map { |a| [a, send(a).to_s] }
.to_h
.reject { |_k, v| v.nil? || v.empty? }
end | [
"def",
"params_hash",
"%i[",
"opcode",
"]",
".",
"push",
"(",
"*",
"ATTRIBUTES",
")",
".",
"map",
"{",
"|",
"a",
"|",
"[",
"a",
",",
"send",
"(",
"a",
")",
".",
"to_s",
"]",
"}",
".",
"to_h",
".",
"reject",
"{",
"|",
"_k",
",",
"v",
"|",
"v",
".",
"nil?",
"||",
"v",
".",
"empty?",
"}",
"end"
]
| Builds hash with meaningful params only
@return [Hash] | [
"Builds",
"hash",
"with",
"meaningful",
"params",
"only"
]
| 142116667248a29de523bfc0a0fd7c0224776401 | https://github.com/OnlinetoursGit/qiwi-pay/blob/142116667248a29de523bfc0a0fd7c0224776401/lib/qiwi-pay/payment_operation.rb#L88-L93 | train |
OnlinetoursGit/qiwi-pay | lib/qiwi-pay/payment_operation.rb | QiwiPay.PaymentOperation.request_params | def request_params
params_hash.tap do |params|
params[:sign] = Signature.new(params, credentials.secret).sign
end
end | ruby | def request_params
params_hash.tap do |params|
params[:sign] = Signature.new(params, credentials.secret).sign
end
end | [
"def",
"request_params",
"params_hash",
".",
"tap",
"do",
"|",
"params",
"|",
"params",
"[",
":sign",
"]",
"=",
"Signature",
".",
"new",
"(",
"params",
",",
"credentials",
".",
"secret",
")",
".",
"sign",
"end",
"end"
]
| Builds and signs request parameters
@return [Hash] | [
"Builds",
"and",
"signs",
"request",
"parameters"
]
| 142116667248a29de523bfc0a0fd7c0224776401 | https://github.com/OnlinetoursGit/qiwi-pay/blob/142116667248a29de523bfc0a0fd7c0224776401/lib/qiwi-pay/payment_operation.rb#L97-L101 | train |
kristianmandrup/troles | lib/trole/storage/base_one.rb | Trole::Storage.BaseOne.set_roles | def set_roles *roles
raise ArgumentError, "A single role strategy can only allow setting a single role, was: #{roles}" if (roles.size > 1)
set_role roles.flat_uniq.first
end | ruby | def set_roles *roles
raise ArgumentError, "A single role strategy can only allow setting a single role, was: #{roles}" if (roles.size > 1)
set_role roles.flat_uniq.first
end | [
"def",
"set_roles",
"*",
"roles",
"raise",
"ArgumentError",
",",
"\"A single role strategy can only allow setting a single role, was: #{roles}\"",
"if",
"(",
"roles",
".",
"size",
">",
"1",
")",
"set_role",
"roles",
".",
"flat_uniq",
".",
"first",
"end"
]
| saves the role for the user in the data store | [
"saves",
"the",
"role",
"for",
"the",
"user",
"in",
"the",
"data",
"store"
]
| c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/trole/storage/base_one.rb#L36-L39 | train |
kristianmandrup/troles | lib/trole/storage/bit_one.rb | Trole::Storage.BitOne.set_role | def set_role role
num = bitmask.write role
set_ds_field(num == 1 ? false : true) # boolean field in Data store
end | ruby | def set_role role
num = bitmask.write role
set_ds_field(num == 1 ? false : true) # boolean field in Data store
end | [
"def",
"set_role",
"role",
"num",
"=",
"bitmask",
".",
"write",
"role",
"set_ds_field",
"(",
"num",
"==",
"1",
"?",
"false",
":",
"true",
")",
"end"
]
| saves the role for the role subject in the data store
@param [Symbol] role name | [
"saves",
"the",
"role",
"for",
"the",
"role",
"subject",
"in",
"the",
"data",
"store"
]
| c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/trole/storage/bit_one.rb#L27-L30 | train |
OnlinetoursGit/qiwi-pay | lib/qiwi-pay/confirmation.rb | QiwiPay.Confirmation.to_h | def to_h
{}.tap do |h|
ALLOWED_PARAMS.each { |p| h[p] = send(p) }
h[:txn_status_message] = txn_status_message
h[:txn_type_message] = txn_type_message
end
end | ruby | def to_h
{}.tap do |h|
ALLOWED_PARAMS.each { |p| h[p] = send(p) }
h[:txn_status_message] = txn_status_message
h[:txn_type_message] = txn_type_message
end
end | [
"def",
"to_h",
"{",
"}",
".",
"tap",
"do",
"|",
"h",
"|",
"ALLOWED_PARAMS",
".",
"each",
"{",
"|",
"p",
"|",
"h",
"[",
"p",
"]",
"=",
"send",
"(",
"p",
")",
"}",
"h",
"[",
":txn_status_message",
"]",
"=",
"txn_status_message",
"h",
"[",
":txn_type_message",
"]",
"=",
"txn_type_message",
"end",
"end"
]
| Converts confirmation data to hash | [
"Converts",
"confirmation",
"data",
"to",
"hash"
]
| 142116667248a29de523bfc0a0fd7c0224776401 | https://github.com/OnlinetoursGit/qiwi-pay/blob/142116667248a29de523bfc0a0fd7c0224776401/lib/qiwi-pay/confirmation.rb#L128-L134 | train |
OnlinetoursGit/qiwi-pay | lib/qiwi-pay/confirmation.rb | QiwiPay.Confirmation.calculated_sign | def calculated_sign
params = SIGN_PARAMS.each_with_object({}) do |p, h|
h[p] = send(p).tap { |v| v ? v.to_s : nil }
end
Signature.new(params, @secret).sign.upcase
end | ruby | def calculated_sign
params = SIGN_PARAMS.each_with_object({}) do |p, h|
h[p] = send(p).tap { |v| v ? v.to_s : nil }
end
Signature.new(params, @secret).sign.upcase
end | [
"def",
"calculated_sign",
"params",
"=",
"SIGN_PARAMS",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"p",
",",
"h",
"|",
"h",
"[",
"p",
"]",
"=",
"send",
"(",
"p",
")",
".",
"tap",
"{",
"|",
"v",
"|",
"v",
"?",
"v",
".",
"to_s",
":",
"nil",
"}",
"end",
"Signature",
".",
"new",
"(",
"params",
",",
"@secret",
")",
".",
"sign",
".",
"upcase",
"end"
]
| Calculates signature for parameters | [
"Calculates",
"signature",
"for",
"parameters"
]
| 142116667248a29de523bfc0a0fd7c0224776401 | https://github.com/OnlinetoursGit/qiwi-pay/blob/142116667248a29de523bfc0a0fd7c0224776401/lib/qiwi-pay/confirmation.rb#L139-L144 | train |
kristianmandrup/troles | lib/trole/api/write.rb | Trole::Api.Write.set_role | def set_role new_role
value = make_valid_role new_role
return false if !value
store.set_role(value)
end | ruby | def set_role new_role
value = make_valid_role new_role
return false if !value
store.set_role(value)
end | [
"def",
"set_role",
"new_role",
"value",
"=",
"make_valid_role",
"new_role",
"return",
"false",
"if",
"!",
"value",
"store",
".",
"set_role",
"(",
"value",
")",
"end"
]
| Set the role of the subject to a new role
@param [Symbol] the role to set
@return [true, false, Error] true if ok, false if not valid, Error on some error | [
"Set",
"the",
"role",
"of",
"the",
"subject",
"to",
"a",
"new",
"role"
]
| c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/trole/api/write.rb#L12-L16 | train |
jgoizueta/float-formats | lib/float-formats/bytes.rb | Flt.Bytes.to_hex | def to_hex(sep_bytes=false)
hx = @bytes.unpack('H*')[0].upcase
if sep_bytes
sep = ""
(0...hx.size).step(2) do |i|
sep << " " unless i==0
sep << hx[i,2]
end
hx = sep
end
hx
end | ruby | def to_hex(sep_bytes=false)
hx = @bytes.unpack('H*')[0].upcase
if sep_bytes
sep = ""
(0...hx.size).step(2) do |i|
sep << " " unless i==0
sep << hx[i,2]
end
hx = sep
end
hx
end | [
"def",
"to_hex",
"(",
"sep_bytes",
"=",
"false",
")",
"hx",
"=",
"@bytes",
".",
"unpack",
"(",
"'H*'",
")",
"[",
"0",
"]",
".",
"upcase",
"if",
"sep_bytes",
"sep",
"=",
"\"\"",
"(",
"0",
"...",
"hx",
".",
"size",
")",
".",
"step",
"(",
"2",
")",
"do",
"|",
"i",
"|",
"sep",
"<<",
"\" \"",
"unless",
"i",
"==",
"0",
"sep",
"<<",
"hx",
"[",
"i",
",",
"2",
"]",
"end",
"hx",
"=",
"sep",
"end",
"hx",
"end"
]
| return an hex representation of a byte string | [
"return",
"an",
"hex",
"representation",
"of",
"a",
"byte",
"string"
]
| e73790e0439141b34e16caa779421fe1d481e0a2 | https://github.com/jgoizueta/float-formats/blob/e73790e0439141b34e16caa779421fe1d481e0a2/lib/float-formats/bytes.rb#L154-L165 | train |
jgoizueta/float-formats | lib/float-formats/bytes.rb | Flt.Bytes.reverse_byte_nibbles! | def reverse_byte_nibbles!
w = ""
w.force_encoding("BINARY") if w.respond_to?(:force_encoding)
@bytes.each_byte do |b|
w << ((b >> 4)|((b&0xF)<<4))
end
@bytes = w
__setobj__ @bytes
self
end | ruby | def reverse_byte_nibbles!
w = ""
w.force_encoding("BINARY") if w.respond_to?(:force_encoding)
@bytes.each_byte do |b|
w << ((b >> 4)|((b&0xF)<<4))
end
@bytes = w
__setobj__ @bytes
self
end | [
"def",
"reverse_byte_nibbles!",
"w",
"=",
"\"\"",
"w",
".",
"force_encoding",
"(",
"\"BINARY\"",
")",
"if",
"w",
".",
"respond_to?",
"(",
":force_encoding",
")",
"@bytes",
".",
"each_byte",
"do",
"|",
"b",
"|",
"w",
"<<",
"(",
"(",
"b",
">>",
"4",
")",
"|",
"(",
"(",
"b",
"&",
"0xF",
")",
"<<",
"4",
")",
")",
"end",
"@bytes",
"=",
"w",
"__setobj__",
"@bytes",
"self",
"end"
]
| Reverse the order of the nibbles in each byte. | [
"Reverse",
"the",
"order",
"of",
"the",
"nibbles",
"in",
"each",
"byte",
"."
]
| e73790e0439141b34e16caa779421fe1d481e0a2 | https://github.com/jgoizueta/float-formats/blob/e73790e0439141b34e16caa779421fe1d481e0a2/lib/float-formats/bytes.rb#L185-L194 | train |
jgoizueta/float-formats | lib/float-formats/bytes.rb | Flt.Bytes.reverse_byte_pairs! | def reverse_byte_pairs!
w = ""
w.force_encoding("BINARY") if w.respond_to?(:force_encoding)
([email protected]).step(2) do |i|
w << @bytes[i+1]
w << @bytes[i]
end
@bytes = w
__setobj__ @bytes
self
end | ruby | def reverse_byte_pairs!
w = ""
w.force_encoding("BINARY") if w.respond_to?(:force_encoding)
([email protected]).step(2) do |i|
w << @bytes[i+1]
w << @bytes[i]
end
@bytes = w
__setobj__ @bytes
self
end | [
"def",
"reverse_byte_pairs!",
"w",
"=",
"\"\"",
"w",
".",
"force_encoding",
"(",
"\"BINARY\"",
")",
"if",
"w",
".",
"respond_to?",
"(",
":force_encoding",
")",
"(",
"0",
"...",
"@bytes",
".",
"size",
")",
".",
"step",
"(",
"2",
")",
"do",
"|",
"i",
"|",
"w",
"<<",
"@bytes",
"[",
"i",
"+",
"1",
"]",
"w",
"<<",
"@bytes",
"[",
"i",
"]",
"end",
"@bytes",
"=",
"w",
"__setobj__",
"@bytes",
"self",
"end"
]
| reverse the order of bytes in 16-bit words | [
"reverse",
"the",
"order",
"of",
"bytes",
"in",
"16",
"-",
"bit",
"words"
]
| e73790e0439141b34e16caa779421fe1d481e0a2 | https://github.com/jgoizueta/float-formats/blob/e73790e0439141b34e16caa779421fe1d481e0a2/lib/float-formats/bytes.rb#L200-L210 | train |
jgoizueta/float-formats | lib/float-formats/bytes.rb | Flt.Bytes.to_bitfields | def to_bitfields(lens,byte_endianness=:little_endian, bits_little_endian=false)
fields = []
i = to_i(byte_endianness,bits_little_endian)
for len in lens
mask = (1<<len)-1
fields << (i&mask)
i >>= len
end
fields
end | ruby | def to_bitfields(lens,byte_endianness=:little_endian, bits_little_endian=false)
fields = []
i = to_i(byte_endianness,bits_little_endian)
for len in lens
mask = (1<<len)-1
fields << (i&mask)
i >>= len
end
fields
end | [
"def",
"to_bitfields",
"(",
"lens",
",",
"byte_endianness",
"=",
":little_endian",
",",
"bits_little_endian",
"=",
"false",
")",
"fields",
"=",
"[",
"]",
"i",
"=",
"to_i",
"(",
"byte_endianness",
",",
"bits_little_endian",
")",
"for",
"len",
"in",
"lens",
"mask",
"=",
"(",
"1",
"<<",
"len",
")",
"-",
"1",
"fields",
"<<",
"(",
"i",
"&",
"mask",
")",
"i",
">>=",
"len",
"end",
"fields",
"end"
]
| convert a byte string to separate fixed-width bit-fields as integers | [
"convert",
"a",
"byte",
"string",
"to",
"separate",
"fixed",
"-",
"width",
"bit",
"-",
"fields",
"as",
"integers"
]
| e73790e0439141b34e16caa779421fe1d481e0a2 | https://github.com/jgoizueta/float-formats/blob/e73790e0439141b34e16caa779421fe1d481e0a2/lib/float-formats/bytes.rb#L280-L289 | train |
dark-panda/activerecord-postgresql-cursors | lib/activerecord-postgresql-cursors.rb | ActiveRecord.PostgreSQLCursor.each | def each
@model.transaction do
begin
declare_cursor
if @join_dependency
rows = Array.new
last_id = nil
while row = fetch_forward
instantiated_row = @join_dependency.instantiate([row], @join_dependency.aliases).first
current_id = instantiated_row[@join_dependency.join_root.primary_key]
last_id ||= current_id
if last_id == current_id
rows << row
last_id = current_id
else
yield @join_dependency.instantiate(rows, @join_dependency.aliases).first
rows = [ row ]
end
last_id = current_id
end
if !rows.empty?
yield @join_dependency.instantiate(rows, @join_dependency.aliases).first
end
else
while row = fetch_forward
yield @model.instantiate(row)
end
end
ensure
close_cursor
end
end
nil
end | ruby | def each
@model.transaction do
begin
declare_cursor
if @join_dependency
rows = Array.new
last_id = nil
while row = fetch_forward
instantiated_row = @join_dependency.instantiate([row], @join_dependency.aliases).first
current_id = instantiated_row[@join_dependency.join_root.primary_key]
last_id ||= current_id
if last_id == current_id
rows << row
last_id = current_id
else
yield @join_dependency.instantiate(rows, @join_dependency.aliases).first
rows = [ row ]
end
last_id = current_id
end
if !rows.empty?
yield @join_dependency.instantiate(rows, @join_dependency.aliases).first
end
else
while row = fetch_forward
yield @model.instantiate(row)
end
end
ensure
close_cursor
end
end
nil
end | [
"def",
"each",
"@model",
".",
"transaction",
"do",
"begin",
"declare_cursor",
"if",
"@join_dependency",
"rows",
"=",
"Array",
".",
"new",
"last_id",
"=",
"nil",
"while",
"row",
"=",
"fetch_forward",
"instantiated_row",
"=",
"@join_dependency",
".",
"instantiate",
"(",
"[",
"row",
"]",
",",
"@join_dependency",
".",
"aliases",
")",
".",
"first",
"current_id",
"=",
"instantiated_row",
"[",
"@join_dependency",
".",
"join_root",
".",
"primary_key",
"]",
"last_id",
"||=",
"current_id",
"if",
"last_id",
"==",
"current_id",
"rows",
"<<",
"row",
"last_id",
"=",
"current_id",
"else",
"yield",
"@join_dependency",
".",
"instantiate",
"(",
"rows",
",",
"@join_dependency",
".",
"aliases",
")",
".",
"first",
"rows",
"=",
"[",
"row",
"]",
"end",
"last_id",
"=",
"current_id",
"end",
"if",
"!",
"rows",
".",
"empty?",
"yield",
"@join_dependency",
".",
"instantiate",
"(",
"rows",
",",
"@join_dependency",
".",
"aliases",
")",
".",
"first",
"end",
"else",
"while",
"row",
"=",
"fetch_forward",
"yield",
"@model",
".",
"instantiate",
"(",
"row",
")",
"end",
"end",
"ensure",
"close_cursor",
"end",
"end",
"nil",
"end"
]
| Calls block once for each record in the cursor, passing that
record as a parameter. | [
"Calls",
"block",
"once",
"for",
"each",
"record",
"in",
"the",
"cursor",
"passing",
"that",
"record",
"as",
"a",
"parameter",
"."
]
| bb727b30a853402a72ddc9c49cdd529c9b17aee2 | https://github.com/dark-panda/activerecord-postgresql-cursors/blob/bb727b30a853402a72ddc9c49cdd529c9b17aee2/lib/activerecord-postgresql-cursors.rb#L35-L71 | train |
OnlinetoursGit/qiwi-pay | lib/qiwi-pay/signature.rb | QiwiPay.Signature.map_sorted | def map_sorted(hash)
hash.keys
.sort_by(&:to_sym)
.map { |k| yield k, hash[k] }
end | ruby | def map_sorted(hash)
hash.keys
.sort_by(&:to_sym)
.map { |k| yield k, hash[k] }
end | [
"def",
"map_sorted",
"(",
"hash",
")",
"hash",
".",
"keys",
".",
"sort_by",
"(",
"&",
":to_sym",
")",
".",
"map",
"{",
"|",
"k",
"|",
"yield",
"k",
",",
"hash",
"[",
"k",
"]",
"}",
"end"
]
| Maps hash yielding key-value pairs ordered by key | [
"Maps",
"hash",
"yielding",
"key",
"-",
"value",
"pairs",
"ordered",
"by",
"key"
]
| 142116667248a29de523bfc0a0fd7c0224776401 | https://github.com/OnlinetoursGit/qiwi-pay/blob/142116667248a29de523bfc0a0fd7c0224776401/lib/qiwi-pay/signature.rb#L35-L39 | train |
arashm/PoParser | lib/poparser/header.rb | PoParser.Header.merge_to_previous_string | def merge_to_previous_string(array)
array.each_with_index do |key, index|
next unless key.length == 1
array[index - 1][1] += key[0]
array.delete_at(index)
end
end | ruby | def merge_to_previous_string(array)
array.each_with_index do |key, index|
next unless key.length == 1
array[index - 1][1] += key[0]
array.delete_at(index)
end
end | [
"def",
"merge_to_previous_string",
"(",
"array",
")",
"array",
".",
"each_with_index",
"do",
"|",
"key",
",",
"index",
"|",
"next",
"unless",
"key",
".",
"length",
"==",
"1",
"array",
"[",
"index",
"-",
"1",
"]",
"[",
"1",
"]",
"+=",
"key",
"[",
"0",
"]",
"array",
".",
"delete_at",
"(",
"index",
")",
"end",
"end"
]
| Sometimes long lines are wrapped into new lines, this function
join them back
[['a', 'b'], ['c']] #=> [['a', 'bc']] | [
"Sometimes",
"long",
"lines",
"are",
"wrapped",
"into",
"new",
"lines",
"this",
"function",
"join",
"them",
"back"
]
| e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/header.rb#L111-L118 | train |
greysteil/spot-gps | lib/spot-gps/api_service.rb | SPOT.ApiService.get | def get(path:, params: {})
params ||= {}
if feed_password && !feed_password.empty?
params = params.merge(feedPassword: feed_password)
end
response = make_request(:get, path, params)
SPOT::ApiResponse.new(response)
end | ruby | def get(path:, params: {})
params ||= {}
if feed_password && !feed_password.empty?
params = params.merge(feedPassword: feed_password)
end
response = make_request(:get, path, params)
SPOT::ApiResponse.new(response)
end | [
"def",
"get",
"(",
"path",
":",
",",
"params",
":",
"{",
"}",
")",
"params",
"||=",
"{",
"}",
"if",
"feed_password",
"&&",
"!",
"feed_password",
".",
"empty?",
"params",
"=",
"params",
".",
"merge",
"(",
"feedPassword",
":",
"feed_password",
")",
"end",
"response",
"=",
"make_request",
"(",
":get",
",",
"path",
",",
"params",
")",
"SPOT",
"::",
"ApiResponse",
".",
"new",
"(",
"response",
")",
"end"
]
| Make a GET request to the SPOT API | [
"Make",
"a",
"GET",
"request",
"to",
"the",
"SPOT",
"API"
]
| 808367da20dd9976f06cf281324566e25d6a3b35 | https://github.com/greysteil/spot-gps/blob/808367da20dd9976f06cf281324566e25d6a3b35/lib/spot-gps/api_service.rb#L21-L31 | train |
kristianmandrup/troles | lib/troles/common/config.rb | Troles::Common.Config.auto_config? | def auto_config? name
return auto_config[name] if !auto_config[name].nil?
Troles::Config.auto_config?(name)
end | ruby | def auto_config? name
return auto_config[name] if !auto_config[name].nil?
Troles::Config.auto_config?(name)
end | [
"def",
"auto_config?",
"name",
"return",
"auto_config",
"[",
"name",
"]",
"if",
"!",
"auto_config",
"[",
"name",
"]",
".",
"nil?",
"Troles",
"::",
"Config",
".",
"auto_config?",
"(",
"name",
")",
"end"
]
| is a certain type of auto configuration enabled? | [
"is",
"a",
"certain",
"type",
"of",
"auto",
"configuration",
"enabled?"
]
| c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/troles/common/config.rb#L53-L56 | train |
kristianmandrup/troles | lib/troles/common/config.rb | Troles::Common.Config.main_field= | def main_field= field_name
name = field_name.to_s.alpha_numeric.to_sym
raise ArgumentException, "Not a valid field name: #{field_name}" if !valid_field_name?(name)
@main_field ||= name
end | ruby | def main_field= field_name
name = field_name.to_s.alpha_numeric.to_sym
raise ArgumentException, "Not a valid field name: #{field_name}" if !valid_field_name?(name)
@main_field ||= name
end | [
"def",
"main_field",
"=",
"field_name",
"name",
"=",
"field_name",
".",
"to_s",
".",
"alpha_numeric",
".",
"to_sym",
"raise",
"ArgumentException",
",",
"\"Not a valid field name: #{field_name}\"",
"if",
"!",
"valid_field_name?",
"(",
"name",
")",
"@main_field",
"||=",
"name",
"end"
]
| Set the main field of the behavior | [
"Set",
"the",
"main",
"field",
"of",
"the",
"behavior"
]
| c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/troles/common/config.rb#L67-L71 | train |
kristianmandrup/troles | lib/troles/adapters/mongoid/config.rb | Troles::Mongoid.Config.configure_relation | def configure_relation
case strategy
when :ref_many
has_many_for subject_class, :role, :through => join_key
belongs_to_for join_model, subject_class
belongs_to_for join_model, object_model
has_many_for role, subject_class, :through => join_key
when :embed_many
embeds_many subject_class, object_model
end
end | ruby | def configure_relation
case strategy
when :ref_many
has_many_for subject_class, :role, :through => join_key
belongs_to_for join_model, subject_class
belongs_to_for join_model, object_model
has_many_for role, subject_class, :through => join_key
when :embed_many
embeds_many subject_class, object_model
end
end | [
"def",
"configure_relation",
"case",
"strategy",
"when",
":ref_many",
"has_many_for",
"subject_class",
",",
":role",
",",
":through",
"=>",
"join_key",
"belongs_to_for",
"join_model",
",",
"subject_class",
"belongs_to_for",
"join_model",
",",
"object_model",
"has_many_for",
"role",
",",
"subject_class",
",",
":through",
"=>",
"join_key",
"when",
":embed_many",
"embeds_many",
"subject_class",
",",
"object_model",
"end",
"end"
]
| more likely, strategy should be part of configuration options directly when Config object is created! | [
"more",
"likely",
"strategy",
"should",
"be",
"part",
"of",
"configuration",
"options",
"directly",
"when",
"Config",
"object",
"is",
"created!"
]
| c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/troles/adapters/mongoid/config.rb#L9-L22 | train |
kristianmandrup/troles | lib/trole_groups/api/write.rb | TroleGroups::Api.Write.set_rolegroups | def set_rolegroups *rolegroups
rolegroups_to_set = make_valid_rolegroups(*rolegroups).flat_uniq
return false if !rolegroups_to_set || rolegroups_to_set.empty?
group_store.set_rolegroups(rolegroups_to_set)
end | ruby | def set_rolegroups *rolegroups
rolegroups_to_set = make_valid_rolegroups(*rolegroups).flat_uniq
return false if !rolegroups_to_set || rolegroups_to_set.empty?
group_store.set_rolegroups(rolegroups_to_set)
end | [
"def",
"set_rolegroups",
"*",
"rolegroups",
"rolegroups_to_set",
"=",
"make_valid_rolegroups",
"(",
"*",
"rolegroups",
")",
".",
"flat_uniq",
"return",
"false",
"if",
"!",
"rolegroups_to_set",
"||",
"rolegroups_to_set",
".",
"empty?",
"group_store",
".",
"set_rolegroups",
"(",
"rolegroups_to_set",
")",
"end"
]
| Sets new rolegroups for the subject
@param [Array<Symbol>] list of rolegroup names
@return [true, false, Error] true if set ok, false if any rolegroups were invalid, Error on some error | [
"Sets",
"new",
"rolegroups",
"for",
"the",
"subject"
]
| c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/trole_groups/api/write.rb#L35-L39 | train |
arashm/PoParser | lib/poparser/po.rb | PoParser.Po.add | def add(entry)
return import_hash(entry) if entry.is_a?(Hash)
return import_array(entry) if entry.is_a?(Array)
raise ArgumentError, 'Must be a hash or an array of hashes'
end | ruby | def add(entry)
return import_hash(entry) if entry.is_a?(Hash)
return import_array(entry) if entry.is_a?(Array)
raise ArgumentError, 'Must be a hash or an array of hashes'
end | [
"def",
"add",
"(",
"entry",
")",
"return",
"import_hash",
"(",
"entry",
")",
"if",
"entry",
".",
"is_a?",
"(",
"Hash",
")",
"return",
"import_array",
"(",
"entry",
")",
"if",
"entry",
".",
"is_a?",
"(",
"Array",
")",
"raise",
"ArgumentError",
",",
"'Must be a hash or an array of hashes'",
"end"
]
| add new entries to po file
@example
entry = {
translator_comment: 'comment',
reference: 'reference comment',
flag: 'fuzzy',
msgid: 'translatable string',
msgstr: 'translation'
}
add(entry)
@param entry [Hash, Array] a hash of entry contents or an array of hashes
@return [Po] | [
"add",
"new",
"entries",
"to",
"po",
"file"
]
| e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/po.rb#L29-L34 | train |
arashm/PoParser | lib/poparser/po.rb | PoParser.Po.delete | def delete(entry)
raise(ArgumentError, 'Must be an Entry') unless entry.is_a?(PoParser::Entry)
@entries.delete(entry)
end | ruby | def delete(entry)
raise(ArgumentError, 'Must be an Entry') unless entry.is_a?(PoParser::Entry)
@entries.delete(entry)
end | [
"def",
"delete",
"(",
"entry",
")",
"raise",
"(",
"ArgumentError",
",",
"'Must be an Entry'",
")",
"unless",
"entry",
".",
"is_a?",
"(",
"PoParser",
"::",
"Entry",
")",
"@entries",
".",
"delete",
"(",
"entry",
")",
"end"
]
| Delete entry from po file
@example
delete(entry)
@param entry [Entry] to be deleted
@return [Entry] | [
"Delete",
"entry",
"from",
"po",
"file"
]
| e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/po.rb#L45-L49 | train |
arashm/PoParser | lib/poparser/po.rb | PoParser.Po.stats | def stats
untranslated_size = untranslated.size
translated_size = translated.size
fuzzy_size = fuzzy.size
{
translated: percentage(translated_size),
untranslated: percentage(untranslated_size),
fuzzy: percentage(fuzzy_size),
}
end | ruby | def stats
untranslated_size = untranslated.size
translated_size = translated.size
fuzzy_size = fuzzy.size
{
translated: percentage(translated_size),
untranslated: percentage(untranslated_size),
fuzzy: percentage(fuzzy_size),
}
end | [
"def",
"stats",
"untranslated_size",
"=",
"untranslated",
".",
"size",
"translated_size",
"=",
"translated",
".",
"size",
"fuzzy_size",
"=",
"fuzzy",
".",
"size",
"{",
"translated",
":",
"percentage",
"(",
"translated_size",
")",
",",
"untranslated",
":",
"percentage",
"(",
"untranslated_size",
")",
",",
"fuzzy",
":",
"percentage",
"(",
"fuzzy_size",
")",
",",
"}",
"end"
]
| Shows statistics and status of the provided file in percentage.
@return [Hash] a hash of translated, untranslated and fuzzy percentages | [
"Shows",
"statistics",
"and",
"status",
"of",
"the",
"provided",
"file",
"in",
"percentage",
"."
]
| e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/po.rb#L116-L126 | train |
arashm/PoParser | lib/poparser/po.rb | PoParser.Po.save_file | def save_file
raise ArgumentError, 'Need a Path to save the file' if @path.nil?
File.open(@path, 'w') { |file| file.write(to_s) }
end | ruby | def save_file
raise ArgumentError, 'Need a Path to save the file' if @path.nil?
File.open(@path, 'w') { |file| file.write(to_s) }
end | [
"def",
"save_file",
"raise",
"ArgumentError",
",",
"'Need a Path to save the file'",
"if",
"@path",
".",
"nil?",
"File",
".",
"open",
"(",
"@path",
",",
"'w'",
")",
"{",
"|",
"file",
"|",
"file",
".",
"write",
"(",
"to_s",
")",
"}",
"end"
]
| Saves the file to the provided path | [
"Saves",
"the",
"file",
"to",
"the",
"provided",
"path"
]
| e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/po.rb#L148-L152 | train |
etagwerker/dinero_mail_ipn | lib/dinero_mail_ipn/notification_parser.rb | DineroMailIpn.NotificationParser.xsd_file | def xsd_file(filename)
xsd_file_location = File.join(DineroMailIpn.resources_path, "/validation/xsd/#{filename}")
xsd_file = File.read(xsd_file_location)
xsd_file
end | ruby | def xsd_file(filename)
xsd_file_location = File.join(DineroMailIpn.resources_path, "/validation/xsd/#{filename}")
xsd_file = File.read(xsd_file_location)
xsd_file
end | [
"def",
"xsd_file",
"(",
"filename",
")",
"xsd_file_location",
"=",
"File",
".",
"join",
"(",
"DineroMailIpn",
".",
"resources_path",
",",
"\"/validation/xsd/#{filename}\"",
")",
"xsd_file",
"=",
"File",
".",
"read",
"(",
"xsd_file_location",
")",
"xsd_file",
"end"
]
| Locates an XSD file.
@param filename [String] the XSD filename | [
"Locates",
"an",
"XSD",
"file",
"."
]
| 50d6932e5db99e34b8e521cc494e19599c009e18 | https://github.com/etagwerker/dinero_mail_ipn/blob/50d6932e5db99e34b8e521cc494e19599c009e18/lib/dinero_mail_ipn/notification_parser.rb#L53-L57 | train |
rightscale/right_git | lib/right_git/shell/default.rb | RightGit::Shell.Default.execute | def execute(cmd, options = {})
options = {
:directory => nil,
:outstream => nil,
:raise_on_failure => true,
:set_env_vars => nil,
:clear_env_vars => nil,
:logger => default_logger,
:timeout => nil,
:keep_alive_interval => nil,
:keep_alive_timeout => nil
}.merge(options)
outstream = options[:outstream]
logger = options[:logger]
if keep_alive_interval = options[:keep_alive_interval]
keep_alive_wake_time = ::Time.now + keep_alive_interval
else
keep_alive_wake_time = nil
end
if keep_alive_timeout = options[:keep_alive_timeout]
unless keep_alive_interval
raise ::ArgumentError,
':keep_alive_interval is required when using :keep_alive_timeout'
end
keep_alive_stop_time = ::Time.now + keep_alive_timeout
else
keep_alive_stop_time = nil
end
# build initial popener.
exitstatus = nil
popener = lambda do |output|
output.sync = true
loop do
# note stdout remains selectable after process dies.
if (::IO.select([output], nil, nil, 0.1) rescue nil)
if data = output.gets
if outstream
outstream << data
else
data = data.strip
unless data.empty?
logger.info(data)
# reset keep alive timer whenever we have normal output.
if keep_alive_wake_time
keep_alive_wake_time = ::Time.now + keep_alive_interval
end
end
end
else
break
end
elsif keep_alive_wake_time
now = ::Time.now
if keep_alive_stop_time && now >= keep_alive_stop_time
keep_alive_wake_time = nil
elsif now >= keep_alive_wake_time
# keep-alives go to logger, not the outstream, if any.
logger.info('.')
keep_alive_wake_time = now + keep_alive_interval
end
now = nil
end
end
end
# timeout optionally wraps popener. the timeout must happen inside of the
# IO.popen block or else it has no good effect.
if timeout = options[:timeout]
popener = lambda do |p|
lambda do |o|
::Timeout.timeout(timeout) { p.call(o) }
end
end.call(popener)
end
# build initial executioner in terms of popener.
executioner = lambda do
logger.info("+ #{cmd}")
error_msg = nil
::IO.popen("#{cmd} 2>&1", 'r') do |output|
begin
popener.call(output)
rescue ::EOFError
# done
rescue ::Timeout::Error
# kill still-running process or else popen's ensure will hang.
::Process.kill('KILL', output.pid)
# intentionally not reading last data as that could still block
# due to a child of created process inheriting stdout.
error_msg = "Execution timed out after #{options[:timeout]} seconds."
end
end
# note that a killed process may exit 0 under Windows.
exitstatus = $?.exitstatus
if 0 == exitstatus && error_msg
exitstatus = 1
end
if (exitstatus != 0 && options[:raise_on_failure])
error_msg ||= "Execution failed with exitstatus #{exitstatus}"
raise ShellError, error_msg
end
end
# configure executioner (by options) and then invoke executioner.
configure_executioner(executioner, options).call
return exitstatus
end | ruby | def execute(cmd, options = {})
options = {
:directory => nil,
:outstream => nil,
:raise_on_failure => true,
:set_env_vars => nil,
:clear_env_vars => nil,
:logger => default_logger,
:timeout => nil,
:keep_alive_interval => nil,
:keep_alive_timeout => nil
}.merge(options)
outstream = options[:outstream]
logger = options[:logger]
if keep_alive_interval = options[:keep_alive_interval]
keep_alive_wake_time = ::Time.now + keep_alive_interval
else
keep_alive_wake_time = nil
end
if keep_alive_timeout = options[:keep_alive_timeout]
unless keep_alive_interval
raise ::ArgumentError,
':keep_alive_interval is required when using :keep_alive_timeout'
end
keep_alive_stop_time = ::Time.now + keep_alive_timeout
else
keep_alive_stop_time = nil
end
# build initial popener.
exitstatus = nil
popener = lambda do |output|
output.sync = true
loop do
# note stdout remains selectable after process dies.
if (::IO.select([output], nil, nil, 0.1) rescue nil)
if data = output.gets
if outstream
outstream << data
else
data = data.strip
unless data.empty?
logger.info(data)
# reset keep alive timer whenever we have normal output.
if keep_alive_wake_time
keep_alive_wake_time = ::Time.now + keep_alive_interval
end
end
end
else
break
end
elsif keep_alive_wake_time
now = ::Time.now
if keep_alive_stop_time && now >= keep_alive_stop_time
keep_alive_wake_time = nil
elsif now >= keep_alive_wake_time
# keep-alives go to logger, not the outstream, if any.
logger.info('.')
keep_alive_wake_time = now + keep_alive_interval
end
now = nil
end
end
end
# timeout optionally wraps popener. the timeout must happen inside of the
# IO.popen block or else it has no good effect.
if timeout = options[:timeout]
popener = lambda do |p|
lambda do |o|
::Timeout.timeout(timeout) { p.call(o) }
end
end.call(popener)
end
# build initial executioner in terms of popener.
executioner = lambda do
logger.info("+ #{cmd}")
error_msg = nil
::IO.popen("#{cmd} 2>&1", 'r') do |output|
begin
popener.call(output)
rescue ::EOFError
# done
rescue ::Timeout::Error
# kill still-running process or else popen's ensure will hang.
::Process.kill('KILL', output.pid)
# intentionally not reading last data as that could still block
# due to a child of created process inheriting stdout.
error_msg = "Execution timed out after #{options[:timeout]} seconds."
end
end
# note that a killed process may exit 0 under Windows.
exitstatus = $?.exitstatus
if 0 == exitstatus && error_msg
exitstatus = 1
end
if (exitstatus != 0 && options[:raise_on_failure])
error_msg ||= "Execution failed with exitstatus #{exitstatus}"
raise ShellError, error_msg
end
end
# configure executioner (by options) and then invoke executioner.
configure_executioner(executioner, options).call
return exitstatus
end | [
"def",
"execute",
"(",
"cmd",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":directory",
"=>",
"nil",
",",
":outstream",
"=>",
"nil",
",",
":raise_on_failure",
"=>",
"true",
",",
":set_env_vars",
"=>",
"nil",
",",
":clear_env_vars",
"=>",
"nil",
",",
":logger",
"=>",
"default_logger",
",",
":timeout",
"=>",
"nil",
",",
":keep_alive_interval",
"=>",
"nil",
",",
":keep_alive_timeout",
"=>",
"nil",
"}",
".",
"merge",
"(",
"options",
")",
"outstream",
"=",
"options",
"[",
":outstream",
"]",
"logger",
"=",
"options",
"[",
":logger",
"]",
"if",
"keep_alive_interval",
"=",
"options",
"[",
":keep_alive_interval",
"]",
"keep_alive_wake_time",
"=",
"::",
"Time",
".",
"now",
"+",
"keep_alive_interval",
"else",
"keep_alive_wake_time",
"=",
"nil",
"end",
"if",
"keep_alive_timeout",
"=",
"options",
"[",
":keep_alive_timeout",
"]",
"unless",
"keep_alive_interval",
"raise",
"::",
"ArgumentError",
",",
"':keep_alive_interval is required when using :keep_alive_timeout'",
"end",
"keep_alive_stop_time",
"=",
"::",
"Time",
".",
"now",
"+",
"keep_alive_timeout",
"else",
"keep_alive_stop_time",
"=",
"nil",
"end",
"exitstatus",
"=",
"nil",
"popener",
"=",
"lambda",
"do",
"|",
"output",
"|",
"output",
".",
"sync",
"=",
"true",
"loop",
"do",
"if",
"(",
"::",
"IO",
".",
"select",
"(",
"[",
"output",
"]",
",",
"nil",
",",
"nil",
",",
"0.1",
")",
"rescue",
"nil",
")",
"if",
"data",
"=",
"output",
".",
"gets",
"if",
"outstream",
"outstream",
"<<",
"data",
"else",
"data",
"=",
"data",
".",
"strip",
"unless",
"data",
".",
"empty?",
"logger",
".",
"info",
"(",
"data",
")",
"if",
"keep_alive_wake_time",
"keep_alive_wake_time",
"=",
"::",
"Time",
".",
"now",
"+",
"keep_alive_interval",
"end",
"end",
"end",
"else",
"break",
"end",
"elsif",
"keep_alive_wake_time",
"now",
"=",
"::",
"Time",
".",
"now",
"if",
"keep_alive_stop_time",
"&&",
"now",
">=",
"keep_alive_stop_time",
"keep_alive_wake_time",
"=",
"nil",
"elsif",
"now",
">=",
"keep_alive_wake_time",
"logger",
".",
"info",
"(",
"'.'",
")",
"keep_alive_wake_time",
"=",
"now",
"+",
"keep_alive_interval",
"end",
"now",
"=",
"nil",
"end",
"end",
"end",
"if",
"timeout",
"=",
"options",
"[",
":timeout",
"]",
"popener",
"=",
"lambda",
"do",
"|",
"p",
"|",
"lambda",
"do",
"|",
"o",
"|",
"::",
"Timeout",
".",
"timeout",
"(",
"timeout",
")",
"{",
"p",
".",
"call",
"(",
"o",
")",
"}",
"end",
"end",
".",
"call",
"(",
"popener",
")",
"end",
"executioner",
"=",
"lambda",
"do",
"logger",
".",
"info",
"(",
"\"+ #{cmd}\"",
")",
"error_msg",
"=",
"nil",
"::",
"IO",
".",
"popen",
"(",
"\"#{cmd} 2>&1\"",
",",
"'r'",
")",
"do",
"|",
"output",
"|",
"begin",
"popener",
".",
"call",
"(",
"output",
")",
"rescue",
"::",
"EOFError",
"rescue",
"::",
"Timeout",
"::",
"Error",
"::",
"Process",
".",
"kill",
"(",
"'KILL'",
",",
"output",
".",
"pid",
")",
"error_msg",
"=",
"\"Execution timed out after #{options[:timeout]} seconds.\"",
"end",
"end",
"exitstatus",
"=",
"$?",
".",
"exitstatus",
"if",
"0",
"==",
"exitstatus",
"&&",
"error_msg",
"exitstatus",
"=",
"1",
"end",
"if",
"(",
"exitstatus",
"!=",
"0",
"&&",
"options",
"[",
":raise_on_failure",
"]",
")",
"error_msg",
"||=",
"\"Execution failed with exitstatus #{exitstatus}\"",
"raise",
"ShellError",
",",
"error_msg",
"end",
"end",
"configure_executioner",
"(",
"executioner",
",",
"options",
")",
".",
"call",
"return",
"exitstatus",
"end"
]
| Implements execute interface. | [
"Implements",
"execute",
"interface",
"."
]
| 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/shell/default.rb#L44-L157 | train |
rightscale/right_git | lib/right_git/shell/default.rb | RightGit::Shell.Default.output_for | def output_for(cmd, options = {})
output = StringIO.new
execute(cmd, options.merge(:outstream => output))
output.string
end | ruby | def output_for(cmd, options = {})
output = StringIO.new
execute(cmd, options.merge(:outstream => output))
output.string
end | [
"def",
"output_for",
"(",
"cmd",
",",
"options",
"=",
"{",
"}",
")",
"output",
"=",
"StringIO",
".",
"new",
"execute",
"(",
"cmd",
",",
"options",
".",
"merge",
"(",
":outstream",
"=>",
"output",
")",
")",
"output",
".",
"string",
"end"
]
| Implements output_for interface. | [
"Implements",
"output_for",
"interface",
"."
]
| 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/shell/default.rb#L160-L164 | train |
rightscale/right_git | lib/right_git/shell/default.rb | RightGit::Shell.Default.configure_executioner | def configure_executioner(executioner, options)
# set specific environment variables, if requested.
sev = options[:set_env_vars]
if (sev && !sev.empty?)
executioner = lambda do |e|
lambda { set_env_vars(sev) { e.call } }
end.call(executioner)
end
# clear specific environment variables, if requested.
cev = options[:clear_env_vars]
if (cev && !cev.empty?)
executioner = lambda do |e|
lambda { clear_env_vars(cev) { e.call } }
end.call(executioner)
end
# working directory.
if directory = options[:directory]
executioner = lambda do |e, d|
lambda { ::Dir.chdir(d) { e.call } }
end.call(executioner, directory)
end
executioner
end | ruby | def configure_executioner(executioner, options)
# set specific environment variables, if requested.
sev = options[:set_env_vars]
if (sev && !sev.empty?)
executioner = lambda do |e|
lambda { set_env_vars(sev) { e.call } }
end.call(executioner)
end
# clear specific environment variables, if requested.
cev = options[:clear_env_vars]
if (cev && !cev.empty?)
executioner = lambda do |e|
lambda { clear_env_vars(cev) { e.call } }
end.call(executioner)
end
# working directory.
if directory = options[:directory]
executioner = lambda do |e, d|
lambda { ::Dir.chdir(d) { e.call } }
end.call(executioner, directory)
end
executioner
end | [
"def",
"configure_executioner",
"(",
"executioner",
",",
"options",
")",
"sev",
"=",
"options",
"[",
":set_env_vars",
"]",
"if",
"(",
"sev",
"&&",
"!",
"sev",
".",
"empty?",
")",
"executioner",
"=",
"lambda",
"do",
"|",
"e",
"|",
"lambda",
"{",
"set_env_vars",
"(",
"sev",
")",
"{",
"e",
".",
"call",
"}",
"}",
"end",
".",
"call",
"(",
"executioner",
")",
"end",
"cev",
"=",
"options",
"[",
":clear_env_vars",
"]",
"if",
"(",
"cev",
"&&",
"!",
"cev",
".",
"empty?",
")",
"executioner",
"=",
"lambda",
"do",
"|",
"e",
"|",
"lambda",
"{",
"clear_env_vars",
"(",
"cev",
")",
"{",
"e",
".",
"call",
"}",
"}",
"end",
".",
"call",
"(",
"executioner",
")",
"end",
"if",
"directory",
"=",
"options",
"[",
":directory",
"]",
"executioner",
"=",
"lambda",
"do",
"|",
"e",
",",
"d",
"|",
"lambda",
"{",
"::",
"Dir",
".",
"chdir",
"(",
"d",
")",
"{",
"e",
".",
"call",
"}",
"}",
"end",
".",
"call",
"(",
"executioner",
",",
"directory",
")",
"end",
"executioner",
"end"
]
| Encapsulates the given executioner with child-process-modifying behavior
based on options. Builds the executioner as a series of callbacks.
@param [Proc] executioner to configure
@param [Hash] options for execution
@return [Proc] configured executioner | [
"Encapsulates",
"the",
"given",
"executioner",
"with",
"child",
"-",
"process",
"-",
"modifying",
"behavior",
"based",
"on",
"options",
".",
"Builds",
"the",
"executioner",
"as",
"a",
"series",
"of",
"callbacks",
"."
]
| 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/shell/default.rb#L173-L197 | train |
rightscale/right_git | lib/right_git/shell/default.rb | RightGit::Shell.Default.set_env_vars | def set_env_vars(variables)
save_vars = {}
variables.each do |k, v|
k = k.to_s
save_vars[k] = ENV[k]
ENV[k] = v.nil? ? v : v.to_s
end
begin
yield
ensure
variables.each_key do |k|
k = k.to_s
ENV[k] = save_vars[k]
end
end
true
end | ruby | def set_env_vars(variables)
save_vars = {}
variables.each do |k, v|
k = k.to_s
save_vars[k] = ENV[k]
ENV[k] = v.nil? ? v : v.to_s
end
begin
yield
ensure
variables.each_key do |k|
k = k.to_s
ENV[k] = save_vars[k]
end
end
true
end | [
"def",
"set_env_vars",
"(",
"variables",
")",
"save_vars",
"=",
"{",
"}",
"variables",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"k",
"=",
"k",
".",
"to_s",
"save_vars",
"[",
"k",
"]",
"=",
"ENV",
"[",
"k",
"]",
"ENV",
"[",
"k",
"]",
"=",
"v",
".",
"nil?",
"?",
"v",
":",
"v",
".",
"to_s",
"end",
"begin",
"yield",
"ensure",
"variables",
".",
"each_key",
"do",
"|",
"k",
"|",
"k",
"=",
"k",
".",
"to_s",
"ENV",
"[",
"k",
"]",
"=",
"save_vars",
"[",
"k",
"]",
"end",
"end",
"true",
"end"
]
| Sets the given list of environment variables while
executing the given block.
=== Parameters
@param [Hash] variables to set
=== Yield
@yield [] called with environment set
=== Return
@return [TrueClass] always true | [
"Sets",
"the",
"given",
"list",
"of",
"environment",
"variables",
"while",
"executing",
"the",
"given",
"block",
"."
]
| 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/shell/default.rb#L210-L226 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.