repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
jondot/version_bumper | lib/bumper/version.rb | Bumper.Version.bump_patch_tag | def bump_patch_tag tag
@v[:build] = '0' unless build.nil?
if patch_tag.nil?
@v[:patch] = patch.succ
return @v[:patch_tag] = tag
elsif patch_tag.start_with? tag
# ensure tag ends with number
if patch_tag !~ %r{\d+$}
@v[:patch_tag] = patch_tag + '1' # required for succ to work
end
# increment this tag
@v[:patch_tag] = patch_tag.succ
else
@v[:patch_tag] = tag # replace tag
end
end | ruby | def bump_patch_tag tag
@v[:build] = '0' unless build.nil?
if patch_tag.nil?
@v[:patch] = patch.succ
return @v[:patch_tag] = tag
elsif patch_tag.start_with? tag
# ensure tag ends with number
if patch_tag !~ %r{\d+$}
@v[:patch_tag] = patch_tag + '1' # required for succ to work
end
# increment this tag
@v[:patch_tag] = patch_tag.succ
else
@v[:patch_tag] = tag # replace tag
end
end | [
"def",
"bump_patch_tag",
"tag",
"@v",
"[",
":build",
"]",
"=",
"'0'",
"unless",
"build",
".",
"nil?",
"if",
"patch_tag",
".",
"nil?",
"@v",
"[",
":patch",
"]",
"=",
"patch",
".",
"succ",
"return",
"@v",
"[",
":patch_tag",
"]",
"=",
"tag",
"elsif",
"patch_tag",
".",
"start_with?",
"tag",
"if",
"patch_tag",
"!~",
"%r{",
"\\d",
"}",
"@v",
"[",
":patch_tag",
"]",
"=",
"patch_tag",
"+",
"'1'",
"end",
"@v",
"[",
":patch_tag",
"]",
"=",
"patch_tag",
".",
"succ",
"else",
"@v",
"[",
":patch_tag",
"]",
"=",
"tag",
"end",
"end"
] | patch tags go from alpha, alpha2, alpha3, etc. | [
"patch",
"tags",
"go",
"from",
"alpha",
"alpha2",
"alpha3",
"etc",
"."
] | 250977316e3bf2079f1a660e03e28ee98256ddc0 | https://github.com/jondot/version_bumper/blob/250977316e3bf2079f1a660e03e28ee98256ddc0/lib/bumper/version.rb#L58-L73 | train |
mbj/morpher | lib/morpher/printer.rb | Morpher.Printer.visit | def visit(name)
child = object.public_send(name)
child_label(name)
visit_child(child)
end | ruby | def visit(name)
child = object.public_send(name)
child_label(name)
visit_child(child)
end | [
"def",
"visit",
"(",
"name",
")",
"child",
"=",
"object",
".",
"public_send",
"(",
"name",
")",
"child_label",
"(",
"name",
")",
"visit_child",
"(",
"child",
")",
"end"
] | Visit a child by name
@param [Symbol] name
the attribute name of the child to visit
@return [undefined]
@api private | [
"Visit",
"a",
"child",
"by",
"name"
] | c9f9f720933835e09acfe6100bb20e8bd3c01915 | https://github.com/mbj/morpher/blob/c9f9f720933835e09acfe6100bb20e8bd3c01915/lib/morpher/printer.rb#L71-L75 | train |
mbj/morpher | lib/morpher/printer.rb | Morpher.Printer.visit_many | def visit_many(name)
children = object.public_send(name)
child_label(name)
children.each do |child|
visit_child(child)
end
end | ruby | def visit_many(name)
children = object.public_send(name)
child_label(name)
children.each do |child|
visit_child(child)
end
end | [
"def",
"visit_many",
"(",
"name",
")",
"children",
"=",
"object",
".",
"public_send",
"(",
"name",
")",
"child_label",
"(",
"name",
")",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"visit_child",
"(",
"child",
")",
"end",
"end"
] | Visit many children
@param [Symbol] name
the name of the collection attribute with children to visit
@return [undefined]
@api private | [
"Visit",
"many",
"children"
] | c9f9f720933835e09acfe6100bb20e8bd3c01915 | https://github.com/mbj/morpher/blob/c9f9f720933835e09acfe6100bb20e8bd3c01915/lib/morpher/printer.rb#L86-L92 | train |
mbj/morpher | lib/morpher/printer.rb | Morpher.Printer.indent | def indent(&block)
printer = new(object, output, indent_level.succ)
printer.instance_eval(&block)
end | ruby | def indent(&block)
printer = new(object, output, indent_level.succ)
printer.instance_eval(&block)
end | [
"def",
"indent",
"(",
"&",
"block",
")",
"printer",
"=",
"new",
"(",
"object",
",",
"output",
",",
"indent_level",
".",
"succ",
")",
"printer",
".",
"instance_eval",
"(",
"&",
"block",
")",
"end"
] | Call block inside indented context
@return [undefined]
@api private | [
"Call",
"block",
"inside",
"indented",
"context"
] | c9f9f720933835e09acfe6100bb20e8bd3c01915 | https://github.com/mbj/morpher/blob/c9f9f720933835e09acfe6100bb20e8bd3c01915/lib/morpher/printer.rb#L203-L206 | train |
ronin-ruby/ronin-support | lib/ronin/fuzzing/fuzzing.rb | Ronin.Fuzzing.bad_strings | def bad_strings(&block)
yield ''
chars = [
'A', 'a', '1', '<', '>', '"', "'", '/', "\\", '?', '=', 'a=', '&',
'.', ',', '(', ')', ']', '[', '%', '*', '-', '+', '{', '}',
"\x14", "\xfe", "\xff"
]
chars.each do |c|
LONG_LENGTHS.each { |length| yield c * length }
end
yield '!@#$%%^#$%#$@#$%$$@#$%^^**(()'
yield '%01%02%03%04%0a%0d%0aADSF'
yield '%01%02%03@%04%0a%0d%0aADSF'
NULL_BYTES.each do |c|
SHORT_LENGTHS.each { |length| yield c * length }
end
yield "%\xfe\xf0%\x00\xff"
yield "%\xfe\xf0%\x00\xff" * 20
SHORT_LENGTHS.each do |length|
yield "\xde\xad\xbe\xef" * length
end
yield "\n\r" * 100
yield "<>" * 500
end | ruby | def bad_strings(&block)
yield ''
chars = [
'A', 'a', '1', '<', '>', '"', "'", '/', "\\", '?', '=', 'a=', '&',
'.', ',', '(', ')', ']', '[', '%', '*', '-', '+', '{', '}',
"\x14", "\xfe", "\xff"
]
chars.each do |c|
LONG_LENGTHS.each { |length| yield c * length }
end
yield '!@#$%%^#$%#$@#$%$$@#$%^^**(()'
yield '%01%02%03%04%0a%0d%0aADSF'
yield '%01%02%03@%04%0a%0d%0aADSF'
NULL_BYTES.each do |c|
SHORT_LENGTHS.each { |length| yield c * length }
end
yield "%\xfe\xf0%\x00\xff"
yield "%\xfe\xf0%\x00\xff" * 20
SHORT_LENGTHS.each do |length|
yield "\xde\xad\xbe\xef" * length
end
yield "\n\r" * 100
yield "<>" * 500
end | [
"def",
"bad_strings",
"(",
"&",
"block",
")",
"yield",
"''",
"chars",
"=",
"[",
"'A'",
",",
"'a'",
",",
"'1'",
",",
"'<'",
",",
"'>'",
",",
"'\"'",
",",
"\"'\"",
",",
"'/'",
",",
"\"\\\\\"",
",",
"'?'",
",",
"'='",
",",
"'a='",
",",
"'&'",
",",
"'.'",
",",
"','",
",",
"'('",
",",
"')'",
",",
"']'",
",",
"'['",
",",
"'%'",
",",
"'*'",
",",
"'-'",
",",
"'+'",
",",
"'{'",
",",
"'}'",
",",
"\"\\x14\"",
",",
"\"\\xfe\"",
",",
"\"\\xff\"",
"]",
"chars",
".",
"each",
"do",
"|",
"c",
"|",
"LONG_LENGTHS",
".",
"each",
"{",
"|",
"length",
"|",
"yield",
"c",
"*",
"length",
"}",
"end",
"yield",
"'!@#$%%^#$%#$@#$%$$@#$%^^**(()'",
"yield",
"'%01%02%03%04%0a%0d%0aADSF'",
"yield",
"'%01%02%03@%04%0a%0d%0aADSF'",
"NULL_BYTES",
".",
"each",
"do",
"|",
"c",
"|",
"SHORT_LENGTHS",
".",
"each",
"{",
"|",
"length",
"|",
"yield",
"c",
"*",
"length",
"}",
"end",
"yield",
"\"%\\xfe\\xf0%\\x00\\xff\"",
"yield",
"\"%\\xfe\\xf0%\\x00\\xff\"",
"*",
"20",
"SHORT_LENGTHS",
".",
"each",
"do",
"|",
"length",
"|",
"yield",
"\"\\xde\\xad\\xbe\\xef\"",
"*",
"length",
"end",
"yield",
"\"\\n\\r\"",
"*",
"100",
"yield",
"\"<>\"",
"*",
"500",
"end"
] | Various bad-strings.
@yield [string]
The given block will be passed each bad-string.
@yieldparam [String] string
A bad-string containing known control characters, deliminators
or null-bytes (see {NULL_BYTES}), of varying length
(see {SHORT_LENGTHS} and {LONG_LENGTHS}). | [
"Various",
"bad",
"-",
"strings",
"."
] | bc2af0e75098c13133789118245cb185f8c6b4c9 | https://github.com/ronin-ruby/ronin-support/blob/bc2af0e75098c13133789118245cb185f8c6b4c9/lib/ronin/fuzzing/fuzzing.rb#L87-L117 | train |
ronin-ruby/ronin-support | lib/ronin/fuzzing/fuzzing.rb | Ronin.Fuzzing.bit_fields | def bit_fields(&block)
("\x00".."\xff").each do |c|
yield c
yield c << c # x2
yield c << c # x4
yield c << c # x8
end
end | ruby | def bit_fields(&block)
("\x00".."\xff").each do |c|
yield c
yield c << c # x2
yield c << c # x4
yield c << c # x8
end
end | [
"def",
"bit_fields",
"(",
"&",
"block",
")",
"(",
"\"\\x00\"",
"..",
"\"\\xff\"",
")",
".",
"each",
"do",
"|",
"c",
"|",
"yield",
"c",
"yield",
"c",
"<<",
"c",
"yield",
"c",
"<<",
"c",
"yield",
"c",
"<<",
"c",
"end",
"end"
] | The range of bit-fields.
@yield [bitfield]
The given block will be passed each bit-field.
@yieldparam [String] bitfield
A bit-field (8bit - 64bit). | [
"The",
"range",
"of",
"bit",
"-",
"fields",
"."
] | bc2af0e75098c13133789118245cb185f8c6b4c9 | https://github.com/ronin-ruby/ronin-support/blob/bc2af0e75098c13133789118245cb185f8c6b4c9/lib/ronin/fuzzing/fuzzing.rb#L176-L183 | train |
ronin-ruby/ronin-support | lib/ronin/fuzzing/fuzzing.rb | Ronin.Fuzzing.signed_bit_fields | def signed_bit_fields(&block)
("\x80".."\xff").each do |c|
yield c
yield c << c # x2
yield c << c # x4
yield c << c # x8
end
end | ruby | def signed_bit_fields(&block)
("\x80".."\xff").each do |c|
yield c
yield c << c # x2
yield c << c # x4
yield c << c # x8
end
end | [
"def",
"signed_bit_fields",
"(",
"&",
"block",
")",
"(",
"\"\\x80\"",
"..",
"\"\\xff\"",
")",
".",
"each",
"do",
"|",
"c",
"|",
"yield",
"c",
"yield",
"c",
"<<",
"c",
"yield",
"c",
"<<",
"c",
"yield",
"c",
"<<",
"c",
"end",
"end"
] | The range of signed bit-fields.
@yield [bitfield]
The given block will be passed each bit-field.
@yieldparam [String] bitfield
A signed bit-field (8bit - 64bit). | [
"The",
"range",
"of",
"signed",
"bit",
"-",
"fields",
"."
] | bc2af0e75098c13133789118245cb185f8c6b4c9 | https://github.com/ronin-ruby/ronin-support/blob/bc2af0e75098c13133789118245cb185f8c6b4c9/lib/ronin/fuzzing/fuzzing.rb#L194-L201 | train |
wearefine/maximus | lib/maximus/statistics/phantomas.rb | Maximus.Phantomas.result | def result
return if @settings[:phantomas].blank?
node_module_exists('phantomjs', 'brew install')
node_module_exists('phantomas')
@path = @settings[:paths] if @path.blank?
@domain = @config.domain
# Phantomas doesn't actually skip the skip-modules defined in the config BUT here's to hoping for future support
phantomas_cli = "phantomas --config=#{@settings[:phantomas]} "
phantomas_cli += @config.is_dev? ? '--colors' : '--reporter=json:no-skip'
phantomas_cli << " --proxy=#{@domain}" if @domain.include?('localhost')
@path.is_a?(Hash) ? @path.each { |label, url| phantomas_by_url(url, phantomas_cli) } : phantomas_by_url(@path, phantomas_cli)
@output
end | ruby | def result
return if @settings[:phantomas].blank?
node_module_exists('phantomjs', 'brew install')
node_module_exists('phantomas')
@path = @settings[:paths] if @path.blank?
@domain = @config.domain
# Phantomas doesn't actually skip the skip-modules defined in the config BUT here's to hoping for future support
phantomas_cli = "phantomas --config=#{@settings[:phantomas]} "
phantomas_cli += @config.is_dev? ? '--colors' : '--reporter=json:no-skip'
phantomas_cli << " --proxy=#{@domain}" if @domain.include?('localhost')
@path.is_a?(Hash) ? @path.each { |label, url| phantomas_by_url(url, phantomas_cli) } : phantomas_by_url(@path, phantomas_cli)
@output
end | [
"def",
"result",
"return",
"if",
"@settings",
"[",
":phantomas",
"]",
".",
"blank?",
"node_module_exists",
"(",
"'phantomjs'",
",",
"'brew install'",
")",
"node_module_exists",
"(",
"'phantomas'",
")",
"@path",
"=",
"@settings",
"[",
":paths",
"]",
"if",
"@path",
".",
"blank?",
"@domain",
"=",
"@config",
".",
"domain",
"phantomas_cli",
"=",
"\"phantomas --config=#{@settings[:phantomas]} \"",
"phantomas_cli",
"+=",
"@config",
".",
"is_dev?",
"?",
"'--colors'",
":",
"'--reporter=json:no-skip'",
"phantomas_cli",
"<<",
"\" --proxy=#{@domain}\"",
"if",
"@domain",
".",
"include?",
"(",
"'localhost'",
")",
"@path",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"@path",
".",
"each",
"{",
"|",
"label",
",",
"url",
"|",
"phantomas_by_url",
"(",
"url",
",",
"phantomas_cli",
")",
"}",
":",
"phantomas_by_url",
"(",
"@path",
",",
"phantomas_cli",
")",
"@output",
"end"
] | Run phantomas through the command line
@see Statistic#initialize | [
"Run",
"phantomas",
"through",
"the",
"command",
"line"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/statistics/phantomas.rb#L8-L24 | train |
chrislee35/snort-rule | lib/snort/rule.rb | Snort.Rule.to_s | def to_s(options_only=false)
rule = ""
if @comments
rule += @comments
end
if not @enabled
rule += "#"
end
rule += [@action, @proto, @src, @sport, @dir, @dst, @dport].join(" ") unless options_only
if @options.any?
rule += " (" unless options_only
rule += @options.join(' ')
rule += ")" unless options_only
end
rule
end | ruby | def to_s(options_only=false)
rule = ""
if @comments
rule += @comments
end
if not @enabled
rule += "#"
end
rule += [@action, @proto, @src, @sport, @dir, @dst, @dport].join(" ") unless options_only
if @options.any?
rule += " (" unless options_only
rule += @options.join(' ')
rule += ")" unless options_only
end
rule
end | [
"def",
"to_s",
"(",
"options_only",
"=",
"false",
")",
"rule",
"=",
"\"\"",
"if",
"@comments",
"rule",
"+=",
"@comments",
"end",
"if",
"not",
"@enabled",
"rule",
"+=",
"\"#\"",
"end",
"rule",
"+=",
"[",
"@action",
",",
"@proto",
",",
"@src",
",",
"@sport",
",",
"@dir",
",",
"@dst",
",",
"@dport",
"]",
".",
"join",
"(",
"\" \"",
")",
"unless",
"options_only",
"if",
"@options",
".",
"any?",
"rule",
"+=",
"\" (\"",
"unless",
"options_only",
"rule",
"+=",
"@options",
".",
"join",
"(",
"' '",
")",
"rule",
"+=",
"\")\"",
"unless",
"options_only",
"end",
"rule",
"end"
] | Initializes the Rule
@param [Hash] kwargs The options to initialize the Rule with
@option kwargs [String] :enabled true or false
@option kwargs [String] :action The action
@option kwargs [String] :proto The protocol
@option kwargs [String] :src The source IP
@option kwargs [String] :sport The source Port
@option kwargs [String] :dir The direction of traffic flow
@option kwargs [String] :dst The destination IP
@option kwargs [String] :dport The destination Port
@option kwargs[Array<Snort::RuleOption>] :options The better way of passing in options, using
option objects that know how to represent themselves as a string properly
Output the current object into a snort rule | [
"Initializes",
"the",
"Rule"
] | b817c467186ea6644886cc79992b75b92add9feb | https://github.com/chrislee35/snort-rule/blob/b817c467186ea6644886cc79992b75b92add9feb/lib/snort/rule.rb#L53-L68 | train |
wearefine/maximus | lib/maximus/statistics/wraith.rb | Maximus.Wraith.wraith_parse | def wraith_parse(browser)
Dir.glob("#{@config.working_dir}/maximus_wraith_#{browser}/**/*").select { |f| File.file? f }.each do |file|
extension = File.extname(file)
next unless extension == '.png' || extension == '.txt'
orig_label = File.dirname(file).split('/').last
path = @settings[:paths][orig_label].to_s
@output[:statistics][path] = {
browser: browser.to_s,
name: orig_label
} if @output[:statistics][path].blank?
browser_output = @output[:statistics][path]
if extension == '.txt'
browser_output = wraith_percentage(file, browser_output)
else
browser_output[:images] ||= []
browser_output[:images] << wraith_image(file)
end
end
@output
end | ruby | def wraith_parse(browser)
Dir.glob("#{@config.working_dir}/maximus_wraith_#{browser}/**/*").select { |f| File.file? f }.each do |file|
extension = File.extname(file)
next unless extension == '.png' || extension == '.txt'
orig_label = File.dirname(file).split('/').last
path = @settings[:paths][orig_label].to_s
@output[:statistics][path] = {
browser: browser.to_s,
name: orig_label
} if @output[:statistics][path].blank?
browser_output = @output[:statistics][path]
if extension == '.txt'
browser_output = wraith_percentage(file, browser_output)
else
browser_output[:images] ||= []
browser_output[:images] << wraith_image(file)
end
end
@output
end | [
"def",
"wraith_parse",
"(",
"browser",
")",
"Dir",
".",
"glob",
"(",
"\"#{@config.working_dir}/maximus_wraith_#{browser}/**/*\"",
")",
".",
"select",
"{",
"|",
"f",
"|",
"File",
".",
"file?",
"f",
"}",
".",
"each",
"do",
"|",
"file",
"|",
"extension",
"=",
"File",
".",
"extname",
"(",
"file",
")",
"next",
"unless",
"extension",
"==",
"'.png'",
"||",
"extension",
"==",
"'.txt'",
"orig_label",
"=",
"File",
".",
"dirname",
"(",
"file",
")",
".",
"split",
"(",
"'/'",
")",
".",
"last",
"path",
"=",
"@settings",
"[",
":paths",
"]",
"[",
"orig_label",
"]",
".",
"to_s",
"@output",
"[",
":statistics",
"]",
"[",
"path",
"]",
"=",
"{",
"browser",
":",
"browser",
".",
"to_s",
",",
"name",
":",
"orig_label",
"}",
"if",
"@output",
"[",
":statistics",
"]",
"[",
"path",
"]",
".",
"blank?",
"browser_output",
"=",
"@output",
"[",
":statistics",
"]",
"[",
"path",
"]",
"if",
"extension",
"==",
"'.txt'",
"browser_output",
"=",
"wraith_percentage",
"(",
"file",
",",
"browser_output",
")",
"else",
"browser_output",
"[",
":images",
"]",
"||=",
"[",
"]",
"browser_output",
"[",
":images",
"]",
"<<",
"wraith_image",
"(",
"file",
")",
"end",
"end",
"@output",
"end"
] | Get a diff percentage of all changes by label and screensize
@example { :statistics => { "/" => { :browser=>"phantomjs", :name=>"home", :percent_changed=>{ 1024=>2.1, 1280=>1.8, 767=>3.4 } } } }
@param browser [String] headless browser used to generate the gallery
@return [Hash] { path: { browser, path_label, percent_changed: { size: percent_diff ] } } | [
"Get",
"a",
"diff",
"percentage",
"of",
"all",
"changes",
"by",
"label",
"and",
"screensize"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/statistics/wraith.rb#L47-L72 | train |
wearefine/maximus | lib/maximus/statistics/wraith.rb | Maximus.Wraith.wraith_percentage | def wraith_percentage(file, browser_output)
file_object = File.open(file, 'rb')
browser_output[:percent_changed] ||= {}
browser_output[:percent_changed][File.basename(file).split('_')[0].to_i] = file_object.read.to_f
file_object.close
browser_output
end | ruby | def wraith_percentage(file, browser_output)
file_object = File.open(file, 'rb')
browser_output[:percent_changed] ||= {}
browser_output[:percent_changed][File.basename(file).split('_')[0].to_i] = file_object.read.to_f
file_object.close
browser_output
end | [
"def",
"wraith_percentage",
"(",
"file",
",",
"browser_output",
")",
"file_object",
"=",
"File",
".",
"open",
"(",
"file",
",",
"'rb'",
")",
"browser_output",
"[",
":percent_changed",
"]",
"||=",
"{",
"}",
"browser_output",
"[",
":percent_changed",
"]",
"[",
"File",
".",
"basename",
"(",
"file",
")",
".",
"split",
"(",
"'_'",
")",
"[",
"0",
"]",
".",
"to_i",
"]",
"=",
"file_object",
".",
"read",
".",
"to_f",
"file_object",
".",
"close",
"browser_output",
"end"
] | Grab the percentage change from previous snapshots
@since 0.1.5
@param file [String]
@param browser_output [Hash]
@return [Hash] | [
"Grab",
"the",
"percentage",
"change",
"from",
"previous",
"snapshots"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/statistics/wraith.rb#L79-L87 | train |
souche/aliyun-ons-ruby-sdk | lib/ons/consumer.rb | Ons.Consumer.subscribe | def subscribe(topic, expression, handler = nil)
@consumer.subscribe(topic, expression, handler || Proc.new)
self
end | ruby | def subscribe(topic, expression, handler = nil)
@consumer.subscribe(topic, expression, handler || Proc.new)
self
end | [
"def",
"subscribe",
"(",
"topic",
",",
"expression",
",",
"handler",
"=",
"nil",
")",
"@consumer",
".",
"subscribe",
"(",
"topic",
",",
"expression",
",",
"handler",
"||",
"Proc",
".",
"new",
")",
"self",
"end"
] | Create a new aliyun ONS Consumer instance.
@param access_key [String] the access key to aliyun ONS
@param secret_key [String] the secret key to aliyun ONS
@param consumer_id [String] the consumer ID
@param options [Hash{String, Symbol => String}]
@option options [String] :namesrv_addr the nameserver used to fetching ons_addr
@option options [String] :ons_addr the ONS server address
@option options [String, Fixnum, Bignum] :thread_num the consumer thread numbers
Subsribe a topic.
@example subscribe tag :tagA under topic :TopicTestMQ
consumer.subscribe('TopicTestMQ', 'tagA') {}
@example subscribe tag :tagA and :tagB under topic :TopicTestMQ
consumer.subscribe('TopicTestMQ', 'tagA || tagB') {}
@example subscribe all tags under topic :TopicTestMQ
consumer.subscribe('TopicTestMQ', '*') {}
@param topic [String] the message topic
@param expression [String] the subsribe expression used to filter messages
@param handler [#call] the handler which will handle the message
@return [self] returns itself | [
"Create",
"a",
"new",
"aliyun",
"ONS",
"Consumer",
"instance",
"."
] | 00d16d5fe4dc55929036544a7667c463694f6b1f | https://github.com/souche/aliyun-ons-ruby-sdk/blob/00d16d5fe4dc55929036544a7667c463694f6b1f/lib/ons/consumer.rb#L45-L48 | train |
pwnall/webkit_remote | lib/webkit_remote/rpc.rb | WebkitRemote.Rpc.call | def call(method, params = nil)
request_id = @next_id
@next_id += 1
request = {
jsonrpc: '2.0',
id: request_id,
method: method,
}
request[:params] = params if params
request_json = JSON.dump request
@web_socket.send_frame request_json
loop do
result = receive_message request_id
return result if result
end
end | ruby | def call(method, params = nil)
request_id = @next_id
@next_id += 1
request = {
jsonrpc: '2.0',
id: request_id,
method: method,
}
request[:params] = params if params
request_json = JSON.dump request
@web_socket.send_frame request_json
loop do
result = receive_message request_id
return result if result
end
end | [
"def",
"call",
"(",
"method",
",",
"params",
"=",
"nil",
")",
"request_id",
"=",
"@next_id",
"@next_id",
"+=",
"1",
"request",
"=",
"{",
"jsonrpc",
":",
"'2.0'",
",",
"id",
":",
"request_id",
",",
"method",
":",
"method",
",",
"}",
"request",
"[",
":params",
"]",
"=",
"params",
"if",
"params",
"request_json",
"=",
"JSON",
".",
"dump",
"request",
"@web_socket",
".",
"send_frame",
"request_json",
"loop",
"do",
"result",
"=",
"receive_message",
"request_id",
"return",
"result",
"if",
"result",
"end",
"end"
] | Connects to the remote debugging server in a Webkit tab.
@param [Hash] opts info on the tab to connect to
@option opts [WebkitRemote::Tab] tab reference to the tab whose debugger
server this RPC client connects to
Remote debugging RPC call.
See the following URL for implemented calls.
https://developers.google.com/chrome-developer-tools/docs/protocol/1.1/index
@param [String] method name of the RPC method to be invoked
@param [Hash<String, Object>, nil] params parameters for the RPC method to
be invoked
@return [Hash<String, Object>] the return value of the RPC method | [
"Connects",
"to",
"the",
"remote",
"debugging",
"server",
"in",
"a",
"Webkit",
"tab",
"."
] | f38ac7e882726ff00e5c56898d06d91340f8179e | https://github.com/pwnall/webkit_remote/blob/f38ac7e882726ff00e5c56898d06d91340f8179e/lib/webkit_remote/rpc.rb#L34-L50 | train |
pwnall/webkit_remote | lib/webkit_remote/rpc.rb | WebkitRemote.Rpc.receive_message | def receive_message(expected_id)
json = @web_socket.recv_frame
begin
data = JSON.parse json
rescue JSONError
close
raise RuntimeError, 'Invalid JSON received'
end
if data['id']
# RPC result.
if data['id'] != expected_id
close
raise RuntimeError, 'Out of sequence RPC response id'
end
if data['error']
code = data['error']['code']
message = data['error']['message']
raise RuntimeError, "RPC Error #{code}: #{message}"
end
return data['result']
elsif data['method']
# RPC notice.
event = { name: data['method'], data: data['params'] }
@events << event
return nil
else
close
raise RuntimeError, "Unexpected / invalid RPC message #{data.inspect}"
end
end | ruby | def receive_message(expected_id)
json = @web_socket.recv_frame
begin
data = JSON.parse json
rescue JSONError
close
raise RuntimeError, 'Invalid JSON received'
end
if data['id']
# RPC result.
if data['id'] != expected_id
close
raise RuntimeError, 'Out of sequence RPC response id'
end
if data['error']
code = data['error']['code']
message = data['error']['message']
raise RuntimeError, "RPC Error #{code}: #{message}"
end
return data['result']
elsif data['method']
# RPC notice.
event = { name: data['method'], data: data['params'] }
@events << event
return nil
else
close
raise RuntimeError, "Unexpected / invalid RPC message #{data.inspect}"
end
end | [
"def",
"receive_message",
"(",
"expected_id",
")",
"json",
"=",
"@web_socket",
".",
"recv_frame",
"begin",
"data",
"=",
"JSON",
".",
"parse",
"json",
"rescue",
"JSONError",
"close",
"raise",
"RuntimeError",
",",
"'Invalid JSON received'",
"end",
"if",
"data",
"[",
"'id'",
"]",
"if",
"data",
"[",
"'id'",
"]",
"!=",
"expected_id",
"close",
"raise",
"RuntimeError",
",",
"'Out of sequence RPC response id'",
"end",
"if",
"data",
"[",
"'error'",
"]",
"code",
"=",
"data",
"[",
"'error'",
"]",
"[",
"'code'",
"]",
"message",
"=",
"data",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"raise",
"RuntimeError",
",",
"\"RPC Error #{code}: #{message}\"",
"end",
"return",
"data",
"[",
"'result'",
"]",
"elsif",
"data",
"[",
"'method'",
"]",
"event",
"=",
"{",
"name",
":",
"data",
"[",
"'method'",
"]",
",",
"data",
":",
"data",
"[",
"'params'",
"]",
"}",
"@events",
"<<",
"event",
"return",
"nil",
"else",
"close",
"raise",
"RuntimeError",
",",
"\"Unexpected / invalid RPC message #{data.inspect}\"",
"end",
"end"
] | Blocks until a WebKit message is received, then parses it.
RPC notifications are added to the @events array.
@param [Integer, nil] expected_id if a RPC response is expected, this
argument has the response id; otherwise, the argument should be nil
@return [Hash<String, Object>, nil] a Hash containing the RPC result if an
expected RPC response was received; nil if an RPC notice was received | [
"Blocks",
"until",
"a",
"WebKit",
"message",
"is",
"received",
"then",
"parses",
"it",
"."
] | f38ac7e882726ff00e5c56898d06d91340f8179e | https://github.com/pwnall/webkit_remote/blob/f38ac7e882726ff00e5c56898d06d91340f8179e/lib/webkit_remote/rpc.rb#L99-L128 | train |
ImpressCMS/vagrant-impressbox | lib/vagrant-impressbox/command.rb | Impressbox.Command.selected_yaml_file | def selected_yaml_file
p = current_impressbox_provisioner
if p.nil? || p.config.nil? || p.config.file.nil? ||
!(p.config.file.is_a?(String) && p.config.file.chop.length > 0)
return 'config.yaml'
end
p.config.file
end | ruby | def selected_yaml_file
p = current_impressbox_provisioner
if p.nil? || p.config.nil? || p.config.file.nil? ||
!(p.config.file.is_a?(String) && p.config.file.chop.length > 0)
return 'config.yaml'
end
p.config.file
end | [
"def",
"selected_yaml_file",
"p",
"=",
"current_impressbox_provisioner",
"if",
"p",
".",
"nil?",
"||",
"p",
".",
"config",
".",
"nil?",
"||",
"p",
".",
"config",
".",
"file",
".",
"nil?",
"||",
"!",
"(",
"p",
".",
"config",
".",
"file",
".",
"is_a?",
"(",
"String",
")",
"&&",
"p",
".",
"config",
".",
"file",
".",
"chop",
".",
"length",
">",
"0",
")",
"return",
"'config.yaml'",
"end",
"p",
".",
"config",
".",
"file",
"end"
] | Gets yaml file from current vagrantfile
@return [String] | [
"Gets",
"yaml",
"file",
"from",
"current",
"vagrantfile"
] | 78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2 | https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/command.rb#L73-L80 | train |
ImpressCMS/vagrant-impressbox | lib/vagrant-impressbox/command.rb | Impressbox.Command.current_impressbox_provisioner | def current_impressbox_provisioner
@env.vagrantfile.config.vm.provisioners.each do |provisioner|
next unless provisioner.type == :impressbox
return provisioner
end
nil
end | ruby | def current_impressbox_provisioner
@env.vagrantfile.config.vm.provisioners.each do |provisioner|
next unless provisioner.type == :impressbox
return provisioner
end
nil
end | [
"def",
"current_impressbox_provisioner",
"@env",
".",
"vagrantfile",
".",
"config",
".",
"vm",
".",
"provisioners",
".",
"each",
"do",
"|",
"provisioner",
"|",
"next",
"unless",
"provisioner",
".",
"type",
"==",
":impressbox",
"return",
"provisioner",
"end",
"nil",
"end"
] | Gets current provisioner with impressbox type
@return [::VagrantPlugins::Kernel_V2::VagrantConfigProvisioner,nil] | [
"Gets",
"current",
"provisioner",
"with",
"impressbox",
"type"
] | 78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2 | https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/command.rb#L85-L91 | train |
ImpressCMS/vagrant-impressbox | lib/vagrant-impressbox/command.rb | Impressbox.Command.update_name | def update_name(options)
if options.key?(:name) && options[:name].is_a?(String) && options[:name].length > 0
return
end
hostname = if options.key?(:hostname) then
options[:hostname]
else
@args.default_values[:hostname]
end
hostname = hostname[0] if hostname.is_a?(Array)
options[:name] = hostname.gsub(/[^A-Za-z0-9_-]/, '-')
end | ruby | def update_name(options)
if options.key?(:name) && options[:name].is_a?(String) && options[:name].length > 0
return
end
hostname = if options.key?(:hostname) then
options[:hostname]
else
@args.default_values[:hostname]
end
hostname = hostname[0] if hostname.is_a?(Array)
options[:name] = hostname.gsub(/[^A-Za-z0-9_-]/, '-')
end | [
"def",
"update_name",
"(",
"options",
")",
"if",
"options",
".",
"key?",
"(",
":name",
")",
"&&",
"options",
"[",
":name",
"]",
".",
"is_a?",
"(",
"String",
")",
"&&",
"options",
"[",
":name",
"]",
".",
"length",
">",
"0",
"return",
"end",
"hostname",
"=",
"if",
"options",
".",
"key?",
"(",
":hostname",
")",
"then",
"options",
"[",
":hostname",
"]",
"else",
"@args",
".",
"default_values",
"[",
":hostname",
"]",
"end",
"hostname",
"=",
"hostname",
"[",
"0",
"]",
"if",
"hostname",
".",
"is_a?",
"(",
"Array",
")",
"options",
"[",
":name",
"]",
"=",
"hostname",
".",
"gsub",
"(",
"/",
"/",
",",
"'-'",
")",
"end"
] | Updates name param in options hash
@param options [Hash] Input/output hash | [
"Updates",
"name",
"param",
"in",
"options",
"hash"
] | 78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2 | https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/command.rb#L108-L119 | train |
ImpressCMS/vagrant-impressbox | lib/vagrant-impressbox/command.rb | Impressbox.Command.write_result_msg | def write_result_msg(result)
msg = if result then
I18n.t 'config.recreated'
else
I18n.t 'config.updated'
end
@env.ui.info msg
end | ruby | def write_result_msg(result)
msg = if result then
I18n.t 'config.recreated'
else
I18n.t 'config.updated'
end
@env.ui.info msg
end | [
"def",
"write_result_msg",
"(",
"result",
")",
"msg",
"=",
"if",
"result",
"then",
"I18n",
".",
"t",
"'config.recreated'",
"else",
"I18n",
".",
"t",
"'config.updated'",
"end",
"@env",
".",
"ui",
".",
"info",
"msg",
"end"
] | Writes message for action result
@param result [Boolean] | [
"Writes",
"message",
"for",
"action",
"result"
] | 78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2 | https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/command.rb#L124-L131 | train |
ImpressCMS/vagrant-impressbox | lib/vagrant-impressbox/command.rb | Impressbox.Command.quick_make_file | def quick_make_file(local_file, tpl_file)
current_file = local_file(local_file)
template_file = @template.real_path(tpl_file)
@template.make_file(
template_file,
current_file,
@args.all.dup,
make_data_files_array(current_file),
method(:update_latest_options)
)
end | ruby | def quick_make_file(local_file, tpl_file)
current_file = local_file(local_file)
template_file = @template.real_path(tpl_file)
@template.make_file(
template_file,
current_file,
@args.all.dup,
make_data_files_array(current_file),
method(:update_latest_options)
)
end | [
"def",
"quick_make_file",
"(",
"local_file",
",",
"tpl_file",
")",
"current_file",
"=",
"local_file",
"(",
"local_file",
")",
"template_file",
"=",
"@template",
".",
"real_path",
"(",
"tpl_file",
")",
"@template",
".",
"make_file",
"(",
"template_file",
",",
"current_file",
",",
"@args",
".",
"all",
".",
"dup",
",",
"make_data_files_array",
"(",
"current_file",
")",
",",
"method",
"(",
":update_latest_options",
")",
")",
"end"
] | Renders and safes file
@param local_file [String] Local filename
@param tpl_file [String] Template filename | [
"Renders",
"and",
"safes",
"file"
] | 78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2 | https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/command.rb#L144-L154 | train |
ImpressCMS/vagrant-impressbox | lib/vagrant-impressbox/command.rb | Impressbox.Command.make_data_files_array | def make_data_files_array(current_file)
data_files = [
ConfigData.real_path('default.yml')
]
unless use_template_filename.nil?
data_files.push use_template_filename
end
unless must_recreate
data_files.push current_file
end
data_files
end | ruby | def make_data_files_array(current_file)
data_files = [
ConfigData.real_path('default.yml')
]
unless use_template_filename.nil?
data_files.push use_template_filename
end
unless must_recreate
data_files.push current_file
end
data_files
end | [
"def",
"make_data_files_array",
"(",
"current_file",
")",
"data_files",
"=",
"[",
"ConfigData",
".",
"real_path",
"(",
"'default.yml'",
")",
"]",
"unless",
"use_template_filename",
".",
"nil?",
"data_files",
".",
"push",
"use_template_filename",
"end",
"unless",
"must_recreate",
"data_files",
".",
"push",
"current_file",
"end",
"data_files",
"end"
] | Makes data files array
@param current_file [String] Current file name
@return [Array] | [
"Makes",
"data",
"files",
"array"
] | 78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2 | https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/command.rb#L161-L172 | train |
9kSoftware/plaid_rails | app/controllers/plaid_rails/accounts_controller.rb | PlaidRails.AccountsController.new | def new
client = Plaid::Client.new(env: PlaidRails.env,
client_id: PlaidRails.client_id,
secret: PlaidRails.secret,
public_key: PlaidRails.public_key)
response = client.accounts.get(account_params["access_token"])
@plaid_accounts = response.accounts
end | ruby | def new
client = Plaid::Client.new(env: PlaidRails.env,
client_id: PlaidRails.client_id,
secret: PlaidRails.secret,
public_key: PlaidRails.public_key)
response = client.accounts.get(account_params["access_token"])
@plaid_accounts = response.accounts
end | [
"def",
"new",
"client",
"=",
"Plaid",
"::",
"Client",
".",
"new",
"(",
"env",
":",
"PlaidRails",
".",
"env",
",",
"client_id",
":",
"PlaidRails",
".",
"client_id",
",",
"secret",
":",
"PlaidRails",
".",
"secret",
",",
"public_key",
":",
"PlaidRails",
".",
"public_key",
")",
"response",
"=",
"client",
".",
"accounts",
".",
"get",
"(",
"account_params",
"[",
"\"access_token\"",
"]",
")",
"@plaid_accounts",
"=",
"response",
".",
"accounts",
"end"
] | display list of accounts for authenticated user | [
"display",
"list",
"of",
"accounts",
"for",
"authenticated",
"user"
] | abad75600c26c20a29d5fa3df80d52487a4e72cc | https://github.com/9kSoftware/plaid_rails/blob/abad75600c26c20a29d5fa3df80d52487a4e72cc/app/controllers/plaid_rails/accounts_controller.rb#L11-L20 | train |
hoanganhhanoi/dhcp_parser | lib/dhcp_parser.rb | DHCPParser.Conf.subnets | def subnets
subnet = []
index = 0
while index < @datas.count
index += 1
subnet << DHCPParser::Conf.get_subnet(@datas["net#{index}"])
end
return subnet
end | ruby | def subnets
subnet = []
index = 0
while index < @datas.count
index += 1
subnet << DHCPParser::Conf.get_subnet(@datas["net#{index}"])
end
return subnet
end | [
"def",
"subnets",
"subnet",
"=",
"[",
"]",
"index",
"=",
"0",
"while",
"index",
"<",
"@datas",
".",
"count",
"index",
"+=",
"1",
"subnet",
"<<",
"DHCPParser",
"::",
"Conf",
".",
"get_subnet",
"(",
"@datas",
"[",
"\"net#{index}\"",
"]",
")",
"end",
"return",
"subnet",
"end"
] | Get list subnet | [
"Get",
"list",
"subnet"
] | baa59aab7b519117c162d323104fb6e56d7fd4fc | https://github.com/hoanganhhanoi/dhcp_parser/blob/baa59aab7b519117c162d323104fb6e56d7fd4fc/lib/dhcp_parser.rb#L254-L262 | train |
hoanganhhanoi/dhcp_parser | lib/dhcp_parser.rb | DHCPParser.Conf.netmasks | def netmasks
netmask = []
index = 0
while index < @datas.count
index += 1
netmask << DHCPParser::Conf.get_netmask(@datas["net#{index}"])
end
return netmask
end | ruby | def netmasks
netmask = []
index = 0
while index < @datas.count
index += 1
netmask << DHCPParser::Conf.get_netmask(@datas["net#{index}"])
end
return netmask
end | [
"def",
"netmasks",
"netmask",
"=",
"[",
"]",
"index",
"=",
"0",
"while",
"index",
"<",
"@datas",
".",
"count",
"index",
"+=",
"1",
"netmask",
"<<",
"DHCPParser",
"::",
"Conf",
".",
"get_netmask",
"(",
"@datas",
"[",
"\"net#{index}\"",
"]",
")",
"end",
"return",
"netmask",
"end"
] | Get list netmask | [
"Get",
"list",
"netmask"
] | baa59aab7b519117c162d323104fb6e56d7fd4fc | https://github.com/hoanganhhanoi/dhcp_parser/blob/baa59aab7b519117c162d323104fb6e56d7fd4fc/lib/dhcp_parser.rb#L265-L273 | train |
hoanganhhanoi/dhcp_parser | lib/dhcp_parser.rb | DHCPParser.Conf.options | def options
option = []
index = 0
while index < @datas.count
index += 1
option << DHCPParser::Conf.get_list_option(@datas["net#{index}"])
end
return option
end | ruby | def options
option = []
index = 0
while index < @datas.count
index += 1
option << DHCPParser::Conf.get_list_option(@datas["net#{index}"])
end
return option
end | [
"def",
"options",
"option",
"=",
"[",
"]",
"index",
"=",
"0",
"while",
"index",
"<",
"@datas",
".",
"count",
"index",
"+=",
"1",
"option",
"<<",
"DHCPParser",
"::",
"Conf",
".",
"get_list_option",
"(",
"@datas",
"[",
"\"net#{index}\"",
"]",
")",
"end",
"return",
"option",
"end"
] | Get list option | [
"Get",
"list",
"option"
] | baa59aab7b519117c162d323104fb6e56d7fd4fc | https://github.com/hoanganhhanoi/dhcp_parser/blob/baa59aab7b519117c162d323104fb6e56d7fd4fc/lib/dhcp_parser.rb#L276-L284 | train |
hoanganhhanoi/dhcp_parser | lib/dhcp_parser.rb | DHCPParser.Conf.authoritative | def authoritative
authori = []
index = 0
while index < @datas.count
index += 1
authori << DHCPParser::Conf.get_authoritative(@datas["net#{index}"])
end
return authori
end | ruby | def authoritative
authori = []
index = 0
while index < @datas.count
index += 1
authori << DHCPParser::Conf.get_authoritative(@datas["net#{index}"])
end
return authori
end | [
"def",
"authoritative",
"authori",
"=",
"[",
"]",
"index",
"=",
"0",
"while",
"index",
"<",
"@datas",
".",
"count",
"index",
"+=",
"1",
"authori",
"<<",
"DHCPParser",
"::",
"Conf",
".",
"get_authoritative",
"(",
"@datas",
"[",
"\"net#{index}\"",
"]",
")",
"end",
"return",
"authori",
"end"
] | Get value authoritative | [
"Get",
"value",
"authoritative"
] | baa59aab7b519117c162d323104fb6e56d7fd4fc | https://github.com/hoanganhhanoi/dhcp_parser/blob/baa59aab7b519117c162d323104fb6e56d7fd4fc/lib/dhcp_parser.rb#L287-L295 | train |
hoanganhhanoi/dhcp_parser | lib/dhcp_parser.rb | DHCPParser.Conf.net | def net
i = 0
while i < @datas.count
i += 1
new_net = Net.new
new_net.subnet = DHCPParser::Conf.get_subnet(@datas["net#{i}"])
new_net.netmask = DHCPParser::Conf.get_netmask(@datas["net#{i}"])
list_option = DHCPParser::Conf.get_list_option(@datas["net#{i}"], true)
new_net.option = list_option[0]
new_net.differ = list_option[1]
pool = DHCPParser::Conf.get_pool(@datas["net#{i}"])
new_net.pool["range"] = pool["range"]
new_net.pool["allow"] = pool["allow"]
new_net.pool["denny"] = pool["denny"]
# set host
index = 0
while index < pool["hosts"].count
index += 1
host_name = pool["hosts"]["host#{index}"]["host"]
ethernet = pool["hosts"]["host#{index}"]["hardware_ethernet"]
address = pool["hosts"]["host#{index}"]["fixed-address"]
host = Host.new(host_name, ethernet, address)
new_net.pool["hosts"] << host
end
@array_net << new_net
end
return @array_net
end | ruby | def net
i = 0
while i < @datas.count
i += 1
new_net = Net.new
new_net.subnet = DHCPParser::Conf.get_subnet(@datas["net#{i}"])
new_net.netmask = DHCPParser::Conf.get_netmask(@datas["net#{i}"])
list_option = DHCPParser::Conf.get_list_option(@datas["net#{i}"], true)
new_net.option = list_option[0]
new_net.differ = list_option[1]
pool = DHCPParser::Conf.get_pool(@datas["net#{i}"])
new_net.pool["range"] = pool["range"]
new_net.pool["allow"] = pool["allow"]
new_net.pool["denny"] = pool["denny"]
# set host
index = 0
while index < pool["hosts"].count
index += 1
host_name = pool["hosts"]["host#{index}"]["host"]
ethernet = pool["hosts"]["host#{index}"]["hardware_ethernet"]
address = pool["hosts"]["host#{index}"]["fixed-address"]
host = Host.new(host_name, ethernet, address)
new_net.pool["hosts"] << host
end
@array_net << new_net
end
return @array_net
end | [
"def",
"net",
"i",
"=",
"0",
"while",
"i",
"<",
"@datas",
".",
"count",
"i",
"+=",
"1",
"new_net",
"=",
"Net",
".",
"new",
"new_net",
".",
"subnet",
"=",
"DHCPParser",
"::",
"Conf",
".",
"get_subnet",
"(",
"@datas",
"[",
"\"net#{i}\"",
"]",
")",
"new_net",
".",
"netmask",
"=",
"DHCPParser",
"::",
"Conf",
".",
"get_netmask",
"(",
"@datas",
"[",
"\"net#{i}\"",
"]",
")",
"list_option",
"=",
"DHCPParser",
"::",
"Conf",
".",
"get_list_option",
"(",
"@datas",
"[",
"\"net#{i}\"",
"]",
",",
"true",
")",
"new_net",
".",
"option",
"=",
"list_option",
"[",
"0",
"]",
"new_net",
".",
"differ",
"=",
"list_option",
"[",
"1",
"]",
"pool",
"=",
"DHCPParser",
"::",
"Conf",
".",
"get_pool",
"(",
"@datas",
"[",
"\"net#{i}\"",
"]",
")",
"new_net",
".",
"pool",
"[",
"\"range\"",
"]",
"=",
"pool",
"[",
"\"range\"",
"]",
"new_net",
".",
"pool",
"[",
"\"allow\"",
"]",
"=",
"pool",
"[",
"\"allow\"",
"]",
"new_net",
".",
"pool",
"[",
"\"denny\"",
"]",
"=",
"pool",
"[",
"\"denny\"",
"]",
"index",
"=",
"0",
"while",
"index",
"<",
"pool",
"[",
"\"hosts\"",
"]",
".",
"count",
"index",
"+=",
"1",
"host_name",
"=",
"pool",
"[",
"\"hosts\"",
"]",
"[",
"\"host#{index}\"",
"]",
"[",
"\"host\"",
"]",
"ethernet",
"=",
"pool",
"[",
"\"hosts\"",
"]",
"[",
"\"host#{index}\"",
"]",
"[",
"\"hardware_ethernet\"",
"]",
"address",
"=",
"pool",
"[",
"\"hosts\"",
"]",
"[",
"\"host#{index}\"",
"]",
"[",
"\"fixed-address\"",
"]",
"host",
"=",
"Host",
".",
"new",
"(",
"host_name",
",",
"ethernet",
",",
"address",
")",
"new_net",
".",
"pool",
"[",
"\"hosts\"",
"]",
"<<",
"host",
"end",
"@array_net",
"<<",
"new_net",
"end",
"return",
"@array_net",
"end"
] | Set data in object | [
"Set",
"data",
"in",
"object"
] | baa59aab7b519117c162d323104fb6e56d7fd4fc | https://github.com/hoanganhhanoi/dhcp_parser/blob/baa59aab7b519117c162d323104fb6e56d7fd4fc/lib/dhcp_parser.rb#L361-L391 | train |
printercu/rails_stuff | lib/rails_stuff/resources_controller.rb | RailsStuff.ResourcesController.resources_controller | def resources_controller(**options)
ResourcesController.inject(self, **options)
self.after_save_action = options[:after_save_action] || after_save_action
resource_belongs_to(*options[:belongs_to]) if options[:belongs_to]
if options[:source_relation]
protected define_method(:source_relation, &options[:source_relation])
end
end | ruby | def resources_controller(**options)
ResourcesController.inject(self, **options)
self.after_save_action = options[:after_save_action] || after_save_action
resource_belongs_to(*options[:belongs_to]) if options[:belongs_to]
if options[:source_relation]
protected define_method(:source_relation, &options[:source_relation])
end
end | [
"def",
"resources_controller",
"(",
"**",
"options",
")",
"ResourcesController",
".",
"inject",
"(",
"self",
",",
"**",
"options",
")",
"self",
".",
"after_save_action",
"=",
"options",
"[",
":after_save_action",
"]",
"||",
"after_save_action",
"resource_belongs_to",
"(",
"*",
"options",
"[",
":belongs_to",
"]",
")",
"if",
"options",
"[",
":belongs_to",
"]",
"if",
"options",
"[",
":source_relation",
"]",
"protected",
"define_method",
"(",
":source_relation",
",",
"&",
"options",
"[",
":source_relation",
"]",
")",
"end",
"end"
] | Setups basic actions and helpers in resources controller.
#### Options
- `sti` - include STI helpers
- `kaminari` - include Kaminari helpers
- `after_save_action` - action to use for `after_save_url`
- `source_relation` - override `source_relation` | [
"Setups",
"basic",
"actions",
"and",
"helpers",
"in",
"resources",
"controller",
"."
] | b3d72daaae6426c8166205f6a7438a89768e8347 | https://github.com/printercu/rails_stuff/blob/b3d72daaae6426c8166205f6a7438a89768e8347/lib/rails_stuff/resources_controller.rb#L41-L50 | train |
stevenchanin/strava-api | lib/strava-api/segments.rb | StravaApi.Segments.segments | def segments(name)
result = call("segments", "segments", {:name => name})
result["segments"].collect {|item| Segment.new(self, item)}
end | ruby | def segments(name)
result = call("segments", "segments", {:name => name})
result["segments"].collect {|item| Segment.new(self, item)}
end | [
"def",
"segments",
"(",
"name",
")",
"result",
"=",
"call",
"(",
"\"segments\"",
",",
"\"segments\"",
",",
"{",
":name",
"=>",
"name",
"}",
")",
"result",
"[",
"\"segments\"",
"]",
".",
"collect",
"{",
"|",
"item",
"|",
"Segment",
".",
"new",
"(",
"self",
",",
"item",
")",
"}",
"end"
] | returns all segments, don't need an offset | [
"returns",
"all",
"segments",
"don",
"t",
"need",
"an",
"offset"
] | a185fee415d606357a462fbeb5cc8de9f6130cdf | https://github.com/stevenchanin/strava-api/blob/a185fee415d606357a462fbeb5cc8de9f6130cdf/lib/strava-api/segments.rb#L4-L8 | train |
blambeau/rack-robustness | lib/rack/robustness.rb | Rack.Robustness.call | def call(env)
dup.call!(env)
rescue => ex
catch_all ? last_resort(ex) : raise(ex)
end | ruby | def call(env)
dup.call!(env)
rescue => ex
catch_all ? last_resort(ex) : raise(ex)
end | [
"def",
"call",
"(",
"env",
")",
"dup",
".",
"call!",
"(",
"env",
")",
"rescue",
"=>",
"ex",
"catch_all",
"?",
"last_resort",
"(",
"ex",
")",
":",
"raise",
"(",
"ex",
")",
"end"
] | Rack's call | [
"Rack",
"s",
"call"
] | c0b9e4fdbb882f786a9306279e73c27761683868 | https://github.com/blambeau/rack-robustness/blob/c0b9e4fdbb882f786a9306279e73c27761683868/lib/rack/robustness.rb#L94-L98 | train |
freayd/osrm | lib/osrm/configuration.rb | OSRM.Configuration.ensure_cache_version | def ensure_cache_version
return unless cache
cache_version = cache[cache_key('version')]
minimum_version = '0.4.0'
if cache_version &&
Gem::Version.new(cache_version) < Gem::Version.new(minimum_version)
@data[:cache] = nil
raise "OSRM API error: Incompatible cache version #{cache_version}, " +
"expected #{minimum_version} or higher"
end
end | ruby | def ensure_cache_version
return unless cache
cache_version = cache[cache_key('version')]
minimum_version = '0.4.0'
if cache_version &&
Gem::Version.new(cache_version) < Gem::Version.new(minimum_version)
@data[:cache] = nil
raise "OSRM API error: Incompatible cache version #{cache_version}, " +
"expected #{minimum_version} or higher"
end
end | [
"def",
"ensure_cache_version",
"return",
"unless",
"cache",
"cache_version",
"=",
"cache",
"[",
"cache_key",
"(",
"'version'",
")",
"]",
"minimum_version",
"=",
"'0.4.0'",
"if",
"cache_version",
"&&",
"Gem",
"::",
"Version",
".",
"new",
"(",
"cache_version",
")",
"<",
"Gem",
"::",
"Version",
".",
"new",
"(",
"minimum_version",
")",
"@data",
"[",
":cache",
"]",
"=",
"nil",
"raise",
"\"OSRM API error: Incompatible cache version #{cache_version}, \"",
"+",
"\"expected #{minimum_version} or higher\"",
"end",
"end"
] | Raise an exception if the cache isn't compatible with the current library version | [
"Raise",
"an",
"exception",
"if",
"the",
"cache",
"isn",
"t",
"compatible",
"with",
"the",
"current",
"library",
"version"
] | 607595db144c62518b083e3ad234b0b916feb3fc | https://github.com/freayd/osrm/blob/607595db144c62518b083e3ad234b0b916feb3fc/lib/osrm/configuration.rb#L105-L116 | train |
cblavier/jobbr | app/models/jobbr/job.rb | Jobbr.Job.cap_runs! | def cap_runs!
runs_count = self.runs.count
if runs_count > max_run_per_job
runs.sort_by(:started_at, order: 'ALPHA ASC', limit: [0, runs_count - max_run_per_job]).each do |run|
if run.status == :failed || run.status == :success
run.delete
end
end
end
end | ruby | def cap_runs!
runs_count = self.runs.count
if runs_count > max_run_per_job
runs.sort_by(:started_at, order: 'ALPHA ASC', limit: [0, runs_count - max_run_per_job]).each do |run|
if run.status == :failed || run.status == :success
run.delete
end
end
end
end | [
"def",
"cap_runs!",
"runs_count",
"=",
"self",
".",
"runs",
".",
"count",
"if",
"runs_count",
">",
"max_run_per_job",
"runs",
".",
"sort_by",
"(",
":started_at",
",",
"order",
":",
"'ALPHA ASC'",
",",
"limit",
":",
"[",
"0",
",",
"runs_count",
"-",
"max_run_per_job",
"]",
")",
".",
"each",
"do",
"|",
"run",
"|",
"if",
"run",
".",
"status",
"==",
":failed",
"||",
"run",
".",
"status",
"==",
":success",
"run",
".",
"delete",
"end",
"end",
"end",
"end"
] | prevents Run collection to grow beyond max_run_per_job | [
"prevents",
"Run",
"collection",
"to",
"grow",
"beyond",
"max_run_per_job"
] | 2fbfa14f5fe1b942e69333e34ea0a086ad052b38 | https://github.com/cblavier/jobbr/blob/2fbfa14f5fe1b942e69333e34ea0a086ad052b38/app/models/jobbr/job.rb#L156-L165 | train |
pwnall/webkit_remote | lib/webkit_remote/browser.rb | WebkitRemote.Browser.tabs | def tabs
http_response = @http.request Net::HTTP::Get.new('/json')
tabs = JSON.parse(http_response.body).map do |json_tab|
title = json_tab['title']
url = json_tab['url']
debug_url = json_tab['webSocketDebuggerUrl']
Tab.new self, debug_url, title: title, url: url
end
# HACK(pwnall): work around the nasty Google Hangouts integration
tabs.select do |tab|
tab.url != 'chrome-extension://nkeimhogjdpnpccoofpliimaahmaaome/background.html'
end
end | ruby | def tabs
http_response = @http.request Net::HTTP::Get.new('/json')
tabs = JSON.parse(http_response.body).map do |json_tab|
title = json_tab['title']
url = json_tab['url']
debug_url = json_tab['webSocketDebuggerUrl']
Tab.new self, debug_url, title: title, url: url
end
# HACK(pwnall): work around the nasty Google Hangouts integration
tabs.select do |tab|
tab.url != 'chrome-extension://nkeimhogjdpnpccoofpliimaahmaaome/background.html'
end
end | [
"def",
"tabs",
"http_response",
"=",
"@http",
".",
"request",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"'/json'",
")",
"tabs",
"=",
"JSON",
".",
"parse",
"(",
"http_response",
".",
"body",
")",
".",
"map",
"do",
"|",
"json_tab",
"|",
"title",
"=",
"json_tab",
"[",
"'title'",
"]",
"url",
"=",
"json_tab",
"[",
"'url'",
"]",
"debug_url",
"=",
"json_tab",
"[",
"'webSocketDebuggerUrl'",
"]",
"Tab",
".",
"new",
"self",
",",
"debug_url",
",",
"title",
":",
"title",
",",
"url",
":",
"url",
"end",
"tabs",
".",
"select",
"do",
"|",
"tab",
"|",
"tab",
".",
"url",
"!=",
"'chrome-extension://nkeimhogjdpnpccoofpliimaahmaaome/background.html'",
"end",
"end"
] | Retrieves the tabs that are currently open in the browser.
These tabs can be used to start debugging.
@return [Array<WebkitRemote::Browser::Tab>] the open tabs | [
"Retrieves",
"the",
"tabs",
"that",
"are",
"currently",
"open",
"in",
"the",
"browser",
"."
] | f38ac7e882726ff00e5c56898d06d91340f8179e | https://github.com/pwnall/webkit_remote/blob/f38ac7e882726ff00e5c56898d06d91340f8179e/lib/webkit_remote/browser.rb#L61-L73 | train |
stevenchanin/strava-api | lib/strava-api/clubs.rb | StravaApi.Clubs.clubs | def clubs(name)
raise StravaApi::CommandError if name.blank?
name = name.strip
raise StravaApi::CommandError if name.empty?
result = call("clubs", "clubs", {:name => name})
result["clubs"].collect {|item| Club.new(self, item)}
end | ruby | def clubs(name)
raise StravaApi::CommandError if name.blank?
name = name.strip
raise StravaApi::CommandError if name.empty?
result = call("clubs", "clubs", {:name => name})
result["clubs"].collect {|item| Club.new(self, item)}
end | [
"def",
"clubs",
"(",
"name",
")",
"raise",
"StravaApi",
"::",
"CommandError",
"if",
"name",
".",
"blank?",
"name",
"=",
"name",
".",
"strip",
"raise",
"StravaApi",
"::",
"CommandError",
"if",
"name",
".",
"empty?",
"result",
"=",
"call",
"(",
"\"clubs\"",
",",
"\"clubs\"",
",",
"{",
":name",
"=>",
"name",
"}",
")",
"result",
"[",
"\"clubs\"",
"]",
".",
"collect",
"{",
"|",
"item",
"|",
"Club",
".",
"new",
"(",
"self",
",",
"item",
")",
"}",
"end"
] | returns all clubs, don't need an offset | [
"returns",
"all",
"clubs",
"don",
"t",
"need",
"an",
"offset"
] | a185fee415d606357a462fbeb5cc8de9f6130cdf | https://github.com/stevenchanin/strava-api/blob/a185fee415d606357a462fbeb5cc8de9f6130cdf/lib/strava-api/clubs.rb#L4-L13 | train |
stevenchanin/strava-api | lib/strava-api/clubs.rb | StravaApi.Clubs.club_members | def club_members(id)
result = call("clubs/#{id}/members", "members", {})
result["members"].collect {|item| Member.new(self, item)}
end | ruby | def club_members(id)
result = call("clubs/#{id}/members", "members", {})
result["members"].collect {|item| Member.new(self, item)}
end | [
"def",
"club_members",
"(",
"id",
")",
"result",
"=",
"call",
"(",
"\"clubs/#{id}/members\"",
",",
"\"members\"",
",",
"{",
"}",
")",
"result",
"[",
"\"members\"",
"]",
".",
"collect",
"{",
"|",
"item",
"|",
"Member",
".",
"new",
"(",
"self",
",",
"item",
")",
"}",
"end"
] | returns all members, don't need an offset | [
"returns",
"all",
"members",
"don",
"t",
"need",
"an",
"offset"
] | a185fee415d606357a462fbeb5cc8de9f6130cdf | https://github.com/stevenchanin/strava-api/blob/a185fee415d606357a462fbeb5cc8de9f6130cdf/lib/strava-api/clubs.rb#L22-L26 | train |
printercu/rails_stuff | lib/rails_stuff/params_parser.rb | RailsStuff.ParamsParser.parse | def parse(val, *args, &block)
parse_not_blank(val, *args, &block)
rescue => e # rubocop:disable Lint/RescueWithoutErrorClass
raise Error.new(e.message, val), nil, e.backtrace
end | ruby | def parse(val, *args, &block)
parse_not_blank(val, *args, &block)
rescue => e # rubocop:disable Lint/RescueWithoutErrorClass
raise Error.new(e.message, val), nil, e.backtrace
end | [
"def",
"parse",
"(",
"val",
",",
"*",
"args",
",",
"&",
"block",
")",
"parse_not_blank",
"(",
"val",
",",
"*",
"args",
",",
"&",
"block",
")",
"rescue",
"=>",
"e",
"raise",
"Error",
".",
"new",
"(",
"e",
".",
"message",
",",
"val",
")",
",",
"nil",
",",
"e",
".",
"backtrace",
"end"
] | Parses value with specified block. Reraises occured error with Error. | [
"Parses",
"value",
"with",
"specified",
"block",
".",
"Reraises",
"occured",
"error",
"with",
"Error",
"."
] | b3d72daaae6426c8166205f6a7438a89768e8347 | https://github.com/printercu/rails_stuff/blob/b3d72daaae6426c8166205f6a7438a89768e8347/lib/rails_stuff/params_parser.rb#L47-L51 | train |
printercu/rails_stuff | lib/rails_stuff/params_parser.rb | RailsStuff.ParamsParser.parse_array | def parse_array(array, *args, &block)
return unless array.is_a?(Array)
parse(array) { array.map { |val| parse_not_blank(val, *args, &block) } }
end | ruby | def parse_array(array, *args, &block)
return unless array.is_a?(Array)
parse(array) { array.map { |val| parse_not_blank(val, *args, &block) } }
end | [
"def",
"parse_array",
"(",
"array",
",",
"*",
"args",
",",
"&",
"block",
")",
"return",
"unless",
"array",
".",
"is_a?",
"(",
"Array",
")",
"parse",
"(",
"array",
")",
"{",
"array",
".",
"map",
"{",
"|",
"val",
"|",
"parse_not_blank",
"(",
"val",
",",
"*",
"args",
",",
"&",
"block",
")",
"}",
"}",
"end"
] | Parses each value in array with specified block.
Returns `nil` if `val` is not an array. | [
"Parses",
"each",
"value",
"in",
"array",
"with",
"specified",
"block",
".",
"Returns",
"nil",
"if",
"val",
"is",
"not",
"an",
"array",
"."
] | b3d72daaae6426c8166205f6a7438a89768e8347 | https://github.com/printercu/rails_stuff/blob/b3d72daaae6426c8166205f6a7438a89768e8347/lib/rails_stuff/params_parser.rb#L55-L58 | train |
dadooda/rails_dt | lib/dt/instance.rb | DT.Instance.rails_logger | def rails_logger
if instance_variable_defined?(k = :@rails_logger)
instance_variable_get(k)
else
instance_variable_set(k, conf.rails && conf.rails.logger)
end
end | ruby | def rails_logger
if instance_variable_defined?(k = :@rails_logger)
instance_variable_get(k)
else
instance_variable_set(k, conf.rails && conf.rails.logger)
end
end | [
"def",
"rails_logger",
"if",
"instance_variable_defined?",
"(",
"k",
"=",
":@rails_logger",
")",
"instance_variable_get",
"(",
"k",
")",
"else",
"instance_variable_set",
"(",
"k",
",",
"conf",
".",
"rails",
"&&",
"conf",
".",
"rails",
".",
"logger",
")",
"end",
"end"
] | An object to use as log in Rails mode.
@return [ActiveSupport::Logger] Default is <tt>conf.rails.logger</tt>. | [
"An",
"object",
"to",
"use",
"as",
"log",
"in",
"Rails",
"mode",
"."
] | a421b678b0041ef7c2af62f516b71df77403bf2b | https://github.com/dadooda/rails_dt/blob/a421b678b0041ef7c2af62f516b71df77403bf2b/lib/dt/instance.rb#L51-L57 | train |
printercu/rails_stuff | lib/rails_stuff/require_nested.rb | RailsStuff.RequireNested.require_nested | def require_nested(dir = 0)
dir = caller_locations(dir + 1, 1)[0].path.sub(/\.rb$/, '') if dir.is_a?(Integer)
Dir["#{dir}/*.rb"].each { |file| require_dependency file }
end | ruby | def require_nested(dir = 0)
dir = caller_locations(dir + 1, 1)[0].path.sub(/\.rb$/, '') if dir.is_a?(Integer)
Dir["#{dir}/*.rb"].each { |file| require_dependency file }
end | [
"def",
"require_nested",
"(",
"dir",
"=",
"0",
")",
"dir",
"=",
"caller_locations",
"(",
"dir",
"+",
"1",
",",
"1",
")",
"[",
"0",
"]",
".",
"path",
".",
"sub",
"(",
"/",
"\\.",
"/",
",",
"''",
")",
"if",
"dir",
".",
"is_a?",
"(",
"Integer",
")",
"Dir",
"[",
"\"#{dir}/*.rb\"",
"]",
".",
"each",
"{",
"|",
"file",
"|",
"require_dependency",
"file",
"}",
"end"
] | Requires nested modules with `require_dependency`.
Pass custom directory to require its content.
By default uses caller's filename with stripped `.rb` extension from. | [
"Requires",
"nested",
"modules",
"with",
"require_dependency",
".",
"Pass",
"custom",
"directory",
"to",
"require",
"its",
"content",
".",
"By",
"default",
"uses",
"caller",
"s",
"filename",
"with",
"stripped",
".",
"rb",
"extension",
"from",
"."
] | b3d72daaae6426c8166205f6a7438a89768e8347 | https://github.com/printercu/rails_stuff/blob/b3d72daaae6426c8166205f6a7438a89768e8347/lib/rails_stuff/require_nested.rb#L17-L20 | train |
stevenchanin/strava-api | lib/strava-api/rides.rb | StravaApi.Rides.ride_efforts | def ride_efforts(id)
result = call("rides/#{id}/efforts", "efforts", {})
result["efforts"].collect {|effort| Effort.new(self, effort)}
end | ruby | def ride_efforts(id)
result = call("rides/#{id}/efforts", "efforts", {})
result["efforts"].collect {|effort| Effort.new(self, effort)}
end | [
"def",
"ride_efforts",
"(",
"id",
")",
"result",
"=",
"call",
"(",
"\"rides/#{id}/efforts\"",
",",
"\"efforts\"",
",",
"{",
"}",
")",
"result",
"[",
"\"efforts\"",
"]",
".",
"collect",
"{",
"|",
"effort",
"|",
"Effort",
".",
"new",
"(",
"self",
",",
"effort",
")",
"}",
"end"
] | returns all efforts, don't need an offset | [
"returns",
"all",
"efforts",
"don",
"t",
"need",
"an",
"offset"
] | a185fee415d606357a462fbeb5cc8de9f6130cdf | https://github.com/stevenchanin/strava-api/blob/a185fee415d606357a462fbeb5cc8de9f6130cdf/lib/strava-api/rides.rb#L33-L37 | train |
blackwinter/wadl | lib/wadl/xml_representation.rb | WADL.XMLRepresentation.each_by_param | def each_by_param(param_name)
REXML::XPath.each(self, lookup_param(param_name).path) { |e| yield e }
end | ruby | def each_by_param(param_name)
REXML::XPath.each(self, lookup_param(param_name).path) { |e| yield e }
end | [
"def",
"each_by_param",
"(",
"param_name",
")",
"REXML",
"::",
"XPath",
".",
"each",
"(",
"self",
",",
"lookup_param",
"(",
"param_name",
")",
".",
"path",
")",
"{",
"|",
"e",
"|",
"yield",
"e",
"}",
"end"
] | Yields up each XML element for the given Param object. | [
"Yields",
"up",
"each",
"XML",
"element",
"for",
"the",
"given",
"Param",
"object",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/xml_representation.rb#L52-L54 | train |
blackwinter/wadl | lib/wadl/param.rb | WADL.Param.format | def format(value, name = nil, style = nil)
name ||= self.name
style ||= self.style
value = fixed if fixed
value ||= default if default
unless value
if required?
raise ArgumentError, %Q{No value provided for required param "#{name}"!}
else
return '' # No value provided and none required.
end
end
if value.respond_to?(:each) && !value.respond_to?(:to_str)
if repeating?
values = value
else
raise ArgumentError, %Q{Multiple values provided for single-value param "#{name}"}
end
else
values = [value]
end
# If the param lists acceptable values in option tags, make sure that
# all values are found in those tags.
if options && !options.empty?
values.each { |_value|
unless find_option(_value)
acceptable = options.map { |o| o.value }.join('", "')
raise ArgumentError, %Q{"#{_value}" is not among the acceptable parameter values ("#{acceptable}")}
end
}
end
if style == 'query' || parent.is_a?(RequestFormat) || (
parent.respond_to?(:is_form_representation?) && parent.is_form_representation?
)
values.map { |v| "#{uri_escape(name)}=#{uri_escape(v.to_s)}" }.join('&')
elsif style == 'matrix'
if type == 'xsd:boolean'
values.map { |v| ";#{name}" if v =~ BOOLEAN_RE }.compact.join
else
values.map { |v| ";#{uri_escape(name)}=#{uri_escape(v.to_s)}" if v }.compact.join
end
elsif style == 'header'
values.join(',')
else
# All other cases: plain text representation.
values.map { |v| uri_escape(v.to_s) }.join(',')
end
end | ruby | def format(value, name = nil, style = nil)
name ||= self.name
style ||= self.style
value = fixed if fixed
value ||= default if default
unless value
if required?
raise ArgumentError, %Q{No value provided for required param "#{name}"!}
else
return '' # No value provided and none required.
end
end
if value.respond_to?(:each) && !value.respond_to?(:to_str)
if repeating?
values = value
else
raise ArgumentError, %Q{Multiple values provided for single-value param "#{name}"}
end
else
values = [value]
end
# If the param lists acceptable values in option tags, make sure that
# all values are found in those tags.
if options && !options.empty?
values.each { |_value|
unless find_option(_value)
acceptable = options.map { |o| o.value }.join('", "')
raise ArgumentError, %Q{"#{_value}" is not among the acceptable parameter values ("#{acceptable}")}
end
}
end
if style == 'query' || parent.is_a?(RequestFormat) || (
parent.respond_to?(:is_form_representation?) && parent.is_form_representation?
)
values.map { |v| "#{uri_escape(name)}=#{uri_escape(v.to_s)}" }.join('&')
elsif style == 'matrix'
if type == 'xsd:boolean'
values.map { |v| ";#{name}" if v =~ BOOLEAN_RE }.compact.join
else
values.map { |v| ";#{uri_escape(name)}=#{uri_escape(v.to_s)}" if v }.compact.join
end
elsif style == 'header'
values.join(',')
else
# All other cases: plain text representation.
values.map { |v| uri_escape(v.to_s) }.join(',')
end
end | [
"def",
"format",
"(",
"value",
",",
"name",
"=",
"nil",
",",
"style",
"=",
"nil",
")",
"name",
"||=",
"self",
".",
"name",
"style",
"||=",
"self",
".",
"style",
"value",
"=",
"fixed",
"if",
"fixed",
"value",
"||=",
"default",
"if",
"default",
"unless",
"value",
"if",
"required?",
"raise",
"ArgumentError",
",",
"%Q{No value provided for required param \"#{name}\"!}",
"else",
"return",
"''",
"end",
"end",
"if",
"value",
".",
"respond_to?",
"(",
":each",
")",
"&&",
"!",
"value",
".",
"respond_to?",
"(",
":to_str",
")",
"if",
"repeating?",
"values",
"=",
"value",
"else",
"raise",
"ArgumentError",
",",
"%Q{Multiple values provided for single-value param \"#{name}\"}",
"end",
"else",
"values",
"=",
"[",
"value",
"]",
"end",
"if",
"options",
"&&",
"!",
"options",
".",
"empty?",
"values",
".",
"each",
"{",
"|",
"_value",
"|",
"unless",
"find_option",
"(",
"_value",
")",
"acceptable",
"=",
"options",
".",
"map",
"{",
"|",
"o",
"|",
"o",
".",
"value",
"}",
".",
"join",
"(",
"'\", \"'",
")",
"raise",
"ArgumentError",
",",
"%Q{\"#{_value}\" is not among the acceptable parameter values (\"#{acceptable}\")}",
"end",
"}",
"end",
"if",
"style",
"==",
"'query'",
"||",
"parent",
".",
"is_a?",
"(",
"RequestFormat",
")",
"||",
"(",
"parent",
".",
"respond_to?",
"(",
":is_form_representation?",
")",
"&&",
"parent",
".",
"is_form_representation?",
")",
"values",
".",
"map",
"{",
"|",
"v",
"|",
"\"#{uri_escape(name)}=#{uri_escape(v.to_s)}\"",
"}",
".",
"join",
"(",
"'&'",
")",
"elsif",
"style",
"==",
"'matrix'",
"if",
"type",
"==",
"'xsd:boolean'",
"values",
".",
"map",
"{",
"|",
"v",
"|",
"\";#{name}\"",
"if",
"v",
"=~",
"BOOLEAN_RE",
"}",
".",
"compact",
".",
"join",
"else",
"values",
".",
"map",
"{",
"|",
"v",
"|",
"\";#{uri_escape(name)}=#{uri_escape(v.to_s)}\"",
"if",
"v",
"}",
".",
"compact",
".",
"join",
"end",
"elsif",
"style",
"==",
"'header'",
"values",
".",
"join",
"(",
"','",
")",
"else",
"values",
".",
"map",
"{",
"|",
"v",
"|",
"uri_escape",
"(",
"v",
".",
"to_s",
")",
"}",
".",
"join",
"(",
"','",
")",
"end",
"end"
] | Validates and formats a proposed value for this parameter. Returns
the formatted value. Raises an ArgumentError if the value
is invalid.
The 'name' and 'style' arguments are used in conjunction with the
default Param object. | [
"Validates",
"and",
"formats",
"a",
"proposed",
"value",
"for",
"this",
"parameter",
".",
"Returns",
"the",
"formatted",
"value",
".",
"Raises",
"an",
"ArgumentError",
"if",
"the",
"value",
"is",
"invalid",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/param.rb#L76-L128 | train |
9kSoftware/plaid_rails | app/models/plaid_rails/account.rb | PlaidRails.Account.delete_updated_token | def delete_updated_token
# change all matching tokens on update
accounts = PlaidRails::Account.where(access_token: my_token)
if accounts.size > 0
delete_connect
end
end | ruby | def delete_updated_token
# change all matching tokens on update
accounts = PlaidRails::Account.where(access_token: my_token)
if accounts.size > 0
delete_connect
end
end | [
"def",
"delete_updated_token",
"accounts",
"=",
"PlaidRails",
"::",
"Account",
".",
"where",
"(",
"access_token",
":",
"my_token",
")",
"if",
"accounts",
".",
"size",
">",
"0",
"delete_connect",
"end",
"end"
] | delete token from Plaid if there are no more accounts for this token | [
"delete",
"token",
"from",
"Plaid",
"if",
"there",
"are",
"no",
"more",
"accounts",
"for",
"this",
"token"
] | abad75600c26c20a29d5fa3df80d52487a4e72cc | https://github.com/9kSoftware/plaid_rails/blob/abad75600c26c20a29d5fa3df80d52487a4e72cc/app/models/plaid_rails/account.rb#L15-L21 | train |
9kSoftware/plaid_rails | app/models/plaid_rails/account.rb | PlaidRails.Account.delete_connect | def delete_connect
begin
Rails.logger.info "Deleting Plaid User with token #{token_last_8}"
client = Plaid::Client.new(env: PlaidRails.env,
client_id: PlaidRails.client_id,
secret: PlaidRails.secret,
public_key: PlaidRails.public_key)
client.item.remove(access_token)
Rails.logger.info "Deleted Plaid User with token #{token_last_8}"
rescue => e
message = "Unable to delete user with token #{token_last_8}"
Rails.logger.error "#{message}: #{e.message}"
end
end | ruby | def delete_connect
begin
Rails.logger.info "Deleting Plaid User with token #{token_last_8}"
client = Plaid::Client.new(env: PlaidRails.env,
client_id: PlaidRails.client_id,
secret: PlaidRails.secret,
public_key: PlaidRails.public_key)
client.item.remove(access_token)
Rails.logger.info "Deleted Plaid User with token #{token_last_8}"
rescue => e
message = "Unable to delete user with token #{token_last_8}"
Rails.logger.error "#{message}: #{e.message}"
end
end | [
"def",
"delete_connect",
"begin",
"Rails",
".",
"logger",
".",
"info",
"\"Deleting Plaid User with token #{token_last_8}\"",
"client",
"=",
"Plaid",
"::",
"Client",
".",
"new",
"(",
"env",
":",
"PlaidRails",
".",
"env",
",",
"client_id",
":",
"PlaidRails",
".",
"client_id",
",",
"secret",
":",
"PlaidRails",
".",
"secret",
",",
"public_key",
":",
"PlaidRails",
".",
"public_key",
")",
"client",
".",
"item",
".",
"remove",
"(",
"access_token",
")",
"Rails",
".",
"logger",
".",
"info",
"\"Deleted Plaid User with token #{token_last_8}\"",
"rescue",
"=>",
"e",
"message",
"=",
"\"Unable to delete user with token #{token_last_8}\"",
"Rails",
".",
"logger",
".",
"error",
"\"#{message}: #{e.message}\"",
"end",
"end"
] | delete Plaid user | [
"delete",
"Plaid",
"user"
] | abad75600c26c20a29d5fa3df80d52487a4e72cc | https://github.com/9kSoftware/plaid_rails/blob/abad75600c26c20a29d5fa3df80d52487a4e72cc/app/models/plaid_rails/account.rb#L24-L38 | train |
printercu/rails_stuff | lib/rails_stuff/types_tracker.rb | RailsStuff.TypesTracker.register_type | def register_type(*args)
if types_list.respond_to?(:add)
types_list.add self, *args
else
types_list << self
end
if types_tracker_base.respond_to?(:scope) &&
!types_tracker_base.respond_to?(model_name.element)
type_name = name
types_tracker_base.scope model_name.element, -> { where(type: type_name) }
end
end | ruby | def register_type(*args)
if types_list.respond_to?(:add)
types_list.add self, *args
else
types_list << self
end
if types_tracker_base.respond_to?(:scope) &&
!types_tracker_base.respond_to?(model_name.element)
type_name = name
types_tracker_base.scope model_name.element, -> { where(type: type_name) }
end
end | [
"def",
"register_type",
"(",
"*",
"args",
")",
"if",
"types_list",
".",
"respond_to?",
"(",
":add",
")",
"types_list",
".",
"add",
"self",
",",
"*",
"args",
"else",
"types_list",
"<<",
"self",
"end",
"if",
"types_tracker_base",
".",
"respond_to?",
"(",
":scope",
")",
"&&",
"!",
"types_tracker_base",
".",
"respond_to?",
"(",
"model_name",
".",
"element",
")",
"type_name",
"=",
"name",
"types_tracker_base",
".",
"scope",
"model_name",
".",
"element",
",",
"->",
"{",
"where",
"(",
"type",
":",
"type_name",
")",
"}",
"end",
"end"
] | Add `self` to `types_list`. Defines scope for ActiveRecord models. | [
"Add",
"self",
"to",
"types_list",
".",
"Defines",
"scope",
"for",
"ActiveRecord",
"models",
"."
] | b3d72daaae6426c8166205f6a7438a89768e8347 | https://github.com/printercu/rails_stuff/blob/b3d72daaae6426c8166205f6a7438a89768e8347/lib/rails_stuff/types_tracker.rb#L26-L37 | train |
printercu/rails_stuff | lib/rails_stuff/redis_storage.rb | RailsStuff.RedisStorage.get | def get(id)
return unless id
with_redis { |redis| redis.get(redis_key_for(id)).try { |data| load(data) } }
end | ruby | def get(id)
return unless id
with_redis { |redis| redis.get(redis_key_for(id)).try { |data| load(data) } }
end | [
"def",
"get",
"(",
"id",
")",
"return",
"unless",
"id",
"with_redis",
"{",
"|",
"redis",
"|",
"redis",
".",
"get",
"(",
"redis_key_for",
"(",
"id",
")",
")",
".",
"try",
"{",
"|",
"data",
"|",
"load",
"(",
"data",
")",
"}",
"}",
"end"
] | Reads value from redis. | [
"Reads",
"value",
"from",
"redis",
"."
] | b3d72daaae6426c8166205f6a7438a89768e8347 | https://github.com/printercu/rails_stuff/blob/b3d72daaae6426c8166205f6a7438a89768e8347/lib/rails_stuff/redis_storage.rb#L107-L110 | train |
printercu/rails_stuff | lib/rails_stuff/redis_storage.rb | RailsStuff.RedisStorage.delete | def delete(id)
return true unless id
with_redis { |redis| redis.del(redis_key_for(id)) }
true
end | ruby | def delete(id)
return true unless id
with_redis { |redis| redis.del(redis_key_for(id)) }
true
end | [
"def",
"delete",
"(",
"id",
")",
"return",
"true",
"unless",
"id",
"with_redis",
"{",
"|",
"redis",
"|",
"redis",
".",
"del",
"(",
"redis_key_for",
"(",
"id",
")",
")",
"}",
"true",
"end"
] | Remove record from redis. | [
"Remove",
"record",
"from",
"redis",
"."
] | b3d72daaae6426c8166205f6a7438a89768e8347 | https://github.com/printercu/rails_stuff/blob/b3d72daaae6426c8166205f6a7438a89768e8347/lib/rails_stuff/redis_storage.rb#L113-L117 | train |
pitluga/keepassx | lib/keepassx/database.rb | Keepassx.Database.add_group | def add_group(opts)
raise ArgumentError, "Expected Hash or Keepassx::Group, got #{opts.class}" unless valid_group?(opts)
if opts.is_a?(Keepassx::Group)
# Assign parent group
parent = opts.parent
index = last_sibling_index(parent) + 1
@groups.insert(index, opts)
# Increment counter
header.groups_count += 1
# Return group
opts
elsif opts.is_a?(Hash)
opts = deep_copy(opts)
opts = build_group_options(opts)
# Create group
group = create_group(opts)
# Increment counter
header.groups_count += 1
# Return group
group
end
end | ruby | def add_group(opts)
raise ArgumentError, "Expected Hash or Keepassx::Group, got #{opts.class}" unless valid_group?(opts)
if opts.is_a?(Keepassx::Group)
# Assign parent group
parent = opts.parent
index = last_sibling_index(parent) + 1
@groups.insert(index, opts)
# Increment counter
header.groups_count += 1
# Return group
opts
elsif opts.is_a?(Hash)
opts = deep_copy(opts)
opts = build_group_options(opts)
# Create group
group = create_group(opts)
# Increment counter
header.groups_count += 1
# Return group
group
end
end | [
"def",
"add_group",
"(",
"opts",
")",
"raise",
"ArgumentError",
",",
"\"Expected Hash or Keepassx::Group, got #{opts.class}\"",
"unless",
"valid_group?",
"(",
"opts",
")",
"if",
"opts",
".",
"is_a?",
"(",
"Keepassx",
"::",
"Group",
")",
"parent",
"=",
"opts",
".",
"parent",
"index",
"=",
"last_sibling_index",
"(",
"parent",
")",
"+",
"1",
"@groups",
".",
"insert",
"(",
"index",
",",
"opts",
")",
"header",
".",
"groups_count",
"+=",
"1",
"opts",
"elsif",
"opts",
".",
"is_a?",
"(",
"Hash",
")",
"opts",
"=",
"deep_copy",
"(",
"opts",
")",
"opts",
"=",
"build_group_options",
"(",
"opts",
")",
"group",
"=",
"create_group",
"(",
"opts",
")",
"header",
".",
"groups_count",
"+=",
"1",
"group",
"end",
"end"
] | Add new group to database.
@param opts [Hash] Options that will be passed to Keepassx::Group#new.
@return [Keepassx::Group]
rubocop:disable Metrics/MethodLength | [
"Add",
"new",
"group",
"to",
"database",
"."
] | a00fd5b71e6a8c742e272fdee456bfbe03b5adec | https://github.com/pitluga/keepassx/blob/a00fd5b71e6a8c742e272fdee456bfbe03b5adec/lib/keepassx/database.rb#L32-L60 | train |
pitluga/keepassx | lib/keepassx/database.rb | Keepassx.Database.next_group_id | def next_group_id
if @groups.empty?
# Start each time from 1 to make sure groups get the same id's for the
# same input data
1
else
id = @groups.last.id
loop do
id += 1
break id if @groups.find { |g| g.id == id }.nil?
end
end
end | ruby | def next_group_id
if @groups.empty?
# Start each time from 1 to make sure groups get the same id's for the
# same input data
1
else
id = @groups.last.id
loop do
id += 1
break id if @groups.find { |g| g.id == id }.nil?
end
end
end | [
"def",
"next_group_id",
"if",
"@groups",
".",
"empty?",
"1",
"else",
"id",
"=",
"@groups",
".",
"last",
".",
"id",
"loop",
"do",
"id",
"+=",
"1",
"break",
"id",
"if",
"@groups",
".",
"find",
"{",
"|",
"g",
"|",
"g",
".",
"id",
"==",
"id",
"}",
".",
"nil?",
"end",
"end",
"end"
] | Get next group ID number.
@return [Fixnum] | [
"Get",
"next",
"group",
"ID",
"number",
"."
] | a00fd5b71e6a8c742e272fdee456bfbe03b5adec | https://github.com/pitluga/keepassx/blob/a00fd5b71e6a8c742e272fdee456bfbe03b5adec/lib/keepassx/database.rb#L131-L143 | train |
pitluga/keepassx | lib/keepassx/database.rb | Keepassx.Database.last_sibling_index | def last_sibling_index(parent)
return -1 if groups.empty?
if parent.nil?
parent_index = 0
sibling_level = 1
else
parent_index = groups.find_index(parent)
sibling_level = parent.level + 1
end
raise "Could not find group #{parent.name}" if parent_index.nil?
(parent_index..(header.groups_count - 1)).each do |i|
break i unless groups[i].level == sibling_level
end
end | ruby | def last_sibling_index(parent)
return -1 if groups.empty?
if parent.nil?
parent_index = 0
sibling_level = 1
else
parent_index = groups.find_index(parent)
sibling_level = parent.level + 1
end
raise "Could not find group #{parent.name}" if parent_index.nil?
(parent_index..(header.groups_count - 1)).each do |i|
break i unless groups[i].level == sibling_level
end
end | [
"def",
"last_sibling_index",
"(",
"parent",
")",
"return",
"-",
"1",
"if",
"groups",
".",
"empty?",
"if",
"parent",
".",
"nil?",
"parent_index",
"=",
"0",
"sibling_level",
"=",
"1",
"else",
"parent_index",
"=",
"groups",
".",
"find_index",
"(",
"parent",
")",
"sibling_level",
"=",
"parent",
".",
"level",
"+",
"1",
"end",
"raise",
"\"Could not find group #{parent.name}\"",
"if",
"parent_index",
".",
"nil?",
"(",
"parent_index",
"..",
"(",
"header",
".",
"groups_count",
"-",
"1",
")",
")",
".",
"each",
"do",
"|",
"i",
"|",
"break",
"i",
"unless",
"groups",
"[",
"i",
"]",
".",
"level",
"==",
"sibling_level",
"end",
"end"
] | Retrieves last sibling index
@param parent [Keepassx::Group] Last sibling group.
@return [Integer] index Group index. | [
"Retrieves",
"last",
"sibling",
"index"
] | a00fd5b71e6a8c742e272fdee456bfbe03b5adec | https://github.com/pitluga/keepassx/blob/a00fd5b71e6a8c742e272fdee456bfbe03b5adec/lib/keepassx/database.rb#L150-L166 | train |
blackwinter/wadl | lib/wadl/resource.rb | WADL.Resource.address | def address(working_address = nil)
working_address &&= working_address.deep_copy
working_address ||= if parent.respond_to?(:base)
address = Address.new
address.path_fragments << parent.base
address
else
parent.address.deep_copy
end
working_address.path_fragments << path.dup
# Install path, query, and header parameters in the Address. These
# may override existing parameters with the same names, but if
# you've got a WADL application that works that way, you should
# have bound parameters to values earlier.
new_path_fragments = []
embedded_param_names = Set.new(Address.embedded_param_names(path))
params.each { |param|
name = param.name
if embedded_param_names.include?(name)
working_address.path_params[name] = param
else
if param.style == 'query'
working_address.query_params[name] = param
elsif param.style == 'header'
working_address.header_params[name] = param
else
new_path_fragments << param
working_address.path_params[name] = param
end
end
}
working_address.path_fragments << new_path_fragments unless new_path_fragments.empty?
working_address
end | ruby | def address(working_address = nil)
working_address &&= working_address.deep_copy
working_address ||= if parent.respond_to?(:base)
address = Address.new
address.path_fragments << parent.base
address
else
parent.address.deep_copy
end
working_address.path_fragments << path.dup
# Install path, query, and header parameters in the Address. These
# may override existing parameters with the same names, but if
# you've got a WADL application that works that way, you should
# have bound parameters to values earlier.
new_path_fragments = []
embedded_param_names = Set.new(Address.embedded_param_names(path))
params.each { |param|
name = param.name
if embedded_param_names.include?(name)
working_address.path_params[name] = param
else
if param.style == 'query'
working_address.query_params[name] = param
elsif param.style == 'header'
working_address.header_params[name] = param
else
new_path_fragments << param
working_address.path_params[name] = param
end
end
}
working_address.path_fragments << new_path_fragments unless new_path_fragments.empty?
working_address
end | [
"def",
"address",
"(",
"working_address",
"=",
"nil",
")",
"working_address",
"&&=",
"working_address",
".",
"deep_copy",
"working_address",
"||=",
"if",
"parent",
".",
"respond_to?",
"(",
":base",
")",
"address",
"=",
"Address",
".",
"new",
"address",
".",
"path_fragments",
"<<",
"parent",
".",
"base",
"address",
"else",
"parent",
".",
"address",
".",
"deep_copy",
"end",
"working_address",
".",
"path_fragments",
"<<",
"path",
".",
"dup",
"new_path_fragments",
"=",
"[",
"]",
"embedded_param_names",
"=",
"Set",
".",
"new",
"(",
"Address",
".",
"embedded_param_names",
"(",
"path",
")",
")",
"params",
".",
"each",
"{",
"|",
"param",
"|",
"name",
"=",
"param",
".",
"name",
"if",
"embedded_param_names",
".",
"include?",
"(",
"name",
")",
"working_address",
".",
"path_params",
"[",
"name",
"]",
"=",
"param",
"else",
"if",
"param",
".",
"style",
"==",
"'query'",
"working_address",
".",
"query_params",
"[",
"name",
"]",
"=",
"param",
"elsif",
"param",
".",
"style",
"==",
"'header'",
"working_address",
".",
"header_params",
"[",
"name",
"]",
"=",
"param",
"else",
"new_path_fragments",
"<<",
"param",
"working_address",
".",
"path_params",
"[",
"name",
"]",
"=",
"param",
"end",
"end",
"}",
"working_address",
".",
"path_fragments",
"<<",
"new_path_fragments",
"unless",
"new_path_fragments",
".",
"empty?",
"working_address",
"end"
] | Returns an Address object refering to this resource | [
"Returns",
"an",
"Address",
"object",
"refering",
"to",
"this",
"resource"
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/resource.rb#L82-L122 | train |
blackwinter/wadl | lib/wadl/representation_format.rb | WADL.RepresentationFormat.% | def %(values)
unless is_form_representation?
raise "wadl can't instantiate a representation of type #{mediaType}"
end
representation = []
params.each { |param|
name = param.name
if param.fixed
p_values = [param.fixed]
elsif p_values = values[name] || values[name.to_sym]
p_values = [p_values] if !param.repeating? || !p_values.respond_to?(:each) || p_values.respond_to?(:to_str)
else
raise ArgumentError, "Your proposed representation is missing a value for #{param.name}" if param.required?
end
p_values.each { |v| representation << "#{CGI.escape(name)}=#{CGI.escape(v.to_s)}" } if p_values
}
representation.join('&')
end | ruby | def %(values)
unless is_form_representation?
raise "wadl can't instantiate a representation of type #{mediaType}"
end
representation = []
params.each { |param|
name = param.name
if param.fixed
p_values = [param.fixed]
elsif p_values = values[name] || values[name.to_sym]
p_values = [p_values] if !param.repeating? || !p_values.respond_to?(:each) || p_values.respond_to?(:to_str)
else
raise ArgumentError, "Your proposed representation is missing a value for #{param.name}" if param.required?
end
p_values.each { |v| representation << "#{CGI.escape(name)}=#{CGI.escape(v.to_s)}" } if p_values
}
representation.join('&')
end | [
"def",
"%",
"(",
"values",
")",
"unless",
"is_form_representation?",
"raise",
"\"wadl can't instantiate a representation of type #{mediaType}\"",
"end",
"representation",
"=",
"[",
"]",
"params",
".",
"each",
"{",
"|",
"param",
"|",
"name",
"=",
"param",
".",
"name",
"if",
"param",
".",
"fixed",
"p_values",
"=",
"[",
"param",
".",
"fixed",
"]",
"elsif",
"p_values",
"=",
"values",
"[",
"name",
"]",
"||",
"values",
"[",
"name",
".",
"to_sym",
"]",
"p_values",
"=",
"[",
"p_values",
"]",
"if",
"!",
"param",
".",
"repeating?",
"||",
"!",
"p_values",
".",
"respond_to?",
"(",
":each",
")",
"||",
"p_values",
".",
"respond_to?",
"(",
":to_str",
")",
"else",
"raise",
"ArgumentError",
",",
"\"Your proposed representation is missing a value for #{param.name}\"",
"if",
"param",
".",
"required?",
"end",
"p_values",
".",
"each",
"{",
"|",
"v",
"|",
"representation",
"<<",
"\"#{CGI.escape(name)}=#{CGI.escape(v.to_s)}\"",
"}",
"if",
"p_values",
"}",
"representation",
".",
"join",
"(",
"'&'",
")",
"end"
] | Creates a representation by plugging a set of parameters
into a representation format. | [
"Creates",
"a",
"representation",
"by",
"plugging",
"a",
"set",
"of",
"parameters",
"into",
"a",
"representation",
"format",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/representation_format.rb#L48-L70 | train |
josephholsten/rets4r | lib/rets4r/client.rb | RETS4R.Client.login | def login(username, password) #:yields: login_results
@request_struct.username = username
@request_struct.password = password
# We are required to set the Accept header to this by the RETS 1.5 specification.
set_header('Accept', '*/*')
response = request(@urls.login)
# Parse response to get other URLS
results = @response_parser.parse_key_value(response.body)
# TODO: fix test to like this
# results = ResponseDocument.safe_parse(response.body).validate!.parse_key_value
if (results.success?)
CAPABILITY_LIST.each do |capability|
next unless results.response[capability]
uri = URI.parse(results.response[capability])
if uri.absolute?
@urls[capability] = uri
else
base = @urls.login.clone
base.path = results.response[capability]
@urls[capability] = base
end
end
logger.debug("Capability URL List: #{@urls.inspect}") if logger
else
raise LoginError.new(response.message + "(#{results.reply_code}: #{results.reply_text})")
end
# Perform the mandatory get request on the action URL.
results.secondary_response = perform_action_url
# We only yield
if block_given?
begin
yield results
ensure
self.logout
end
else
results
end
end | ruby | def login(username, password) #:yields: login_results
@request_struct.username = username
@request_struct.password = password
# We are required to set the Accept header to this by the RETS 1.5 specification.
set_header('Accept', '*/*')
response = request(@urls.login)
# Parse response to get other URLS
results = @response_parser.parse_key_value(response.body)
# TODO: fix test to like this
# results = ResponseDocument.safe_parse(response.body).validate!.parse_key_value
if (results.success?)
CAPABILITY_LIST.each do |capability|
next unless results.response[capability]
uri = URI.parse(results.response[capability])
if uri.absolute?
@urls[capability] = uri
else
base = @urls.login.clone
base.path = results.response[capability]
@urls[capability] = base
end
end
logger.debug("Capability URL List: #{@urls.inspect}") if logger
else
raise LoginError.new(response.message + "(#{results.reply_code}: #{results.reply_text})")
end
# Perform the mandatory get request on the action URL.
results.secondary_response = perform_action_url
# We only yield
if block_given?
begin
yield results
ensure
self.logout
end
else
results
end
end | [
"def",
"login",
"(",
"username",
",",
"password",
")",
"@request_struct",
".",
"username",
"=",
"username",
"@request_struct",
".",
"password",
"=",
"password",
"set_header",
"(",
"'Accept'",
",",
"'*/*'",
")",
"response",
"=",
"request",
"(",
"@urls",
".",
"login",
")",
"results",
"=",
"@response_parser",
".",
"parse_key_value",
"(",
"response",
".",
"body",
")",
"if",
"(",
"results",
".",
"success?",
")",
"CAPABILITY_LIST",
".",
"each",
"do",
"|",
"capability",
"|",
"next",
"unless",
"results",
".",
"response",
"[",
"capability",
"]",
"uri",
"=",
"URI",
".",
"parse",
"(",
"results",
".",
"response",
"[",
"capability",
"]",
")",
"if",
"uri",
".",
"absolute?",
"@urls",
"[",
"capability",
"]",
"=",
"uri",
"else",
"base",
"=",
"@urls",
".",
"login",
".",
"clone",
"base",
".",
"path",
"=",
"results",
".",
"response",
"[",
"capability",
"]",
"@urls",
"[",
"capability",
"]",
"=",
"base",
"end",
"end",
"logger",
".",
"debug",
"(",
"\"Capability URL List: #{@urls.inspect}\"",
")",
"if",
"logger",
"else",
"raise",
"LoginError",
".",
"new",
"(",
"response",
".",
"message",
"+",
"\"(#{results.reply_code}: #{results.reply_text})\"",
")",
"end",
"results",
".",
"secondary_response",
"=",
"perform_action_url",
"if",
"block_given?",
"begin",
"yield",
"results",
"ensure",
"self",
".",
"logout",
"end",
"else",
"results",
"end",
"end"
] | RETS Transaction Methods
Most of these transaction methods mirror the RETS specification methods, so if you are
unsure what they mean, you should check the RETS specification. The latest version can be
found at http://www.rets.org
Attempts to log into the server using the provided username and password.
If called with a block, the results of the login action are yielded,
and logout is called when the block returns. In that case, #login
returns the block's value. If called without a block, returns the
result.
As specified in the RETS specification, the Action URL is called and
the results made available in the #secondary_results accessor of the
results object. | [
"RETS",
"Transaction",
"Methods"
] | ced066582823d2d0cdd2012d36a6898dbe9edb85 | https://github.com/josephholsten/rets4r/blob/ced066582823d2d0cdd2012d36a6898dbe9edb85/lib/rets4r/client.rb#L176-L223 | train |
josephholsten/rets4r | lib/rets4r/client.rb | RETS4R.Client.get_metadata | def get_metadata(type = 'METADATA-SYSTEM', id = '*')
xml = download_metadata(type, id)
result = @response_parser.parse_metadata(xml, @format)
# TODO: fix test to like this
# result = ResponseDocument.safe_parse(xml).validate!.to_rexml
if block_given?
yield result
else
result
end
end | ruby | def get_metadata(type = 'METADATA-SYSTEM', id = '*')
xml = download_metadata(type, id)
result = @response_parser.parse_metadata(xml, @format)
# TODO: fix test to like this
# result = ResponseDocument.safe_parse(xml).validate!.to_rexml
if block_given?
yield result
else
result
end
end | [
"def",
"get_metadata",
"(",
"type",
"=",
"'METADATA-SYSTEM'",
",",
"id",
"=",
"'*'",
")",
"xml",
"=",
"download_metadata",
"(",
"type",
",",
"id",
")",
"result",
"=",
"@response_parser",
".",
"parse_metadata",
"(",
"xml",
",",
"@format",
")",
"if",
"block_given?",
"yield",
"result",
"else",
"result",
"end",
"end"
] | Requests Metadata from the server. An optional type and id can be specified to request
subsets of the Metadata. Please see the RETS specification for more details on this.
The format variable tells the server which format to return the Metadata in. Unless you
need the raw metadata in a specified format, you really shouldn't specify the format.
If called with a block, yields the results and returns the value of the block, or
returns the metadata directly. | [
"Requests",
"Metadata",
"from",
"the",
"server",
".",
"An",
"optional",
"type",
"and",
"id",
"can",
"be",
"specified",
"to",
"request",
"subsets",
"of",
"the",
"Metadata",
".",
"Please",
"see",
"the",
"RETS",
"specification",
"for",
"more",
"details",
"on",
"this",
".",
"The",
"format",
"variable",
"tells",
"the",
"server",
"which",
"format",
"to",
"return",
"the",
"Metadata",
"in",
".",
"Unless",
"you",
"need",
"the",
"raw",
"metadata",
"in",
"a",
"specified",
"format",
"you",
"really",
"shouldn",
"t",
"specify",
"the",
"format",
"."
] | ced066582823d2d0cdd2012d36a6898dbe9edb85 | https://github.com/josephholsten/rets4r/blob/ced066582823d2d0cdd2012d36a6898dbe9edb85/lib/rets4r/client.rb#L241-L253 | train |
josephholsten/rets4r | lib/rets4r/client.rb | RETS4R.Client.get_object | def get_object(resource, type, id, location = false) #:yields: data_object
header = {
'Accept' => mimemap.keys.join(',')
}
data = {
'Resource' => resource,
'Type' => type,
'ID' => id,
'Location' => location ? '1' : '0'
}
response = request(@urls.objects, data, header)
results = block_given? ? 0 : []
if response['content-type'] && response['content-type'].include?('text/xml')
# This probably means that there was an error.
# Response parser will likely raise an exception.
# TODO: test this
rr = ResponseDocument.safe_parse(response.body).validate!.to_transaction
return rr
elsif response['content-type'] && response['content-type'].include?('multipart/parallel')
content_type = process_content_type(response['content-type'])
# TODO: log this
# puts "SPLIT ON #{content_type['boundary']}"
boundary = content_type['boundary']
if boundary =~ /\s*'([^']*)\s*/
boundary = $1
end
parts = response.body.split("\r\n--#{boundary}")
parts.shift # Get rid of the initial boundary
# TODO: log this
# puts "GOT PARTS #{parts.length}"
parts.each do |part|
(raw_header, raw_data) = part.split("\r\n\r\n")
# TODO: log this
# puts raw_data.nil?
next unless raw_data
data_header = process_header(raw_header)
data_object = DataObject.new(data_header, raw_data)
if block_given?
yield data_object
results += 1
else
results << data_object
end
end
else
info = {
'content-type' => response['content-type'], # Compatibility shim. Deprecated.
'Content-Type' => response['content-type'],
'Object-ID' => response['Object-ID'],
'Content-ID' => response['Content-ID']
}
if response['Transfer-Encoding'].to_s.downcase == "chunked" || response['Content-Length'].to_i > 100 then
data_object = DataObject.new(info, response.body)
if block_given?
yield data_object
results += 1
else
results << data_object
end
end
end
results
end | ruby | def get_object(resource, type, id, location = false) #:yields: data_object
header = {
'Accept' => mimemap.keys.join(',')
}
data = {
'Resource' => resource,
'Type' => type,
'ID' => id,
'Location' => location ? '1' : '0'
}
response = request(@urls.objects, data, header)
results = block_given? ? 0 : []
if response['content-type'] && response['content-type'].include?('text/xml')
# This probably means that there was an error.
# Response parser will likely raise an exception.
# TODO: test this
rr = ResponseDocument.safe_parse(response.body).validate!.to_transaction
return rr
elsif response['content-type'] && response['content-type'].include?('multipart/parallel')
content_type = process_content_type(response['content-type'])
# TODO: log this
# puts "SPLIT ON #{content_type['boundary']}"
boundary = content_type['boundary']
if boundary =~ /\s*'([^']*)\s*/
boundary = $1
end
parts = response.body.split("\r\n--#{boundary}")
parts.shift # Get rid of the initial boundary
# TODO: log this
# puts "GOT PARTS #{parts.length}"
parts.each do |part|
(raw_header, raw_data) = part.split("\r\n\r\n")
# TODO: log this
# puts raw_data.nil?
next unless raw_data
data_header = process_header(raw_header)
data_object = DataObject.new(data_header, raw_data)
if block_given?
yield data_object
results += 1
else
results << data_object
end
end
else
info = {
'content-type' => response['content-type'], # Compatibility shim. Deprecated.
'Content-Type' => response['content-type'],
'Object-ID' => response['Object-ID'],
'Content-ID' => response['Content-ID']
}
if response['Transfer-Encoding'].to_s.downcase == "chunked" || response['Content-Length'].to_i > 100 then
data_object = DataObject.new(info, response.body)
if block_given?
yield data_object
results += 1
else
results << data_object
end
end
end
results
end | [
"def",
"get_object",
"(",
"resource",
",",
"type",
",",
"id",
",",
"location",
"=",
"false",
")",
"header",
"=",
"{",
"'Accept'",
"=>",
"mimemap",
".",
"keys",
".",
"join",
"(",
"','",
")",
"}",
"data",
"=",
"{",
"'Resource'",
"=>",
"resource",
",",
"'Type'",
"=>",
"type",
",",
"'ID'",
"=>",
"id",
",",
"'Location'",
"=>",
"location",
"?",
"'1'",
":",
"'0'",
"}",
"response",
"=",
"request",
"(",
"@urls",
".",
"objects",
",",
"data",
",",
"header",
")",
"results",
"=",
"block_given?",
"?",
"0",
":",
"[",
"]",
"if",
"response",
"[",
"'content-type'",
"]",
"&&",
"response",
"[",
"'content-type'",
"]",
".",
"include?",
"(",
"'text/xml'",
")",
"rr",
"=",
"ResponseDocument",
".",
"safe_parse",
"(",
"response",
".",
"body",
")",
".",
"validate!",
".",
"to_transaction",
"return",
"rr",
"elsif",
"response",
"[",
"'content-type'",
"]",
"&&",
"response",
"[",
"'content-type'",
"]",
".",
"include?",
"(",
"'multipart/parallel'",
")",
"content_type",
"=",
"process_content_type",
"(",
"response",
"[",
"'content-type'",
"]",
")",
"boundary",
"=",
"content_type",
"[",
"'boundary'",
"]",
"if",
"boundary",
"=~",
"/",
"\\s",
"\\s",
"/",
"boundary",
"=",
"$1",
"end",
"parts",
"=",
"response",
".",
"body",
".",
"split",
"(",
"\"\\r\\n--#{boundary}\"",
")",
"parts",
".",
"shift",
"parts",
".",
"each",
"do",
"|",
"part",
"|",
"(",
"raw_header",
",",
"raw_data",
")",
"=",
"part",
".",
"split",
"(",
"\"\\r\\n\\r\\n\"",
")",
"next",
"unless",
"raw_data",
"data_header",
"=",
"process_header",
"(",
"raw_header",
")",
"data_object",
"=",
"DataObject",
".",
"new",
"(",
"data_header",
",",
"raw_data",
")",
"if",
"block_given?",
"yield",
"data_object",
"results",
"+=",
"1",
"else",
"results",
"<<",
"data_object",
"end",
"end",
"else",
"info",
"=",
"{",
"'content-type'",
"=>",
"response",
"[",
"'content-type'",
"]",
",",
"'Content-Type'",
"=>",
"response",
"[",
"'content-type'",
"]",
",",
"'Object-ID'",
"=>",
"response",
"[",
"'Object-ID'",
"]",
",",
"'Content-ID'",
"=>",
"response",
"[",
"'Content-ID'",
"]",
"}",
"if",
"response",
"[",
"'Transfer-Encoding'",
"]",
".",
"to_s",
".",
"downcase",
"==",
"\"chunked\"",
"||",
"response",
"[",
"'Content-Length'",
"]",
".",
"to_i",
">",
"100",
"then",
"data_object",
"=",
"DataObject",
".",
"new",
"(",
"info",
",",
"response",
".",
"body",
")",
"if",
"block_given?",
"yield",
"data_object",
"results",
"+=",
"1",
"else",
"results",
"<<",
"data_object",
"end",
"end",
"end",
"results",
"end"
] | Performs a GetObject transaction on the server. For details on the arguments, please see
the RETS specification on GetObject requests.
This method either returns an Array of DataObject instances, or yields each DataObject
as it is created. If a block is given, the number of objects yielded is returned.
TODO: how much of this could we move over to WEBrick::HTTPRequest#parse? | [
"Performs",
"a",
"GetObject",
"transaction",
"on",
"the",
"server",
".",
"For",
"details",
"on",
"the",
"arguments",
"please",
"see",
"the",
"RETS",
"specification",
"on",
"GetObject",
"requests",
"."
] | ced066582823d2d0cdd2012d36a6898dbe9edb85 | https://github.com/josephholsten/rets4r/blob/ced066582823d2d0cdd2012d36a6898dbe9edb85/lib/rets4r/client.rb#L267-L341 | train |
josephholsten/rets4r | lib/rets4r/client.rb | RETS4R.Client.search | def search(search_type, klass, query, options = false)
header = {}
# Required Data
data = {
'SearchType' => search_type,
'Class' => klass,
'Query' => query,
'QueryType' => 'DMQL2',
'Format' => format,
'Count' => '0'
}
# Options
#--
# We might want to switch this to merge!, but I've kept it like this for now because it
# explicitly casts each value as a string prior to performing the search, so we find out now
# if can't force a value into the string context. I suppose it doesn't really matter when
# that happens, though...
#++
options.each { |k,v| data[k] = v.to_s } if options
response = request(@urls.search, data, header)
# TODO: make parser configurable
results = RETS4R::Client::CompactNokogiriParser.new(response.body)
if block_given?
results.each {|result| yield result}
else
return results.to_a
end
end | ruby | def search(search_type, klass, query, options = false)
header = {}
# Required Data
data = {
'SearchType' => search_type,
'Class' => klass,
'Query' => query,
'QueryType' => 'DMQL2',
'Format' => format,
'Count' => '0'
}
# Options
#--
# We might want to switch this to merge!, but I've kept it like this for now because it
# explicitly casts each value as a string prior to performing the search, so we find out now
# if can't force a value into the string context. I suppose it doesn't really matter when
# that happens, though...
#++
options.each { |k,v| data[k] = v.to_s } if options
response = request(@urls.search, data, header)
# TODO: make parser configurable
results = RETS4R::Client::CompactNokogiriParser.new(response.body)
if block_given?
results.each {|result| yield result}
else
return results.to_a
end
end | [
"def",
"search",
"(",
"search_type",
",",
"klass",
",",
"query",
",",
"options",
"=",
"false",
")",
"header",
"=",
"{",
"}",
"data",
"=",
"{",
"'SearchType'",
"=>",
"search_type",
",",
"'Class'",
"=>",
"klass",
",",
"'Query'",
"=>",
"query",
",",
"'QueryType'",
"=>",
"'DMQL2'",
",",
"'Format'",
"=>",
"format",
",",
"'Count'",
"=>",
"'0'",
"}",
"options",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"data",
"[",
"k",
"]",
"=",
"v",
".",
"to_s",
"}",
"if",
"options",
"response",
"=",
"request",
"(",
"@urls",
".",
"search",
",",
"data",
",",
"header",
")",
"results",
"=",
"RETS4R",
"::",
"Client",
"::",
"CompactNokogiriParser",
".",
"new",
"(",
"response",
".",
"body",
")",
"if",
"block_given?",
"results",
".",
"each",
"{",
"|",
"result",
"|",
"yield",
"result",
"}",
"else",
"return",
"results",
".",
"to_a",
"end",
"end"
] | Peforms a RETS search transaction. Again, please see the RETS specification for details
on what these parameters mean. The options parameter takes a hash of options that will
added to the search statement. | [
"Peforms",
"a",
"RETS",
"search",
"transaction",
".",
"Again",
"please",
"see",
"the",
"RETS",
"specification",
"for",
"details",
"on",
"what",
"these",
"parameters",
"mean",
".",
"The",
"options",
"parameter",
"takes",
"a",
"hash",
"of",
"options",
"that",
"will",
"added",
"to",
"the",
"search",
"statement",
"."
] | ced066582823d2d0cdd2012d36a6898dbe9edb85 | https://github.com/josephholsten/rets4r/blob/ced066582823d2d0cdd2012d36a6898dbe9edb85/lib/rets4r/client.rb#L346-L378 | train |
phatblat/xcode-installer | lib/xcode-installer/install.rb | XcodeInstaller.Install.cp_r | def cp_r(src, dest, options = {})
# fu_check_options options, OPT_TABLE['cp_r']
# fu_output_message "cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
options = options.dup
options[:dereference_root] = true unless options.key?(:dereference_root)
fu_each_src_dest(src, dest) do |s, d|
copy_entry s, d, options[:preserve], options[:dereference_root], options[:remove_destination]
end
end | ruby | def cp_r(src, dest, options = {})
# fu_check_options options, OPT_TABLE['cp_r']
# fu_output_message "cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
options = options.dup
options[:dereference_root] = true unless options.key?(:dereference_root)
fu_each_src_dest(src, dest) do |s, d|
copy_entry s, d, options[:preserve], options[:dereference_root], options[:remove_destination]
end
end | [
"def",
"cp_r",
"(",
"src",
",",
"dest",
",",
"options",
"=",
"{",
"}",
")",
"return",
"if",
"options",
"[",
":noop",
"]",
"options",
"=",
"options",
".",
"dup",
"options",
"[",
":dereference_root",
"]",
"=",
"true",
"unless",
"options",
".",
"key?",
"(",
":dereference_root",
")",
"fu_each_src_dest",
"(",
"src",
",",
"dest",
")",
"do",
"|",
"s",
",",
"d",
"|",
"copy_entry",
"s",
",",
"d",
",",
"options",
"[",
":preserve",
"]",
",",
"options",
"[",
":dereference_root",
"]",
",",
"options",
"[",
":remove_destination",
"]",
"end",
"end"
] | The following code was copied out of fileutils.rb from ruby 1.9.3-p392 | [
"The",
"following",
"code",
"was",
"copied",
"out",
"of",
"fileutils",
".",
"rb",
"from",
"ruby",
"1",
".",
"9",
".",
"3",
"-",
"p392"
] | f59aebb0fe14d4a2d2eda668dca368fc1f9f9020 | https://github.com/phatblat/xcode-installer/blob/f59aebb0fe14d4a2d2eda668dca368fc1f9f9020/lib/xcode-installer/install.rb#L103-L112 | train |
cblavier/jobbr | lib/jobbr/ohm.rb | Jobbr.Ohm.models | def models(parent = nil)
model_paths = Dir["#{Rails.root}/app/models/*_jobs/*.rb"]
model_paths.each{ |path| require path }
sanitized_model_paths = model_paths.map { |path| path.gsub(/.*\/app\/models\//, '').gsub('.rb', '') }
model_constants = sanitized_model_paths.map do |path|
path.split('/').map { |token| token.camelize }.join('::').constantize
end
model_constants.select { |model| superclasses(model).include?(::Ohm::Model) }
if parent
model_constants.select { |model| model.included_modules.include?(parent) }
else
model_constants
end
end | ruby | def models(parent = nil)
model_paths = Dir["#{Rails.root}/app/models/*_jobs/*.rb"]
model_paths.each{ |path| require path }
sanitized_model_paths = model_paths.map { |path| path.gsub(/.*\/app\/models\//, '').gsub('.rb', '') }
model_constants = sanitized_model_paths.map do |path|
path.split('/').map { |token| token.camelize }.join('::').constantize
end
model_constants.select { |model| superclasses(model).include?(::Ohm::Model) }
if parent
model_constants.select { |model| model.included_modules.include?(parent) }
else
model_constants
end
end | [
"def",
"models",
"(",
"parent",
"=",
"nil",
")",
"model_paths",
"=",
"Dir",
"[",
"\"#{Rails.root}/app/models/*_jobs/*.rb\"",
"]",
"model_paths",
".",
"each",
"{",
"|",
"path",
"|",
"require",
"path",
"}",
"sanitized_model_paths",
"=",
"model_paths",
".",
"map",
"{",
"|",
"path",
"|",
"path",
".",
"gsub",
"(",
"/",
"\\/",
"\\/",
"\\/",
"/",
",",
"''",
")",
".",
"gsub",
"(",
"'.rb'",
",",
"''",
")",
"}",
"model_constants",
"=",
"sanitized_model_paths",
".",
"map",
"do",
"|",
"path",
"|",
"path",
".",
"split",
"(",
"'/'",
")",
".",
"map",
"{",
"|",
"token",
"|",
"token",
".",
"camelize",
"}",
".",
"join",
"(",
"'::'",
")",
".",
"constantize",
"end",
"model_constants",
".",
"select",
"{",
"|",
"model",
"|",
"superclasses",
"(",
"model",
")",
".",
"include?",
"(",
"::",
"Ohm",
"::",
"Model",
")",
"}",
"if",
"parent",
"model_constants",
".",
"select",
"{",
"|",
"model",
"|",
"model",
".",
"included_modules",
".",
"include?",
"(",
"parent",
")",
"}",
"else",
"model_constants",
"end",
"end"
] | Return all Ohm models.
You can also pass a module class to get all models including that module | [
"Return",
"all",
"Ohm",
"models",
".",
"You",
"can",
"also",
"pass",
"a",
"module",
"class",
"to",
"get",
"all",
"models",
"including",
"that",
"module"
] | 2fbfa14f5fe1b942e69333e34ea0a086ad052b38 | https://github.com/cblavier/jobbr/blob/2fbfa14f5fe1b942e69333e34ea0a086ad052b38/lib/jobbr/ohm.rb#L11-L25 | train |
cblavier/jobbr | lib/jobbr/ohm.rb | Jobbr.Ohm.superclasses | def superclasses(klass)
super_classes = []
while klass != Object
klass = klass.superclass
super_classes << klass
end
super_classes
end | ruby | def superclasses(klass)
super_classes = []
while klass != Object
klass = klass.superclass
super_classes << klass
end
super_classes
end | [
"def",
"superclasses",
"(",
"klass",
")",
"super_classes",
"=",
"[",
"]",
"while",
"klass",
"!=",
"Object",
"klass",
"=",
"klass",
".",
"superclass",
"super_classes",
"<<",
"klass",
"end",
"super_classes",
"end"
] | Return all superclasses for a given class. | [
"Return",
"all",
"superclasses",
"for",
"a",
"given",
"class",
"."
] | 2fbfa14f5fe1b942e69333e34ea0a086ad052b38 | https://github.com/cblavier/jobbr/blob/2fbfa14f5fe1b942e69333e34ea0a086ad052b38/lib/jobbr/ohm.rb#L30-L37 | train |
blackwinter/wadl | lib/wadl/has_docs.rb | WADL.HasDocs.define_singleton | def define_singleton(r, sym, method)
name = r.send(sym)
if name && name !~ /\W/ && !r.respond_to?(name) && !respond_to?(name)
instance_eval(%Q{def #{name}\n#{method}('#{name}')\nend})
end
end | ruby | def define_singleton(r, sym, method)
name = r.send(sym)
if name && name !~ /\W/ && !r.respond_to?(name) && !respond_to?(name)
instance_eval(%Q{def #{name}\n#{method}('#{name}')\nend})
end
end | [
"def",
"define_singleton",
"(",
"r",
",",
"sym",
",",
"method",
")",
"name",
"=",
"r",
".",
"send",
"(",
"sym",
")",
"if",
"name",
"&&",
"name",
"!~",
"/",
"\\W",
"/",
"&&",
"!",
"r",
".",
"respond_to?",
"(",
"name",
")",
"&&",
"!",
"respond_to?",
"(",
"name",
")",
"instance_eval",
"(",
"%Q{def #{name}\\n#{method}('#{name}')\\nend}",
")",
"end",
"end"
] | Convenience method to define a no-argument singleton method on
this object. | [
"Convenience",
"method",
"to",
"define",
"a",
"no",
"-",
"argument",
"singleton",
"method",
"on",
"this",
"object",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/has_docs.rb#L37-L43 | train |
pwnall/webkit_remote | lib/webkit_remote/process.rb | WebkitRemote.Process.start | def start
return self if running?
unless @pid = ::Process.spawn(*@cli)
# The launch failed.
stop
return nil
end
(@timeout * 20).times do
# Check if the browser exited.
begin
break if ::Process.wait(@pid, ::Process::WNOHANG)
rescue SystemCallError # no children
break
end
# Check if the browser finished starting up.
begin
browser = WebkitRemote::Browser.new process: self
@running = true
return browser
rescue SystemCallError # most likely ECONNREFUSED
Kernel.sleep 0.05
end
end
# The browser failed, or was too slow to start.
stop
nil
end | ruby | def start
return self if running?
unless @pid = ::Process.spawn(*@cli)
# The launch failed.
stop
return nil
end
(@timeout * 20).times do
# Check if the browser exited.
begin
break if ::Process.wait(@pid, ::Process::WNOHANG)
rescue SystemCallError # no children
break
end
# Check if the browser finished starting up.
begin
browser = WebkitRemote::Browser.new process: self
@running = true
return browser
rescue SystemCallError # most likely ECONNREFUSED
Kernel.sleep 0.05
end
end
# The browser failed, or was too slow to start.
stop
nil
end | [
"def",
"start",
"return",
"self",
"if",
"running?",
"unless",
"@pid",
"=",
"::",
"Process",
".",
"spawn",
"(",
"*",
"@cli",
")",
"stop",
"return",
"nil",
"end",
"(",
"@timeout",
"*",
"20",
")",
".",
"times",
"do",
"begin",
"break",
"if",
"::",
"Process",
".",
"wait",
"(",
"@pid",
",",
"::",
"Process",
"::",
"WNOHANG",
")",
"rescue",
"SystemCallError",
"break",
"end",
"begin",
"browser",
"=",
"WebkitRemote",
"::",
"Browser",
".",
"new",
"process",
":",
"self",
"@running",
"=",
"true",
"return",
"browser",
"rescue",
"SystemCallError",
"Kernel",
".",
"sleep",
"0.05",
"end",
"end",
"stop",
"nil",
"end"
] | Tracker for a yet-unlaunched process.
@param [Hash] opts tweak the options below
@option opts [Integer] port the port used by the remote debugging server;
the default port is 9292
@option opts [Number] timeout number of seconds to wait for the browser
to start; the default timeout is 10 seconds
@option opts [Hash<Symbol, Number>] window set the :left, :top, :width and
:height of the browser window; by default, the browser window is
256x256 starting at 0,0.
@option opts [Boolean] allow_popups when true, the popup blocker is
disabled; this is sometimes necessary when driving a Web UI via
JavaScript
@option opts [Boolean] headless if true, Chrome runs without any dependency
on a display server
@option opts [String] chrome_binary path to the Chrome binary to be used;
by default, the path is automatically detected
Starts the browser process.
@return [WebkitRemote::Browser] master session to the started Browser
process; the session's auto_close is set to false so that it can be
safely discarded; nil if the launch fails | [
"Tracker",
"for",
"a",
"yet",
"-",
"unlaunched",
"process",
"."
] | f38ac7e882726ff00e5c56898d06d91340f8179e | https://github.com/pwnall/webkit_remote/blob/f38ac7e882726ff00e5c56898d06d91340f8179e/lib/webkit_remote/process.rb#L49-L78 | train |
pwnall/webkit_remote | lib/webkit_remote/process.rb | WebkitRemote.Process.stop | def stop
return self unless running?
if @pid
begin
::Process.kill 'TERM', @pid
::Process.wait @pid
rescue SystemCallError
# Process died on its own.
ensure
@pid = nil
end
end
FileUtils.rm_rf @data_dir if File.exist?(@data_dir)
@running = false
self
end | ruby | def stop
return self unless running?
if @pid
begin
::Process.kill 'TERM', @pid
::Process.wait @pid
rescue SystemCallError
# Process died on its own.
ensure
@pid = nil
end
end
FileUtils.rm_rf @data_dir if File.exist?(@data_dir)
@running = false
self
end | [
"def",
"stop",
"return",
"self",
"unless",
"running?",
"if",
"@pid",
"begin",
"::",
"Process",
".",
"kill",
"'TERM'",
",",
"@pid",
"::",
"Process",
".",
"wait",
"@pid",
"rescue",
"SystemCallError",
"ensure",
"@pid",
"=",
"nil",
"end",
"end",
"FileUtils",
".",
"rm_rf",
"@data_dir",
"if",
"File",
".",
"exist?",
"(",
"@data_dir",
")",
"@running",
"=",
"false",
"self",
"end"
] | Stops the browser process.
Only call this after you're done with the process.
@return [WebkitRemote::Process] self | [
"Stops",
"the",
"browser",
"process",
"."
] | f38ac7e882726ff00e5c56898d06d91340f8179e | https://github.com/pwnall/webkit_remote/blob/f38ac7e882726ff00e5c56898d06d91340f8179e/lib/webkit_remote/process.rb#L89-L105 | train |
blackwinter/wadl | lib/wadl/response_format.rb | WADL.ResponseFormat.build | def build(http_response)
# Figure out which fault or representation to use.
status = http_response.status[0]
unless response_format = faults.find { |f| f.dereference.status == status }
# Try to match the response to a response format using a media
# type.
response_media_type = http_response.content_type
response_format = representations.find { |f|
t = f.dereference.mediaType and response_media_type.index(t) == 0
}
# If an exact media type match fails, use the mime-types gem to
# match the response to a response format using the underlying
# subtype. This will match "application/xml" with "text/xml".
response_format ||= begin
mime_type = MIME::Types[response_media_type]
raw_sub_type = mime_type[0].raw_sub_type if mime_type && !mime_type.empty?
representations.find { |f|
if t = f.dereference.mediaType
response_mime_type = MIME::Types[t]
response_raw_sub_type = response_mime_type[0].raw_sub_type if response_mime_type && !response_mime_type.empty?
response_raw_sub_type == raw_sub_type
end
}
end
# If all else fails, try to find a response that specifies no
# media type. TODO: check if this would be valid WADL.
response_format ||= representations.find { |f| !f.dereference.mediaType }
end
body = http_response.read
if response_format && response_format.mediaType =~ /xml/
begin
body = REXML::Document.new(body)
# Find the appropriate element of the document
if response_format.element
# TODO: don't strip the damn namespace. I'm not very good at
# namespaces and I don't see how to deal with them here.
element = response_format.element.sub(/.*:/, '')
body = REXML::XPath.first(body, "//#{element}")
end
rescue REXML::ParseException
end
body.extend(XMLRepresentation)
body.representation_of(response_format)
end
klass = response_format.is_a?(FaultFormat) ? response_format.subclass : Response
obj = klass.new(http_response.status, http_response.headers, body, response_format)
obj.is_a?(Exception) ? raise(obj) : obj
end | ruby | def build(http_response)
# Figure out which fault or representation to use.
status = http_response.status[0]
unless response_format = faults.find { |f| f.dereference.status == status }
# Try to match the response to a response format using a media
# type.
response_media_type = http_response.content_type
response_format = representations.find { |f|
t = f.dereference.mediaType and response_media_type.index(t) == 0
}
# If an exact media type match fails, use the mime-types gem to
# match the response to a response format using the underlying
# subtype. This will match "application/xml" with "text/xml".
response_format ||= begin
mime_type = MIME::Types[response_media_type]
raw_sub_type = mime_type[0].raw_sub_type if mime_type && !mime_type.empty?
representations.find { |f|
if t = f.dereference.mediaType
response_mime_type = MIME::Types[t]
response_raw_sub_type = response_mime_type[0].raw_sub_type if response_mime_type && !response_mime_type.empty?
response_raw_sub_type == raw_sub_type
end
}
end
# If all else fails, try to find a response that specifies no
# media type. TODO: check if this would be valid WADL.
response_format ||= representations.find { |f| !f.dereference.mediaType }
end
body = http_response.read
if response_format && response_format.mediaType =~ /xml/
begin
body = REXML::Document.new(body)
# Find the appropriate element of the document
if response_format.element
# TODO: don't strip the damn namespace. I'm not very good at
# namespaces and I don't see how to deal with them here.
element = response_format.element.sub(/.*:/, '')
body = REXML::XPath.first(body, "//#{element}")
end
rescue REXML::ParseException
end
body.extend(XMLRepresentation)
body.representation_of(response_format)
end
klass = response_format.is_a?(FaultFormat) ? response_format.subclass : Response
obj = klass.new(http_response.status, http_response.headers, body, response_format)
obj.is_a?(Exception) ? raise(obj) : obj
end | [
"def",
"build",
"(",
"http_response",
")",
"status",
"=",
"http_response",
".",
"status",
"[",
"0",
"]",
"unless",
"response_format",
"=",
"faults",
".",
"find",
"{",
"|",
"f",
"|",
"f",
".",
"dereference",
".",
"status",
"==",
"status",
"}",
"response_media_type",
"=",
"http_response",
".",
"content_type",
"response_format",
"=",
"representations",
".",
"find",
"{",
"|",
"f",
"|",
"t",
"=",
"f",
".",
"dereference",
".",
"mediaType",
"and",
"response_media_type",
".",
"index",
"(",
"t",
")",
"==",
"0",
"}",
"response_format",
"||=",
"begin",
"mime_type",
"=",
"MIME",
"::",
"Types",
"[",
"response_media_type",
"]",
"raw_sub_type",
"=",
"mime_type",
"[",
"0",
"]",
".",
"raw_sub_type",
"if",
"mime_type",
"&&",
"!",
"mime_type",
".",
"empty?",
"representations",
".",
"find",
"{",
"|",
"f",
"|",
"if",
"t",
"=",
"f",
".",
"dereference",
".",
"mediaType",
"response_mime_type",
"=",
"MIME",
"::",
"Types",
"[",
"t",
"]",
"response_raw_sub_type",
"=",
"response_mime_type",
"[",
"0",
"]",
".",
"raw_sub_type",
"if",
"response_mime_type",
"&&",
"!",
"response_mime_type",
".",
"empty?",
"response_raw_sub_type",
"==",
"raw_sub_type",
"end",
"}",
"end",
"response_format",
"||=",
"representations",
".",
"find",
"{",
"|",
"f",
"|",
"!",
"f",
".",
"dereference",
".",
"mediaType",
"}",
"end",
"body",
"=",
"http_response",
".",
"read",
"if",
"response_format",
"&&",
"response_format",
".",
"mediaType",
"=~",
"/",
"/",
"begin",
"body",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"body",
")",
"if",
"response_format",
".",
"element",
"element",
"=",
"response_format",
".",
"element",
".",
"sub",
"(",
"/",
"/",
",",
"''",
")",
"body",
"=",
"REXML",
"::",
"XPath",
".",
"first",
"(",
"body",
",",
"\"//#{element}\"",
")",
"end",
"rescue",
"REXML",
"::",
"ParseException",
"end",
"body",
".",
"extend",
"(",
"XMLRepresentation",
")",
"body",
".",
"representation_of",
"(",
"response_format",
")",
"end",
"klass",
"=",
"response_format",
".",
"is_a?",
"(",
"FaultFormat",
")",
"?",
"response_format",
".",
"subclass",
":",
"Response",
"obj",
"=",
"klass",
".",
"new",
"(",
"http_response",
".",
"status",
",",
"http_response",
".",
"headers",
",",
"body",
",",
"response_format",
")",
"obj",
".",
"is_a?",
"(",
"Exception",
")",
"?",
"raise",
"(",
"obj",
")",
":",
"obj",
"end"
] | Builds a service response object out of an HTTPResponse object. | [
"Builds",
"a",
"service",
"response",
"object",
"out",
"of",
"an",
"HTTPResponse",
"object",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/response_format.rb#L41-L99 | train |
badboy/i3-ipc | lib/i3-ipc.rb | I3.IPC.handle_response | def handle_response(type)
# reads 14 bytes
# length of "i3-ipc" + 4 bytes length + 4 bytes type
buffer = read 14
raise WrongMagicCode unless buffer[0, (MAGIC_STRING.length)] == MAGIC_STRING
len, recv_type = buffer[6..-1].unpack("LL")
raise WrongType unless recv_type == type
answer = read len
::JSON.parse(answer)
end | ruby | def handle_response(type)
# reads 14 bytes
# length of "i3-ipc" + 4 bytes length + 4 bytes type
buffer = read 14
raise WrongMagicCode unless buffer[0, (MAGIC_STRING.length)] == MAGIC_STRING
len, recv_type = buffer[6..-1].unpack("LL")
raise WrongType unless recv_type == type
answer = read len
::JSON.parse(answer)
end | [
"def",
"handle_response",
"(",
"type",
")",
"buffer",
"=",
"read",
"14",
"raise",
"WrongMagicCode",
"unless",
"buffer",
"[",
"0",
",",
"(",
"MAGIC_STRING",
".",
"length",
")",
"]",
"==",
"MAGIC_STRING",
"len",
",",
"recv_type",
"=",
"buffer",
"[",
"6",
"..",
"-",
"1",
"]",
".",
"unpack",
"(",
"\"LL\"",
")",
"raise",
"WrongType",
"unless",
"recv_type",
"==",
"type",
"answer",
"=",
"read",
"len",
"::",
"JSON",
".",
"parse",
"(",
"answer",
")",
"end"
] | Reads the reply from the socket
and parses the returned json into a ruby object.
Throws WrongMagicCode when magic word is wrong.
Throws WrongType if returned type does not match expected.
This is a bit duplicated code
but I don't know a way to read the full send reply
without knowing its length | [
"Reads",
"the",
"reply",
"from",
"the",
"socket",
"and",
"parses",
"the",
"returned",
"json",
"into",
"a",
"ruby",
"object",
"."
] | 63b6d25552de4e6025fdcad14502d60140b478c3 | https://github.com/badboy/i3-ipc/blob/63b6d25552de4e6025fdcad14502d60140b478c3/lib/i3-ipc.rb#L110-L121 | train |
blackwinter/wadl | lib/wadl/resource_and_address.rb | WADL.ResourceAndAddress.method_missing | def method_missing(name, *args, &block)
if @resource.respond_to?(name)
result = @resource.send(name, *args, &block)
result.is_a?(Resource) ? ResourceAndAddress.new(result, @address.dup) : result
else
super
end
end | ruby | def method_missing(name, *args, &block)
if @resource.respond_to?(name)
result = @resource.send(name, *args, &block)
result.is_a?(Resource) ? ResourceAndAddress.new(result, @address.dup) : result
else
super
end
end | [
"def",
"method_missing",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"@resource",
".",
"respond_to?",
"(",
"name",
")",
"result",
"=",
"@resource",
".",
"send",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"result",
".",
"is_a?",
"(",
"Resource",
")",
"?",
"ResourceAndAddress",
".",
"new",
"(",
"result",
",",
"@address",
".",
"dup",
")",
":",
"result",
"else",
"super",
"end",
"end"
] | method_missing is to catch generated methods that don't get delegated. | [
"method_missing",
"is",
"to",
"catch",
"generated",
"methods",
"that",
"don",
"t",
"get",
"delegated",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/resource_and_address.rb#L82-L89 | train |
blackwinter/wadl | lib/wadl/resource_and_address.rb | WADL.ResourceAndAddress.resource | def resource(*args, &block)
resource = @resource.resource(*args, &block)
resource && ResourceAndAddress.new(resource, @address)
end | ruby | def resource(*args, &block)
resource = @resource.resource(*args, &block)
resource && ResourceAndAddress.new(resource, @address)
end | [
"def",
"resource",
"(",
"*",
"args",
",",
"&",
"block",
")",
"resource",
"=",
"@resource",
".",
"resource",
"(",
"*",
"args",
",",
"&",
"block",
")",
"resource",
"&&",
"ResourceAndAddress",
".",
"new",
"(",
"resource",
",",
"@address",
")",
"end"
] | method_missing won't catch these guys because they were defined in
the delegation operation. | [
"method_missing",
"won",
"t",
"catch",
"these",
"guys",
"because",
"they",
"were",
"defined",
"in",
"the",
"delegation",
"operation",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/resource_and_address.rb#L93-L96 | train |
cblavier/jobbr | lib/jobbr/whenever.rb | Jobbr.Whenever.schedule_jobs | def schedule_jobs(job_list)
Jobbr::Ohm.models(Jobbr::Scheduled).each do |job|
if job.every
job_list.every job.every[0], job.every[1] do
job_list.jobbr job.task_name
end
end
end
end | ruby | def schedule_jobs(job_list)
Jobbr::Ohm.models(Jobbr::Scheduled).each do |job|
if job.every
job_list.every job.every[0], job.every[1] do
job_list.jobbr job.task_name
end
end
end
end | [
"def",
"schedule_jobs",
"(",
"job_list",
")",
"Jobbr",
"::",
"Ohm",
".",
"models",
"(",
"Jobbr",
"::",
"Scheduled",
")",
".",
"each",
"do",
"|",
"job",
"|",
"if",
"job",
".",
"every",
"job_list",
".",
"every",
"job",
".",
"every",
"[",
"0",
"]",
",",
"job",
".",
"every",
"[",
"1",
"]",
"do",
"job_list",
".",
"jobbr",
"job",
".",
"task_name",
"end",
"end",
"end",
"end"
] | Generates crontab for each scheduled Job using Whenever DSL. | [
"Generates",
"crontab",
"for",
"each",
"scheduled",
"Job",
"using",
"Whenever",
"DSL",
"."
] | 2fbfa14f5fe1b942e69333e34ea0a086ad052b38 | https://github.com/cblavier/jobbr/blob/2fbfa14f5fe1b942e69333e34ea0a086ad052b38/lib/jobbr/whenever.rb#L10-L18 | train |
galetahub/sunrise | app/helpers/sunrise/activities_helper.rb | Sunrise.ActivitiesHelper.timeago_tag | def timeago_tag(time, options = {})
options[:class] ||= "timeago"
content_tag(:abbr, time.to_s, options.merge(:title => time.getutc.iso8601)) if time
end | ruby | def timeago_tag(time, options = {})
options[:class] ||= "timeago"
content_tag(:abbr, time.to_s, options.merge(:title => time.getutc.iso8601)) if time
end | [
"def",
"timeago_tag",
"(",
"time",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":class",
"]",
"||=",
"\"timeago\"",
"content_tag",
"(",
":abbr",
",",
"time",
".",
"to_s",
",",
"options",
".",
"merge",
"(",
":title",
"=>",
"time",
".",
"getutc",
".",
"iso8601",
")",
")",
"if",
"time",
"end"
] | For generating time tags calculated using jquery.timeago | [
"For",
"generating",
"time",
"tags",
"calculated",
"using",
"jquery",
".",
"timeago"
] | c65a8c6150180ae5569e45c57c1ff2c1092d0ab9 | https://github.com/galetahub/sunrise/blob/c65a8c6150180ae5569e45c57c1ff2c1092d0ab9/app/helpers/sunrise/activities_helper.rb#L5-L8 | train |
galetahub/sunrise | app/helpers/sunrise/activities_helper.rb | Sunrise.ActivitiesHelper.link_to_trackable | def link_to_trackable(object, object_type)
model_name = object_type.downcase
if object
link_to(model_name, edit_path(:model_name => model_name.pluralize, :id => object.id))
else
"a #{model_name} which does not exist anymore"
end
end | ruby | def link_to_trackable(object, object_type)
model_name = object_type.downcase
if object
link_to(model_name, edit_path(:model_name => model_name.pluralize, :id => object.id))
else
"a #{model_name} which does not exist anymore"
end
end | [
"def",
"link_to_trackable",
"(",
"object",
",",
"object_type",
")",
"model_name",
"=",
"object_type",
".",
"downcase",
"if",
"object",
"link_to",
"(",
"model_name",
",",
"edit_path",
"(",
":model_name",
"=>",
"model_name",
".",
"pluralize",
",",
":id",
"=>",
"object",
".",
"id",
")",
")",
"else",
"\"a #{model_name} which does not exist anymore\"",
"end",
"end"
] | Check if object still exists in the database and display a link to it,
otherwise display a proper message about it.
This is used in activities that can refer to
objects which no longer exist, like removed posts. | [
"Check",
"if",
"object",
"still",
"exists",
"in",
"the",
"database",
"and",
"display",
"a",
"link",
"to",
"it",
"otherwise",
"display",
"a",
"proper",
"message",
"about",
"it",
".",
"This",
"is",
"used",
"in",
"activities",
"that",
"can",
"refer",
"to",
"objects",
"which",
"no",
"longer",
"exist",
"like",
"removed",
"posts",
"."
] | c65a8c6150180ae5569e45c57c1ff2c1092d0ab9 | https://github.com/galetahub/sunrise/blob/c65a8c6150180ae5569e45c57c1ff2c1092d0ab9/app/helpers/sunrise/activities_helper.rb#L26-L34 | train |
blackwinter/wadl | lib/wadl/address.rb | WADL.Address.deep_copy | def deep_copy
address = Address.new(
_deep_copy_array(@path_fragments),
_deep_copy_array(@query_vars),
_deep_copy_hash(@headers),
@path_params.dup,
@query_params.dup,
@header_params.dup
)
@auth.each { |header, value| address.auth(header, value) }
address
end | ruby | def deep_copy
address = Address.new(
_deep_copy_array(@path_fragments),
_deep_copy_array(@query_vars),
_deep_copy_hash(@headers),
@path_params.dup,
@query_params.dup,
@header_params.dup
)
@auth.each { |header, value| address.auth(header, value) }
address
end | [
"def",
"deep_copy",
"address",
"=",
"Address",
".",
"new",
"(",
"_deep_copy_array",
"(",
"@path_fragments",
")",
",",
"_deep_copy_array",
"(",
"@query_vars",
")",
",",
"_deep_copy_hash",
"(",
"@headers",
")",
",",
"@path_params",
".",
"dup",
",",
"@query_params",
".",
"dup",
",",
"@header_params",
".",
"dup",
")",
"@auth",
".",
"each",
"{",
"|",
"header",
",",
"value",
"|",
"address",
".",
"auth",
"(",
"header",
",",
"value",
")",
"}",
"address",
"end"
] | Perform a deep copy. | [
"Perform",
"a",
"deep",
"copy",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/address.rb#L56-L69 | train |
blackwinter/wadl | lib/wadl/address.rb | WADL.Address.bind! | def bind!(args = {})
path_var_values = args[:path] || {}
query_var_values = args[:query] || {}
header_var_values = args[:headers] || {}
@auth.each { |header, value| header_var_values[header] = value }.clear
# Bind variables found in the path fragments.
path_params_to_delete = []
path_fragments.each { |fragment|
if fragment.respond_to?(:to_str)
# This fragment is a string which might contain {} substitutions.
# Make any substitutions available to the provided path variables.
self.class.embedded_param_names(fragment).each { |name|
value = path_var_values[name] || path_var_values[name.to_sym]
value = if param = path_params[name]
path_params_to_delete << param
param % value
else
Param.default.format(value, name)
end
fragment.gsub!("{#{name}}", value)
}
else
# This fragment is an array of Param objects (style 'matrix'
# or 'plain') which may be bound to strings. As substitutions
# happen, the array will become a mixed array of Param objects
# and strings.
fragment.each_with_index { |param, i|
next unless param.respond_to?(:name)
name = param.name
value = path_var_values[name] || path_var_values[name.to_sym]
value = param % value
fragment[i] = value if value
path_params_to_delete << param
}
end
}
# Delete any embedded path parameters that are now bound from
# our list of unbound parameters.
path_params_to_delete.each { |p| path_params.delete(p.name) }
# Bind query variable values to query parameters
query_var_values.each { |name, value|
param = query_params.delete(name.to_s)
query_vars << param % value if param
}
# Bind header variables to header parameters
header_var_values.each { |name, value|
if param = header_params.delete(name.to_s)
headers[name] = param % value
else
warn %Q{Ignoring unknown header parameter "#{name}"!}
end
}
self
end | ruby | def bind!(args = {})
path_var_values = args[:path] || {}
query_var_values = args[:query] || {}
header_var_values = args[:headers] || {}
@auth.each { |header, value| header_var_values[header] = value }.clear
# Bind variables found in the path fragments.
path_params_to_delete = []
path_fragments.each { |fragment|
if fragment.respond_to?(:to_str)
# This fragment is a string which might contain {} substitutions.
# Make any substitutions available to the provided path variables.
self.class.embedded_param_names(fragment).each { |name|
value = path_var_values[name] || path_var_values[name.to_sym]
value = if param = path_params[name]
path_params_to_delete << param
param % value
else
Param.default.format(value, name)
end
fragment.gsub!("{#{name}}", value)
}
else
# This fragment is an array of Param objects (style 'matrix'
# or 'plain') which may be bound to strings. As substitutions
# happen, the array will become a mixed array of Param objects
# and strings.
fragment.each_with_index { |param, i|
next unless param.respond_to?(:name)
name = param.name
value = path_var_values[name] || path_var_values[name.to_sym]
value = param % value
fragment[i] = value if value
path_params_to_delete << param
}
end
}
# Delete any embedded path parameters that are now bound from
# our list of unbound parameters.
path_params_to_delete.each { |p| path_params.delete(p.name) }
# Bind query variable values to query parameters
query_var_values.each { |name, value|
param = query_params.delete(name.to_s)
query_vars << param % value if param
}
# Bind header variables to header parameters
header_var_values.each { |name, value|
if param = header_params.delete(name.to_s)
headers[name] = param % value
else
warn %Q{Ignoring unknown header parameter "#{name}"!}
end
}
self
end | [
"def",
"bind!",
"(",
"args",
"=",
"{",
"}",
")",
"path_var_values",
"=",
"args",
"[",
":path",
"]",
"||",
"{",
"}",
"query_var_values",
"=",
"args",
"[",
":query",
"]",
"||",
"{",
"}",
"header_var_values",
"=",
"args",
"[",
":headers",
"]",
"||",
"{",
"}",
"@auth",
".",
"each",
"{",
"|",
"header",
",",
"value",
"|",
"header_var_values",
"[",
"header",
"]",
"=",
"value",
"}",
".",
"clear",
"path_params_to_delete",
"=",
"[",
"]",
"path_fragments",
".",
"each",
"{",
"|",
"fragment",
"|",
"if",
"fragment",
".",
"respond_to?",
"(",
":to_str",
")",
"self",
".",
"class",
".",
"embedded_param_names",
"(",
"fragment",
")",
".",
"each",
"{",
"|",
"name",
"|",
"value",
"=",
"path_var_values",
"[",
"name",
"]",
"||",
"path_var_values",
"[",
"name",
".",
"to_sym",
"]",
"value",
"=",
"if",
"param",
"=",
"path_params",
"[",
"name",
"]",
"path_params_to_delete",
"<<",
"param",
"param",
"%",
"value",
"else",
"Param",
".",
"default",
".",
"format",
"(",
"value",
",",
"name",
")",
"end",
"fragment",
".",
"gsub!",
"(",
"\"{#{name}}\"",
",",
"value",
")",
"}",
"else",
"fragment",
".",
"each_with_index",
"{",
"|",
"param",
",",
"i",
"|",
"next",
"unless",
"param",
".",
"respond_to?",
"(",
":name",
")",
"name",
"=",
"param",
".",
"name",
"value",
"=",
"path_var_values",
"[",
"name",
"]",
"||",
"path_var_values",
"[",
"name",
".",
"to_sym",
"]",
"value",
"=",
"param",
"%",
"value",
"fragment",
"[",
"i",
"]",
"=",
"value",
"if",
"value",
"path_params_to_delete",
"<<",
"param",
"}",
"end",
"}",
"path_params_to_delete",
".",
"each",
"{",
"|",
"p",
"|",
"path_params",
".",
"delete",
"(",
"p",
".",
"name",
")",
"}",
"query_var_values",
".",
"each",
"{",
"|",
"name",
",",
"value",
"|",
"param",
"=",
"query_params",
".",
"delete",
"(",
"name",
".",
"to_s",
")",
"query_vars",
"<<",
"param",
"%",
"value",
"if",
"param",
"}",
"header_var_values",
".",
"each",
"{",
"|",
"name",
",",
"value",
"|",
"if",
"param",
"=",
"header_params",
".",
"delete",
"(",
"name",
".",
"to_s",
")",
"headers",
"[",
"name",
"]",
"=",
"param",
"%",
"value",
"else",
"warn",
"%Q{Ignoring unknown header parameter \"#{name}\"!}",
"end",
"}",
"self",
"end"
] | Binds some or all of the unbound variables in this address to values. | [
"Binds",
"some",
"or",
"all",
"of",
"the",
"unbound",
"variables",
"in",
"this",
"address",
"to",
"values",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/address.rb#L85-L150 | train |
thomasjachmann/launchpad | lib/launchpad/interaction.rb | Launchpad.Interaction.start | def start(opts = nil)
logger.debug "starting Launchpad::Interaction##{object_id}"
opts = {
:detached => false
}.merge(opts || {})
@active = true
@reader_thread ||= Thread.new do
begin
while @active do
@device.read_pending_actions.each do |action|
action_thread = Thread.new(action) do |action|
respond_to_action(action)
end
@action_threads.add(action_thread)
end
sleep @latency# if @latency > 0.0
end
rescue Portmidi::DeviceError => e
logger.fatal "could not read from device, stopping to read actions"
raise CommunicationError.new(e)
rescue Exception => e
logger.fatal "error causing action reading to stop: #{e.inspect}"
raise e
ensure
@device.reset
end
end
@reader_thread.join unless opts[:detached]
end | ruby | def start(opts = nil)
logger.debug "starting Launchpad::Interaction##{object_id}"
opts = {
:detached => false
}.merge(opts || {})
@active = true
@reader_thread ||= Thread.new do
begin
while @active do
@device.read_pending_actions.each do |action|
action_thread = Thread.new(action) do |action|
respond_to_action(action)
end
@action_threads.add(action_thread)
end
sleep @latency# if @latency > 0.0
end
rescue Portmidi::DeviceError => e
logger.fatal "could not read from device, stopping to read actions"
raise CommunicationError.new(e)
rescue Exception => e
logger.fatal "error causing action reading to stop: #{e.inspect}"
raise e
ensure
@device.reset
end
end
@reader_thread.join unless opts[:detached]
end | [
"def",
"start",
"(",
"opts",
"=",
"nil",
")",
"logger",
".",
"debug",
"\"starting Launchpad::Interaction##{object_id}\"",
"opts",
"=",
"{",
":detached",
"=>",
"false",
"}",
".",
"merge",
"(",
"opts",
"||",
"{",
"}",
")",
"@active",
"=",
"true",
"@reader_thread",
"||=",
"Thread",
".",
"new",
"do",
"begin",
"while",
"@active",
"do",
"@device",
".",
"read_pending_actions",
".",
"each",
"do",
"|",
"action",
"|",
"action_thread",
"=",
"Thread",
".",
"new",
"(",
"action",
")",
"do",
"|",
"action",
"|",
"respond_to_action",
"(",
"action",
")",
"end",
"@action_threads",
".",
"add",
"(",
"action_thread",
")",
"end",
"sleep",
"@latency",
"end",
"rescue",
"Portmidi",
"::",
"DeviceError",
"=>",
"e",
"logger",
".",
"fatal",
"\"could not read from device, stopping to read actions\"",
"raise",
"CommunicationError",
".",
"new",
"(",
"e",
")",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"fatal",
"\"error causing action reading to stop: #{e.inspect}\"",
"raise",
"e",
"ensure",
"@device",
".",
"reset",
"end",
"end",
"@reader_thread",
".",
"join",
"unless",
"opts",
"[",
":detached",
"]",
"end"
] | Starts interacting with the launchpad. Resets the device when
the interaction was properly stopped via stop or close.
Optional options hash:
[<tt>:detached</tt>] <tt>true/false</tt>,
whether to detach the interaction, method is blocking when +false+,
optional, defaults to +false+
Errors raised:
[Launchpad::NoInputAllowedError] when input is not enabled on the interaction's device
[Launchpad::NoOutputAllowedError] when output is not enabled on the interaction's device
[Launchpad::CommunicationError] when anything unexpected happens while communicating with the launchpad | [
"Starts",
"interacting",
"with",
"the",
"launchpad",
".",
"Resets",
"the",
"device",
"when",
"the",
"interaction",
"was",
"properly",
"stopped",
"via",
"stop",
"or",
"close",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/interaction.rb#L108-L139 | train |
thomasjachmann/launchpad | lib/launchpad/interaction.rb | Launchpad.Interaction.stop | def stop
logger.debug "stopping Launchpad::Interaction##{object_id}"
@active = false
if @reader_thread
# run (resume from sleep) and wait for @reader_thread to end
@reader_thread.run if @reader_thread.alive?
@reader_thread.join
@reader_thread = nil
end
ensure
@action_threads.list.each do |thread|
begin
thread.kill
thread.join
rescue Exception => e
logger.error "error when killing action thread: #{e.inspect}"
end
end
nil
end | ruby | def stop
logger.debug "stopping Launchpad::Interaction##{object_id}"
@active = false
if @reader_thread
# run (resume from sleep) and wait for @reader_thread to end
@reader_thread.run if @reader_thread.alive?
@reader_thread.join
@reader_thread = nil
end
ensure
@action_threads.list.each do |thread|
begin
thread.kill
thread.join
rescue Exception => e
logger.error "error when killing action thread: #{e.inspect}"
end
end
nil
end | [
"def",
"stop",
"logger",
".",
"debug",
"\"stopping Launchpad::Interaction##{object_id}\"",
"@active",
"=",
"false",
"if",
"@reader_thread",
"@reader_thread",
".",
"run",
"if",
"@reader_thread",
".",
"alive?",
"@reader_thread",
".",
"join",
"@reader_thread",
"=",
"nil",
"end",
"ensure",
"@action_threads",
".",
"list",
".",
"each",
"do",
"|",
"thread",
"|",
"begin",
"thread",
".",
"kill",
"thread",
".",
"join",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"error",
"\"error when killing action thread: #{e.inspect}\"",
"end",
"end",
"nil",
"end"
] | Stops interacting with the launchpad.
Errors raised:
[Launchpad::NoInputAllowedError] when input is not enabled on the interaction's device
[Launchpad::CommunicationError] when anything unexpected happens while communicating with the | [
"Stops",
"interacting",
"with",
"the",
"launchpad",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/interaction.rb#L147-L166 | train |
thomasjachmann/launchpad | lib/launchpad/interaction.rb | Launchpad.Interaction.response_to | def response_to(types = :all, state = :both, opts = nil, &block)
logger.debug "setting response to #{types.inspect} for state #{state.inspect} with #{opts.inspect}"
types = Array(types)
opts ||= {}
no_response_to(types, state) if opts[:exclusive] == true
Array(state == :both ? %w(down up) : state).each do |state|
types.each do |type|
combined_types(type, opts).each do |combined_type|
responses[combined_type][state.to_sym] << block
end
end
end
nil
end | ruby | def response_to(types = :all, state = :both, opts = nil, &block)
logger.debug "setting response to #{types.inspect} for state #{state.inspect} with #{opts.inspect}"
types = Array(types)
opts ||= {}
no_response_to(types, state) if opts[:exclusive] == true
Array(state == :both ? %w(down up) : state).each do |state|
types.each do |type|
combined_types(type, opts).each do |combined_type|
responses[combined_type][state.to_sym] << block
end
end
end
nil
end | [
"def",
"response_to",
"(",
"types",
"=",
":all",
",",
"state",
"=",
":both",
",",
"opts",
"=",
"nil",
",",
"&",
"block",
")",
"logger",
".",
"debug",
"\"setting response to #{types.inspect} for state #{state.inspect} with #{opts.inspect}\"",
"types",
"=",
"Array",
"(",
"types",
")",
"opts",
"||=",
"{",
"}",
"no_response_to",
"(",
"types",
",",
"state",
")",
"if",
"opts",
"[",
":exclusive",
"]",
"==",
"true",
"Array",
"(",
"state",
"==",
":both",
"?",
"%w(",
"down",
"up",
")",
":",
"state",
")",
".",
"each",
"do",
"|",
"state",
"|",
"types",
".",
"each",
"do",
"|",
"type",
"|",
"combined_types",
"(",
"type",
",",
"opts",
")",
".",
"each",
"do",
"|",
"combined_type",
"|",
"responses",
"[",
"combined_type",
"]",
"[",
"state",
".",
"to_sym",
"]",
"<<",
"block",
"end",
"end",
"end",
"nil",
"end"
] | Registers a response to one or more actions.
Parameters (see Launchpad for values):
[+types+] one or an array of button types to respond to,
additional value <tt>:all</tt> for all buttons
[+state+] button state to respond to,
additional value <tt>:both</tt>
Optional options hash:
[<tt>:exclusive</tt>] <tt>true/false</tt>,
whether to deregister all other responses to the specified actions,
optional, defaults to +false+
[<tt>:x</tt>] x coordinate(s), can contain arrays and ranges, when specified
without y coordinate, it's interpreted as a whole column
[<tt>:y</tt>] y coordinate(s), can contain arrays and ranges, when specified
without x coordinate, it's interpreted as a whole row
Takes a block which will be called when an action matching the parameters occurs.
Block parameters:
[+interaction+] the interaction object that received the action
[+action+] the action received from Launchpad::Device.read_pending_actions | [
"Registers",
"a",
"response",
"to",
"one",
"or",
"more",
"actions",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/interaction.rb#L193-L206 | train |
thomasjachmann/launchpad | lib/launchpad/interaction.rb | Launchpad.Interaction.no_response_to | def no_response_to(types = nil, state = :both, opts = nil)
logger.debug "removing response to #{types.inspect} for state #{state.inspect}"
types = Array(types)
Array(state == :both ? %w(down up) : state).each do |state|
types.each do |type|
combined_types(type, opts).each do |combined_type|
responses[combined_type][state.to_sym].clear
end
end
end
nil
end | ruby | def no_response_to(types = nil, state = :both, opts = nil)
logger.debug "removing response to #{types.inspect} for state #{state.inspect}"
types = Array(types)
Array(state == :both ? %w(down up) : state).each do |state|
types.each do |type|
combined_types(type, opts).each do |combined_type|
responses[combined_type][state.to_sym].clear
end
end
end
nil
end | [
"def",
"no_response_to",
"(",
"types",
"=",
"nil",
",",
"state",
"=",
":both",
",",
"opts",
"=",
"nil",
")",
"logger",
".",
"debug",
"\"removing response to #{types.inspect} for state #{state.inspect}\"",
"types",
"=",
"Array",
"(",
"types",
")",
"Array",
"(",
"state",
"==",
":both",
"?",
"%w(",
"down",
"up",
")",
":",
"state",
")",
".",
"each",
"do",
"|",
"state",
"|",
"types",
".",
"each",
"do",
"|",
"type",
"|",
"combined_types",
"(",
"type",
",",
"opts",
")",
".",
"each",
"do",
"|",
"combined_type",
"|",
"responses",
"[",
"combined_type",
"]",
"[",
"state",
".",
"to_sym",
"]",
".",
"clear",
"end",
"end",
"end",
"nil",
"end"
] | Deregisters all responses to one or more actions.
Parameters (see Launchpad for values):
[+types+] one or an array of button types to respond to,
additional value <tt>:all</tt> for actions on all buttons
(but not meaning "all responses"),
optional, defaults to +nil+, meaning "all responses"
[+state+] button state to respond to,
additional value <tt>:both</tt>
Optional options hash:
[<tt>:x</tt>] x coordinate(s), can contain arrays and ranges, when specified
without y coordinate, it's interpreted as a whole column
[<tt>:y</tt>] y coordinate(s), can contain arrays and ranges, when specified
without x coordinate, it's interpreted as a whole row | [
"Deregisters",
"all",
"responses",
"to",
"one",
"or",
"more",
"actions",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/interaction.rb#L225-L236 | train |
thomasjachmann/launchpad | lib/launchpad/interaction.rb | Launchpad.Interaction.grid_range | def grid_range(range)
return nil if range.nil?
Array(range).flatten.map do |pos|
pos.respond_to?(:to_a) ? pos.to_a : pos
end.flatten.uniq
end | ruby | def grid_range(range)
return nil if range.nil?
Array(range).flatten.map do |pos|
pos.respond_to?(:to_a) ? pos.to_a : pos
end.flatten.uniq
end | [
"def",
"grid_range",
"(",
"range",
")",
"return",
"nil",
"if",
"range",
".",
"nil?",
"Array",
"(",
"range",
")",
".",
"flatten",
".",
"map",
"do",
"|",
"pos",
"|",
"pos",
".",
"respond_to?",
"(",
":to_a",
")",
"?",
"pos",
".",
"to_a",
":",
"pos",
"end",
".",
"flatten",
".",
"uniq",
"end"
] | Returns an array of grid positions for a range.
Parameters:
[+range+] the range definitions, can be
* a Fixnum
* a Range
* an Array of Fixnum, Range or Array objects | [
"Returns",
"an",
"array",
"of",
"grid",
"positions",
"for",
"a",
"range",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/interaction.rb#L270-L275 | train |
pwnall/webkit_remote | lib/webkit_remote/event.rb | WebkitRemote.Event.matches? | def matches?(conditions)
conditions.all? do |key, value|
case key
when :class, :type
kind_of? value
when :name
name == value
else
# Simple cop-out.
send(key) == value
end
end
end | ruby | def matches?(conditions)
conditions.all? do |key, value|
case key
when :class, :type
kind_of? value
when :name
name == value
else
# Simple cop-out.
send(key) == value
end
end
end | [
"def",
"matches?",
"(",
"conditions",
")",
"conditions",
".",
"all?",
"do",
"|",
"key",
",",
"value",
"|",
"case",
"key",
"when",
":class",
",",
":type",
"kind_of?",
"value",
"when",
":name",
"name",
"==",
"value",
"else",
"send",
"(",
"key",
")",
"==",
"value",
"end",
"end",
"end"
] | Checks if the event meets a set of conditions.
This is used in WebkitRemote::Client#wait_for.
@param [Hash<Symbol, Object>] conditions the conditions that must be met
by an event to get out of the waiting loop
@option conditions [Class] class the class of events to wait for; this
condition is met if the event's class is a sub-class of the given class
@option conditions [Class] type synonym for class that can be used with the
Ruby 1.9 hash syntax
@option conditions [String] name the event's name, e.g.
"Page.loadEventFired"
@return [Boolean] true if this event matches all the given conditions | [
"Checks",
"if",
"the",
"event",
"meets",
"a",
"set",
"of",
"conditions",
"."
] | f38ac7e882726ff00e5c56898d06d91340f8179e | https://github.com/pwnall/webkit_remote/blob/f38ac7e882726ff00e5c56898d06d91340f8179e/lib/webkit_remote/event.rb#L30-L42 | train |
printercu/rails_stuff | lib/rails_stuff/statusable.rb | RailsStuff.Statusable.statusable_methods | def statusable_methods
# Include generated methods with a module, not right in class.
@statusable_methods ||= Module.new.tap do |m|
m.const_set :ClassMethods, Module.new
include m
extend m::ClassMethods
end
end | ruby | def statusable_methods
# Include generated methods with a module, not right in class.
@statusable_methods ||= Module.new.tap do |m|
m.const_set :ClassMethods, Module.new
include m
extend m::ClassMethods
end
end | [
"def",
"statusable_methods",
"@statusable_methods",
"||=",
"Module",
".",
"new",
".",
"tap",
"do",
"|",
"m",
"|",
"m",
".",
"const_set",
":ClassMethods",
",",
"Module",
".",
"new",
"include",
"m",
"extend",
"m",
"::",
"ClassMethods",
"end",
"end"
] | Module to hold generated methods. Single for all status fields in model. | [
"Module",
"to",
"hold",
"generated",
"methods",
".",
"Single",
"for",
"all",
"status",
"fields",
"in",
"model",
"."
] | b3d72daaae6426c8166205f6a7438a89768e8347 | https://github.com/printercu/rails_stuff/blob/b3d72daaae6426c8166205f6a7438a89768e8347/lib/rails_stuff/statusable.rb#L95-L102 | train |
galetahub/sunrise | lib/sunrise/abstract_model.rb | Sunrise.AbstractModel.build_record | def build_record
record = model.new
record.send("#{parent_association.name}=", parent_record) if parent_record
record.build_defaults if record.respond_to?(:build_defaults)
record
end | ruby | def build_record
record = model.new
record.send("#{parent_association.name}=", parent_record) if parent_record
record.build_defaults if record.respond_to?(:build_defaults)
record
end | [
"def",
"build_record",
"record",
"=",
"model",
".",
"new",
"record",
".",
"send",
"(",
"\"#{parent_association.name}=\"",
",",
"parent_record",
")",
"if",
"parent_record",
"record",
".",
"build_defaults",
"if",
"record",
".",
"respond_to?",
"(",
":build_defaults",
")",
"record",
"end"
] | Initialize new model, sets parent record and call build_defaults method | [
"Initialize",
"new",
"model",
"sets",
"parent",
"record",
"and",
"call",
"build_defaults",
"method"
] | c65a8c6150180ae5569e45c57c1ff2c1092d0ab9 | https://github.com/galetahub/sunrise/blob/c65a8c6150180ae5569e45c57c1ff2c1092d0ab9/lib/sunrise/abstract_model.rb#L157-L162 | train |
galetahub/sunrise | lib/sunrise/abstract_model.rb | Sunrise.AbstractModel.apply_scopes | def apply_scopes(params = nil, pagination = true)
raise ::AbstractController::ActionNotFound.new("List config is turn off") if without_index?
params ||= @request_params
scope = default_scope(params)
if current_list == :tree
scope = scope.roots
elsif pagination
scope = page_scope(scope, params[:page], params[:per])
end
scope
end | ruby | def apply_scopes(params = nil, pagination = true)
raise ::AbstractController::ActionNotFound.new("List config is turn off") if without_index?
params ||= @request_params
scope = default_scope(params)
if current_list == :tree
scope = scope.roots
elsif pagination
scope = page_scope(scope, params[:page], params[:per])
end
scope
end | [
"def",
"apply_scopes",
"(",
"params",
"=",
"nil",
",",
"pagination",
"=",
"true",
")",
"raise",
"::",
"AbstractController",
"::",
"ActionNotFound",
".",
"new",
"(",
"\"List config is turn off\"",
")",
"if",
"without_index?",
"params",
"||=",
"@request_params",
"scope",
"=",
"default_scope",
"(",
"params",
")",
"if",
"current_list",
"==",
":tree",
"scope",
"=",
"scope",
".",
"roots",
"elsif",
"pagination",
"scope",
"=",
"page_scope",
"(",
"scope",
",",
"params",
"[",
":page",
"]",
",",
"params",
"[",
":per",
"]",
")",
"end",
"scope",
"end"
] | Convert request params to model scopes | [
"Convert",
"request",
"params",
"to",
"model",
"scopes"
] | c65a8c6150180ae5569e45c57c1ff2c1092d0ab9 | https://github.com/galetahub/sunrise/blob/c65a8c6150180ae5569e45c57c1ff2c1092d0ab9/lib/sunrise/abstract_model.rb#L165-L178 | train |
badboy/i3-ipc | lib/i3-ipc/manpage.rb | I3.Manpage.manpage | def manpage(name)
return "** Can't find groff(1)" unless groff?
require 'open3'
out = nil
Open3.popen3(groff_command) do |stdin, stdout, _|
stdin.puts raw_manpage(name)
stdin.close
out = stdout.read.strip
end
out
end | ruby | def manpage(name)
return "** Can't find groff(1)" unless groff?
require 'open3'
out = nil
Open3.popen3(groff_command) do |stdin, stdout, _|
stdin.puts raw_manpage(name)
stdin.close
out = stdout.read.strip
end
out
end | [
"def",
"manpage",
"(",
"name",
")",
"return",
"\"** Can't find groff(1)\"",
"unless",
"groff?",
"require",
"'open3'",
"out",
"=",
"nil",
"Open3",
".",
"popen3",
"(",
"groff_command",
")",
"do",
"|",
"stdin",
",",
"stdout",
",",
"_",
"|",
"stdin",
".",
"puts",
"raw_manpage",
"(",
"name",
")",
"stdin",
".",
"close",
"out",
"=",
"stdout",
".",
"read",
".",
"strip",
"end",
"out",
"end"
] | Prints a manpage, all pretty and paged.
Returns the terminal-formatted manpage, ready to be printed to
the screen. | [
"Prints",
"a",
"manpage",
"all",
"pretty",
"and",
"paged",
".",
"Returns",
"the",
"terminal",
"-",
"formatted",
"manpage",
"ready",
"to",
"be",
"printed",
"to",
"the",
"screen",
"."
] | 63b6d25552de4e6025fdcad14502d60140b478c3 | https://github.com/badboy/i3-ipc/blob/63b6d25552de4e6025fdcad14502d60140b478c3/lib/i3-ipc/manpage.rb#L12-L23 | train |
badboy/i3-ipc | lib/i3-ipc/manpage.rb | I3.Manpage.raw_manpage | def raw_manpage(name)
if File.exists? file = File.dirname(__FILE__) + "/../../man/#{name}.1"
File.read(file)
else
DATA.read
end
end | ruby | def raw_manpage(name)
if File.exists? file = File.dirname(__FILE__) + "/../../man/#{name}.1"
File.read(file)
else
DATA.read
end
end | [
"def",
"raw_manpage",
"(",
"name",
")",
"if",
"File",
".",
"exists?",
"file",
"=",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
"+",
"\"/../../man/#{name}.1\"",
"File",
".",
"read",
"(",
"file",
")",
"else",
"DATA",
".",
"read",
"end",
"end"
] | Returns the raw manpage. If we're not running in standalone
mode, it's a file sitting at the root under the `man`
directory.
If we are running in standalone mode the manpage will be
included after the __END__ of the file so we can grab it using
DATA. | [
"Returns",
"the",
"raw",
"manpage",
".",
"If",
"we",
"re",
"not",
"running",
"in",
"standalone",
"mode",
"it",
"s",
"a",
"file",
"sitting",
"at",
"the",
"root",
"under",
"the",
"man",
"directory",
"."
] | 63b6d25552de4e6025fdcad14502d60140b478c3 | https://github.com/badboy/i3-ipc/blob/63b6d25552de4e6025fdcad14502d60140b478c3/lib/i3-ipc/manpage.rb#L32-L38 | train |
printercu/rails_stuff | lib/rails_stuff/rspec_helpers.rb | RailsStuff.RSpecHelpers.clear_logs | def clear_logs
::RSpec.configure do |config|
config.add_setting :clear_log_file
config.clear_log_file = Rails.root.join('log', 'test.log') if defined?(Rails.root)
config.add_setting :clear_log_file_proc
config.clear_log_file_proc = ->(file) do
next unless file && File.exist?(file)
FileUtils.cp(file, "#{file}.last")
File.open(file, 'w').close
end
config.after(:suite) do
instance_exec(config.clear_log_file, &config.clear_log_file_proc) unless ENV['KEEP_LOG']
end
end
end | ruby | def clear_logs
::RSpec.configure do |config|
config.add_setting :clear_log_file
config.clear_log_file = Rails.root.join('log', 'test.log') if defined?(Rails.root)
config.add_setting :clear_log_file_proc
config.clear_log_file_proc = ->(file) do
next unless file && File.exist?(file)
FileUtils.cp(file, "#{file}.last")
File.open(file, 'w').close
end
config.after(:suite) do
instance_exec(config.clear_log_file, &config.clear_log_file_proc) unless ENV['KEEP_LOG']
end
end
end | [
"def",
"clear_logs",
"::",
"RSpec",
".",
"configure",
"do",
"|",
"config",
"|",
"config",
".",
"add_setting",
":clear_log_file",
"config",
".",
"clear_log_file",
"=",
"Rails",
".",
"root",
".",
"join",
"(",
"'log'",
",",
"'test.log'",
")",
"if",
"defined?",
"(",
"Rails",
".",
"root",
")",
"config",
".",
"add_setting",
":clear_log_file_proc",
"config",
".",
"clear_log_file_proc",
"=",
"->",
"(",
"file",
")",
"do",
"next",
"unless",
"file",
"&&",
"File",
".",
"exist?",
"(",
"file",
")",
"FileUtils",
".",
"cp",
"(",
"file",
",",
"\"#{file}.last\"",
")",
"File",
".",
"open",
"(",
"file",
",",
"'w'",
")",
".",
"close",
"end",
"config",
".",
"after",
"(",
":suite",
")",
"do",
"instance_exec",
"(",
"config",
".",
"clear_log_file",
",",
"&",
"config",
".",
"clear_log_file_proc",
")",
"unless",
"ENV",
"[",
"'KEEP_LOG'",
"]",
"end",
"end",
"end"
] | Clear logs `tail -f`-safely. | [
"Clear",
"logs",
"tail",
"-",
"f",
"-",
"safely",
"."
] | b3d72daaae6426c8166205f6a7438a89768e8347 | https://github.com/printercu/rails_stuff/blob/b3d72daaae6426c8166205f6a7438a89768e8347/lib/rails_stuff/rspec_helpers.rb#L100-L114 | train |
blackwinter/wadl | lib/wadl/request_format.rb | WADL.RequestFormat.uri | def uri(resource, args = {})
uri = resource.uri(args)
query_values = args[:query] || {}
header_values = args[:headers] || {}
params.each { |param|
name = param.name
if param.style == 'header'
value = header_values[name] || header_values[name.to_sym]
value = param % value
uri.headers[name] = value if value
else
value = query_values[name] || query_values[name.to_sym]
value = param.format(value, nil, 'query')
uri.query << value if value && !value.empty?
end
}
uri
end | ruby | def uri(resource, args = {})
uri = resource.uri(args)
query_values = args[:query] || {}
header_values = args[:headers] || {}
params.each { |param|
name = param.name
if param.style == 'header'
value = header_values[name] || header_values[name.to_sym]
value = param % value
uri.headers[name] = value if value
else
value = query_values[name] || query_values[name.to_sym]
value = param.format(value, nil, 'query')
uri.query << value if value && !value.empty?
end
}
uri
end | [
"def",
"uri",
"(",
"resource",
",",
"args",
"=",
"{",
"}",
")",
"uri",
"=",
"resource",
".",
"uri",
"(",
"args",
")",
"query_values",
"=",
"args",
"[",
":query",
"]",
"||",
"{",
"}",
"header_values",
"=",
"args",
"[",
":headers",
"]",
"||",
"{",
"}",
"params",
".",
"each",
"{",
"|",
"param",
"|",
"name",
"=",
"param",
".",
"name",
"if",
"param",
".",
"style",
"==",
"'header'",
"value",
"=",
"header_values",
"[",
"name",
"]",
"||",
"header_values",
"[",
"name",
".",
"to_sym",
"]",
"value",
"=",
"param",
"%",
"value",
"uri",
".",
"headers",
"[",
"name",
"]",
"=",
"value",
"if",
"value",
"else",
"value",
"=",
"query_values",
"[",
"name",
"]",
"||",
"query_values",
"[",
"name",
".",
"to_sym",
"]",
"value",
"=",
"param",
".",
"format",
"(",
"value",
",",
"nil",
",",
"'query'",
")",
"uri",
".",
"query",
"<<",
"value",
"if",
"value",
"&&",
"!",
"value",
".",
"empty?",
"end",
"}",
"uri",
"end"
] | Returns a URI and a set of HTTP headers for this request. | [
"Returns",
"a",
"URI",
"and",
"a",
"set",
"of",
"HTTP",
"headers",
"for",
"this",
"request",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/request_format.rb#L39-L62 | train |
thomasjachmann/launchpad | lib/launchpad/device.rb | Launchpad.Device.change | def change(type, opts = nil)
opts ||= {}
status = %w(up down left right session user1 user2 mixer).include?(type.to_s) ? Status::CC : Status::ON
output(status, note(type, opts), velocity(opts))
end | ruby | def change(type, opts = nil)
opts ||= {}
status = %w(up down left right session user1 user2 mixer).include?(type.to_s) ? Status::CC : Status::ON
output(status, note(type, opts), velocity(opts))
end | [
"def",
"change",
"(",
"type",
",",
"opts",
"=",
"nil",
")",
"opts",
"||=",
"{",
"}",
"status",
"=",
"%w(",
"up",
"down",
"left",
"right",
"session",
"user1",
"user2",
"mixer",
")",
".",
"include?",
"(",
"type",
".",
"to_s",
")",
"?",
"Status",
"::",
"CC",
":",
"Status",
"::",
"ON",
"output",
"(",
"status",
",",
"note",
"(",
"type",
",",
"opts",
")",
",",
"velocity",
"(",
"opts",
")",
")",
"end"
] | Changes a single LED.
Parameters (see Launchpad for values):
[+type+] type of the button to change
Optional options hash (see Launchpad for values):
[<tt>:x</tt>] x coordinate
[<tt>:y</tt>] y coordinate
[<tt>:red</tt>] brightness of red LED
[<tt>:green</tt>] brightness of green LED
[<tt>:mode</tt>] button mode, defaults to <tt>:normal</tt>, one of:
[<tt>:normal/tt>] updates the LED for all circumstances (the new value will be written to both buffers)
[<tt>:flashing/tt>] updates the LED for flashing (the new value will be written to buffer 0 while the LED will be off in buffer 1, see buffering_mode)
[<tt>:buffering/tt>] updates the LED for the current update_buffer only
Errors raised:
[Launchpad::NoValidGridCoordinatesError] when coordinates aren't within the valid range
[Launchpad::NoValidBrightnessError] when brightness values aren't within the valid range
[Launchpad::NoOutputAllowedError] when output is not enabled | [
"Changes",
"a",
"single",
"LED",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/device.rb#L183-L187 | train |
thomasjachmann/launchpad | lib/launchpad/device.rb | Launchpad.Device.change_all | def change_all(*colors)
# ensure that colors is at least and most 80 elements long
colors = colors.flatten[0..79]
colors += [0] * (80 - colors.size) if colors.size < 80
# send normal MIDI message to reset rapid LED change pointer
# in this case, set mapping mode to x-y layout (the default)
output(Status::CC, Status::NIL, GridLayout::XY)
# send colors in slices of 2
messages = []
colors.each_slice(2) do |c1, c2|
messages << message(Status::MULTI, velocity(c1), velocity(c2))
end
output_messages(messages)
end | ruby | def change_all(*colors)
# ensure that colors is at least and most 80 elements long
colors = colors.flatten[0..79]
colors += [0] * (80 - colors.size) if colors.size < 80
# send normal MIDI message to reset rapid LED change pointer
# in this case, set mapping mode to x-y layout (the default)
output(Status::CC, Status::NIL, GridLayout::XY)
# send colors in slices of 2
messages = []
colors.each_slice(2) do |c1, c2|
messages << message(Status::MULTI, velocity(c1), velocity(c2))
end
output_messages(messages)
end | [
"def",
"change_all",
"(",
"*",
"colors",
")",
"colors",
"=",
"colors",
".",
"flatten",
"[",
"0",
"..",
"79",
"]",
"colors",
"+=",
"[",
"0",
"]",
"*",
"(",
"80",
"-",
"colors",
".",
"size",
")",
"if",
"colors",
".",
"size",
"<",
"80",
"output",
"(",
"Status",
"::",
"CC",
",",
"Status",
"::",
"NIL",
",",
"GridLayout",
"::",
"XY",
")",
"messages",
"=",
"[",
"]",
"colors",
".",
"each_slice",
"(",
"2",
")",
"do",
"|",
"c1",
",",
"c2",
"|",
"messages",
"<<",
"message",
"(",
"Status",
"::",
"MULTI",
",",
"velocity",
"(",
"c1",
")",
",",
"velocity",
"(",
"c2",
")",
")",
"end",
"output_messages",
"(",
"messages",
")",
"end"
] | Changes all LEDs in batch mode.
Parameters (see Launchpad for values):
[+colors] an array of colors, each either being an integer or a Hash
* integer: calculated using the formula
<tt>color = 16 * green + red</tt>
* Hash:
[<tt>:red</tt>] brightness of red LED
[<tt>:green</tt>] brightness of green LED
[<tt>:mode</tt>] button mode, defaults to <tt>:normal</tt>, one of:
[<tt>:normal/tt>] updates the LEDs for all circumstances (the new value will be written to both buffers)
[<tt>:flashing/tt>] updates the LEDs for flashing (the new values will be written to buffer 0 while the LEDs will be off in buffer 1, see buffering_mode)
[<tt>:buffering/tt>] updates the LEDs for the current update_buffer only
the array consists of 64 colors for the grid buttons,
8 colors for the scene buttons (top to bottom)
and 8 colors for the top control buttons (left to right),
maximum 80 values - excessive values will be ignored,
missing values will be filled with 0
Errors raised:
[Launchpad::NoValidBrightnessError] when brightness values aren't within the valid range
[Launchpad::NoOutputAllowedError] when output is not enabled | [
"Changes",
"all",
"LEDs",
"in",
"batch",
"mode",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/device.rb#L213-L226 | train |
thomasjachmann/launchpad | lib/launchpad/device.rb | Launchpad.Device.buffering_mode | def buffering_mode(opts = nil)
opts = {
:display_buffer => 0,
:update_buffer => 0,
:copy => false,
:flashing => false
}.merge(opts || {})
data = opts[:display_buffer] + 4 * opts[:update_buffer] + 32
data += 16 if opts[:copy]
data += 8 if opts[:flashing]
output(Status::CC, Status::NIL, data)
end | ruby | def buffering_mode(opts = nil)
opts = {
:display_buffer => 0,
:update_buffer => 0,
:copy => false,
:flashing => false
}.merge(opts || {})
data = opts[:display_buffer] + 4 * opts[:update_buffer] + 32
data += 16 if opts[:copy]
data += 8 if opts[:flashing]
output(Status::CC, Status::NIL, data)
end | [
"def",
"buffering_mode",
"(",
"opts",
"=",
"nil",
")",
"opts",
"=",
"{",
":display_buffer",
"=>",
"0",
",",
":update_buffer",
"=>",
"0",
",",
":copy",
"=>",
"false",
",",
":flashing",
"=>",
"false",
"}",
".",
"merge",
"(",
"opts",
"||",
"{",
"}",
")",
"data",
"=",
"opts",
"[",
":display_buffer",
"]",
"+",
"4",
"*",
"opts",
"[",
":update_buffer",
"]",
"+",
"32",
"data",
"+=",
"16",
"if",
"opts",
"[",
":copy",
"]",
"data",
"+=",
"8",
"if",
"opts",
"[",
":flashing",
"]",
"output",
"(",
"Status",
"::",
"CC",
",",
"Status",
"::",
"NIL",
",",
"data",
")",
"end"
] | Controls the two buffers.
Optional options hash:
[<tt>:display_buffer</tt>] which buffer to use for display, defaults to +0+
[<tt>:update_buffer</tt>] which buffer to use for updates when <tt>:mode</tt> is set to <tt>:buffering</tt>, defaults to +0+ (see change)
[<tt>:copy</tt>] whether to copy the LEDs states from the new display_buffer over to the new update_buffer, <tt>true/false</tt>, defaults to <tt>false</tt>
[<tt>:flashing</tt>] whether to start flashing by automatically switching between the two buffers for display, <tt>true/false</tt>, defaults to <tt>false</tt>
Errors raised:
[Launchpad::NoOutputAllowedError] when output is not enabled | [
"Controls",
"the",
"two",
"buffers",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/device.rb#L268-L279 | train |
thomasjachmann/launchpad | lib/launchpad/device.rb | Launchpad.Device.output_messages | def output_messages(messages)
if @output.nil?
logger.error "trying to write to device that's not been initialized for output"
raise NoOutputAllowedError
end
logger.debug "writing messages to launchpad:\n #{messages.join("\n ")}" if logger.debug?
@output.write(messages)
nil
end | ruby | def output_messages(messages)
if @output.nil?
logger.error "trying to write to device that's not been initialized for output"
raise NoOutputAllowedError
end
logger.debug "writing messages to launchpad:\n #{messages.join("\n ")}" if logger.debug?
@output.write(messages)
nil
end | [
"def",
"output_messages",
"(",
"messages",
")",
"if",
"@output",
".",
"nil?",
"logger",
".",
"error",
"\"trying to write to device that's not been initialized for output\"",
"raise",
"NoOutputAllowedError",
"end",
"logger",
".",
"debug",
"\"writing messages to launchpad:\\n #{messages.join(\"\\n \")}\"",
"if",
"logger",
".",
"debug?",
"@output",
".",
"write",
"(",
"messages",
")",
"nil",
"end"
] | Writes several messages to the MIDI device.
Parameters:
[+messages+] an array of hashes (usually created with message) with:
[<tt>:message</tt>] an array of
MIDI status code,
MIDI data 1 (note),
MIDI data 2 (velocity)
[<tt>:timestamp</tt>] integer indicating the time when the MIDI message was created | [
"Writes",
"several",
"messages",
"to",
"the",
"MIDI",
"device",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/device.rb#L405-L413 | train |
ImpressCMS/vagrant-impressbox | lib/vagrant-impressbox/provisioner.rb | Impressbox.Provisioner.provision | def provision
mass_loader('provision').each do |configurator|
next unless configurator.can_be_configured?(@machine, @@__loaded_config)
@machine.ui.info configurator.description if configurator.description
configurator.configure @machine, @@__loaded_config
end
end | ruby | def provision
mass_loader('provision').each do |configurator|
next unless configurator.can_be_configured?(@machine, @@__loaded_config)
@machine.ui.info configurator.description if configurator.description
configurator.configure @machine, @@__loaded_config
end
end | [
"def",
"provision",
"mass_loader",
"(",
"'provision'",
")",
".",
"each",
"do",
"|",
"configurator",
"|",
"next",
"unless",
"configurator",
".",
"can_be_configured?",
"(",
"@machine",
",",
"@@__loaded_config",
")",
"@machine",
".",
"ui",
".",
"info",
"configurator",
".",
"description",
"if",
"configurator",
".",
"description",
"configurator",
".",
"configure",
"@machine",
",",
"@@__loaded_config",
"end",
"end"
] | Do provision tasks | [
"Do",
"provision",
"tasks"
] | 78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2 | https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/provisioner.rb#L34-L40 | train |
ImpressCMS/vagrant-impressbox | lib/vagrant-impressbox/provisioner.rb | Impressbox.Provisioner.run_primaty_configuration | def run_primaty_configuration(root_config)
old_root = root_config.dup
old_loaded = @@__loaded_config.dup
mass_loader('primary').each do |configurator|
next unless configurator.can_be_configured?(old_root, old_loaded)
@machine.ui.info configurator.description if configurator.description
configurator.configure root_config, old_loaded
end
end | ruby | def run_primaty_configuration(root_config)
old_root = root_config.dup
old_loaded = @@__loaded_config.dup
mass_loader('primary').each do |configurator|
next unless configurator.can_be_configured?(old_root, old_loaded)
@machine.ui.info configurator.description if configurator.description
configurator.configure root_config, old_loaded
end
end | [
"def",
"run_primaty_configuration",
"(",
"root_config",
")",
"old_root",
"=",
"root_config",
".",
"dup",
"old_loaded",
"=",
"@@__loaded_config",
".",
"dup",
"mass_loader",
"(",
"'primary'",
")",
".",
"each",
"do",
"|",
"configurator",
"|",
"next",
"unless",
"configurator",
".",
"can_be_configured?",
"(",
"old_root",
",",
"old_loaded",
")",
"@machine",
".",
"ui",
".",
"info",
"configurator",
".",
"description",
"if",
"configurator",
".",
"description",
"configurator",
".",
"configure",
"root_config",
",",
"old_loaded",
"end",
"end"
] | Runs primary configuration
@param root_config [Object] Root Vagrant config | [
"Runs",
"primary",
"configuration"
] | 78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2 | https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/provisioner.rb#L47-L55 | train |
ImpressCMS/vagrant-impressbox | lib/vagrant-impressbox/provisioner.rb | Impressbox.Provisioner.mass_loader | def mass_loader(type)
namespace = 'Impressbox::Configurators::' + ucfirst(type)
path = File.join('..', 'configurators', type)
Impressbox::Objects::MassFileLoader.new namespace, path
end | ruby | def mass_loader(type)
namespace = 'Impressbox::Configurators::' + ucfirst(type)
path = File.join('..', 'configurators', type)
Impressbox::Objects::MassFileLoader.new namespace, path
end | [
"def",
"mass_loader",
"(",
"type",
")",
"namespace",
"=",
"'Impressbox::Configurators::'",
"+",
"ucfirst",
"(",
"type",
")",
"path",
"=",
"File",
".",
"join",
"(",
"'..'",
",",
"'configurators'",
",",
"type",
")",
"Impressbox",
"::",
"Objects",
"::",
"MassFileLoader",
".",
"new",
"namespace",
",",
"path",
"end"
] | Gets preconfigured MassFileLoader instance
@param type [String] Files type
@return [::Impressbox::Objects::MassFileLoader] | [
"Gets",
"preconfigured",
"MassFileLoader",
"instance"
] | 78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2 | https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/provisioner.rb#L62-L66 | train |
ImpressCMS/vagrant-impressbox | lib/vagrant-impressbox/provisioner.rb | Impressbox.Provisioner.xaml_config | def xaml_config
require_relative File.join('objects', 'config_file')
file = detect_file(config.file)
@machine.ui.info "\t" + I18n.t('config.loaded_from_file', file: file)
Impressbox::Objects::ConfigFile.new file
end | ruby | def xaml_config
require_relative File.join('objects', 'config_file')
file = detect_file(config.file)
@machine.ui.info "\t" + I18n.t('config.loaded_from_file', file: file)
Impressbox::Objects::ConfigFile.new file
end | [
"def",
"xaml_config",
"require_relative",
"File",
".",
"join",
"(",
"'objects'",
",",
"'config_file'",
")",
"file",
"=",
"detect_file",
"(",
"config",
".",
"file",
")",
"@machine",
".",
"ui",
".",
"info",
"\"\\t\"",
"+",
"I18n",
".",
"t",
"(",
"'config.loaded_from_file'",
",",
"file",
":",
"file",
")",
"Impressbox",
"::",
"Objects",
"::",
"ConfigFile",
".",
"new",
"file",
"end"
] | Loads xaml config
@return [::Impressbox::Objects::ConfigFile] | [
"Loads",
"xaml",
"config"
] | 78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2 | https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/provisioner.rb#L81-L86 | train |
pwnall/webkit_remote | lib/webkit_remote/client.rb | WebkitRemote.Client.wait_for | def wait_for(conditions)
unless WebkitRemote::Event.can_receive? self, conditions
raise ArgumentError, "Cannot receive event with #{conditions.inspect}"
end
events = []
each_event do |event|
events << event
break if event.matches?(conditions)
end
events
end | ruby | def wait_for(conditions)
unless WebkitRemote::Event.can_receive? self, conditions
raise ArgumentError, "Cannot receive event with #{conditions.inspect}"
end
events = []
each_event do |event|
events << event
break if event.matches?(conditions)
end
events
end | [
"def",
"wait_for",
"(",
"conditions",
")",
"unless",
"WebkitRemote",
"::",
"Event",
".",
"can_receive?",
"self",
",",
"conditions",
"raise",
"ArgumentError",
",",
"\"Cannot receive event with #{conditions.inspect}\"",
"end",
"events",
"=",
"[",
"]",
"each_event",
"do",
"|",
"event",
"|",
"events",
"<<",
"event",
"break",
"if",
"event",
".",
"matches?",
"(",
"conditions",
")",
"end",
"events",
"end"
] | Waits for the remote debugging server to send a specific event.
@param (see WebkitRemote::Event#matches?)
@return [Array<WebkitRemote::Event>] all the events received, including the
event that matches the class requirement | [
"Waits",
"for",
"the",
"remote",
"debugging",
"server",
"to",
"send",
"a",
"specific",
"event",
"."
] | f38ac7e882726ff00e5c56898d06d91340f8179e | https://github.com/pwnall/webkit_remote/blob/f38ac7e882726ff00e5c56898d06d91340f8179e/lib/webkit_remote/client.rb#L72-L83 | train |
esumbar/passphrase | lib/passphrase/wordlist_database.rb | Passphrase.Language.validate | def validate(language_list)
language_list.each do |l|
matches_language = @languages.any? { |language| language.match("^#{l}") }
raise "No language match for #{l}" unless matches_language
end
end | ruby | def validate(language_list)
language_list.each do |l|
matches_language = @languages.any? { |language| language.match("^#{l}") }
raise "No language match for #{l}" unless matches_language
end
end | [
"def",
"validate",
"(",
"language_list",
")",
"language_list",
".",
"each",
"do",
"|",
"l",
"|",
"matches_language",
"=",
"@languages",
".",
"any?",
"{",
"|",
"language",
"|",
"language",
".",
"match",
"(",
"\"^#{l}\"",
")",
"}",
"raise",
"\"No language match for #{l}\"",
"unless",
"matches_language",
"end",
"end"
] | Make sure that each language specification matches at least one
language. | [
"Make",
"sure",
"that",
"each",
"language",
"specification",
"matches",
"at",
"least",
"one",
"language",
"."
] | 5faaa6dcf71f31bc6acad6f683f581408e0b5c32 | https://github.com/esumbar/passphrase/blob/5faaa6dcf71f31bc6acad6f683f581408e0b5c32/lib/passphrase/wordlist_database.rb#L45-L50 | train |
boris-s/y_petri | lib/y_petri/agent/simulation_aspect.rb | YPetri::Agent::SimulationAspect.SimulationPoint.identify | def identify( name: nil, net: nil, cc: nil, imc: nil, ssc: nil, **nn )
name || { net: net, cc: cc, imc: imc, ssc: ssc }.merge( nn )
end | ruby | def identify( name: nil, net: nil, cc: nil, imc: nil, ssc: nil, **nn )
name || { net: net, cc: cc, imc: imc, ssc: ssc }.merge( nn )
end | [
"def",
"identify",
"(",
"name",
":",
"nil",
",",
"net",
":",
"nil",
",",
"cc",
":",
"nil",
",",
"imc",
":",
"nil",
",",
"ssc",
":",
"nil",
",",
"**",
"nn",
")",
"name",
"||",
"{",
"net",
":",
"net",
",",
"cc",
":",
"cc",
",",
"imc",
":",
"imc",
",",
"ssc",
":",
"ssc",
"}",
".",
"merge",
"(",
"nn",
")",
"end"
] | Helper method specifying how a simulation is identified by arguments. | [
"Helper",
"method",
"specifying",
"how",
"a",
"simulation",
"is",
"identified",
"by",
"arguments",
"."
] | f69630d9f1e2ec85c528a9f62e8ba53138e0939e | https://github.com/boris-s/y_petri/blob/f69630d9f1e2ec85c528a9f62e8ba53138e0939e/lib/y_petri/agent/simulation_aspect.rb#L45-L47 | train |
justice3120/danger-conflict_checker | lib/conflict_checker/plugin.rb | Danger.DangerConflictChecker.check_conflict_and_comment | def check_conflict_and_comment()
results = check_conflict()
results.each do |result|
next if result[:mergeable]
message = "<p>This PR conflicts with <a href=\"#{result[:pull_request][:html_url]}\">##{result[:pull_request][:number]}</a>.</p>"
table = '<table><thead><tr><th width="100%">File</th><th>Line</th></tr></thead><tbody>' + result[:conflicts].map do |conflict|
file = conflict[:file]
line = conflict[:line]
line_link = "#{result[:pull_request][:head][:repo][:html_url]}/blob/#{result[:pull_request][:head][:ref]}/#{file}#L#{line}"
"<tr><td>#{file}</td><td><a href=\"#{line_link}\">#L#{line}</a></td></tr>"
end.join('') + '</tbody></table>'
puts (message + table)
warn("<div>" + message + table + "</div>")
end
results
end | ruby | def check_conflict_and_comment()
results = check_conflict()
results.each do |result|
next if result[:mergeable]
message = "<p>This PR conflicts with <a href=\"#{result[:pull_request][:html_url]}\">##{result[:pull_request][:number]}</a>.</p>"
table = '<table><thead><tr><th width="100%">File</th><th>Line</th></tr></thead><tbody>' + result[:conflicts].map do |conflict|
file = conflict[:file]
line = conflict[:line]
line_link = "#{result[:pull_request][:head][:repo][:html_url]}/blob/#{result[:pull_request][:head][:ref]}/#{file}#L#{line}"
"<tr><td>#{file}</td><td><a href=\"#{line_link}\">#L#{line}</a></td></tr>"
end.join('') + '</tbody></table>'
puts (message + table)
warn("<div>" + message + table + "</div>")
end
results
end | [
"def",
"check_conflict_and_comment",
"(",
")",
"results",
"=",
"check_conflict",
"(",
")",
"results",
".",
"each",
"do",
"|",
"result",
"|",
"next",
"if",
"result",
"[",
":mergeable",
"]",
"message",
"=",
"\"<p>This PR conflicts with <a href=\\\"#{result[:pull_request][:html_url]}\\\">##{result[:pull_request][:number]}</a>.</p>\"",
"table",
"=",
"'<table><thead><tr><th width=\"100%\">File</th><th>Line</th></tr></thead><tbody>'",
"+",
"result",
"[",
":conflicts",
"]",
".",
"map",
"do",
"|",
"conflict",
"|",
"file",
"=",
"conflict",
"[",
":file",
"]",
"line",
"=",
"conflict",
"[",
":line",
"]",
"line_link",
"=",
"\"#{result[:pull_request][:head][:repo][:html_url]}/blob/#{result[:pull_request][:head][:ref]}/#{file}#L#{line}\"",
"\"<tr><td>#{file}</td><td><a href=\\\"#{line_link}\\\">#L#{line}</a></td></tr>\"",
"end",
".",
"join",
"(",
"''",
")",
"+",
"'</tbody></table>'",
"puts",
"(",
"message",
"+",
"table",
")",
"warn",
"(",
"\"<div>\"",
"+",
"message",
"+",
"table",
"+",
"\"</div>\"",
")",
"end",
"results",
"end"
] | Warn in PR comment about the conflict between PRs
@return [Array<Hash>] | [
"Warn",
"in",
"PR",
"comment",
"about",
"the",
"conflict",
"between",
"PRs"
] | b3ac6a5f18553e455a9a474b3cd85fa8c2c83ebe | https://github.com/justice3120/danger-conflict_checker/blob/b3ac6a5f18553e455a9a474b3cd85fa8c2c83ebe/lib/conflict_checker/plugin.rb#L88-L105 | train |
bmuller/ankusa | lib/ankusa/cassandra_storage.rb | Ankusa.CassandraStorage.init_tables | def init_tables
# Do nothing if keyspace already exists
if @cassandra.keyspaces.include?(@keyspace)
@cassandra.keyspace = @keyspace
else
freq_table = Cassandra::ColumnFamily.new({:keyspace => @keyspace, :name => "classes"}) # word => {classname => count}
summary_table = Cassandra::ColumnFamily.new({:keyspace => @keyspace, :name => "totals"}) # class => {wordcount => count}
ks_def = Cassandra::Keyspace.new({
:name => @keyspace,
:strategy_class => 'org.apache.cassandra.locator.SimpleStrategy',
:replication_factor => 1,
:cf_defs => [freq_table, summary_table]
})
@cassandra.add_keyspace ks_def
@cassandra.keyspace = @keyspace
end
end | ruby | def init_tables
# Do nothing if keyspace already exists
if @cassandra.keyspaces.include?(@keyspace)
@cassandra.keyspace = @keyspace
else
freq_table = Cassandra::ColumnFamily.new({:keyspace => @keyspace, :name => "classes"}) # word => {classname => count}
summary_table = Cassandra::ColumnFamily.new({:keyspace => @keyspace, :name => "totals"}) # class => {wordcount => count}
ks_def = Cassandra::Keyspace.new({
:name => @keyspace,
:strategy_class => 'org.apache.cassandra.locator.SimpleStrategy',
:replication_factor => 1,
:cf_defs => [freq_table, summary_table]
})
@cassandra.add_keyspace ks_def
@cassandra.keyspace = @keyspace
end
end | [
"def",
"init_tables",
"if",
"@cassandra",
".",
"keyspaces",
".",
"include?",
"(",
"@keyspace",
")",
"@cassandra",
".",
"keyspace",
"=",
"@keyspace",
"else",
"freq_table",
"=",
"Cassandra",
"::",
"ColumnFamily",
".",
"new",
"(",
"{",
":keyspace",
"=>",
"@keyspace",
",",
":name",
"=>",
"\"classes\"",
"}",
")",
"summary_table",
"=",
"Cassandra",
"::",
"ColumnFamily",
".",
"new",
"(",
"{",
":keyspace",
"=>",
"@keyspace",
",",
":name",
"=>",
"\"totals\"",
"}",
")",
"ks_def",
"=",
"Cassandra",
"::",
"Keyspace",
".",
"new",
"(",
"{",
":name",
"=>",
"@keyspace",
",",
":strategy_class",
"=>",
"'org.apache.cassandra.locator.SimpleStrategy'",
",",
":replication_factor",
"=>",
"1",
",",
":cf_defs",
"=>",
"[",
"freq_table",
",",
"summary_table",
"]",
"}",
")",
"@cassandra",
".",
"add_keyspace",
"ks_def",
"@cassandra",
".",
"keyspace",
"=",
"@keyspace",
"end",
"end"
] | Create required keyspace and column families | [
"Create",
"required",
"keyspace",
"and",
"column",
"families"
] | af946f130aa63532fdb67d8382cfaaf81b38027b | https://github.com/bmuller/ankusa/blob/af946f130aa63532fdb67d8382cfaaf81b38027b/lib/ankusa/cassandra_storage.rb#L62-L78 | train |
bmuller/ankusa | lib/ankusa/cassandra_storage.rb | Ankusa.CassandraStorage.get_word_counts | def get_word_counts(word)
# fetch all (class,count) pairs for a given word
row = @cassandra.get(:classes, word.to_s)
return row.to_hash if row.empty?
row.inject({}){|counts, col| counts[col.first.to_sym] = [col.last.to_f,0].max; counts}
end | ruby | def get_word_counts(word)
# fetch all (class,count) pairs for a given word
row = @cassandra.get(:classes, word.to_s)
return row.to_hash if row.empty?
row.inject({}){|counts, col| counts[col.first.to_sym] = [col.last.to_f,0].max; counts}
end | [
"def",
"get_word_counts",
"(",
"word",
")",
"row",
"=",
"@cassandra",
".",
"get",
"(",
":classes",
",",
"word",
".",
"to_s",
")",
"return",
"row",
".",
"to_hash",
"if",
"row",
".",
"empty?",
"row",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"counts",
",",
"col",
"|",
"counts",
"[",
"col",
".",
"first",
".",
"to_sym",
"]",
"=",
"[",
"col",
".",
"last",
".",
"to_f",
",",
"0",
"]",
".",
"max",
";",
"counts",
"}",
"end"
] | Fetch hash of word counts as a single row from cassandra.
Here column_name is the class and column value is the count | [
"Fetch",
"hash",
"of",
"word",
"counts",
"as",
"a",
"single",
"row",
"from",
"cassandra",
".",
"Here",
"column_name",
"is",
"the",
"class",
"and",
"column",
"value",
"is",
"the",
"count"
] | af946f130aa63532fdb67d8382cfaaf81b38027b | https://github.com/bmuller/ankusa/blob/af946f130aa63532fdb67d8382cfaaf81b38027b/lib/ankusa/cassandra_storage.rb#L84-L89 | train |
bmuller/ankusa | lib/ankusa/cassandra_storage.rb | Ankusa.CassandraStorage.incr_total_word_count | def incr_total_word_count(klass, count)
klass = klass.to_s
wordcount = @cassandra.get(:totals, klass, "wordcount").values.last.to_i
wordcount += count
@cassandra.insert(:totals, klass, {"wordcount" => wordcount.to_s})
@klass_word_counts[klass.to_sym] = wordcount
end | ruby | def incr_total_word_count(klass, count)
klass = klass.to_s
wordcount = @cassandra.get(:totals, klass, "wordcount").values.last.to_i
wordcount += count
@cassandra.insert(:totals, klass, {"wordcount" => wordcount.to_s})
@klass_word_counts[klass.to_sym] = wordcount
end | [
"def",
"incr_total_word_count",
"(",
"klass",
",",
"count",
")",
"klass",
"=",
"klass",
".",
"to_s",
"wordcount",
"=",
"@cassandra",
".",
"get",
"(",
":totals",
",",
"klass",
",",
"\"wordcount\"",
")",
".",
"values",
".",
"last",
".",
"to_i",
"wordcount",
"+=",
"count",
"@cassandra",
".",
"insert",
"(",
":totals",
",",
"klass",
",",
"{",
"\"wordcount\"",
"=>",
"wordcount",
".",
"to_s",
"}",
")",
"@klass_word_counts",
"[",
"klass",
".",
"to_sym",
"]",
"=",
"wordcount",
"end"
] | Increment total word count for a given class by 'count' | [
"Increment",
"total",
"word",
"count",
"for",
"a",
"given",
"class",
"by",
"count"
] | af946f130aa63532fdb67d8382cfaaf81b38027b | https://github.com/bmuller/ankusa/blob/af946f130aa63532fdb67d8382cfaaf81b38027b/lib/ankusa/cassandra_storage.rb#L148-L154 | train |
bmuller/ankusa | lib/ankusa/cassandra_storage.rb | Ankusa.CassandraStorage.incr_doc_count | def incr_doc_count(klass, count)
klass = klass.to_s
doc_count = @cassandra.get(:totals, klass, "doc_count").values.last.to_i
doc_count += count
@cassandra.insert(:totals, klass, {"doc_count" => doc_count.to_s})
@klass_doc_counts[klass.to_sym] = doc_count
end | ruby | def incr_doc_count(klass, count)
klass = klass.to_s
doc_count = @cassandra.get(:totals, klass, "doc_count").values.last.to_i
doc_count += count
@cassandra.insert(:totals, klass, {"doc_count" => doc_count.to_s})
@klass_doc_counts[klass.to_sym] = doc_count
end | [
"def",
"incr_doc_count",
"(",
"klass",
",",
"count",
")",
"klass",
"=",
"klass",
".",
"to_s",
"doc_count",
"=",
"@cassandra",
".",
"get",
"(",
":totals",
",",
"klass",
",",
"\"doc_count\"",
")",
".",
"values",
".",
"last",
".",
"to_i",
"doc_count",
"+=",
"count",
"@cassandra",
".",
"insert",
"(",
":totals",
",",
"klass",
",",
"{",
"\"doc_count\"",
"=>",
"doc_count",
".",
"to_s",
"}",
")",
"@klass_doc_counts",
"[",
"klass",
".",
"to_sym",
"]",
"=",
"doc_count",
"end"
] | Increment total document count for a given class by 'count' | [
"Increment",
"total",
"document",
"count",
"for",
"a",
"given",
"class",
"by",
"count"
] | af946f130aa63532fdb67d8382cfaaf81b38027b | https://github.com/bmuller/ankusa/blob/af946f130aa63532fdb67d8382cfaaf81b38027b/lib/ankusa/cassandra_storage.rb#L159-L165 | train |
bmuller/ankusa | lib/ankusa/cassandra_storage.rb | Ankusa.CassandraStorage.get_summary | def get_summary(name)
counts = {}
@cassandra.get_range(:totals, {:start => '', :finish => '', :count => @max_classes}).each do |key_slice|
# keyslice is a clunky thrift object, map into a ruby hash
row = key_slice.columns.inject({}){|hsh, c| hsh[c.column.name] = c.column.value; hsh}
counts[key_slice.key.to_sym] = row[name].to_f
end
counts
end | ruby | def get_summary(name)
counts = {}
@cassandra.get_range(:totals, {:start => '', :finish => '', :count => @max_classes}).each do |key_slice|
# keyslice is a clunky thrift object, map into a ruby hash
row = key_slice.columns.inject({}){|hsh, c| hsh[c.column.name] = c.column.value; hsh}
counts[key_slice.key.to_sym] = row[name].to_f
end
counts
end | [
"def",
"get_summary",
"(",
"name",
")",
"counts",
"=",
"{",
"}",
"@cassandra",
".",
"get_range",
"(",
":totals",
",",
"{",
":start",
"=>",
"''",
",",
":finish",
"=>",
"''",
",",
":count",
"=>",
"@max_classes",
"}",
")",
".",
"each",
"do",
"|",
"key_slice",
"|",
"row",
"=",
"key_slice",
".",
"columns",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"hsh",
",",
"c",
"|",
"hsh",
"[",
"c",
".",
"column",
".",
"name",
"]",
"=",
"c",
".",
"column",
".",
"value",
";",
"hsh",
"}",
"counts",
"[",
"key_slice",
".",
"key",
".",
"to_sym",
"]",
"=",
"row",
"[",
"name",
"]",
".",
"to_f",
"end",
"counts",
"end"
] | Fetch 100 rows from summary table, yes, increase if necessary | [
"Fetch",
"100",
"rows",
"from",
"summary",
"table",
"yes",
"increase",
"if",
"necessary"
] | af946f130aa63532fdb67d8382cfaaf81b38027b | https://github.com/bmuller/ankusa/blob/af946f130aa63532fdb67d8382cfaaf81b38027b/lib/ankusa/cassandra_storage.rb#L182-L190 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.