id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
|
---|---|---|---|---|---|---|---|---|---|---|---|
24,500 | archan937/motion-bundler | lib/motion-bundler/mocks/zliby-0.0.5/zlib.rb | Zlib.ZStream.get_bits | def get_bits need
val = @bit_bucket
while @bit_count < need
val |= (@input_buffer[@in_pos+=1] << @bit_count)
@bit_count += 8
end
@bit_bucket = val >> need
@bit_count -= need
val & ((1 << need) - 1)
end | ruby | def get_bits need
val = @bit_bucket
while @bit_count < need
val |= (@input_buffer[@in_pos+=1] << @bit_count)
@bit_count += 8
end
@bit_bucket = val >> need
@bit_count -= need
val & ((1 << need) - 1)
end | [
"def",
"get_bits",
"need",
"val",
"=",
"@bit_bucket",
"while",
"@bit_count",
"<",
"need",
"val",
"|=",
"(",
"@input_buffer",
"[",
"@in_pos",
"+=",
"1",
"]",
"<<",
"@bit_count",
")",
"@bit_count",
"+=",
"8",
"end",
"@bit_bucket",
"=",
"val",
">>",
"need",
"@bit_count",
"-=",
"need",
"val",
"&",
"(",
"(",
"1",
"<<",
"need",
")",
"-",
"1",
")",
"end"
] | returns need bits from the input buffer
== Format Notes
bits are stored LSB to MSB | [
"returns",
"need",
"bits",
"from",
"the",
"input",
"buffer",
"==",
"Format",
"Notes",
"bits",
"are",
"stored",
"LSB",
"to",
"MSB"
] | 9cbfc90d4d4c7d5c61f954760f9568d5cac5b04f | https://github.com/archan937/motion-bundler/blob/9cbfc90d4d4c7d5c61f954760f9568d5cac5b04f/lib/motion-bundler/mocks/zliby-0.0.5/zlib.rb#L171-L181 |
24,501 | archan937/motion-bundler | lib/motion-bundler/mocks/zliby-0.0.5/zlib.rb | Zlib.Inflate.inflate | def inflate zstring=nil
@zstring = zstring unless zstring.nil?
#We can't use unpack, IronRuby doesn't have it yet.
@zstring.each_byte {|b| @input_buffer << b}
unless @rawdeflate then
compression_method_and_flags = @input_buffer[@in_pos+=1]
flags = @input_buffer[@in_pos+=1]
#CMF and FLG, when viewed as a 16-bit unsigned integer stored inMSB order (CMF*256 + FLG), is a multiple of 31
if ((compression_method_and_flags << 0x08) + flags) % 31 != 0 then raise Zlib::DataError.new("incorrect header check") end
#CM = 8 denotes the ìdeflateî compression method with a window size up to 32K. (RFC's only specify CM 8)
compression_method = compression_method_and_flags & 0x0F
if compression_method != Z_DEFLATED then raise Zlib::DataError.new("unknown compression method") end
#For CM = 8, CINFO is the base-2 logarithm of the LZ77 window size,minus eight (CINFO=7 indicates a 32K window size)
compression_info = compression_method_and_flags >> 0x04
if (compression_info + 8) > @w_bits then raise Zlib::DataError.new("invalid window size") end
preset_dictionary_flag = ((flags & 0x20) >> 0x05) == 1
compression_level = (flags & 0xC0) >> 0x06
if preset_dictionary_flag and @dict.nil? then raise Zlib::NeedDict.new "Preset dictionary needed!" end
#TODO: Add Preset dictionary support
if preset_dictionary_flag then
@dict_crc = @input_buffer[@in_pos+=1] << 24 | @input_buffer[@in_pos+=1] << 16 | @input_buffer[@in_pos+=1] << 8 | @input_buffer[@in_pos+=1]
end
end
last_block = false
#Begin processing DEFLATE stream
until last_block
last_block = (get_bits(1) == 1)
block_type = get_bits(2)
case block_type
when 0 then no_compression
when 1 then fixed_codes
when 2 then dynamic_codes
when 3 then raise Zlib::DataError.new("invalid block type")
end
end
finish
end | ruby | def inflate zstring=nil
@zstring = zstring unless zstring.nil?
#We can't use unpack, IronRuby doesn't have it yet.
@zstring.each_byte {|b| @input_buffer << b}
unless @rawdeflate then
compression_method_and_flags = @input_buffer[@in_pos+=1]
flags = @input_buffer[@in_pos+=1]
#CMF and FLG, when viewed as a 16-bit unsigned integer stored inMSB order (CMF*256 + FLG), is a multiple of 31
if ((compression_method_and_flags << 0x08) + flags) % 31 != 0 then raise Zlib::DataError.new("incorrect header check") end
#CM = 8 denotes the ìdeflateî compression method with a window size up to 32K. (RFC's only specify CM 8)
compression_method = compression_method_and_flags & 0x0F
if compression_method != Z_DEFLATED then raise Zlib::DataError.new("unknown compression method") end
#For CM = 8, CINFO is the base-2 logarithm of the LZ77 window size,minus eight (CINFO=7 indicates a 32K window size)
compression_info = compression_method_and_flags >> 0x04
if (compression_info + 8) > @w_bits then raise Zlib::DataError.new("invalid window size") end
preset_dictionary_flag = ((flags & 0x20) >> 0x05) == 1
compression_level = (flags & 0xC0) >> 0x06
if preset_dictionary_flag and @dict.nil? then raise Zlib::NeedDict.new "Preset dictionary needed!" end
#TODO: Add Preset dictionary support
if preset_dictionary_flag then
@dict_crc = @input_buffer[@in_pos+=1] << 24 | @input_buffer[@in_pos+=1] << 16 | @input_buffer[@in_pos+=1] << 8 | @input_buffer[@in_pos+=1]
end
end
last_block = false
#Begin processing DEFLATE stream
until last_block
last_block = (get_bits(1) == 1)
block_type = get_bits(2)
case block_type
when 0 then no_compression
when 1 then fixed_codes
when 2 then dynamic_codes
when 3 then raise Zlib::DataError.new("invalid block type")
end
end
finish
end | [
"def",
"inflate",
"zstring",
"=",
"nil",
"@zstring",
"=",
"zstring",
"unless",
"zstring",
".",
"nil?",
"#We can't use unpack, IronRuby doesn't have it yet.",
"@zstring",
".",
"each_byte",
"{",
"|",
"b",
"|",
"@input_buffer",
"<<",
"b",
"}",
"unless",
"@rawdeflate",
"then",
"compression_method_and_flags",
"=",
"@input_buffer",
"[",
"@in_pos",
"+=",
"1",
"]",
"flags",
"=",
"@input_buffer",
"[",
"@in_pos",
"+=",
"1",
"]",
"#CMF and FLG, when viewed as a 16-bit unsigned integer stored inMSB order (CMF*256 + FLG), is a multiple of 31",
"if",
"(",
"(",
"compression_method_and_flags",
"<<",
"0x08",
")",
"+",
"flags",
")",
"%",
"31",
"!=",
"0",
"then",
"raise",
"Zlib",
"::",
"DataError",
".",
"new",
"(",
"\"incorrect header check\"",
")",
"end",
"#CM = 8 denotes the ìdeflateî compression method with a window size up to 32K. (RFC's only specify CM 8)",
"compression_method",
"=",
"compression_method_and_flags",
"&",
"0x0F",
"if",
"compression_method",
"!=",
"Z_DEFLATED",
"then",
"raise",
"Zlib",
"::",
"DataError",
".",
"new",
"(",
"\"unknown compression method\"",
")",
"end",
"#For CM = 8, CINFO is the base-2 logarithm of the LZ77 window size,minus eight (CINFO=7 indicates a 32K window size)",
"compression_info",
"=",
"compression_method_and_flags",
">>",
"0x04",
"if",
"(",
"compression_info",
"+",
"8",
")",
">",
"@w_bits",
"then",
"raise",
"Zlib",
"::",
"DataError",
".",
"new",
"(",
"\"invalid window size\"",
")",
"end",
"preset_dictionary_flag",
"=",
"(",
"(",
"flags",
"&",
"0x20",
")",
">>",
"0x05",
")",
"==",
"1",
"compression_level",
"=",
"(",
"flags",
"&",
"0xC0",
")",
">>",
"0x06",
"if",
"preset_dictionary_flag",
"and",
"@dict",
".",
"nil?",
"then",
"raise",
"Zlib",
"::",
"NeedDict",
".",
"new",
"\"Preset dictionary needed!\"",
"end",
"#TODO: Add Preset dictionary support",
"if",
"preset_dictionary_flag",
"then",
"@dict_crc",
"=",
"@input_buffer",
"[",
"@in_pos",
"+=",
"1",
"]",
"<<",
"24",
"|",
"@input_buffer",
"[",
"@in_pos",
"+=",
"1",
"]",
"<<",
"16",
"|",
"@input_buffer",
"[",
"@in_pos",
"+=",
"1",
"]",
"<<",
"8",
"|",
"@input_buffer",
"[",
"@in_pos",
"+=",
"1",
"]",
"end",
"end",
"last_block",
"=",
"false",
"#Begin processing DEFLATE stream",
"until",
"last_block",
"last_block",
"=",
"(",
"get_bits",
"(",
"1",
")",
"==",
"1",
")",
"block_type",
"=",
"get_bits",
"(",
"2",
")",
"case",
"block_type",
"when",
"0",
"then",
"no_compression",
"when",
"1",
"then",
"fixed_codes",
"when",
"2",
"then",
"dynamic_codes",
"when",
"3",
"then",
"raise",
"Zlib",
"::",
"DataError",
".",
"new",
"(",
"\"invalid block type\"",
")",
"end",
"end",
"finish",
"end"
] | ==Example
f = File.open "example.z"
i = Inflate.new
i.inflate f.read | [
"==",
"Example",
"f",
"=",
"File",
".",
"open",
"example",
".",
"z",
"i",
"=",
"Inflate",
".",
"new",
"i",
".",
"inflate",
"f",
".",
"read"
] | 9cbfc90d4d4c7d5c61f954760f9568d5cac5b04f | https://github.com/archan937/motion-bundler/blob/9cbfc90d4d4c7d5c61f954760f9568d5cac5b04f/lib/motion-bundler/mocks/zliby-0.0.5/zlib.rb#L215-L262 |
24,502 | octopress/hooks | lib/octopress-hooks.rb | Jekyll.Convertible.do_layout | def do_layout(payload, layouts)
pre_render if respond_to?(:pre_render) && hooks
if respond_to?(:merge_payload) && hooks
old_do_layout(merge_payload(payload.dup), layouts)
else
old_do_layout(payload, layouts)
end
post_render if respond_to?(:post_render) && hooks
end | ruby | def do_layout(payload, layouts)
pre_render if respond_to?(:pre_render) && hooks
if respond_to?(:merge_payload) && hooks
old_do_layout(merge_payload(payload.dup), layouts)
else
old_do_layout(payload, layouts)
end
post_render if respond_to?(:post_render) && hooks
end | [
"def",
"do_layout",
"(",
"payload",
",",
"layouts",
")",
"pre_render",
"if",
"respond_to?",
"(",
":pre_render",
")",
"&&",
"hooks",
"if",
"respond_to?",
"(",
":merge_payload",
")",
"&&",
"hooks",
"old_do_layout",
"(",
"merge_payload",
"(",
"payload",
".",
"dup",
")",
",",
"layouts",
")",
"else",
"old_do_layout",
"(",
"payload",
",",
"layouts",
")",
"end",
"post_render",
"if",
"respond_to?",
"(",
":post_render",
")",
"&&",
"hooks",
"end"
] | Calls the pre_render method if it exists and then adds any necessary
layouts to this convertible document.
payload - The site payload Hash.
layouts - A Hash of {"name" => "layout"}.
Returns nothing. | [
"Calls",
"the",
"pre_render",
"method",
"if",
"it",
"exists",
"and",
"then",
"adds",
"any",
"necessary",
"layouts",
"to",
"this",
"convertible",
"document",
"."
] | ac460266254ed23e7d656767ec346eea63b29788 | https://github.com/octopress/hooks/blob/ac460266254ed23e7d656767ec346eea63b29788/lib/octopress-hooks.rb#L346-L356 |
24,503 | octopress/hooks | lib/octopress-hooks.rb | Jekyll.Site.site_payload | def site_payload
@cached_payload = begin
payload = old_site_payload
site_hooks.each do |hook|
p = hook.merge_payload(payload, self)
next unless p && p.is_a?(Hash)
payload = Jekyll::Utils.deep_merge_hashes(payload, p)
end
payload
end
end | ruby | def site_payload
@cached_payload = begin
payload = old_site_payload
site_hooks.each do |hook|
p = hook.merge_payload(payload, self)
next unless p && p.is_a?(Hash)
payload = Jekyll::Utils.deep_merge_hashes(payload, p)
end
payload
end
end | [
"def",
"site_payload",
"@cached_payload",
"=",
"begin",
"payload",
"=",
"old_site_payload",
"site_hooks",
".",
"each",
"do",
"|",
"hook",
"|",
"p",
"=",
"hook",
".",
"merge_payload",
"(",
"payload",
",",
"self",
")",
"next",
"unless",
"p",
"&&",
"p",
".",
"is_a?",
"(",
"Hash",
")",
"payload",
"=",
"Jekyll",
"::",
"Utils",
".",
"deep_merge_hashes",
"(",
"payload",
",",
"p",
")",
"end",
"payload",
"end",
"end"
] | Allows site hooks to merge data into the site payload
Returns the patched site payload | [
"Allows",
"site",
"hooks",
"to",
"merge",
"data",
"into",
"the",
"site",
"payload"
] | ac460266254ed23e7d656767ec346eea63b29788 | https://github.com/octopress/hooks/blob/ac460266254ed23e7d656767ec346eea63b29788/lib/octopress-hooks.rb#L203-L214 |
24,504 | oliamb/knnball | lib/knnball/ball.rb | KnnBall.Ball.distance | def distance(coordinates)
coordinates = coordinates.center if coordinates.respond_to?(:center)
Math.sqrt([center, coordinates].transpose.map {|a,b| (b - a)**2}.reduce {|d1,d2| d1 + d2})
end | ruby | def distance(coordinates)
coordinates = coordinates.center if coordinates.respond_to?(:center)
Math.sqrt([center, coordinates].transpose.map {|a,b| (b - a)**2}.reduce {|d1,d2| d1 + d2})
end | [
"def",
"distance",
"(",
"coordinates",
")",
"coordinates",
"=",
"coordinates",
".",
"center",
"if",
"coordinates",
".",
"respond_to?",
"(",
":center",
")",
"Math",
".",
"sqrt",
"(",
"[",
"center",
",",
"coordinates",
"]",
".",
"transpose",
".",
"map",
"{",
"|",
"a",
",",
"b",
"|",
"(",
"b",
"-",
"a",
")",
"**",
"2",
"}",
".",
"reduce",
"{",
"|",
"d1",
",",
"d2",
"|",
"d1",
"+",
"d2",
"}",
")",
"end"
] | Compute euclidien distance.
@param coordinates an array of coord or a Ball instance | [
"Compute",
"euclidien",
"distance",
"."
] | eb67c4452481d727ded06984ba7d82a92b5a8e03 | https://github.com/oliamb/knnball/blob/eb67c4452481d727ded06984ba7d82a92b5a8e03/lib/knnball/ball.rb#L78-L81 |
24,505 | rkh/tool | lib/tool/decoration.rb | Tool.Decoration.decorate | def decorate(block = nil, name: "generated", &callback)
@decorations << callback
if block
alias_name = "__" << name.to_s.downcase.gsub(/[^a-z]+/, ?_) << ?1
alias_name = alias_name.succ while private_method_defined? alias_name or method_defined? alias_name
without_decorations { define_method(name, &block) }
alias_method(alias_name, name)
remove_method(name)
private(alias_name)
end
end | ruby | def decorate(block = nil, name: "generated", &callback)
@decorations << callback
if block
alias_name = "__" << name.to_s.downcase.gsub(/[^a-z]+/, ?_) << ?1
alias_name = alias_name.succ while private_method_defined? alias_name or method_defined? alias_name
without_decorations { define_method(name, &block) }
alias_method(alias_name, name)
remove_method(name)
private(alias_name)
end
end | [
"def",
"decorate",
"(",
"block",
"=",
"nil",
",",
"name",
":",
"\"generated\"",
",",
"&",
"callback",
")",
"@decorations",
"<<",
"callback",
"if",
"block",
"alias_name",
"=",
"\"__\"",
"<<",
"name",
".",
"to_s",
".",
"downcase",
".",
"gsub",
"(",
"/",
"/",
",",
"?_",
")",
"<<",
"?1",
"alias_name",
"=",
"alias_name",
".",
"succ",
"while",
"private_method_defined?",
"alias_name",
"or",
"method_defined?",
"alias_name",
"without_decorations",
"{",
"define_method",
"(",
"name",
",",
"block",
")",
"}",
"alias_method",
"(",
"alias_name",
",",
"name",
")",
"remove_method",
"(",
"name",
")",
"private",
"(",
"alias_name",
")",
"end",
"end"
] | Set up a decoration.
@param [Proc, UnboundMethod, nil] block used for defining a method right away
@param [String, Symbol] name given to the generated method if block is given
@yield callback called with method name once method is defined
@yieldparam [Symbol] method name of the method that is to be decorated | [
"Set",
"up",
"a",
"decoration",
"."
] | 9a84fc6a60ecdf51cf17e90ae1331b4550d5d677 | https://github.com/rkh/tool/blob/9a84fc6a60ecdf51cf17e90ae1331b4550d5d677/lib/tool/decoration.rb#L67-L78 |
24,506 | nikhgupta/scrapix | lib/scrapix/vbulletin.rb | Scrapix.VBulletin.find | def find
reset; return @images unless @url
@page_no = @options["start"]
until @images.count > @options["total"] || thread_has_ended?
page = @agent.get "#{@url}&page=#{@page_no}"
puts "[VERBOSE] Searching: #{@url}&page=#{@page_no}" if @options["verbose"] && options["cli"]
sources = page.image_urls.map{|x| x.to_s}
sources = filter_images sources # hook for sub-classes
@page_no += 1
continue if sources.empty?
sources.each do |source|
hash = Digest::MD5.hexdigest(source)
unless @images.has_key?(hash)
@images[hash] = {url: source}
puts source if options["cli"]
end
end
end
@images = @images.map{|x, y| y}
end | ruby | def find
reset; return @images unless @url
@page_no = @options["start"]
until @images.count > @options["total"] || thread_has_ended?
page = @agent.get "#{@url}&page=#{@page_no}"
puts "[VERBOSE] Searching: #{@url}&page=#{@page_no}" if @options["verbose"] && options["cli"]
sources = page.image_urls.map{|x| x.to_s}
sources = filter_images sources # hook for sub-classes
@page_no += 1
continue if sources.empty?
sources.each do |source|
hash = Digest::MD5.hexdigest(source)
unless @images.has_key?(hash)
@images[hash] = {url: source}
puts source if options["cli"]
end
end
end
@images = @images.map{|x, y| y}
end | [
"def",
"find",
"reset",
";",
"return",
"@images",
"unless",
"@url",
"@page_no",
"=",
"@options",
"[",
"\"start\"",
"]",
"until",
"@images",
".",
"count",
">",
"@options",
"[",
"\"total\"",
"]",
"||",
"thread_has_ended?",
"page",
"=",
"@agent",
".",
"get",
"\"#{@url}&page=#{@page_no}\"",
"puts",
"\"[VERBOSE] Searching: #{@url}&page=#{@page_no}\"",
"if",
"@options",
"[",
"\"verbose\"",
"]",
"&&",
"options",
"[",
"\"cli\"",
"]",
"sources",
"=",
"page",
".",
"image_urls",
".",
"map",
"{",
"|",
"x",
"|",
"x",
".",
"to_s",
"}",
"sources",
"=",
"filter_images",
"sources",
"# hook for sub-classes",
"@page_no",
"+=",
"1",
"continue",
"if",
"sources",
".",
"empty?",
"sources",
".",
"each",
"do",
"|",
"source",
"|",
"hash",
"=",
"Digest",
"::",
"MD5",
".",
"hexdigest",
"(",
"source",
")",
"unless",
"@images",
".",
"has_key?",
"(",
"hash",
")",
"@images",
"[",
"hash",
"]",
"=",
"{",
"url",
":",
"source",
"}",
"puts",
"source",
"if",
"options",
"[",
"\"cli\"",
"]",
"end",
"end",
"end",
"@images",
"=",
"@images",
".",
"map",
"{",
"|",
"x",
",",
"y",
"|",
"y",
"}",
"end"
] | find images for this thread, specified by starting page_no | [
"find",
"images",
"for",
"this",
"thread",
"specified",
"by",
"starting",
"page_no"
] | 0a28a57a4ca423fb275e0d4e63fc1b9a824d9819 | https://github.com/nikhgupta/scrapix/blob/0a28a57a4ca423fb275e0d4e63fc1b9a824d9819/lib/scrapix/vbulletin.rb#L16-L35 |
24,507 | NFesquet/danger-kotlin_detekt | lib/kotlin_detekt/plugin.rb | Danger.DangerKotlinDetekt.detekt | def detekt(inline_mode: false)
unless skip_gradle_task || gradlew_exists?
fail("Could not find `gradlew` inside current directory")
return
end
unless SEVERITY_LEVELS.include?(severity)
fail("'#{severity}' is not a valid value for `severity` parameter.")
return
end
system "./gradlew #{gradle_task || 'detektCheck'}" unless skip_gradle_task
unless File.exist?(report_file)
fail("Detekt report not found at `#{report_file}`. "\
"Have you forgot to add `xmlReport true` to your `build.gradle` file?")
end
issues = read_issues_from_report
filtered_issues = filter_issues_by_severity(issues)
if inline_mode
# Report with inline comment
send_inline_comment(filtered_issues)
else
message = message_for_issues(filtered_issues)
markdown("### Detekt found issues\n\n" + message) unless message.to_s.empty?
end
end | ruby | def detekt(inline_mode: false)
unless skip_gradle_task || gradlew_exists?
fail("Could not find `gradlew` inside current directory")
return
end
unless SEVERITY_LEVELS.include?(severity)
fail("'#{severity}' is not a valid value for `severity` parameter.")
return
end
system "./gradlew #{gradle_task || 'detektCheck'}" unless skip_gradle_task
unless File.exist?(report_file)
fail("Detekt report not found at `#{report_file}`. "\
"Have you forgot to add `xmlReport true` to your `build.gradle` file?")
end
issues = read_issues_from_report
filtered_issues = filter_issues_by_severity(issues)
if inline_mode
# Report with inline comment
send_inline_comment(filtered_issues)
else
message = message_for_issues(filtered_issues)
markdown("### Detekt found issues\n\n" + message) unless message.to_s.empty?
end
end | [
"def",
"detekt",
"(",
"inline_mode",
":",
"false",
")",
"unless",
"skip_gradle_task",
"||",
"gradlew_exists?",
"fail",
"(",
"\"Could not find `gradlew` inside current directory\"",
")",
"return",
"end",
"unless",
"SEVERITY_LEVELS",
".",
"include?",
"(",
"severity",
")",
"fail",
"(",
"\"'#{severity}' is not a valid value for `severity` parameter.\"",
")",
"return",
"end",
"system",
"\"./gradlew #{gradle_task || 'detektCheck'}\"",
"unless",
"skip_gradle_task",
"unless",
"File",
".",
"exist?",
"(",
"report_file",
")",
"fail",
"(",
"\"Detekt report not found at `#{report_file}`. \"",
"\"Have you forgot to add `xmlReport true` to your `build.gradle` file?\"",
")",
"end",
"issues",
"=",
"read_issues_from_report",
"filtered_issues",
"=",
"filter_issues_by_severity",
"(",
"issues",
")",
"if",
"inline_mode",
"# Report with inline comment",
"send_inline_comment",
"(",
"filtered_issues",
")",
"else",
"message",
"=",
"message_for_issues",
"(",
"filtered_issues",
")",
"markdown",
"(",
"\"### Detekt found issues\\n\\n\"",
"+",
"message",
")",
"unless",
"message",
".",
"to_s",
".",
"empty?",
"end",
"end"
] | Calls Detekt task of your gradle project.
It fails if `gradlew` cannot be found inside current directory.
It fails if `severity` level is not a valid option.
It fails if `xmlReport` configuration is not set to `true` in your `build.gradle` file.
@return [void] | [
"Calls",
"Detekt",
"task",
"of",
"your",
"gradle",
"project",
".",
"It",
"fails",
"if",
"gradlew",
"cannot",
"be",
"found",
"inside",
"current",
"directory",
".",
"It",
"fails",
"if",
"severity",
"level",
"is",
"not",
"a",
"valid",
"option",
".",
"It",
"fails",
"if",
"xmlReport",
"configuration",
"is",
"not",
"set",
"to",
"true",
"in",
"your",
"build",
".",
"gradle",
"file",
"."
] | b45824e4bc8e02feb4f3fc78cb7e2741cb7fcdb5 | https://github.com/NFesquet/danger-kotlin_detekt/blob/b45824e4bc8e02feb4f3fc78cb7e2741cb7fcdb5/lib/kotlin_detekt/plugin.rb#L64-L92 |
24,508 | chef-boneyard/winrm-s | lib/winrm/winrm_service_patch.rb | WinRM.WinRMWebService.get_builder_obj | def get_builder_obj(shell_id, command_id, &block)
body = { "#{NS_WIN_SHELL}:DesiredStream" => 'stdout stderr',
:attributes! => {"#{NS_WIN_SHELL}:DesiredStream" => {'CommandId' => command_id}}}
builder = Builder::XmlMarkup.new
builder.instruct!(:xml, :encoding => 'UTF-8')
builder.tag! :env, :Envelope, namespaces do |env|
env.tag!(:env, :Header) { |h| h << Gyoku.xml(merge_headers(header,resource_uri_cmd,action_receive,selector_shell_id(shell_id))) }
env.tag!(:env, :Body) do |env_body|
env_body.tag!("#{NS_WIN_SHELL}:Receive") { |cl| cl << Gyoku.xml(body) }
end
end
builder
end | ruby | def get_builder_obj(shell_id, command_id, &block)
body = { "#{NS_WIN_SHELL}:DesiredStream" => 'stdout stderr',
:attributes! => {"#{NS_WIN_SHELL}:DesiredStream" => {'CommandId' => command_id}}}
builder = Builder::XmlMarkup.new
builder.instruct!(:xml, :encoding => 'UTF-8')
builder.tag! :env, :Envelope, namespaces do |env|
env.tag!(:env, :Header) { |h| h << Gyoku.xml(merge_headers(header,resource_uri_cmd,action_receive,selector_shell_id(shell_id))) }
env.tag!(:env, :Body) do |env_body|
env_body.tag!("#{NS_WIN_SHELL}:Receive") { |cl| cl << Gyoku.xml(body) }
end
end
builder
end | [
"def",
"get_builder_obj",
"(",
"shell_id",
",",
"command_id",
",",
"&",
"block",
")",
"body",
"=",
"{",
"\"#{NS_WIN_SHELL}:DesiredStream\"",
"=>",
"'stdout stderr'",
",",
":attributes!",
"=>",
"{",
"\"#{NS_WIN_SHELL}:DesiredStream\"",
"=>",
"{",
"'CommandId'",
"=>",
"command_id",
"}",
"}",
"}",
"builder",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"builder",
".",
"instruct!",
"(",
":xml",
",",
":encoding",
"=>",
"'UTF-8'",
")",
"builder",
".",
"tag!",
":env",
",",
":Envelope",
",",
"namespaces",
"do",
"|",
"env",
"|",
"env",
".",
"tag!",
"(",
":env",
",",
":Header",
")",
"{",
"|",
"h",
"|",
"h",
"<<",
"Gyoku",
".",
"xml",
"(",
"merge_headers",
"(",
"header",
",",
"resource_uri_cmd",
",",
"action_receive",
",",
"selector_shell_id",
"(",
"shell_id",
")",
")",
")",
"}",
"env",
".",
"tag!",
"(",
":env",
",",
":Body",
")",
"do",
"|",
"env_body",
"|",
"env_body",
".",
"tag!",
"(",
"\"#{NS_WIN_SHELL}:Receive\"",
")",
"{",
"|",
"cl",
"|",
"cl",
"<<",
"Gyoku",
".",
"xml",
"(",
"body",
")",
"}",
"end",
"end",
"builder",
"end"
] | Override winrm to support sspinegotiate option.
@param [String,URI] endpoint the WinRM webservice endpoint
@param [Symbol] transport either :kerberos(default)/:ssl/:plaintext
@param [Hash] opts Misc opts for the various transports.
@see WinRM::HTTP::HttpTransport
@see WinRM::HTTP::HttpGSSAPI
@see WinRM::HTTP::HttpSSL
Get the builder obj for output request
@param [String] shell_id The shell id on the remote machine. See #open_shell
@param [String] command_id The command id on the remote machine. See #run_command
@return [Builder::XmlMarkup] Returns a Builder::XmlMarkup for request message | [
"Override",
"winrm",
"to",
"support",
"sspinegotiate",
"option",
"."
] | 6c0e9027a79acfb9252caa701b1b383073bee865 | https://github.com/chef-boneyard/winrm-s/blob/6c0e9027a79acfb9252caa701b1b383073bee865/lib/winrm/winrm_service_patch.rb#L41-L53 |
24,509 | chef-boneyard/winrm-s | lib/winrm/winrm_service_patch.rb | WinRM.WinRMWebService.get_command_output | def get_command_output(shell_id, command_id, &block)
done_elems = []
output = Output.new
while done_elems.empty?
resp_doc = nil
builder = get_builder_obj(shell_id, command_id, &block)
request_msg = builder.target!
resp_doc = send_get_output_message(request_msg)
REXML::XPath.match(resp_doc, "//#{NS_WIN_SHELL}:Stream").each do |n|
next if n.text.nil? || n.text.empty?
stream = { n.attributes['Name'].to_sym => Base64.decode64(n.text).force_encoding('utf-8').sub("\xEF\xBB\xBF", "") }
output[:data] << stream
yield stream[:stdout], stream[:stderr] if block_given?
end
# We may need to get additional output if the stream has not finished.
# The CommandState will change from Running to Done like so:
# @example
# from...
# <rsp:CommandState CommandId="..." State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Running"/>
# to...
# <rsp:CommandState CommandId="..." State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done">
# <rsp:ExitCode>0</rsp:ExitCode>
# </rsp:CommandState>
done_elems = REXML::XPath.match(resp_doc, "//*[@State='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done']")
end
output[:exitcode] = REXML::XPath.first(resp_doc, "//#{NS_WIN_SHELL}:ExitCode").text.to_i
output
end | ruby | def get_command_output(shell_id, command_id, &block)
done_elems = []
output = Output.new
while done_elems.empty?
resp_doc = nil
builder = get_builder_obj(shell_id, command_id, &block)
request_msg = builder.target!
resp_doc = send_get_output_message(request_msg)
REXML::XPath.match(resp_doc, "//#{NS_WIN_SHELL}:Stream").each do |n|
next if n.text.nil? || n.text.empty?
stream = { n.attributes['Name'].to_sym => Base64.decode64(n.text).force_encoding('utf-8').sub("\xEF\xBB\xBF", "") }
output[:data] << stream
yield stream[:stdout], stream[:stderr] if block_given?
end
# We may need to get additional output if the stream has not finished.
# The CommandState will change from Running to Done like so:
# @example
# from...
# <rsp:CommandState CommandId="..." State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Running"/>
# to...
# <rsp:CommandState CommandId="..." State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done">
# <rsp:ExitCode>0</rsp:ExitCode>
# </rsp:CommandState>
done_elems = REXML::XPath.match(resp_doc, "//*[@State='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done']")
end
output[:exitcode] = REXML::XPath.first(resp_doc, "//#{NS_WIN_SHELL}:ExitCode").text.to_i
output
end | [
"def",
"get_command_output",
"(",
"shell_id",
",",
"command_id",
",",
"&",
"block",
")",
"done_elems",
"=",
"[",
"]",
"output",
"=",
"Output",
".",
"new",
"while",
"done_elems",
".",
"empty?",
"resp_doc",
"=",
"nil",
"builder",
"=",
"get_builder_obj",
"(",
"shell_id",
",",
"command_id",
",",
"block",
")",
"request_msg",
"=",
"builder",
".",
"target!",
"resp_doc",
"=",
"send_get_output_message",
"(",
"request_msg",
")",
"REXML",
"::",
"XPath",
".",
"match",
"(",
"resp_doc",
",",
"\"//#{NS_WIN_SHELL}:Stream\"",
")",
".",
"each",
"do",
"|",
"n",
"|",
"next",
"if",
"n",
".",
"text",
".",
"nil?",
"||",
"n",
".",
"text",
".",
"empty?",
"stream",
"=",
"{",
"n",
".",
"attributes",
"[",
"'Name'",
"]",
".",
"to_sym",
"=>",
"Base64",
".",
"decode64",
"(",
"n",
".",
"text",
")",
".",
"force_encoding",
"(",
"'utf-8'",
")",
".",
"sub",
"(",
"\"\\xEF\\xBB\\xBF\"",
",",
"\"\"",
")",
"}",
"output",
"[",
":data",
"]",
"<<",
"stream",
"yield",
"stream",
"[",
":stdout",
"]",
",",
"stream",
"[",
":stderr",
"]",
"if",
"block_given?",
"end",
"# We may need to get additional output if the stream has not finished.\r",
"# The CommandState will change from Running to Done like so:\r",
"# @example\r",
"# from...\r",
"# <rsp:CommandState CommandId=\"...\" State=\"http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Running\"/>\r",
"# to...\r",
"# <rsp:CommandState CommandId=\"...\" State=\"http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done\">\r",
"# <rsp:ExitCode>0</rsp:ExitCode>\r",
"# </rsp:CommandState>\r",
"done_elems",
"=",
"REXML",
"::",
"XPath",
".",
"match",
"(",
"resp_doc",
",",
"\"//*[@State='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done']\"",
")",
"end",
"output",
"[",
":exitcode",
"]",
"=",
"REXML",
"::",
"XPath",
".",
"first",
"(",
"resp_doc",
",",
"\"//#{NS_WIN_SHELL}:ExitCode\"",
")",
".",
"text",
".",
"to_i",
"output",
"end"
] | Get the Output of the given shell and command
@param [String] shell_id The shell id on the remote machine. See #open_shell
@param [String] command_id The command id on the remote machine. See #run_command
@return [Hash] Returns a Hash with a key :exitcode and :data. Data is an Array of Hashes where the cooresponding key
is either :stdout or :stderr. The reason it is in an Array so so we can get the output in the order it ocurrs on
the console. | [
"Get",
"the",
"Output",
"of",
"the",
"given",
"shell",
"and",
"command"
] | 6c0e9027a79acfb9252caa701b1b383073bee865 | https://github.com/chef-boneyard/winrm-s/blob/6c0e9027a79acfb9252caa701b1b383073bee865/lib/winrm/winrm_service_patch.rb#L61-L91 |
24,510 | argosity/hippo | lib/hippo/concerns/set_attribute_data.rb | Hippo::Concerns.ApiAttributeAccess.setting_attribute_is_allowed? | def setting_attribute_is_allowed?(name, user)
return false unless user.can_write?(self, name)
(self.whitelisted_attributes && self.whitelisted_attributes.has_key?( name.to_sym)) ||
(
self.attribute_names.include?( name.to_s ) &&
( self.blacklisted_attributes.nil? ||
! self.blacklisted_attributes.has_key?( name.to_sym ) )
)
end | ruby | def setting_attribute_is_allowed?(name, user)
return false unless user.can_write?(self, name)
(self.whitelisted_attributes && self.whitelisted_attributes.has_key?( name.to_sym)) ||
(
self.attribute_names.include?( name.to_s ) &&
( self.blacklisted_attributes.nil? ||
! self.blacklisted_attributes.has_key?( name.to_sym ) )
)
end | [
"def",
"setting_attribute_is_allowed?",
"(",
"name",
",",
"user",
")",
"return",
"false",
"unless",
"user",
".",
"can_write?",
"(",
"self",
",",
"name",
")",
"(",
"self",
".",
"whitelisted_attributes",
"&&",
"self",
".",
"whitelisted_attributes",
".",
"has_key?",
"(",
"name",
".",
"to_sym",
")",
")",
"||",
"(",
"self",
".",
"attribute_names",
".",
"include?",
"(",
"name",
".",
"to_s",
")",
"&&",
"(",
"self",
".",
"blacklisted_attributes",
".",
"nil?",
"||",
"!",
"self",
".",
"blacklisted_attributes",
".",
"has_key?",
"(",
"name",
".",
"to_sym",
")",
")",
")",
"end"
] | An attribute is allowed if it's white listed
or it's a valid attribute and not black listed
@param name [Symbol]
@param user [User] who is performing request | [
"An",
"attribute",
"is",
"allowed",
"if",
"it",
"s",
"white",
"listed",
"or",
"it",
"s",
"a",
"valid",
"attribute",
"and",
"not",
"black",
"listed"
] | 83be4c164897be3854325ff7fe0854604740df5e | https://github.com/argosity/hippo/blob/83be4c164897be3854325ff7fe0854604740df5e/lib/hippo/concerns/set_attribute_data.rb#L64-L72 |
24,511 | openc/turbot-client | lib/turbot/helpers/api_helper.rb | Turbot.Helpers.turbot_api_parameters | def turbot_api_parameters
uri = URI.parse(host)
{
:host => uri.host,
:port => uri.port,
:scheme => uri.scheme,
}
end | ruby | def turbot_api_parameters
uri = URI.parse(host)
{
:host => uri.host,
:port => uri.port,
:scheme => uri.scheme,
}
end | [
"def",
"turbot_api_parameters",
"uri",
"=",
"URI",
".",
"parse",
"(",
"host",
")",
"{",
":host",
"=>",
"uri",
".",
"host",
",",
":port",
"=>",
"uri",
".",
"port",
",",
":scheme",
"=>",
"uri",
".",
"scheme",
",",
"}",
"end"
] | Returns the parameters for the Turbot API, based on the base URL of the
Turbot server.
@return [Hash] the parameters for the Turbot API | [
"Returns",
"the",
"parameters",
"for",
"the",
"Turbot",
"API",
"based",
"on",
"the",
"base",
"URL",
"of",
"the",
"Turbot",
"server",
"."
] | 01225a5c7e155b7b34f1ae8de107c0b97201b42d | https://github.com/openc/turbot-client/blob/01225a5c7e155b7b34f1ae8de107c0b97201b42d/lib/turbot/helpers/api_helper.rb#L20-L28 |
24,512 | flinc/pling | lib/pling/gateway.rb | Pling.Gateway.handles? | def handles?(device)
device = Pling._convert(device, :device)
self.class.handled_types.include?(device.type)
end | ruby | def handles?(device)
device = Pling._convert(device, :device)
self.class.handled_types.include?(device.type)
end | [
"def",
"handles?",
"(",
"device",
")",
"device",
"=",
"Pling",
".",
"_convert",
"(",
"device",
",",
":device",
")",
"self",
".",
"class",
".",
"handled_types",
".",
"include?",
"(",
"device",
".",
"type",
")",
"end"
] | Checks if this gateway is able to handle the given device
@param device [#to_pling_device]
@return [Boolean] | [
"Checks",
"if",
"this",
"gateway",
"is",
"able",
"to",
"handle",
"the",
"given",
"device"
] | fdbf998a393502de4fd193b5ffb454bd4b100ac6 | https://github.com/flinc/pling/blob/fdbf998a393502de4fd193b5ffb454bd4b100ac6/lib/pling/gateway.rb#L85-L88 |
24,513 | kiwanami/ruby-elparser | lib/elparser.rb | Elparser.SExpList.to_h | def to_h
ret = Hash.new
@list.each do |i|
ret[i.car.to_ruby] = i.cdr.to_ruby
end
ret
end | ruby | def to_h
ret = Hash.new
@list.each do |i|
ret[i.car.to_ruby] = i.cdr.to_ruby
end
ret
end | [
"def",
"to_h",
"ret",
"=",
"Hash",
".",
"new",
"@list",
".",
"each",
"do",
"|",
"i",
"|",
"ret",
"[",
"i",
".",
"car",
".",
"to_ruby",
"]",
"=",
"i",
".",
"cdr",
".",
"to_ruby",
"end",
"ret",
"end"
] | alist -> hash | [
"alist",
"-",
">",
"hash"
] | 7b7edd13d7a3bd1a8a092983950aa5a9cc1cad5d | https://github.com/kiwanami/ruby-elparser/blob/7b7edd13d7a3bd1a8a092983950aa5a9cc1cad5d/lib/elparser.rb#L172-L178 |
24,514 | kiwanami/ruby-elparser | lib/elparser.rb | Elparser.Parser.parse | def parse(str)
if str.nil? || str == ""
raise ParserError.new("Empty input",0,"")
end
s = StringScanner.new str
@tokens = []
until s.eos?
s.skip(/\s+/) ? nil :
s.scan(/\A[-+]?[0-9]*\.[0-9]+(e[-+]?[0-9]+)?/i) ? (@tokens << [:FLOAT, s.matched]) :
s.scan(/\A[-+]?(0|[1-9]\d*)/) ? (@tokens << [:INTEGER, s.matched]) :
s.scan(/\A\.(?=\s)/) ? (@tokens << ['.', '.']) :
s.scan(/\A[a-z\-.\/_:*<>+=$#][a-z\-.\/_:$*<>+=0-9]*/i) ? (@tokens << [:SYMBOL, s.matched]) :
s.scan(/\A"(([^\\"]|\\.)*)"/) ? (@tokens << [:STRING, _unescape_string(s.matched.slice(1...-1))]) :
s.scan(/\A./) ? (a = s.matched; @tokens << [a, a]) :
(raise ParserError.new("Scanner error",s.pos,s.peek(5)))
end
@tokens.push [false, 'END']
return do_parse.map do |i|
normalize(i)
end
end | ruby | def parse(str)
if str.nil? || str == ""
raise ParserError.new("Empty input",0,"")
end
s = StringScanner.new str
@tokens = []
until s.eos?
s.skip(/\s+/) ? nil :
s.scan(/\A[-+]?[0-9]*\.[0-9]+(e[-+]?[0-9]+)?/i) ? (@tokens << [:FLOAT, s.matched]) :
s.scan(/\A[-+]?(0|[1-9]\d*)/) ? (@tokens << [:INTEGER, s.matched]) :
s.scan(/\A\.(?=\s)/) ? (@tokens << ['.', '.']) :
s.scan(/\A[a-z\-.\/_:*<>+=$#][a-z\-.\/_:$*<>+=0-9]*/i) ? (@tokens << [:SYMBOL, s.matched]) :
s.scan(/\A"(([^\\"]|\\.)*)"/) ? (@tokens << [:STRING, _unescape_string(s.matched.slice(1...-1))]) :
s.scan(/\A./) ? (a = s.matched; @tokens << [a, a]) :
(raise ParserError.new("Scanner error",s.pos,s.peek(5)))
end
@tokens.push [false, 'END']
return do_parse.map do |i|
normalize(i)
end
end | [
"def",
"parse",
"(",
"str",
")",
"if",
"str",
".",
"nil?",
"||",
"str",
"==",
"\"\"",
"raise",
"ParserError",
".",
"new",
"(",
"\"Empty input\"",
",",
"0",
",",
"\"\"",
")",
"end",
"s",
"=",
"StringScanner",
".",
"new",
"str",
"@tokens",
"=",
"[",
"]",
"until",
"s",
".",
"eos?",
"s",
".",
"skip",
"(",
"/",
"\\s",
"/",
")",
"?",
"nil",
":",
"s",
".",
"scan",
"(",
"/",
"\\A",
"\\.",
"/i",
")",
"?",
"(",
"@tokens",
"<<",
"[",
":FLOAT",
",",
"s",
".",
"matched",
"]",
")",
":",
"s",
".",
"scan",
"(",
"/",
"\\A",
"\\d",
"/",
")",
"?",
"(",
"@tokens",
"<<",
"[",
":INTEGER",
",",
"s",
".",
"matched",
"]",
")",
":",
"s",
".",
"scan",
"(",
"/",
"\\A",
"\\.",
"\\s",
"/",
")",
"?",
"(",
"@tokens",
"<<",
"[",
"'.'",
",",
"'.'",
"]",
")",
":",
"s",
".",
"scan",
"(",
"/",
"\\A",
"\\-",
"\\/",
"\\-",
"\\/",
"/i",
")",
"?",
"(",
"@tokens",
"<<",
"[",
":SYMBOL",
",",
"s",
".",
"matched",
"]",
")",
":",
"s",
".",
"scan",
"(",
"/",
"\\A",
"\\\\",
"\\\\",
"/",
")",
"?",
"(",
"@tokens",
"<<",
"[",
":STRING",
",",
"_unescape_string",
"(",
"s",
".",
"matched",
".",
"slice",
"(",
"1",
"...",
"-",
"1",
")",
")",
"]",
")",
":",
"s",
".",
"scan",
"(",
"/",
"\\A",
"/",
")",
"?",
"(",
"a",
"=",
"s",
".",
"matched",
";",
"@tokens",
"<<",
"[",
"a",
",",
"a",
"]",
")",
":",
"(",
"raise",
"ParserError",
".",
"new",
"(",
"\"Scanner error\"",
",",
"s",
".",
"pos",
",",
"s",
".",
"peek",
"(",
"5",
")",
")",
")",
"end",
"@tokens",
".",
"push",
"[",
"false",
",",
"'END'",
"]",
"return",
"do_parse",
".",
"map",
"do",
"|",
"i",
"|",
"normalize",
"(",
"i",
")",
"end",
"end"
] | parse s-expression string and return sexp objects. | [
"parse",
"s",
"-",
"expression",
"string",
"and",
"return",
"sexp",
"objects",
"."
] | 7b7edd13d7a3bd1a8a092983950aa5a9cc1cad5d | https://github.com/kiwanami/ruby-elparser/blob/7b7edd13d7a3bd1a8a092983950aa5a9cc1cad5d/lib/elparser.rb#L245-L268 |
24,515 | kiwanami/ruby-elparser | lib/elparser.rb | Elparser.Parser.normalize | def normalize(ast)
if ast.class == SExpSymbol
case ast.name
when "nil"
return SExpNil.new
else
return ast
end
elsif ast.cons? then
ast.visit do |i|
normalize(i)
end
end
return ast
end | ruby | def normalize(ast)
if ast.class == SExpSymbol
case ast.name
when "nil"
return SExpNil.new
else
return ast
end
elsif ast.cons? then
ast.visit do |i|
normalize(i)
end
end
return ast
end | [
"def",
"normalize",
"(",
"ast",
")",
"if",
"ast",
".",
"class",
"==",
"SExpSymbol",
"case",
"ast",
".",
"name",
"when",
"\"nil\"",
"return",
"SExpNil",
".",
"new",
"else",
"return",
"ast",
"end",
"elsif",
"ast",
".",
"cons?",
"then",
"ast",
".",
"visit",
"do",
"|",
"i",
"|",
"normalize",
"(",
"i",
")",
"end",
"end",
"return",
"ast",
"end"
] | replace special symbols | [
"replace",
"special",
"symbols"
] | 7b7edd13d7a3bd1a8a092983950aa5a9cc1cad5d | https://github.com/kiwanami/ruby-elparser/blob/7b7edd13d7a3bd1a8a092983950aa5a9cc1cad5d/lib/elparser.rb#L297-L311 |
24,516 | david942j/memory_io | lib/memory_io/io.rb | MemoryIO.IO.write | def write(objects, from: nil, as: nil)
stream.pos = from if from
as ||= objects.class if objects.class.ancestors.include?(MemoryIO::Types::Type)
return stream.write(objects) if as.nil?
conv = to_proc(as, :write)
Array(objects).map { |o| conv.call(stream, o) }
end | ruby | def write(objects, from: nil, as: nil)
stream.pos = from if from
as ||= objects.class if objects.class.ancestors.include?(MemoryIO::Types::Type)
return stream.write(objects) if as.nil?
conv = to_proc(as, :write)
Array(objects).map { |o| conv.call(stream, o) }
end | [
"def",
"write",
"(",
"objects",
",",
"from",
":",
"nil",
",",
"as",
":",
"nil",
")",
"stream",
".",
"pos",
"=",
"from",
"if",
"from",
"as",
"||=",
"objects",
".",
"class",
"if",
"objects",
".",
"class",
".",
"ancestors",
".",
"include?",
"(",
"MemoryIO",
"::",
"Types",
"::",
"Type",
")",
"return",
"stream",
".",
"write",
"(",
"objects",
")",
"if",
"as",
".",
"nil?",
"conv",
"=",
"to_proc",
"(",
"as",
",",
":write",
")",
"Array",
"(",
"objects",
")",
".",
"map",
"{",
"|",
"o",
"|",
"conv",
".",
"call",
"(",
"stream",
",",
"o",
")",
"}",
"end"
] | Write to stream.
@param [Object, Array<Object>] objects
Objects to be written.
@param [Integer] from
The position to start to write.
@param [nil, Symbol, Proc] as
Decide the method to process writing procedure.
See {MemoryIO::Types} for all supported types.
A +Proc+ is allowed, which should accept +stream+ and one object as arguments.
If +objects+ is a descendent instance of {Types::Type} and +as+ is +nil,
+objects.class+ will be used for +as+.
Otherwise, when +as = nil+, this method will simply call +stream.write(objects)+.
@return [void]
@example
stream = StringIO.new
io = MemoryIO::IO.new(stream)
io.write('abcd')
stream.string
#=> "abcd"
io.write([1, 2, 3, 4], from: 2, as: :u16)
stream.string
#=> "ab\x01\x00\x02\x00\x03\x00\x04\x00"
io.write(['A', 'BB', 'CCC'], from: 0, as: :c_str)
stream.string
#=> "A\x00BB\x00CCC\x00\x00"
@example
stream = StringIO.new
io = MemoryIO::IO.new(stream)
io.write(%w[123 4567], as: ->(s, str) { s.write(str.size.chr + str) })
stream.string
#=> "\x03123\x044567"
@example
stream = StringIO.new
io = MemoryIO::IO.new(stream)
cpp_string = CPP::String.new('A' * 4, 15, 16)
# equivalent to io.write(cpp_string, as: :'cpp/string')
io.write(cpp_string)
stream.string
#=> "\x10\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00AAAA\x00"
@see Types | [
"Write",
"to",
"stream",
"."
] | 97a4206974b699767c57f3e113f78bdae69f950f | https://github.com/david942j/memory_io/blob/97a4206974b699767c57f3e113f78bdae69f950f/lib/memory_io/io.rb#L163-L170 |
24,517 | david942j/memory_io | lib/memory_io/util.rb | MemoryIO.Util.underscore | def underscore(str)
return '' if str.empty?
str = str.gsub('::', '/')
str.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
str.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
str.downcase!
str
end | ruby | def underscore(str)
return '' if str.empty?
str = str.gsub('::', '/')
str.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
str.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
str.downcase!
str
end | [
"def",
"underscore",
"(",
"str",
")",
"return",
"''",
"if",
"str",
".",
"empty?",
"str",
"=",
"str",
".",
"gsub",
"(",
"'::'",
",",
"'/'",
")",
"str",
".",
"gsub!",
"(",
"/",
"/",
",",
"'\\1_\\2'",
")",
"str",
".",
"gsub!",
"(",
"/",
"\\d",
"/",
",",
"'\\1_\\2'",
")",
"str",
".",
"downcase!",
"str",
"end"
] | Convert input into snake-case.
This method also converts +'::'+ to +'/'+.
@param [String] str
String to be converted.
@return [String]
Converted string.
@example
Util.underscore('MemoryIO')
#=> 'memory_io'
Util.underscore('MyModule::MyClass')
#=> 'my_module/my_class' | [
"Convert",
"input",
"into",
"snake",
"-",
"case",
"."
] | 97a4206974b699767c57f3e113f78bdae69f950f | https://github.com/david942j/memory_io/blob/97a4206974b699767c57f3e113f78bdae69f950f/lib/memory_io/util.rb#L25-L33 |
24,518 | david942j/memory_io | lib/memory_io/util.rb | MemoryIO.Util.safe_eval | def safe_eval(str, **vars)
return str if str.is_a?(Integer)
# dentaku 2 doesn't support hex
str = str.gsub(/0x[0-9a-zA-Z]+/) { |c| c.to_i(16) }
Dentaku::Calculator.new.store(vars).evaluate(str)
end | ruby | def safe_eval(str, **vars)
return str if str.is_a?(Integer)
# dentaku 2 doesn't support hex
str = str.gsub(/0x[0-9a-zA-Z]+/) { |c| c.to_i(16) }
Dentaku::Calculator.new.store(vars).evaluate(str)
end | [
"def",
"safe_eval",
"(",
"str",
",",
"**",
"vars",
")",
"return",
"str",
"if",
"str",
".",
"is_a?",
"(",
"Integer",
")",
"# dentaku 2 doesn't support hex",
"str",
"=",
"str",
".",
"gsub",
"(",
"/",
"/",
")",
"{",
"|",
"c",
"|",
"c",
".",
"to_i",
"(",
"16",
")",
"}",
"Dentaku",
"::",
"Calculator",
".",
"new",
".",
"store",
"(",
"vars",
")",
".",
"evaluate",
"(",
"str",
")",
"end"
] | Evaluate string safely.
@param [String] str
String to be evaluated.
@param [{Symbol => Integer}] vars
Predefined variables
@return [Integer]
Result.
@example
Util.safe_eval('heap + 0x10 * pp', heap: 0xde00, pp: 8)
#=> 56960 # 0xde80 | [
"Evaluate",
"string",
"safely",
"."
] | 97a4206974b699767c57f3e113f78bdae69f950f | https://github.com/david942j/memory_io/blob/97a4206974b699767c57f3e113f78bdae69f950f/lib/memory_io/util.rb#L75-L81 |
24,519 | david942j/memory_io | lib/memory_io/util.rb | MemoryIO.Util.unpack | def unpack(str)
str.bytes.reverse.reduce(0) { |s, c| s * 256 + c }
end | ruby | def unpack(str)
str.bytes.reverse.reduce(0) { |s, c| s * 256 + c }
end | [
"def",
"unpack",
"(",
"str",
")",
"str",
".",
"bytes",
".",
"reverse",
".",
"reduce",
"(",
"0",
")",
"{",
"|",
"s",
",",
"c",
"|",
"s",
"*",
"256",
"+",
"c",
"}",
"end"
] | Unpack a string into an integer.
Little endian is used.
@param [String] str
String.
@return [Integer]
Result.
@example
Util.unpack("\xff")
#=> 255
Util.unpack("@\xE2\x01\x00")
#=> 123456 | [
"Unpack",
"a",
"string",
"into",
"an",
"integer",
".",
"Little",
"endian",
"is",
"used",
"."
] | 97a4206974b699767c57f3e113f78bdae69f950f | https://github.com/david942j/memory_io/blob/97a4206974b699767c57f3e113f78bdae69f950f/lib/memory_io/util.rb#L97-L99 |
24,520 | david942j/memory_io | lib/memory_io/util.rb | MemoryIO.Util.pack | def pack(val, b)
Array.new(b) { |i| (val >> (i * 8)) & 0xff }.pack('C*')
end | ruby | def pack(val, b)
Array.new(b) { |i| (val >> (i * 8)) & 0xff }.pack('C*')
end | [
"def",
"pack",
"(",
"val",
",",
"b",
")",
"Array",
".",
"new",
"(",
"b",
")",
"{",
"|",
"i",
"|",
"(",
"val",
">>",
"(",
"i",
"*",
"8",
")",
")",
"&",
"0xff",
"}",
".",
"pack",
"(",
"'C*'",
")",
"end"
] | Pack an integer into +b+ bytes.
Little endian is used.
@param [Integer] val
The integer to pack.
If +val+ contains more than +b+ bytes,
only lower +b+ bytes in +val+ will be packed.
@param [Integer] b
@return [String]
Packing result with length +b+.
@example
Util.pack(0x123, 4)
#=> "\x23\x01\x00\x00" | [
"Pack",
"an",
"integer",
"into",
"+",
"b",
"+",
"bytes",
".",
"Little",
"endian",
"is",
"used",
"."
] | 97a4206974b699767c57f3e113f78bdae69f950f | https://github.com/david942j/memory_io/blob/97a4206974b699767c57f3e113f78bdae69f950f/lib/memory_io/util.rb#L117-L119 |
24,521 | oliamb/knnball | lib/knnball/kdtree.rb | KnnBall.KDTree.nearest | def nearest(coord, options = {})
return nil if root.nil?
return nil if coord.nil?
results = (options[:results] ? options[:results] : ResultSet.new({limit: options[:limit] || 1}))
root_ball = options[:root] || root
# keep the stack while finding the leaf best match.
parents = []
best_balls = []
in_target = []
# Move down to best match
current_best = nil
current = root_ball
while current_best.nil?
dim = current.dimension-1
if(current.complete?)
next_ball = (coord[dim] <= current.center[dim] ? current.left : current.right)
elsif(current.leaf?)
next_ball = nil
else
next_ball = (current.left.nil? ? current.right : current.left)
end
if ( next_ball.nil? )
current_best = current
else
parents.push current
current = next_ball
end
end
# Move up to check split
parents.reverse!
results.add(current_best.quick_distance(coord), current_best.value)
parents.each do |current_node|
dist = current_node.quick_distance(coord)
if results.eligible?( dist )
results.add(dist, current_node.value)
end
dim = current_node.dimension-1
if current_node.complete?
# retrieve the splitting node.
split_node = (coord[dim] <= current_node.center[dim] ? current_node.right : current_node.left)
best_dist = results.barrier_value
if( (coord[dim] - current_node.center[dim]).abs <= best_dist)
# potential match, need to investigate subtree
nearest(coord, root: split_node, results: results)
end
end
end
return results.limit == 1 ? results.items.first : results.items
end | ruby | def nearest(coord, options = {})
return nil if root.nil?
return nil if coord.nil?
results = (options[:results] ? options[:results] : ResultSet.new({limit: options[:limit] || 1}))
root_ball = options[:root] || root
# keep the stack while finding the leaf best match.
parents = []
best_balls = []
in_target = []
# Move down to best match
current_best = nil
current = root_ball
while current_best.nil?
dim = current.dimension-1
if(current.complete?)
next_ball = (coord[dim] <= current.center[dim] ? current.left : current.right)
elsif(current.leaf?)
next_ball = nil
else
next_ball = (current.left.nil? ? current.right : current.left)
end
if ( next_ball.nil? )
current_best = current
else
parents.push current
current = next_ball
end
end
# Move up to check split
parents.reverse!
results.add(current_best.quick_distance(coord), current_best.value)
parents.each do |current_node|
dist = current_node.quick_distance(coord)
if results.eligible?( dist )
results.add(dist, current_node.value)
end
dim = current_node.dimension-1
if current_node.complete?
# retrieve the splitting node.
split_node = (coord[dim] <= current_node.center[dim] ? current_node.right : current_node.left)
best_dist = results.barrier_value
if( (coord[dim] - current_node.center[dim]).abs <= best_dist)
# potential match, need to investigate subtree
nearest(coord, root: split_node, results: results)
end
end
end
return results.limit == 1 ? results.items.first : results.items
end | [
"def",
"nearest",
"(",
"coord",
",",
"options",
"=",
"{",
"}",
")",
"return",
"nil",
"if",
"root",
".",
"nil?",
"return",
"nil",
"if",
"coord",
".",
"nil?",
"results",
"=",
"(",
"options",
"[",
":results",
"]",
"?",
"options",
"[",
":results",
"]",
":",
"ResultSet",
".",
"new",
"(",
"{",
"limit",
":",
"options",
"[",
":limit",
"]",
"||",
"1",
"}",
")",
")",
"root_ball",
"=",
"options",
"[",
":root",
"]",
"||",
"root",
"# keep the stack while finding the leaf best match.",
"parents",
"=",
"[",
"]",
"best_balls",
"=",
"[",
"]",
"in_target",
"=",
"[",
"]",
"# Move down to best match",
"current_best",
"=",
"nil",
"current",
"=",
"root_ball",
"while",
"current_best",
".",
"nil?",
"dim",
"=",
"current",
".",
"dimension",
"-",
"1",
"if",
"(",
"current",
".",
"complete?",
")",
"next_ball",
"=",
"(",
"coord",
"[",
"dim",
"]",
"<=",
"current",
".",
"center",
"[",
"dim",
"]",
"?",
"current",
".",
"left",
":",
"current",
".",
"right",
")",
"elsif",
"(",
"current",
".",
"leaf?",
")",
"next_ball",
"=",
"nil",
"else",
"next_ball",
"=",
"(",
"current",
".",
"left",
".",
"nil?",
"?",
"current",
".",
"right",
":",
"current",
".",
"left",
")",
"end",
"if",
"(",
"next_ball",
".",
"nil?",
")",
"current_best",
"=",
"current",
"else",
"parents",
".",
"push",
"current",
"current",
"=",
"next_ball",
"end",
"end",
"# Move up to check split",
"parents",
".",
"reverse!",
"results",
".",
"add",
"(",
"current_best",
".",
"quick_distance",
"(",
"coord",
")",
",",
"current_best",
".",
"value",
")",
"parents",
".",
"each",
"do",
"|",
"current_node",
"|",
"dist",
"=",
"current_node",
".",
"quick_distance",
"(",
"coord",
")",
"if",
"results",
".",
"eligible?",
"(",
"dist",
")",
"results",
".",
"add",
"(",
"dist",
",",
"current_node",
".",
"value",
")",
"end",
"dim",
"=",
"current_node",
".",
"dimension",
"-",
"1",
"if",
"current_node",
".",
"complete?",
"# retrieve the splitting node.",
"split_node",
"=",
"(",
"coord",
"[",
"dim",
"]",
"<=",
"current_node",
".",
"center",
"[",
"dim",
"]",
"?",
"current_node",
".",
"right",
":",
"current_node",
".",
"left",
")",
"best_dist",
"=",
"results",
".",
"barrier_value",
"if",
"(",
"(",
"coord",
"[",
"dim",
"]",
"-",
"current_node",
".",
"center",
"[",
"dim",
"]",
")",
".",
"abs",
"<=",
"best_dist",
")",
"# potential match, need to investigate subtree",
"nearest",
"(",
"coord",
",",
"root",
":",
"split_node",
",",
"results",
":",
"results",
")",
"end",
"end",
"end",
"return",
"results",
".",
"limit",
"==",
"1",
"?",
"results",
".",
"items",
".",
"first",
":",
"results",
".",
"items",
"end"
] | Retrieve the nearest point from the given coord array.
available keys for options are :root and :limit
Wikipedia tell us (excerpt from url http://en.wikipedia.org/wiki/Kd%5Ftree#Nearest%5Fneighbor%5Fsearch)
Searching for a nearest neighbour in a k-d tree proceeds as follows:
1. Starting with the root node, the algorithm moves down the tree recursively,
in the same way that it would if the search point were being inserted
(i.e. it goes left or right depending on whether the point is less than or
greater than the current node in the split dimension).
2. Once the algorithm reaches a leaf node, it saves that node point as the "current best"
3. The algorithm unwinds the recursion of the tree, performing the following steps at each node:
1. If the current node is closer than the current best, then it becomes the current best.
2. The algorithm checks whether there could be any points on the other side of the splitting
plane that are closer to the search point than the current best. In concept, this is done
by intersecting the splitting hyperplane with a hypersphere around the search point that
has a radius equal to the current nearest distance. Since the hyperplanes are all axis-aligned
this is implemented as a simple comparison to see whether the difference between the splitting
coordinate of the search point and current node is less than the distance (overall coordinates) from
the search point to the current best.
1. If the hypersphere crosses the plane, there could be nearer points on the other side of the plane,
so the algorithm must move down the other branch of the tree from the current node looking for
closer points, following the same recursive process as the entire search.
2. If the hypersphere doesn't intersect the splitting plane, then the algorithm continues walking
up the tree, and the entire branch on the other side of that node is eliminated.
4. When the algorithm finishes this process for the root node, then the search is complete.
Generally the algorithm uses squared distances for comparison to avoid computing square roots. Additionally,
it can save computation by holding the squared current best distance in a variable for comparison. | [
"Retrieve",
"the",
"nearest",
"point",
"from",
"the",
"given",
"coord",
"array",
"."
] | eb67c4452481d727ded06984ba7d82a92b5a8e03 | https://github.com/oliamb/knnball/blob/eb67c4452481d727ded06984ba7d82a92b5a8e03/lib/knnball/kdtree.rb#L50-L104 |
24,522 | oliamb/knnball | lib/knnball/kdtree.rb | KnnBall.KDTree.parent_ball | def parent_ball(coord)
current = root
d_idx = current.dimension-1
result = nil
while(result.nil?)
if(coord[d_idx] <= current.center[d_idx])
if current.left.nil?
result = current
else
current = current.left
end
else
if current.right.nil?
result = current
else
current = current.right
end
end
d_idx = current.dimension-1
end
return result
end | ruby | def parent_ball(coord)
current = root
d_idx = current.dimension-1
result = nil
while(result.nil?)
if(coord[d_idx] <= current.center[d_idx])
if current.left.nil?
result = current
else
current = current.left
end
else
if current.right.nil?
result = current
else
current = current.right
end
end
d_idx = current.dimension-1
end
return result
end | [
"def",
"parent_ball",
"(",
"coord",
")",
"current",
"=",
"root",
"d_idx",
"=",
"current",
".",
"dimension",
"-",
"1",
"result",
"=",
"nil",
"while",
"(",
"result",
".",
"nil?",
")",
"if",
"(",
"coord",
"[",
"d_idx",
"]",
"<=",
"current",
".",
"center",
"[",
"d_idx",
"]",
")",
"if",
"current",
".",
"left",
".",
"nil?",
"result",
"=",
"current",
"else",
"current",
"=",
"current",
".",
"left",
"end",
"else",
"if",
"current",
".",
"right",
".",
"nil?",
"result",
"=",
"current",
"else",
"current",
"=",
"current",
".",
"right",
"end",
"end",
"d_idx",
"=",
"current",
".",
"dimension",
"-",
"1",
"end",
"return",
"result",
"end"
] | Retrieve the parent to which this coord should belongs to | [
"Retrieve",
"the",
"parent",
"to",
"which",
"this",
"coord",
"should",
"belongs",
"to"
] | eb67c4452481d727ded06984ba7d82a92b5a8e03 | https://github.com/oliamb/knnball/blob/eb67c4452481d727ded06984ba7d82a92b5a8e03/lib/knnball/kdtree.rb#L107-L128 |
24,523 | matthin/teamspeak-ruby | lib/teamspeak-ruby/client.rb | Teamspeak.Client.command | def command(cmd, params = {}, options = '')
flood_control
out = ''
response = ''
out += cmd
params.each_pair do |key, value|
out += " #{key}=#{encode_param(value.to_s)}"
end
out += ' ' + options
@sock.puts out
if cmd == 'servernotifyregister'
2.times { response += @sock.gets }
return parse_response(response)
end
loop do
response += @sock.gets
break if response.index(' msg=')
end
# Array of commands that are expected to return as an array.
# Not sure - clientgetids
should_be_array = %w(
bindinglist serverlist servergrouplist servergroupclientlist
servergroupsbyclientid servergroupclientlist logview channellist
channelfind channelgrouplist channelgroupclientlist channelgrouppermlist
channelpermlist clientlist clientfind clientdblist clientdbfind
channelclientpermlist permissionlist permoverview privilegekeylist
messagelist complainlist banlist ftlist custominfo permfind
)
parsed_response = parse_response(response)
should_be_array.include?(cmd) ? parsed_response : parsed_response.first
end | ruby | def command(cmd, params = {}, options = '')
flood_control
out = ''
response = ''
out += cmd
params.each_pair do |key, value|
out += " #{key}=#{encode_param(value.to_s)}"
end
out += ' ' + options
@sock.puts out
if cmd == 'servernotifyregister'
2.times { response += @sock.gets }
return parse_response(response)
end
loop do
response += @sock.gets
break if response.index(' msg=')
end
# Array of commands that are expected to return as an array.
# Not sure - clientgetids
should_be_array = %w(
bindinglist serverlist servergrouplist servergroupclientlist
servergroupsbyclientid servergroupclientlist logview channellist
channelfind channelgrouplist channelgroupclientlist channelgrouppermlist
channelpermlist clientlist clientfind clientdblist clientdbfind
channelclientpermlist permissionlist permoverview privilegekeylist
messagelist complainlist banlist ftlist custominfo permfind
)
parsed_response = parse_response(response)
should_be_array.include?(cmd) ? parsed_response : parsed_response.first
end | [
"def",
"command",
"(",
"cmd",
",",
"params",
"=",
"{",
"}",
",",
"options",
"=",
"''",
")",
"flood_control",
"out",
"=",
"''",
"response",
"=",
"''",
"out",
"+=",
"cmd",
"params",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"out",
"+=",
"\" #{key}=#{encode_param(value.to_s)}\"",
"end",
"out",
"+=",
"' '",
"+",
"options",
"@sock",
".",
"puts",
"out",
"if",
"cmd",
"==",
"'servernotifyregister'",
"2",
".",
"times",
"{",
"response",
"+=",
"@sock",
".",
"gets",
"}",
"return",
"parse_response",
"(",
"response",
")",
"end",
"loop",
"do",
"response",
"+=",
"@sock",
".",
"gets",
"break",
"if",
"response",
".",
"index",
"(",
"' msg='",
")",
"end",
"# Array of commands that are expected to return as an array.",
"# Not sure - clientgetids",
"should_be_array",
"=",
"%w(",
"bindinglist",
"serverlist",
"servergrouplist",
"servergroupclientlist",
"servergroupsbyclientid",
"servergroupclientlist",
"logview",
"channellist",
"channelfind",
"channelgrouplist",
"channelgroupclientlist",
"channelgrouppermlist",
"channelpermlist",
"clientlist",
"clientfind",
"clientdblist",
"clientdbfind",
"channelclientpermlist",
"permissionlist",
"permoverview",
"privilegekeylist",
"messagelist",
"complainlist",
"banlist",
"ftlist",
"custominfo",
"permfind",
")",
"parsed_response",
"=",
"parse_response",
"(",
"response",
")",
"should_be_array",
".",
"include?",
"(",
"cmd",
")",
"?",
"parsed_response",
":",
"parsed_response",
".",
"first",
"end"
] | Sends command to the TeamSpeak 3 server and returns the response
command('use', {'sid' => 1}, '-away') | [
"Sends",
"command",
"to",
"the",
"TeamSpeak",
"3",
"server",
"and",
"returns",
"the",
"response"
] | a72ae0f9b1fdab013708dae1559361e280aac8a1 | https://github.com/matthin/teamspeak-ruby/blob/a72ae0f9b1fdab013708dae1559361e280aac8a1/lib/teamspeak-ruby/client.rb#L76-L117 |
24,524 | translationexchange/tml-rails | lib/tml_rails/extensions/action_view_extension.rb | TmlRails.ActionViewExtension.trh | def trh(tokens = {}, options = {}, &block)
return '' unless block_given?
label = capture(&block)
tokenizer = Tml::Tokenizers::Dom.new(tokens, options)
tokenizer.translate(label).html_safe
end | ruby | def trh(tokens = {}, options = {}, &block)
return '' unless block_given?
label = capture(&block)
tokenizer = Tml::Tokenizers::Dom.new(tokens, options)
tokenizer.translate(label).html_safe
end | [
"def",
"trh",
"(",
"tokens",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"return",
"''",
"unless",
"block_given?",
"label",
"=",
"capture",
"(",
"block",
")",
"tokenizer",
"=",
"Tml",
"::",
"Tokenizers",
"::",
"Dom",
".",
"new",
"(",
"tokens",
",",
"options",
")",
"tokenizer",
".",
"translate",
"(",
"label",
")",
".",
"html_safe",
"end"
] | Translates HTML block
noinspection RubyArgCount | [
"Translates",
"HTML",
"block",
"noinspection",
"RubyArgCount"
] | 6050b0e5f0ba1d64bb09b6356ac7e41782e949a5 | https://github.com/translationexchange/tml-rails/blob/6050b0e5f0ba1d64bb09b6356ac7e41782e949a5/lib/tml_rails/extensions/action_view_extension.rb#L38-L45 |
24,525 | translationexchange/tml-rails | lib/tml_rails/extensions/action_view_extension.rb | TmlRails.ActionViewExtension.tml_language_flag_tag | def tml_language_flag_tag(lang = tml_current_language, opts = {})
return '' unless tml_application.feature_enabled?(:language_flags)
html = image_tag(lang.flag_url, :style => (opts[:style] || 'vertical-align:middle;'), :title => lang.native_name)
html << ' '.html_safe
html.html_safe
end | ruby | def tml_language_flag_tag(lang = tml_current_language, opts = {})
return '' unless tml_application.feature_enabled?(:language_flags)
html = image_tag(lang.flag_url, :style => (opts[:style] || 'vertical-align:middle;'), :title => lang.native_name)
html << ' '.html_safe
html.html_safe
end | [
"def",
"tml_language_flag_tag",
"(",
"lang",
"=",
"tml_current_language",
",",
"opts",
"=",
"{",
"}",
")",
"return",
"''",
"unless",
"tml_application",
".",
"feature_enabled?",
"(",
":language_flags",
")",
"html",
"=",
"image_tag",
"(",
"lang",
".",
"flag_url",
",",
":style",
"=>",
"(",
"opts",
"[",
":style",
"]",
"||",
"'vertical-align:middle;'",
")",
",",
":title",
"=>",
"lang",
".",
"native_name",
")",
"html",
"<<",
"' '",
".",
"html_safe",
"html",
".",
"html_safe",
"end"
] | Returns language flag | [
"Returns",
"language",
"flag"
] | 6050b0e5f0ba1d64bb09b6356ac7e41782e949a5 | https://github.com/translationexchange/tml-rails/blob/6050b0e5f0ba1d64bb09b6356ac7e41782e949a5/lib/tml_rails/extensions/action_view_extension.rb#L53-L58 |
24,526 | translationexchange/tml-rails | lib/tml_rails/extensions/action_view_extension.rb | TmlRails.ActionViewExtension.tml_language_name_tag | def tml_language_name_tag(lang = tml_current_language, opts = {})
show_flag = opts[:flag].nil? ? true : opts[:flag]
name_type = opts[:language].nil? ? :english : opts[:language].to_sym # :full, :native, :english, :locale, :both
html = []
html << "<span style='white-space: nowrap'>"
html << tml_language_flag_tag(lang, opts) if show_flag
html << "<span dir='ltr'>"
if name_type == :both
html << lang.english_name.to_s
html << '<span class="trex-native-name">'
html << lang.native_name
html << '</span>'
else
name = case name_type
when :native then lang.native_name
when :full then lang.full_name
when :locale then lang.locale
else lang.english_name
end
html << name.to_s
end
html << '</span></span>'
html.join.html_safe
end | ruby | def tml_language_name_tag(lang = tml_current_language, opts = {})
show_flag = opts[:flag].nil? ? true : opts[:flag]
name_type = opts[:language].nil? ? :english : opts[:language].to_sym # :full, :native, :english, :locale, :both
html = []
html << "<span style='white-space: nowrap'>"
html << tml_language_flag_tag(lang, opts) if show_flag
html << "<span dir='ltr'>"
if name_type == :both
html << lang.english_name.to_s
html << '<span class="trex-native-name">'
html << lang.native_name
html << '</span>'
else
name = case name_type
when :native then lang.native_name
when :full then lang.full_name
when :locale then lang.locale
else lang.english_name
end
html << name.to_s
end
html << '</span></span>'
html.join.html_safe
end | [
"def",
"tml_language_name_tag",
"(",
"lang",
"=",
"tml_current_language",
",",
"opts",
"=",
"{",
"}",
")",
"show_flag",
"=",
"opts",
"[",
":flag",
"]",
".",
"nil?",
"?",
"true",
":",
"opts",
"[",
":flag",
"]",
"name_type",
"=",
"opts",
"[",
":language",
"]",
".",
"nil?",
"?",
":english",
":",
"opts",
"[",
":language",
"]",
".",
"to_sym",
"# :full, :native, :english, :locale, :both",
"html",
"=",
"[",
"]",
"html",
"<<",
"\"<span style='white-space: nowrap'>\"",
"html",
"<<",
"tml_language_flag_tag",
"(",
"lang",
",",
"opts",
")",
"if",
"show_flag",
"html",
"<<",
"\"<span dir='ltr'>\"",
"if",
"name_type",
"==",
":both",
"html",
"<<",
"lang",
".",
"english_name",
".",
"to_s",
"html",
"<<",
"'<span class=\"trex-native-name\">'",
"html",
"<<",
"lang",
".",
"native_name",
"html",
"<<",
"'</span>'",
"else",
"name",
"=",
"case",
"name_type",
"when",
":native",
"then",
"lang",
".",
"native_name",
"when",
":full",
"then",
"lang",
".",
"full_name",
"when",
":locale",
"then",
"lang",
".",
"locale",
"else",
"lang",
".",
"english_name",
"end",
"html",
"<<",
"name",
".",
"to_s",
"end",
"html",
"<<",
"'</span></span>'",
"html",
".",
"join",
".",
"html_safe",
"end"
] | Returns language name | [
"Returns",
"language",
"name"
] | 6050b0e5f0ba1d64bb09b6356ac7e41782e949a5 | https://github.com/translationexchange/tml-rails/blob/6050b0e5f0ba1d64bb09b6356ac7e41782e949a5/lib/tml_rails/extensions/action_view_extension.rb#L61-L87 |
24,527 | translationexchange/tml-rails | lib/tml_rails/extensions/action_view_extension.rb | TmlRails.ActionViewExtension.tml_language_selector_tag | def tml_language_selector_tag(type = nil, opts = {})
return unless Tml.config.enabled?
type ||= :default
type = :dropdown if type == :select
opts = opts.collect{|key, value| "data-tml-#{key}='#{value}'"}.join(' ')
"<div data-tml-language-selector='#{type}' #{opts}></div>".html_safe
end | ruby | def tml_language_selector_tag(type = nil, opts = {})
return unless Tml.config.enabled?
type ||= :default
type = :dropdown if type == :select
opts = opts.collect{|key, value| "data-tml-#{key}='#{value}'"}.join(' ')
"<div data-tml-language-selector='#{type}' #{opts}></div>".html_safe
end | [
"def",
"tml_language_selector_tag",
"(",
"type",
"=",
"nil",
",",
"opts",
"=",
"{",
"}",
")",
"return",
"unless",
"Tml",
".",
"config",
".",
"enabled?",
"type",
"||=",
":default",
"type",
"=",
":dropdown",
"if",
"type",
"==",
":select",
"opts",
"=",
"opts",
".",
"collect",
"{",
"|",
"key",
",",
"value",
"|",
"\"data-tml-#{key}='#{value}'\"",
"}",
".",
"join",
"(",
"' '",
")",
"\"<div data-tml-language-selector='#{type}' #{opts}></div>\"",
".",
"html_safe",
"end"
] | Returns language selector UI | [
"Returns",
"language",
"selector",
"UI"
] | 6050b0e5f0ba1d64bb09b6356ac7e41782e949a5 | https://github.com/translationexchange/tml-rails/blob/6050b0e5f0ba1d64bb09b6356ac7e41782e949a5/lib/tml_rails/extensions/action_view_extension.rb#L90-L98 |
24,528 | translationexchange/tml-rails | lib/tml_rails/extensions/action_view_extension.rb | TmlRails.ActionViewExtension.tml_style_attribute_tag | def tml_style_attribute_tag(attr_name = 'float', default = 'right', lang = tml_current_language)
return "#{attr_name}:#{default}".html_safe if Tml.config.disabled?
"#{attr_name}:#{lang.align(default)}".html_safe
end | ruby | def tml_style_attribute_tag(attr_name = 'float', default = 'right', lang = tml_current_language)
return "#{attr_name}:#{default}".html_safe if Tml.config.disabled?
"#{attr_name}:#{lang.align(default)}".html_safe
end | [
"def",
"tml_style_attribute_tag",
"(",
"attr_name",
"=",
"'float'",
",",
"default",
"=",
"'right'",
",",
"lang",
"=",
"tml_current_language",
")",
"return",
"\"#{attr_name}:#{default}\"",
".",
"html_safe",
"if",
"Tml",
".",
"config",
".",
"disabled?",
"\"#{attr_name}:#{lang.align(default)}\"",
".",
"html_safe",
"end"
] | Language Direction Support
switches CSS positions based on the language direction
<%= tml_style_attribute_tag('float', 'right') %> => "float: right" : "float: left"
<%= tml_style_attribute_tag('align', 'right') %> => "align: right" : "align: left" | [
"Language",
"Direction",
"Support"
] | 6050b0e5f0ba1d64bb09b6356ac7e41782e949a5 | https://github.com/translationexchange/tml-rails/blob/6050b0e5f0ba1d64bb09b6356ac7e41782e949a5/lib/tml_rails/extensions/action_view_extension.rb#L232-L235 |
24,529 | jferris/effigy | lib/effigy/example_element_transformer.rb | Effigy.ExampleElementTransformer.clone_and_transform_each | def clone_and_transform_each(collection, &block)
collection.inject(element_to_clone) do |sibling, item|
item_element = clone_with_item(item, &block)
sibling.add_next_sibling(item_element)
end
end | ruby | def clone_and_transform_each(collection, &block)
collection.inject(element_to_clone) do |sibling, item|
item_element = clone_with_item(item, &block)
sibling.add_next_sibling(item_element)
end
end | [
"def",
"clone_and_transform_each",
"(",
"collection",
",",
"&",
"block",
")",
"collection",
".",
"inject",
"(",
"element_to_clone",
")",
"do",
"|",
"sibling",
",",
"item",
"|",
"item_element",
"=",
"clone_with_item",
"(",
"item",
",",
"block",
")",
"sibling",
".",
"add_next_sibling",
"(",
"item_element",
")",
"end",
"end"
] | Creates a clone for each item in the collection and yields it for
transformation along with the corresponding item. The transformed clones
are inserted after the element to clone.
@param [Array] collection data that cloned elements should be transformed with
@yield [Nokogiri::XML::Node] the cloned element
@yield [Object] an item from the collection | [
"Creates",
"a",
"clone",
"for",
"each",
"item",
"in",
"the",
"collection",
"and",
"yields",
"it",
"for",
"transformation",
"along",
"with",
"the",
"corresponding",
"item",
".",
"The",
"transformed",
"clones",
"are",
"inserted",
"after",
"the",
"element",
"to",
"clone",
"."
] | 366ad3571b0fc81f681472eb0ae911f47c60a405 | https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/example_element_transformer.rb#L35-L40 |
24,530 | jferris/effigy | lib/effigy/example_element_transformer.rb | Effigy.ExampleElementTransformer.clone_with_item | def clone_with_item(item, &block)
item_element = element_to_clone.dup
view.find(item_element) { yield(item) }
item_element
end | ruby | def clone_with_item(item, &block)
item_element = element_to_clone.dup
view.find(item_element) { yield(item) }
item_element
end | [
"def",
"clone_with_item",
"(",
"item",
",",
"&",
"block",
")",
"item_element",
"=",
"element_to_clone",
".",
"dup",
"view",
".",
"find",
"(",
"item_element",
")",
"{",
"yield",
"(",
"item",
")",
"}",
"item_element",
"end"
] | Creates a clone and yields it to the given block along with the given item.
@param [Object] item the item to use with the clone
@yield [Nokogiri::XML:Node] the cloned node
@yield [Object] the given item
@return [Nokogiri::XML::Node] the transformed clone | [
"Creates",
"a",
"clone",
"and",
"yields",
"it",
"to",
"the",
"given",
"block",
"along",
"with",
"the",
"given",
"item",
"."
] | 366ad3571b0fc81f681472eb0ae911f47c60a405 | https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/example_element_transformer.rb#L57-L61 |
24,531 | jferris/effigy | lib/effigy/view.rb | Effigy.View.text | def text(selector, content)
select(selector).each do |node|
node.content = content
end
end | ruby | def text(selector, content)
select(selector).each do |node|
node.content = content
end
end | [
"def",
"text",
"(",
"selector",
",",
"content",
")",
"select",
"(",
"selector",
")",
".",
"each",
"do",
"|",
"node",
"|",
"node",
".",
"content",
"=",
"content",
"end",
"end"
] | Replaces the text content of the selected elements.
Markup in the given content is escaped. Use {#html} if you want to
replace the contents with live markup.
@param [String] selector a CSS or XPath string describing the elements to
transform
@param [String] content the text that should be the new contents
@example
text('h1', 'a title')
find('h1').text('a title')
text('p', '<b>title</b>') # <p><b>title</title></p> | [
"Replaces",
"the",
"text",
"content",
"of",
"the",
"selected",
"elements",
"."
] | 366ad3571b0fc81f681472eb0ae911f47c60a405 | https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L38-L42 |
24,532 | jferris/effigy | lib/effigy/view.rb | Effigy.View.attr | def attr(selector, attributes_or_attribute_name, value = nil)
attributes = attributes_or_attribute_name.to_effigy_attributes(value)
select(selector).each do |element|
element.merge!(attributes)
end
end | ruby | def attr(selector, attributes_or_attribute_name, value = nil)
attributes = attributes_or_attribute_name.to_effigy_attributes(value)
select(selector).each do |element|
element.merge!(attributes)
end
end | [
"def",
"attr",
"(",
"selector",
",",
"attributes_or_attribute_name",
",",
"value",
"=",
"nil",
")",
"attributes",
"=",
"attributes_or_attribute_name",
".",
"to_effigy_attributes",
"(",
"value",
")",
"select",
"(",
"selector",
")",
".",
"each",
"do",
"|",
"element",
"|",
"element",
".",
"merge!",
"(",
"attributes",
")",
"end",
"end"
] | Adds or updates the given attribute or attributes of the selected elements.
@param [String] selector a CSS or XPath string describing the elements to
transform
@param [String,Hash] attributes_or_attribute_name if a String, replaces
that attribute with the given value. If a Hash, uses the keys as
attribute names and values as attribute values
@param [String] value the value for the replaced attribute. Used only if
attributes_or_attribute_name is a String
@example
attr('p', :id => 'an_id', :style => 'display: none')
attr('p', :id, 'an_id')
find('p').attr(:id, 'an_id') | [
"Adds",
"or",
"updates",
"the",
"given",
"attribute",
"or",
"attributes",
"of",
"the",
"selected",
"elements",
"."
] | 366ad3571b0fc81f681472eb0ae911f47c60a405 | https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L57-L62 |
24,533 | jferris/effigy | lib/effigy/view.rb | Effigy.View.replace_each | def replace_each(selector, collection, &block)
selected_elements = select(selector)
ExampleElementTransformer.new(self, selected_elements).replace_each(collection, &block)
end | ruby | def replace_each(selector, collection, &block)
selected_elements = select(selector)
ExampleElementTransformer.new(self, selected_elements).replace_each(collection, &block)
end | [
"def",
"replace_each",
"(",
"selector",
",",
"collection",
",",
"&",
"block",
")",
"selected_elements",
"=",
"select",
"(",
"selector",
")",
"ExampleElementTransformer",
".",
"new",
"(",
"self",
",",
"selected_elements",
")",
".",
"replace_each",
"(",
"collection",
",",
"block",
")",
"end"
] | Replaces the selected elements with a clone for each item in the
collection. If multiple elements are selected, only the first element
will be used for cloning. All selected elements will be removed.
@param [String] selector a CSS or XPath string describing the elements to
transform
@param [Enumerable] collection the items that are the base for each
cloned element
@example
titles = %w(one two three)
find('.post').replace_each(titles) do |title|
text('h1', title)
end | [
"Replaces",
"the",
"selected",
"elements",
"with",
"a",
"clone",
"for",
"each",
"item",
"in",
"the",
"collection",
".",
"If",
"multiple",
"elements",
"are",
"selected",
"only",
"the",
"first",
"element",
"will",
"be",
"used",
"for",
"cloning",
".",
"All",
"selected",
"elements",
"will",
"be",
"removed",
"."
] | 366ad3571b0fc81f681472eb0ae911f47c60a405 | https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L77-L80 |
24,534 | jferris/effigy | lib/effigy/view.rb | Effigy.View.add_class | def add_class(selector, *class_names)
select(selector).each do |element|
class_list = ClassList.new(element)
class_list.add class_names
end
end | ruby | def add_class(selector, *class_names)
select(selector).each do |element|
class_list = ClassList.new(element)
class_list.add class_names
end
end | [
"def",
"add_class",
"(",
"selector",
",",
"*",
"class_names",
")",
"select",
"(",
"selector",
")",
".",
"each",
"do",
"|",
"element",
"|",
"class_list",
"=",
"ClassList",
".",
"new",
"(",
"element",
")",
"class_list",
".",
"add",
"class_names",
"end",
"end"
] | Adds the given class names to the selected elements.
@param [String] selector a CSS or XPath string describing the elements to
transform
@param [String] class_names a CSS class name that should be added
@example
add_class('a#home', 'selected')
find('a#home').add_class('selected') | [
"Adds",
"the",
"given",
"class",
"names",
"to",
"the",
"selected",
"elements",
"."
] | 366ad3571b0fc81f681472eb0ae911f47c60a405 | https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L123-L128 |
24,535 | jferris/effigy | lib/effigy/view.rb | Effigy.View.remove_class | def remove_class(selector, *class_names)
select(selector).each do |element|
class_list = ClassList.new(element)
class_list.remove(class_names)
end
end | ruby | def remove_class(selector, *class_names)
select(selector).each do |element|
class_list = ClassList.new(element)
class_list.remove(class_names)
end
end | [
"def",
"remove_class",
"(",
"selector",
",",
"*",
"class_names",
")",
"select",
"(",
"selector",
")",
".",
"each",
"do",
"|",
"element",
"|",
"class_list",
"=",
"ClassList",
".",
"new",
"(",
"element",
")",
"class_list",
".",
"remove",
"(",
"class_names",
")",
"end",
"end"
] | Removes the given class names from the selected elements.
Ignores class names that are not present.
@param [String] selector a CSS or XPath string describing the elements to
transform
@param [String] class_names a CSS class name that should be removed
@example
remove_class('a#home', 'selected')
find('a#home').remove_class('selected') | [
"Removes",
"the",
"given",
"class",
"names",
"from",
"the",
"selected",
"elements",
"."
] | 366ad3571b0fc81f681472eb0ae911f47c60a405 | https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L140-L145 |
24,536 | jferris/effigy | lib/effigy/view.rb | Effigy.View.html | def html(selector, inner_html)
select(selector).each do |node|
node.inner_html = inner_html
end
end | ruby | def html(selector, inner_html)
select(selector).each do |node|
node.inner_html = inner_html
end
end | [
"def",
"html",
"(",
"selector",
",",
"inner_html",
")",
"select",
"(",
"selector",
")",
".",
"each",
"do",
"|",
"node",
"|",
"node",
".",
"inner_html",
"=",
"inner_html",
"end",
"end"
] | Replaces the contents of the selected elements with live markup.
@param [String] selector a CSS or XPath string describing the elements to
transform
@param [String] inner_html the new contents of the selected elements. Markup is
@example
html('p', '<b>Welcome!</b>')
find('p').html('<b>Welcome!</b>') | [
"Replaces",
"the",
"contents",
"of",
"the",
"selected",
"elements",
"with",
"live",
"markup",
"."
] | 366ad3571b0fc81f681472eb0ae911f47c60a405 | https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L155-L159 |
24,537 | jferris/effigy | lib/effigy/view.rb | Effigy.View.append | def append(selector, html_to_append)
select(selector).each { |node| node.append_fragment html_to_append }
end | ruby | def append(selector, html_to_append)
select(selector).each { |node| node.append_fragment html_to_append }
end | [
"def",
"append",
"(",
"selector",
",",
"html_to_append",
")",
"select",
"(",
"selector",
")",
".",
"each",
"{",
"|",
"node",
"|",
"node",
".",
"append_fragment",
"html_to_append",
"}",
"end"
] | Adds the given markup to the end of the selected elements.
@param [String] selector a CSS or XPath string describing the elements to
which this HTML should be appended
@param [String] html_to_append the new markup to append to the selected
element. Markup is not escaped. | [
"Adds",
"the",
"given",
"markup",
"to",
"the",
"end",
"of",
"the",
"selected",
"elements",
"."
] | 366ad3571b0fc81f681472eb0ae911f47c60a405 | https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L179-L181 |
24,538 | jferris/effigy | lib/effigy/view.rb | Effigy.View.find | def find(selector)
if block_given?
old_context = @current_context
@current_context = select(selector)
yield
@current_context = old_context
else
Selection.new(self, selector)
end
end | ruby | def find(selector)
if block_given?
old_context = @current_context
@current_context = select(selector)
yield
@current_context = old_context
else
Selection.new(self, selector)
end
end | [
"def",
"find",
"(",
"selector",
")",
"if",
"block_given?",
"old_context",
"=",
"@current_context",
"@current_context",
"=",
"select",
"(",
"selector",
")",
"yield",
"@current_context",
"=",
"old_context",
"else",
"Selection",
".",
"new",
"(",
"self",
",",
"selector",
")",
"end",
"end"
] | Selects an element or elements for chained transformation.
If given a block, the selection will be in effect during the block.
If not given a block, a {Selection} will be returned on which
transformation methods can be called. Any methods called on the
Selection will be delegated back to the view with the selector inserted
into the parameter list.
@param [String] selector a CSS or XPath string describing the element to
transform
@return [Selection] a proxy object on which transformation methods can be
called
@example
find('.post') do
text('h1', post.title)
text('p', post.body)
end
find('h1').text(post.title).add_class('active') | [
"Selects",
"an",
"element",
"or",
"elements",
"for",
"chained",
"transformation",
"."
] | 366ad3571b0fc81f681472eb0ae911f47c60a405 | https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L202-L211 |
24,539 | jferris/effigy | lib/effigy/view.rb | Effigy.View.clone_element_with_item | def clone_element_with_item(original_element, item, &block)
item_element = original_element.dup
find(item_element) { yield(item) }
item_element
end | ruby | def clone_element_with_item(original_element, item, &block)
item_element = original_element.dup
find(item_element) { yield(item) }
item_element
end | [
"def",
"clone_element_with_item",
"(",
"original_element",
",",
"item",
",",
"&",
"block",
")",
"item_element",
"=",
"original_element",
".",
"dup",
"find",
"(",
"item_element",
")",
"{",
"yield",
"(",
"item",
")",
"}",
"item_element",
"end"
] | Clones an element, sets it as the current context, and yields to the
given block with the given item.
@param [Nokogiri::HTML::Element] the element to clone
@param [Object] item the item that should be yielded to the block
@yield [Object] the item passed as item
@return [Nokogiri::HTML::Element] the clone of the original element | [
"Clones",
"an",
"element",
"sets",
"it",
"as",
"the",
"current",
"context",
"and",
"yields",
"to",
"the",
"given",
"block",
"with",
"the",
"given",
"item",
"."
] | 366ad3571b0fc81f681472eb0ae911f47c60a405 | https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L265-L269 |
24,540 | movitto/reterm | lib/reterm/mixins/component_input.rb | RETerm.ComponentInput.handle_input | def handle_input(*input)
while ch = next_ch(input)
quit = QUIT_CONTROLS.include?(ch)
enter = ENTER_CONTROLS.include?(ch)
inc = INC_CONTROLS.include?(ch)
dec = DEC_CONTROLS.include?(ch)
break if shutdown? ||
(quit && (!enter || quit_on_enter?))
if enter
on_enter
elsif inc
on_inc
elsif dec
on_dec
end
if key_bound?(ch)
invoke_key_bindings(ch)
end
on_key(ch)
end
ch
end | ruby | def handle_input(*input)
while ch = next_ch(input)
quit = QUIT_CONTROLS.include?(ch)
enter = ENTER_CONTROLS.include?(ch)
inc = INC_CONTROLS.include?(ch)
dec = DEC_CONTROLS.include?(ch)
break if shutdown? ||
(quit && (!enter || quit_on_enter?))
if enter
on_enter
elsif inc
on_inc
elsif dec
on_dec
end
if key_bound?(ch)
invoke_key_bindings(ch)
end
on_key(ch)
end
ch
end | [
"def",
"handle_input",
"(",
"*",
"input",
")",
"while",
"ch",
"=",
"next_ch",
"(",
"input",
")",
"quit",
"=",
"QUIT_CONTROLS",
".",
"include?",
"(",
"ch",
")",
"enter",
"=",
"ENTER_CONTROLS",
".",
"include?",
"(",
"ch",
")",
"inc",
"=",
"INC_CONTROLS",
".",
"include?",
"(",
"ch",
")",
"dec",
"=",
"DEC_CONTROLS",
".",
"include?",
"(",
"ch",
")",
"break",
"if",
"shutdown?",
"||",
"(",
"quit",
"&&",
"(",
"!",
"enter",
"||",
"quit_on_enter?",
")",
")",
"if",
"enter",
"on_enter",
"elsif",
"inc",
"on_inc",
"elsif",
"dec",
"on_dec",
"end",
"if",
"key_bound?",
"(",
"ch",
")",
"invoke_key_bindings",
"(",
"ch",
")",
"end",
"on_key",
"(",
"ch",
")",
"end",
"ch",
"end"
] | Helper to be internally invoked by component on activation | [
"Helper",
"to",
"be",
"internally",
"invoked",
"by",
"component",
"on",
"activation"
] | 3e78c64e677f69b22f00dc89c2b515b9188c5e15 | https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/mixins/component_input.rb#L32-L60 |
24,541 | shanebdavis/Babel-Bridge | lib/babel_bridge/nodes/rule_node.rb | BabelBridge.RuleNode.match | def match(pattern_element)
@num_match_attempts += 1
return :no_pattern_element unless pattern_element
return :skipped if pattern_element.delimiter &&
(
if last_match
last_match.delimiter # don't match two delimiters in a row
else
@num_match_attempts > 1 # don't match a delimiter as the first element unless this is the first match attempt
end
)
if result = pattern_element.parse(self)
add_match result, pattern_element.name # success, but don't keep EmptyNodes
end
end | ruby | def match(pattern_element)
@num_match_attempts += 1
return :no_pattern_element unless pattern_element
return :skipped if pattern_element.delimiter &&
(
if last_match
last_match.delimiter # don't match two delimiters in a row
else
@num_match_attempts > 1 # don't match a delimiter as the first element unless this is the first match attempt
end
)
if result = pattern_element.parse(self)
add_match result, pattern_element.name # success, but don't keep EmptyNodes
end
end | [
"def",
"match",
"(",
"pattern_element",
")",
"@num_match_attempts",
"+=",
"1",
"return",
":no_pattern_element",
"unless",
"pattern_element",
"return",
":skipped",
"if",
"pattern_element",
".",
"delimiter",
"&&",
"(",
"if",
"last_match",
"last_match",
".",
"delimiter",
"# don't match two delimiters in a row",
"else",
"@num_match_attempts",
">",
"1",
"# don't match a delimiter as the first element unless this is the first match attempt",
"end",
")",
"if",
"result",
"=",
"pattern_element",
".",
"parse",
"(",
"self",
")",
"add_match",
"result",
",",
"pattern_element",
".",
"name",
"# success, but don't keep EmptyNodes",
"end",
"end"
] | Attempts to match the pattern_element starting at the end of what has already been matched
If successful, adds the resulting Node to matches.
returns nil on if pattern_element wasn't matched; non-nil if it was skipped or matched | [
"Attempts",
"to",
"match",
"the",
"pattern_element",
"starting",
"at",
"the",
"end",
"of",
"what",
"has",
"already",
"been",
"matched",
"If",
"successful",
"adds",
"the",
"resulting",
"Node",
"to",
"matches",
".",
"returns",
"nil",
"on",
"if",
"pattern_element",
"wasn",
"t",
"matched",
";",
"non",
"-",
"nil",
"if",
"it",
"was",
"skipped",
"or",
"matched"
] | 415c6be1e3002b5eec96a8f1e3bcc7769eb29a57 | https://github.com/shanebdavis/Babel-Bridge/blob/415c6be1e3002b5eec96a8f1e3bcc7769eb29a57/lib/babel_bridge/nodes/rule_node.rb#L113-L128 |
24,542 | shanebdavis/Babel-Bridge | lib/babel_bridge/nodes/rule_node.rb | BabelBridge.RuleNode.attempt_match | def attempt_match
matches_before = matches.length
match_length_before = match_length
(yield && match_length > match_length_before).tap do |success| # match_length test returns failure if no progress is made (our source position isn't advanced)
unless success
@matches = matches[0..matches_before-1]
update_match_length
end
end
end | ruby | def attempt_match
matches_before = matches.length
match_length_before = match_length
(yield && match_length > match_length_before).tap do |success| # match_length test returns failure if no progress is made (our source position isn't advanced)
unless success
@matches = matches[0..matches_before-1]
update_match_length
end
end
end | [
"def",
"attempt_match",
"matches_before",
"=",
"matches",
".",
"length",
"match_length_before",
"=",
"match_length",
"(",
"yield",
"&&",
"match_length",
">",
"match_length_before",
")",
".",
"tap",
"do",
"|",
"success",
"|",
"# match_length test returns failure if no progress is made (our source position isn't advanced)",
"unless",
"success",
"@matches",
"=",
"matches",
"[",
"0",
"..",
"matches_before",
"-",
"1",
"]",
"update_match_length",
"end",
"end",
"end"
] | a simple "transaction" - logs the curent number of matches,
if the block's result is false, it discards all new matches | [
"a",
"simple",
"transaction",
"-",
"logs",
"the",
"curent",
"number",
"of",
"matches",
"if",
"the",
"block",
"s",
"result",
"is",
"false",
"it",
"discards",
"all",
"new",
"matches"
] | 415c6be1e3002b5eec96a8f1e3bcc7769eb29a57 | https://github.com/shanebdavis/Babel-Bridge/blob/415c6be1e3002b5eec96a8f1e3bcc7769eb29a57/lib/babel_bridge/nodes/rule_node.rb#L143-L152 |
24,543 | dburkes/people_places_things | lib/people_places_things/street_address.rb | PeoplePlacesThings.StreetAddress.to_canonical_s | def to_canonical_s
parts = []
parts << self.number.upcase if self.number
parts << StreetAddress.string_for(self.pre_direction, :short).upcase if self.pre_direction
parts << StreetAddress.string_for(StreetAddress.find_token(self.ordinal, ORDINALS), :short).upcase if self.ordinal
canonical_name = self.name.gsub(/[(,?!\'":.#)]/, '').gsub(PO_BOX_PATTERN, 'PO BOX').upcase if self.name
canonical_name.gsub!(/(rr|r.r.)/i, 'RR') if canonical_name =~ RR_PATTERN
# remove the original ordinal and box from the name, they are output in canonical form separately
canonical_name.gsub!(self.ordinal.upcase, '') if self.ordinal
canonical_name.gsub!(self.box_number, '') if self.box_number
parts << canonical_name.chomp(' ') if canonical_name
parts << self.box_number if self.box_number
parts << StreetAddress.string_for(self.suffix, :short).upcase if self.suffix
parts << StreetAddress.string_for(self.post_direction, :short).upcase if self.post_direction
# make all unit type as the canoncial number "#"
parts << StreetAddress.string_for(:number, :short).upcase if self.unit_type
parts << self.unit.upcase if self.unit
parts.delete('')
parts.join(' ')
end | ruby | def to_canonical_s
parts = []
parts << self.number.upcase if self.number
parts << StreetAddress.string_for(self.pre_direction, :short).upcase if self.pre_direction
parts << StreetAddress.string_for(StreetAddress.find_token(self.ordinal, ORDINALS), :short).upcase if self.ordinal
canonical_name = self.name.gsub(/[(,?!\'":.#)]/, '').gsub(PO_BOX_PATTERN, 'PO BOX').upcase if self.name
canonical_name.gsub!(/(rr|r.r.)/i, 'RR') if canonical_name =~ RR_PATTERN
# remove the original ordinal and box from the name, they are output in canonical form separately
canonical_name.gsub!(self.ordinal.upcase, '') if self.ordinal
canonical_name.gsub!(self.box_number, '') if self.box_number
parts << canonical_name.chomp(' ') if canonical_name
parts << self.box_number if self.box_number
parts << StreetAddress.string_for(self.suffix, :short).upcase if self.suffix
parts << StreetAddress.string_for(self.post_direction, :short).upcase if self.post_direction
# make all unit type as the canoncial number "#"
parts << StreetAddress.string_for(:number, :short).upcase if self.unit_type
parts << self.unit.upcase if self.unit
parts.delete('')
parts.join(' ')
end | [
"def",
"to_canonical_s",
"parts",
"=",
"[",
"]",
"parts",
"<<",
"self",
".",
"number",
".",
"upcase",
"if",
"self",
".",
"number",
"parts",
"<<",
"StreetAddress",
".",
"string_for",
"(",
"self",
".",
"pre_direction",
",",
":short",
")",
".",
"upcase",
"if",
"self",
".",
"pre_direction",
"parts",
"<<",
"StreetAddress",
".",
"string_for",
"(",
"StreetAddress",
".",
"find_token",
"(",
"self",
".",
"ordinal",
",",
"ORDINALS",
")",
",",
":short",
")",
".",
"upcase",
"if",
"self",
".",
"ordinal",
"canonical_name",
"=",
"self",
".",
"name",
".",
"gsub",
"(",
"/",
"\\'",
"/",
",",
"''",
")",
".",
"gsub",
"(",
"PO_BOX_PATTERN",
",",
"'PO BOX'",
")",
".",
"upcase",
"if",
"self",
".",
"name",
"canonical_name",
".",
"gsub!",
"(",
"/",
"/i",
",",
"'RR'",
")",
"if",
"canonical_name",
"=~",
"RR_PATTERN",
"# remove the original ordinal and box from the name, they are output in canonical form separately",
"canonical_name",
".",
"gsub!",
"(",
"self",
".",
"ordinal",
".",
"upcase",
",",
"''",
")",
"if",
"self",
".",
"ordinal",
"canonical_name",
".",
"gsub!",
"(",
"self",
".",
"box_number",
",",
"''",
")",
"if",
"self",
".",
"box_number",
"parts",
"<<",
"canonical_name",
".",
"chomp",
"(",
"' '",
")",
"if",
"canonical_name",
"parts",
"<<",
"self",
".",
"box_number",
"if",
"self",
".",
"box_number",
"parts",
"<<",
"StreetAddress",
".",
"string_for",
"(",
"self",
".",
"suffix",
",",
":short",
")",
".",
"upcase",
"if",
"self",
".",
"suffix",
"parts",
"<<",
"StreetAddress",
".",
"string_for",
"(",
"self",
".",
"post_direction",
",",
":short",
")",
".",
"upcase",
"if",
"self",
".",
"post_direction",
"# make all unit type as the canoncial number \"#\"",
"parts",
"<<",
"StreetAddress",
".",
"string_for",
"(",
":number",
",",
":short",
")",
".",
"upcase",
"if",
"self",
".",
"unit_type",
"parts",
"<<",
"self",
".",
"unit",
".",
"upcase",
"if",
"self",
".",
"unit",
"parts",
".",
"delete",
"(",
"''",
")",
"parts",
".",
"join",
"(",
"' '",
")",
"end"
] | to_canonical_s
format the address in a postal service canonical format | [
"to_canonical_s",
"format",
"the",
"address",
"in",
"a",
"postal",
"service",
"canonical",
"format"
] | 69d18c0f236e40701fe58fa0d14e0dee03c879fc | https://github.com/dburkes/people_places_things/blob/69d18c0f236e40701fe58fa0d14e0dee03c879fc/lib/people_places_things/street_address.rb#L99-L118 |
24,544 | kevgo/active_cucumber | lib/active_cucumber/cucumparer.rb | ActiveCucumber.Cucumparer.to_horizontal_table | def to_horizontal_table
mortadella = Mortadella::Horizontal.new headers: @cucumber_table.headers
@database_content = @database_content.all if @database_content.respond_to? :all
@database_content.each do |record|
cucumberator = cucumberator_for record
mortadella << @cucumber_table.headers.map do |header|
cucumberator.value_for header
end
end
mortadella.table
end | ruby | def to_horizontal_table
mortadella = Mortadella::Horizontal.new headers: @cucumber_table.headers
@database_content = @database_content.all if @database_content.respond_to? :all
@database_content.each do |record|
cucumberator = cucumberator_for record
mortadella << @cucumber_table.headers.map do |header|
cucumberator.value_for header
end
end
mortadella.table
end | [
"def",
"to_horizontal_table",
"mortadella",
"=",
"Mortadella",
"::",
"Horizontal",
".",
"new",
"headers",
":",
"@cucumber_table",
".",
"headers",
"@database_content",
"=",
"@database_content",
".",
"all",
"if",
"@database_content",
".",
"respond_to?",
":all",
"@database_content",
".",
"each",
"do",
"|",
"record",
"|",
"cucumberator",
"=",
"cucumberator_for",
"record",
"mortadella",
"<<",
"@cucumber_table",
".",
"headers",
".",
"map",
"do",
"|",
"header",
"|",
"cucumberator",
".",
"value_for",
"header",
"end",
"end",
"mortadella",
".",
"table",
"end"
] | Returns all entries in the database as a horizontal Mortadella table | [
"Returns",
"all",
"entries",
"in",
"the",
"database",
"as",
"a",
"horizontal",
"Mortadella",
"table"
] | 9f3609abbfe2c4c3534c2c64d2f638a6bb6347cf | https://github.com/kevgo/active_cucumber/blob/9f3609abbfe2c4c3534c2c64d2f638a6bb6347cf/lib/active_cucumber/cucumparer.rb#L12-L22 |
24,545 | kevgo/active_cucumber | lib/active_cucumber/cucumparer.rb | ActiveCucumber.Cucumparer.to_vertical_table | def to_vertical_table object
mortadella = Mortadella::Vertical.new
cucumberator = cucumberator_for object
@cucumber_table.rows_hash.each do |key, _|
mortadella[key] = cucumberator.value_for key
end
mortadella.table
end | ruby | def to_vertical_table object
mortadella = Mortadella::Vertical.new
cucumberator = cucumberator_for object
@cucumber_table.rows_hash.each do |key, _|
mortadella[key] = cucumberator.value_for key
end
mortadella.table
end | [
"def",
"to_vertical_table",
"object",
"mortadella",
"=",
"Mortadella",
"::",
"Vertical",
".",
"new",
"cucumberator",
"=",
"cucumberator_for",
"object",
"@cucumber_table",
".",
"rows_hash",
".",
"each",
"do",
"|",
"key",
",",
"_",
"|",
"mortadella",
"[",
"key",
"]",
"=",
"cucumberator",
".",
"value_for",
"key",
"end",
"mortadella",
".",
"table",
"end"
] | Returns the given object as a vertical Mortadella table | [
"Returns",
"the",
"given",
"object",
"as",
"a",
"vertical",
"Mortadella",
"table"
] | 9f3609abbfe2c4c3534c2c64d2f638a6bb6347cf | https://github.com/kevgo/active_cucumber/blob/9f3609abbfe2c4c3534c2c64d2f638a6bb6347cf/lib/active_cucumber/cucumparer.rb#L25-L32 |
24,546 | coopernurse/barrister-ruby | lib/barrister.rb | Barrister.Server.handle_json | def handle_json(json_str)
begin
req = JSON::parse(json_str)
resp = handle(req)
rescue JSON::ParserError => e
resp = err_resp({ }, -32700, "Unable to parse JSON: #{e.message}")
end
# Note the `:ascii_only` usage here. Important.
return JSON::generate(resp, { :ascii_only=>true })
end | ruby | def handle_json(json_str)
begin
req = JSON::parse(json_str)
resp = handle(req)
rescue JSON::ParserError => e
resp = err_resp({ }, -32700, "Unable to parse JSON: #{e.message}")
end
# Note the `:ascii_only` usage here. Important.
return JSON::generate(resp, { :ascii_only=>true })
end | [
"def",
"handle_json",
"(",
"json_str",
")",
"begin",
"req",
"=",
"JSON",
"::",
"parse",
"(",
"json_str",
")",
"resp",
"=",
"handle",
"(",
"req",
")",
"rescue",
"JSON",
"::",
"ParserError",
"=>",
"e",
"resp",
"=",
"err_resp",
"(",
"{",
"}",
",",
"-",
"32700",
",",
"\"Unable to parse JSON: #{e.message}\"",
")",
"end",
"# Note the `:ascii_only` usage here. Important.",
"return",
"JSON",
"::",
"generate",
"(",
"resp",
",",
"{",
":ascii_only",
"=>",
"true",
"}",
")",
"end"
] | Handles a request encoded as JSON.
Returns the result as a JSON encoded string. | [
"Handles",
"a",
"request",
"encoded",
"as",
"JSON",
".",
"Returns",
"the",
"result",
"as",
"a",
"JSON",
"encoded",
"string",
"."
] | 5606e7dc591762fc28a338dee48093aaaafb106e | https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L165-L175 |
24,547 | coopernurse/barrister-ruby | lib/barrister.rb | Barrister.Server.handle | def handle(req)
if req.kind_of?(Array)
resp_list = [ ]
req.each do |r|
resp_list << handle_single(r)
end
return resp_list
else
return handle_single(req)
end
end | ruby | def handle(req)
if req.kind_of?(Array)
resp_list = [ ]
req.each do |r|
resp_list << handle_single(r)
end
return resp_list
else
return handle_single(req)
end
end | [
"def",
"handle",
"(",
"req",
")",
"if",
"req",
".",
"kind_of?",
"(",
"Array",
")",
"resp_list",
"=",
"[",
"]",
"req",
".",
"each",
"do",
"|",
"r",
"|",
"resp_list",
"<<",
"handle_single",
"(",
"r",
")",
"end",
"return",
"resp_list",
"else",
"return",
"handle_single",
"(",
"req",
")",
"end",
"end"
] | Handles a deserialized request and returns the result
`req` must either be a Hash (single request), or an Array (batch request)
`handle` returns an Array of results for batch requests, and a single
Hash for single requests. | [
"Handles",
"a",
"deserialized",
"request",
"and",
"returns",
"the",
"result"
] | 5606e7dc591762fc28a338dee48093aaaafb106e | https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L183-L193 |
24,548 | coopernurse/barrister-ruby | lib/barrister.rb | Barrister.Server.handle_single | def handle_single(req)
method = req["method"]
if !method
return err_resp(req, -32600, "No method provided on request")
end
# Special case - client is requesting the IDL bound to this server, so
# we return it verbatim. No further validation is needed in this case.
if method == "barrister-idl"
return ok_resp(req, @contract.idl)
end
# Make sure we can find an interface and function on the IDL for this
# request method string
err_resp, iface, func = @contract.resolve_method(req)
if err_resp != nil
return err_resp
end
# Make sure that the params on the request match the IDL types
err_resp = @contract.validate_params(req, func)
if err_resp != nil
return err_resp
end
params = [ ]
if req["params"]
params = req["params"]
end
# Make sure we have a handler bound to this Server for the interface.
# If not, that means `server.add_handler` was not called for this interface
# name. That's likely a misconfiguration.
handler = @handlers[iface.name]
if !handler
return err_resp(req, -32000, "Server error. No handler is bound to interface #{iface.name}")
end
# Make sure that the handler has a method for the given function.
if !handler.respond_to?(func.name)
return err_resp(req, -32000, "Server error. Handler for #{iface.name} does not implement #{func.name}")
end
begin
# Call the handler function. This is where your code gets invoked.
result = handler.send(func.name, *params)
# Verify that the handler function's return value matches the
# correct type as specified in the IDL
err_resp = @contract.validate_result(req, result, func)
if err_resp != nil
return err_resp
else
return ok_resp(req, result)
end
rescue RpcException => e
# If the handler raised a RpcException, that's ok - return it unmodified.
return err_resp(req, e.code, e.message, e.data)
rescue => e
# If any other error was raised, print it and return a generic error to the client
puts e.inspect
puts e.backtrace
return err_resp(req, -32000, "Unknown error: #{e}")
end
end | ruby | def handle_single(req)
method = req["method"]
if !method
return err_resp(req, -32600, "No method provided on request")
end
# Special case - client is requesting the IDL bound to this server, so
# we return it verbatim. No further validation is needed in this case.
if method == "barrister-idl"
return ok_resp(req, @contract.idl)
end
# Make sure we can find an interface and function on the IDL for this
# request method string
err_resp, iface, func = @contract.resolve_method(req)
if err_resp != nil
return err_resp
end
# Make sure that the params on the request match the IDL types
err_resp = @contract.validate_params(req, func)
if err_resp != nil
return err_resp
end
params = [ ]
if req["params"]
params = req["params"]
end
# Make sure we have a handler bound to this Server for the interface.
# If not, that means `server.add_handler` was not called for this interface
# name. That's likely a misconfiguration.
handler = @handlers[iface.name]
if !handler
return err_resp(req, -32000, "Server error. No handler is bound to interface #{iface.name}")
end
# Make sure that the handler has a method for the given function.
if !handler.respond_to?(func.name)
return err_resp(req, -32000, "Server error. Handler for #{iface.name} does not implement #{func.name}")
end
begin
# Call the handler function. This is where your code gets invoked.
result = handler.send(func.name, *params)
# Verify that the handler function's return value matches the
# correct type as specified in the IDL
err_resp = @contract.validate_result(req, result, func)
if err_resp != nil
return err_resp
else
return ok_resp(req, result)
end
rescue RpcException => e
# If the handler raised a RpcException, that's ok - return it unmodified.
return err_resp(req, e.code, e.message, e.data)
rescue => e
# If any other error was raised, print it and return a generic error to the client
puts e.inspect
puts e.backtrace
return err_resp(req, -32000, "Unknown error: #{e}")
end
end | [
"def",
"handle_single",
"(",
"req",
")",
"method",
"=",
"req",
"[",
"\"method\"",
"]",
"if",
"!",
"method",
"return",
"err_resp",
"(",
"req",
",",
"-",
"32600",
",",
"\"No method provided on request\"",
")",
"end",
"# Special case - client is requesting the IDL bound to this server, so",
"# we return it verbatim. No further validation is needed in this case.",
"if",
"method",
"==",
"\"barrister-idl\"",
"return",
"ok_resp",
"(",
"req",
",",
"@contract",
".",
"idl",
")",
"end",
"# Make sure we can find an interface and function on the IDL for this",
"# request method string",
"err_resp",
",",
"iface",
",",
"func",
"=",
"@contract",
".",
"resolve_method",
"(",
"req",
")",
"if",
"err_resp",
"!=",
"nil",
"return",
"err_resp",
"end",
"# Make sure that the params on the request match the IDL types",
"err_resp",
"=",
"@contract",
".",
"validate_params",
"(",
"req",
",",
"func",
")",
"if",
"err_resp",
"!=",
"nil",
"return",
"err_resp",
"end",
"params",
"=",
"[",
"]",
"if",
"req",
"[",
"\"params\"",
"]",
"params",
"=",
"req",
"[",
"\"params\"",
"]",
"end",
"# Make sure we have a handler bound to this Server for the interface.",
"# If not, that means `server.add_handler` was not called for this interface",
"# name. That's likely a misconfiguration.",
"handler",
"=",
"@handlers",
"[",
"iface",
".",
"name",
"]",
"if",
"!",
"handler",
"return",
"err_resp",
"(",
"req",
",",
"-",
"32000",
",",
"\"Server error. No handler is bound to interface #{iface.name}\"",
")",
"end",
"# Make sure that the handler has a method for the given function.",
"if",
"!",
"handler",
".",
"respond_to?",
"(",
"func",
".",
"name",
")",
"return",
"err_resp",
"(",
"req",
",",
"-",
"32000",
",",
"\"Server error. Handler for #{iface.name} does not implement #{func.name}\"",
")",
"end",
"begin",
"# Call the handler function. This is where your code gets invoked.",
"result",
"=",
"handler",
".",
"send",
"(",
"func",
".",
"name",
",",
"params",
")",
"# Verify that the handler function's return value matches the",
"# correct type as specified in the IDL",
"err_resp",
"=",
"@contract",
".",
"validate_result",
"(",
"req",
",",
"result",
",",
"func",
")",
"if",
"err_resp",
"!=",
"nil",
"return",
"err_resp",
"else",
"return",
"ok_resp",
"(",
"req",
",",
"result",
")",
"end",
"rescue",
"RpcException",
"=>",
"e",
"# If the handler raised a RpcException, that's ok - return it unmodified.",
"return",
"err_resp",
"(",
"req",
",",
"e",
".",
"code",
",",
"e",
".",
"message",
",",
"e",
".",
"data",
")",
"rescue",
"=>",
"e",
"# If any other error was raised, print it and return a generic error to the client",
"puts",
"e",
".",
"inspect",
"puts",
"e",
".",
"backtrace",
"return",
"err_resp",
"(",
"req",
",",
"-",
"32000",
",",
"\"Unknown error: #{e}\"",
")",
"end",
"end"
] | Internal method that validates and executes a single request. | [
"Internal",
"method",
"that",
"validates",
"and",
"executes",
"a",
"single",
"request",
"."
] | 5606e7dc591762fc28a338dee48093aaaafb106e | https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L196-L260 |
24,549 | coopernurse/barrister-ruby | lib/barrister.rb | Barrister.Client.init_proxies | def init_proxies
singleton = class << self; self end
@contract.interfaces.each do |iface|
proxy = InterfaceProxy.new(self, iface)
singleton.send :define_method, iface.name do
return proxy
end
end
end | ruby | def init_proxies
singleton = class << self; self end
@contract.interfaces.each do |iface|
proxy = InterfaceProxy.new(self, iface)
singleton.send :define_method, iface.name do
return proxy
end
end
end | [
"def",
"init_proxies",
"singleton",
"=",
"class",
"<<",
"self",
";",
"self",
"end",
"@contract",
".",
"interfaces",
".",
"each",
"do",
"|",
"iface",
"|",
"proxy",
"=",
"InterfaceProxy",
".",
"new",
"(",
"self",
",",
"iface",
")",
"singleton",
".",
"send",
":define_method",
",",
"iface",
".",
"name",
"do",
"return",
"proxy",
"end",
"end",
"end"
] | Internal method invoked by `initialize`. Iterates through the Contract and
creates proxy classes for each interface. | [
"Internal",
"method",
"invoked",
"by",
"initialize",
".",
"Iterates",
"through",
"the",
"Contract",
"and",
"creates",
"proxy",
"classes",
"for",
"each",
"interface",
"."
] | 5606e7dc591762fc28a338dee48093aaaafb106e | https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L322-L330 |
24,550 | coopernurse/barrister-ruby | lib/barrister.rb | Barrister.Client.request | def request(method, params)
req = { "jsonrpc" => "2.0", "id" => Barrister::rand_str(22), "method" => method }
if params
req["params"] = params
end
# We always validate that the method is valid
err_resp, iface, func = @contract.resolve_method(req)
if err_resp != nil
return err_resp
end
if @validate_req
err_resp = @contract.validate_params(req, func)
if err_resp != nil
return err_resp
end
end
# This makes the request to the server
resp = @trans.request(req)
if @validate_result && resp != nil && resp.key?("result")
err_resp = @contract.validate_result(req, resp["result"], func)
if err_resp != nil
resp = err_resp
end
end
return resp
end | ruby | def request(method, params)
req = { "jsonrpc" => "2.0", "id" => Barrister::rand_str(22), "method" => method }
if params
req["params"] = params
end
# We always validate that the method is valid
err_resp, iface, func = @contract.resolve_method(req)
if err_resp != nil
return err_resp
end
if @validate_req
err_resp = @contract.validate_params(req, func)
if err_resp != nil
return err_resp
end
end
# This makes the request to the server
resp = @trans.request(req)
if @validate_result && resp != nil && resp.key?("result")
err_resp = @contract.validate_result(req, resp["result"], func)
if err_resp != nil
resp = err_resp
end
end
return resp
end | [
"def",
"request",
"(",
"method",
",",
"params",
")",
"req",
"=",
"{",
"\"jsonrpc\"",
"=>",
"\"2.0\"",
",",
"\"id\"",
"=>",
"Barrister",
"::",
"rand_str",
"(",
"22",
")",
",",
"\"method\"",
"=>",
"method",
"}",
"if",
"params",
"req",
"[",
"\"params\"",
"]",
"=",
"params",
"end",
"# We always validate that the method is valid",
"err_resp",
",",
"iface",
",",
"func",
"=",
"@contract",
".",
"resolve_method",
"(",
"req",
")",
"if",
"err_resp",
"!=",
"nil",
"return",
"err_resp",
"end",
"if",
"@validate_req",
"err_resp",
"=",
"@contract",
".",
"validate_params",
"(",
"req",
",",
"func",
")",
"if",
"err_resp",
"!=",
"nil",
"return",
"err_resp",
"end",
"end",
"# This makes the request to the server",
"resp",
"=",
"@trans",
".",
"request",
"(",
"req",
")",
"if",
"@validate_result",
"&&",
"resp",
"!=",
"nil",
"&&",
"resp",
".",
"key?",
"(",
"\"result\"",
")",
"err_resp",
"=",
"@contract",
".",
"validate_result",
"(",
"req",
",",
"resp",
"[",
"\"result\"",
"]",
",",
"func",
")",
"if",
"err_resp",
"!=",
"nil",
"resp",
"=",
"err_resp",
"end",
"end",
"return",
"resp",
"end"
] | Sends a JSON-RPC request. This method is automatically called by the proxy classes,
so in practice you don't usually call it directly. However, it is available if you
wish to avoid the use of proxy classes.
* `method` - string of the method to invoke. Format: "interface.function".
For example: "ContactService.saveContact"
* `params` - parameters to pass to the function. Must be an Array | [
"Sends",
"a",
"JSON",
"-",
"RPC",
"request",
".",
"This",
"method",
"is",
"automatically",
"called",
"by",
"the",
"proxy",
"classes",
"so",
"in",
"practice",
"you",
"don",
"t",
"usually",
"call",
"it",
"directly",
".",
"However",
"it",
"is",
"available",
"if",
"you",
"wish",
"to",
"avoid",
"the",
"use",
"of",
"proxy",
"classes",
"."
] | 5606e7dc591762fc28a338dee48093aaaafb106e | https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L339-L369 |
24,551 | coopernurse/barrister-ruby | lib/barrister.rb | Barrister.HttpTransport.request | def request(req)
json_str = JSON::generate(req, { :ascii_only=>true })
http = Net::HTTP.new(@uri.host, @uri.port)
request = Net::HTTP::Post.new(@uri.request_uri)
request.body = json_str
request["Content-Type"] = "application/json"
response = http.request(request)
if response.code != "200"
raise RpcException.new(-32000, "Non-200 response #{response.code} from #{@url}")
else
return JSON::parse(response.body)
end
end | ruby | def request(req)
json_str = JSON::generate(req, { :ascii_only=>true })
http = Net::HTTP.new(@uri.host, @uri.port)
request = Net::HTTP::Post.new(@uri.request_uri)
request.body = json_str
request["Content-Type"] = "application/json"
response = http.request(request)
if response.code != "200"
raise RpcException.new(-32000, "Non-200 response #{response.code} from #{@url}")
else
return JSON::parse(response.body)
end
end | [
"def",
"request",
"(",
"req",
")",
"json_str",
"=",
"JSON",
"::",
"generate",
"(",
"req",
",",
"{",
":ascii_only",
"=>",
"true",
"}",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"@uri",
".",
"host",
",",
"@uri",
".",
"port",
")",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"@uri",
".",
"request_uri",
")",
"request",
".",
"body",
"=",
"json_str",
"request",
"[",
"\"Content-Type\"",
"]",
"=",
"\"application/json\"",
"response",
"=",
"http",
".",
"request",
"(",
"request",
")",
"if",
"response",
".",
"code",
"!=",
"\"200\"",
"raise",
"RpcException",
".",
"new",
"(",
"-",
"32000",
",",
"\"Non-200 response #{response.code} from #{@url}\"",
")",
"else",
"return",
"JSON",
"::",
"parse",
"(",
"response",
".",
"body",
")",
"end",
"end"
] | Takes the URL to the server endpoint and parses it
`request` is the only required method on a transport class.
`req` is a JSON-RPC request with `id`, `method`, and optionally `params` slots.
The transport is very simple, and does the following:
* Serialize `req` to JSON. Make sure to use `:ascii_only=true`
* POST the JSON string to the endpoint, setting the MIME type correctly
* Deserialize the JSON response string
* Return the deserialized hash | [
"Takes",
"the",
"URL",
"to",
"the",
"server",
"endpoint",
"and",
"parses",
"it",
"request",
"is",
"the",
"only",
"required",
"method",
"on",
"a",
"transport",
"class",
"."
] | 5606e7dc591762fc28a338dee48093aaaafb106e | https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L395-L407 |
24,552 | coopernurse/barrister-ruby | lib/barrister.rb | Barrister.BatchClient.send | def send
if @trans.sent
raise "Batch has already been sent!"
end
@trans.sent = true
requests = @trans.requests
if requests.length < 1
raise RpcException.new(-32600, "Batch cannot be empty")
end
# Send request batch to server
resp_list = @parent.trans.request(requests)
# Build a hash for the responses so we can re-order them
# in request order.
sorted = [ ]
by_req_id = { }
resp_list.each do |resp|
by_req_id[resp["id"]] = resp
end
# Iterate through the requests in the batch and assemble
# the sorted result array
requests.each do |req|
id = req["id"]
resp = by_req_id[id]
if !resp
msg = "No result for request id: #{id}"
resp = { "id" => id, "error" => { "code"=>-32603, "message" => msg } }
end
sorted << RpcResponse.new(req, resp)
end
return sorted
end | ruby | def send
if @trans.sent
raise "Batch has already been sent!"
end
@trans.sent = true
requests = @trans.requests
if requests.length < 1
raise RpcException.new(-32600, "Batch cannot be empty")
end
# Send request batch to server
resp_list = @parent.trans.request(requests)
# Build a hash for the responses so we can re-order them
# in request order.
sorted = [ ]
by_req_id = { }
resp_list.each do |resp|
by_req_id[resp["id"]] = resp
end
# Iterate through the requests in the batch and assemble
# the sorted result array
requests.each do |req|
id = req["id"]
resp = by_req_id[id]
if !resp
msg = "No result for request id: #{id}"
resp = { "id" => id, "error" => { "code"=>-32603, "message" => msg } }
end
sorted << RpcResponse.new(req, resp)
end
return sorted
end | [
"def",
"send",
"if",
"@trans",
".",
"sent",
"raise",
"\"Batch has already been sent!\"",
"end",
"@trans",
".",
"sent",
"=",
"true",
"requests",
"=",
"@trans",
".",
"requests",
"if",
"requests",
".",
"length",
"<",
"1",
"raise",
"RpcException",
".",
"new",
"(",
"-",
"32600",
",",
"\"Batch cannot be empty\"",
")",
"end",
"# Send request batch to server",
"resp_list",
"=",
"@parent",
".",
"trans",
".",
"request",
"(",
"requests",
")",
"# Build a hash for the responses so we can re-order them",
"# in request order.",
"sorted",
"=",
"[",
"]",
"by_req_id",
"=",
"{",
"}",
"resp_list",
".",
"each",
"do",
"|",
"resp",
"|",
"by_req_id",
"[",
"resp",
"[",
"\"id\"",
"]",
"]",
"=",
"resp",
"end",
"# Iterate through the requests in the batch and assemble",
"# the sorted result array",
"requests",
".",
"each",
"do",
"|",
"req",
"|",
"id",
"=",
"req",
"[",
"\"id\"",
"]",
"resp",
"=",
"by_req_id",
"[",
"id",
"]",
"if",
"!",
"resp",
"msg",
"=",
"\"No result for request id: #{id}\"",
"resp",
"=",
"{",
"\"id\"",
"=>",
"id",
",",
"\"error\"",
"=>",
"{",
"\"code\"",
"=>",
"-",
"32603",
",",
"\"message\"",
"=>",
"msg",
"}",
"}",
"end",
"sorted",
"<<",
"RpcResponse",
".",
"new",
"(",
"req",
",",
"resp",
")",
"end",
"return",
"sorted",
"end"
] | Sends the batch of requests to the server.
Returns an Array of RpcResponse instances. The Array is ordered
in the order of the requests made to the batch. Your code needs
to check each element in the Array for errors.
* Cannot be called more than once
* Will raise RpcException if the batch is empty | [
"Sends",
"the",
"batch",
"of",
"requests",
"to",
"the",
"server",
"."
] | 5606e7dc591762fc28a338dee48093aaaafb106e | https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L496-L532 |
24,553 | coopernurse/barrister-ruby | lib/barrister.rb | Barrister.Contract.resolve_method | def resolve_method(req)
method = req["method"]
iface_name, func_name = Barrister::parse_method(method)
if iface_name == nil
return err_resp(req, -32601, "Method not found: #{method}")
end
iface = interface(iface_name)
if !iface
return err_resp(req, -32601, "Interface not found on IDL: #{iface_name}")
end
func = iface.function(func_name)
if !func
return err_resp(req, -32601, "Function #{func_name} does not exist on interface #{iface_name}")
end
return nil, iface, func
end | ruby | def resolve_method(req)
method = req["method"]
iface_name, func_name = Barrister::parse_method(method)
if iface_name == nil
return err_resp(req, -32601, "Method not found: #{method}")
end
iface = interface(iface_name)
if !iface
return err_resp(req, -32601, "Interface not found on IDL: #{iface_name}")
end
func = iface.function(func_name)
if !func
return err_resp(req, -32601, "Function #{func_name} does not exist on interface #{iface_name}")
end
return nil, iface, func
end | [
"def",
"resolve_method",
"(",
"req",
")",
"method",
"=",
"req",
"[",
"\"method\"",
"]",
"iface_name",
",",
"func_name",
"=",
"Barrister",
"::",
"parse_method",
"(",
"method",
")",
"if",
"iface_name",
"==",
"nil",
"return",
"err_resp",
"(",
"req",
",",
"-",
"32601",
",",
"\"Method not found: #{method}\"",
")",
"end",
"iface",
"=",
"interface",
"(",
"iface_name",
")",
"if",
"!",
"iface",
"return",
"err_resp",
"(",
"req",
",",
"-",
"32601",
",",
"\"Interface not found on IDL: #{iface_name}\"",
")",
"end",
"func",
"=",
"iface",
".",
"function",
"(",
"func_name",
")",
"if",
"!",
"func",
"return",
"err_resp",
"(",
"req",
",",
"-",
"32601",
",",
"\"Function #{func_name} does not exist on interface #{iface_name}\"",
")",
"end",
"return",
"nil",
",",
"iface",
",",
"func",
"end"
] | Takes a JSON-RPC request hash, and returns a 3 element tuple. This is called as
part of the request validation sequence.
`0` - JSON-RPC response hash representing an error. nil if valid.
`1` - Interface instance on this Contract that matches `req["method"]`
`2` - Function instance on the Interface that matches `req["method"]` | [
"Takes",
"a",
"JSON",
"-",
"RPC",
"request",
"hash",
"and",
"returns",
"a",
"3",
"element",
"tuple",
".",
"This",
"is",
"called",
"as",
"part",
"of",
"the",
"request",
"validation",
"sequence",
"."
] | 5606e7dc591762fc28a338dee48093aaaafb106e | https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L620-L638 |
24,554 | coopernurse/barrister-ruby | lib/barrister.rb | Barrister.Contract.validate_params | def validate_params(req, func)
params = req["params"]
if !params
params = []
end
e_params = func.params.length
r_params = params.length
if e_params != r_params
msg = "Function #{func.name}: Param length #{r_params} != expected length: #{e_params}"
return err_resp(req, -32602, msg)
end
for i in (0..(e_params-1))
expected = func.params[i]
invalid = validate("Param[#{i}]", expected, expected["is_array"], params[i])
if invalid != nil
return err_resp(req, -32602, invalid)
end
end
# valid
return nil
end | ruby | def validate_params(req, func)
params = req["params"]
if !params
params = []
end
e_params = func.params.length
r_params = params.length
if e_params != r_params
msg = "Function #{func.name}: Param length #{r_params} != expected length: #{e_params}"
return err_resp(req, -32602, msg)
end
for i in (0..(e_params-1))
expected = func.params[i]
invalid = validate("Param[#{i}]", expected, expected["is_array"], params[i])
if invalid != nil
return err_resp(req, -32602, invalid)
end
end
# valid
return nil
end | [
"def",
"validate_params",
"(",
"req",
",",
"func",
")",
"params",
"=",
"req",
"[",
"\"params\"",
"]",
"if",
"!",
"params",
"params",
"=",
"[",
"]",
"end",
"e_params",
"=",
"func",
".",
"params",
".",
"length",
"r_params",
"=",
"params",
".",
"length",
"if",
"e_params",
"!=",
"r_params",
"msg",
"=",
"\"Function #{func.name}: Param length #{r_params} != expected length: #{e_params}\"",
"return",
"err_resp",
"(",
"req",
",",
"-",
"32602",
",",
"msg",
")",
"end",
"for",
"i",
"in",
"(",
"0",
"..",
"(",
"e_params",
"-",
"1",
")",
")",
"expected",
"=",
"func",
".",
"params",
"[",
"i",
"]",
"invalid",
"=",
"validate",
"(",
"\"Param[#{i}]\"",
",",
"expected",
",",
"expected",
"[",
"\"is_array\"",
"]",
",",
"params",
"[",
"i",
"]",
")",
"if",
"invalid",
"!=",
"nil",
"return",
"err_resp",
"(",
"req",
",",
"-",
"32602",
",",
"invalid",
")",
"end",
"end",
"# valid",
"return",
"nil",
"end"
] | Validates that the parameters on the JSON-RPC request match the types specified for
this function
Returns a JSON-RPC response hash if invalid, or nil if valid.
* `req` - JSON-RPC request hash
* `func` - Barrister::Function instance | [
"Validates",
"that",
"the",
"parameters",
"on",
"the",
"JSON",
"-",
"RPC",
"request",
"match",
"the",
"types",
"specified",
"for",
"this",
"function"
] | 5606e7dc591762fc28a338dee48093aaaafb106e | https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L648-L670 |
24,555 | coopernurse/barrister-ruby | lib/barrister.rb | Barrister.Contract.validate_result | def validate_result(req, result, func)
invalid = validate("", func.returns, func.returns["is_array"], result)
if invalid == nil
return nil
else
return err_resp(req, -32001, invalid)
end
end | ruby | def validate_result(req, result, func)
invalid = validate("", func.returns, func.returns["is_array"], result)
if invalid == nil
return nil
else
return err_resp(req, -32001, invalid)
end
end | [
"def",
"validate_result",
"(",
"req",
",",
"result",
",",
"func",
")",
"invalid",
"=",
"validate",
"(",
"\"\"",
",",
"func",
".",
"returns",
",",
"func",
".",
"returns",
"[",
"\"is_array\"",
"]",
",",
"result",
")",
"if",
"invalid",
"==",
"nil",
"return",
"nil",
"else",
"return",
"err_resp",
"(",
"req",
",",
"-",
"32001",
",",
"invalid",
")",
"end",
"end"
] | Validates that the result from a handler method invocation match the return type
for this function
Returns a JSON-RPC response hash if invalid, or nil if valid.
* `req` - JSON-RPC request hash
* `result` - Result object from the handler method call
* `func` - Barrister::Function instance | [
"Validates",
"that",
"the",
"result",
"from",
"a",
"handler",
"method",
"invocation",
"match",
"the",
"return",
"type",
"for",
"this",
"function"
] | 5606e7dc591762fc28a338dee48093aaaafb106e | https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L681-L688 |
24,556 | coopernurse/barrister-ruby | lib/barrister.rb | Barrister.Contract.validate | def validate(name, expected, expect_array, val)
# If val is nil, then check if the IDL allows this type to be optional
if val == nil
if expected["optional"]
return nil
else
return "#{name} cannot be null"
end
else
exp_type = expected["type"]
# If we expect an array, make sure that val is an Array, and then
# recursively validate the elements in the array
if expect_array
if val.kind_of?(Array)
stop = val.length - 1
for i in (0..stop)
invalid = validate("#{name}[#{i}]", expected, false, val[i])
if invalid != nil
return invalid
end
end
return nil
else
return type_err(name, "[]"+expected["type"], val)
end
# Check the built in Barrister primitive types
elsif exp_type == "string"
if val.class == String
return nil
else
return type_err(name, exp_type, val)
end
elsif exp_type == "bool"
if val.class == TrueClass || val.class == FalseClass
return nil
else
return type_err(name, exp_type, val)
end
elsif exp_type == "int" || exp_type == "float"
if val.class == Integer || val.class == Fixnum || val.class == Bignum
return nil
elsif val.class == Float && exp_type == "float"
return nil
else
return type_err(name, exp_type, val)
end
# Expected type is not an array or a Barrister primitive.
# It must be a struct or an enum.
else
# Try to find a struct
struct = @structs[exp_type]
if struct
if !val.kind_of?(Hash)
return "#{name} #{exp_type} value must be a map/hash. not: " + val.class.name
end
s_field_keys = { }
# Resolve all fields on the struct and its ancestors
s_fields = all_struct_fields([], struct)
# Validate that each field on the struct has a valid value
s_fields.each do |f|
fname = f["name"]
invalid = validate("#{name}.#{fname}", f, f["is_array"], val[fname])
if invalid != nil
return invalid
end
s_field_keys[fname] = 1
end
# Validate that there are no extraneous elements on the value
val.keys.each do |k|
if !s_field_keys.key?(k)
return "#{name}.#{k} is not a field in struct '#{exp_type}'"
end
end
# Struct is valid
return nil
end
# Try to find an enum
enum = @enums[exp_type]
if enum
if val.class != String
return "#{name} enum value must be a string. got: " + val.class.name
end
# Try to find an enum value that matches this val
enum["values"].each do |en|
if en["value"] == val
return nil
end
end
# Invalid
return "#{name} #{val} is not a value in enum '#{exp_type}'"
end
# Unlikely branch - suggests the IDL is internally inconsistent
return "#{name} unknown type: #{exp_type}"
end
# Panic if we have a branch unaccounted for. Indicates a Barrister bug.
raise "Barrister ERROR: validate did not return for: #{name} #{expected}"
end
end | ruby | def validate(name, expected, expect_array, val)
# If val is nil, then check if the IDL allows this type to be optional
if val == nil
if expected["optional"]
return nil
else
return "#{name} cannot be null"
end
else
exp_type = expected["type"]
# If we expect an array, make sure that val is an Array, and then
# recursively validate the elements in the array
if expect_array
if val.kind_of?(Array)
stop = val.length - 1
for i in (0..stop)
invalid = validate("#{name}[#{i}]", expected, false, val[i])
if invalid != nil
return invalid
end
end
return nil
else
return type_err(name, "[]"+expected["type"], val)
end
# Check the built in Barrister primitive types
elsif exp_type == "string"
if val.class == String
return nil
else
return type_err(name, exp_type, val)
end
elsif exp_type == "bool"
if val.class == TrueClass || val.class == FalseClass
return nil
else
return type_err(name, exp_type, val)
end
elsif exp_type == "int" || exp_type == "float"
if val.class == Integer || val.class == Fixnum || val.class == Bignum
return nil
elsif val.class == Float && exp_type == "float"
return nil
else
return type_err(name, exp_type, val)
end
# Expected type is not an array or a Barrister primitive.
# It must be a struct or an enum.
else
# Try to find a struct
struct = @structs[exp_type]
if struct
if !val.kind_of?(Hash)
return "#{name} #{exp_type} value must be a map/hash. not: " + val.class.name
end
s_field_keys = { }
# Resolve all fields on the struct and its ancestors
s_fields = all_struct_fields([], struct)
# Validate that each field on the struct has a valid value
s_fields.each do |f|
fname = f["name"]
invalid = validate("#{name}.#{fname}", f, f["is_array"], val[fname])
if invalid != nil
return invalid
end
s_field_keys[fname] = 1
end
# Validate that there are no extraneous elements on the value
val.keys.each do |k|
if !s_field_keys.key?(k)
return "#{name}.#{k} is not a field in struct '#{exp_type}'"
end
end
# Struct is valid
return nil
end
# Try to find an enum
enum = @enums[exp_type]
if enum
if val.class != String
return "#{name} enum value must be a string. got: " + val.class.name
end
# Try to find an enum value that matches this val
enum["values"].each do |en|
if en["value"] == val
return nil
end
end
# Invalid
return "#{name} #{val} is not a value in enum '#{exp_type}'"
end
# Unlikely branch - suggests the IDL is internally inconsistent
return "#{name} unknown type: #{exp_type}"
end
# Panic if we have a branch unaccounted for. Indicates a Barrister bug.
raise "Barrister ERROR: validate did not return for: #{name} #{expected}"
end
end | [
"def",
"validate",
"(",
"name",
",",
"expected",
",",
"expect_array",
",",
"val",
")",
"# If val is nil, then check if the IDL allows this type to be optional",
"if",
"val",
"==",
"nil",
"if",
"expected",
"[",
"\"optional\"",
"]",
"return",
"nil",
"else",
"return",
"\"#{name} cannot be null\"",
"end",
"else",
"exp_type",
"=",
"expected",
"[",
"\"type\"",
"]",
"# If we expect an array, make sure that val is an Array, and then",
"# recursively validate the elements in the array",
"if",
"expect_array",
"if",
"val",
".",
"kind_of?",
"(",
"Array",
")",
"stop",
"=",
"val",
".",
"length",
"-",
"1",
"for",
"i",
"in",
"(",
"0",
"..",
"stop",
")",
"invalid",
"=",
"validate",
"(",
"\"#{name}[#{i}]\"",
",",
"expected",
",",
"false",
",",
"val",
"[",
"i",
"]",
")",
"if",
"invalid",
"!=",
"nil",
"return",
"invalid",
"end",
"end",
"return",
"nil",
"else",
"return",
"type_err",
"(",
"name",
",",
"\"[]\"",
"+",
"expected",
"[",
"\"type\"",
"]",
",",
"val",
")",
"end",
"# Check the built in Barrister primitive types",
"elsif",
"exp_type",
"==",
"\"string\"",
"if",
"val",
".",
"class",
"==",
"String",
"return",
"nil",
"else",
"return",
"type_err",
"(",
"name",
",",
"exp_type",
",",
"val",
")",
"end",
"elsif",
"exp_type",
"==",
"\"bool\"",
"if",
"val",
".",
"class",
"==",
"TrueClass",
"||",
"val",
".",
"class",
"==",
"FalseClass",
"return",
"nil",
"else",
"return",
"type_err",
"(",
"name",
",",
"exp_type",
",",
"val",
")",
"end",
"elsif",
"exp_type",
"==",
"\"int\"",
"||",
"exp_type",
"==",
"\"float\"",
"if",
"val",
".",
"class",
"==",
"Integer",
"||",
"val",
".",
"class",
"==",
"Fixnum",
"||",
"val",
".",
"class",
"==",
"Bignum",
"return",
"nil",
"elsif",
"val",
".",
"class",
"==",
"Float",
"&&",
"exp_type",
"==",
"\"float\"",
"return",
"nil",
"else",
"return",
"type_err",
"(",
"name",
",",
"exp_type",
",",
"val",
")",
"end",
"# Expected type is not an array or a Barrister primitive.",
"# It must be a struct or an enum.",
"else",
"# Try to find a struct",
"struct",
"=",
"@structs",
"[",
"exp_type",
"]",
"if",
"struct",
"if",
"!",
"val",
".",
"kind_of?",
"(",
"Hash",
")",
"return",
"\"#{name} #{exp_type} value must be a map/hash. not: \"",
"+",
"val",
".",
"class",
".",
"name",
"end",
"s_field_keys",
"=",
"{",
"}",
"# Resolve all fields on the struct and its ancestors",
"s_fields",
"=",
"all_struct_fields",
"(",
"[",
"]",
",",
"struct",
")",
"# Validate that each field on the struct has a valid value",
"s_fields",
".",
"each",
"do",
"|",
"f",
"|",
"fname",
"=",
"f",
"[",
"\"name\"",
"]",
"invalid",
"=",
"validate",
"(",
"\"#{name}.#{fname}\"",
",",
"f",
",",
"f",
"[",
"\"is_array\"",
"]",
",",
"val",
"[",
"fname",
"]",
")",
"if",
"invalid",
"!=",
"nil",
"return",
"invalid",
"end",
"s_field_keys",
"[",
"fname",
"]",
"=",
"1",
"end",
"# Validate that there are no extraneous elements on the value",
"val",
".",
"keys",
".",
"each",
"do",
"|",
"k",
"|",
"if",
"!",
"s_field_keys",
".",
"key?",
"(",
"k",
")",
"return",
"\"#{name}.#{k} is not a field in struct '#{exp_type}'\"",
"end",
"end",
"# Struct is valid",
"return",
"nil",
"end",
"# Try to find an enum",
"enum",
"=",
"@enums",
"[",
"exp_type",
"]",
"if",
"enum",
"if",
"val",
".",
"class",
"!=",
"String",
"return",
"\"#{name} enum value must be a string. got: \"",
"+",
"val",
".",
"class",
".",
"name",
"end",
"# Try to find an enum value that matches this val",
"enum",
"[",
"\"values\"",
"]",
".",
"each",
"do",
"|",
"en",
"|",
"if",
"en",
"[",
"\"value\"",
"]",
"==",
"val",
"return",
"nil",
"end",
"end",
"# Invalid",
"return",
"\"#{name} #{val} is not a value in enum '#{exp_type}'\"",
"end",
"# Unlikely branch - suggests the IDL is internally inconsistent",
"return",
"\"#{name} unknown type: #{exp_type}\"",
"end",
"# Panic if we have a branch unaccounted for. Indicates a Barrister bug.",
"raise",
"\"Barrister ERROR: validate did not return for: #{name} #{expected}\"",
"end",
"end"
] | Validates the type for a single value. This method is recursive when validating
arrays or structs.
Returns a string describing the validation error if invalid, or nil if valid
* `name` - string to prefix onto the validation error
* `expected` - expected type (hash)
* `expect_array` - if true, we expect val to be an Array
* `val` - value to validate | [
"Validates",
"the",
"type",
"for",
"a",
"single",
"value",
".",
"This",
"method",
"is",
"recursive",
"when",
"validating",
"arrays",
"or",
"structs",
"."
] | 5606e7dc591762fc28a338dee48093aaaafb106e | https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L700-L812 |
24,557 | coopernurse/barrister-ruby | lib/barrister.rb | Barrister.Contract.all_struct_fields | def all_struct_fields(arr, struct)
struct["fields"].each do |f|
arr << f
end
if struct["extends"]
parent = @structs[struct["extends"]]
if parent
return all_struct_fields(arr, parent)
end
end
return arr
end | ruby | def all_struct_fields(arr, struct)
struct["fields"].each do |f|
arr << f
end
if struct["extends"]
parent = @structs[struct["extends"]]
if parent
return all_struct_fields(arr, parent)
end
end
return arr
end | [
"def",
"all_struct_fields",
"(",
"arr",
",",
"struct",
")",
"struct",
"[",
"\"fields\"",
"]",
".",
"each",
"do",
"|",
"f",
"|",
"arr",
"<<",
"f",
"end",
"if",
"struct",
"[",
"\"extends\"",
"]",
"parent",
"=",
"@structs",
"[",
"struct",
"[",
"\"extends\"",
"]",
"]",
"if",
"parent",
"return",
"all_struct_fields",
"(",
"arr",
",",
"parent",
")",
"end",
"end",
"return",
"arr",
"end"
] | Recursively resolves all fields for the struct and its ancestors
Returns an Array with all the fields | [
"Recursively",
"resolves",
"all",
"fields",
"for",
"the",
"struct",
"and",
"its",
"ancestors"
] | 5606e7dc591762fc28a338dee48093aaaafb106e | https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L817-L830 |
24,558 | moove-it/rusen | lib/rusen/notifier.rb | Rusen.Notifier.notify | def notify(exception, request = {}, environment = {}, session = {})
begin
notification = Notification.new(exception, request, environment, session)
@notifiers.each do |notifier|
notifier.notify(notification)
end
# We need to ignore all the exceptions thrown by the notifiers.
rescue Exception
warn('Rusen: Some or all the notifiers failed to sent the notification.')
end
end | ruby | def notify(exception, request = {}, environment = {}, session = {})
begin
notification = Notification.new(exception, request, environment, session)
@notifiers.each do |notifier|
notifier.notify(notification)
end
# We need to ignore all the exceptions thrown by the notifiers.
rescue Exception
warn('Rusen: Some or all the notifiers failed to sent the notification.')
end
end | [
"def",
"notify",
"(",
"exception",
",",
"request",
"=",
"{",
"}",
",",
"environment",
"=",
"{",
"}",
",",
"session",
"=",
"{",
"}",
")",
"begin",
"notification",
"=",
"Notification",
".",
"new",
"(",
"exception",
",",
"request",
",",
"environment",
",",
"session",
")",
"@notifiers",
".",
"each",
"do",
"|",
"notifier",
"|",
"notifier",
".",
"notify",
"(",
"notification",
")",
"end",
"# We need to ignore all the exceptions thrown by the notifiers.",
"rescue",
"Exception",
"warn",
"(",
"'Rusen: Some or all the notifiers failed to sent the notification.'",
")",
"end",
"end"
] | Sends a notification to the configured outputs.
@param [Exception] exception The error.
@param [Hash<Object, Object>] request The request params
@param [Hash<Object, Object>] environment The environment status.
@param [Hash<Object, Object>] session The session status. | [
"Sends",
"a",
"notification",
"to",
"the",
"configured",
"outputs",
"."
] | 6cef7b47017844b2e680baa19a28bff17bb68da2 | https://github.com/moove-it/rusen/blob/6cef7b47017844b2e680baa19a28bff17bb68da2/lib/rusen/notifier.rb#L39-L51 |
24,559 | reset/chozo | lib/chozo/hashie_ext/mash.rb | Hashie.Mash.[]= | def []=(key, value)
coerced_value = coercion(key).present? ? coercion(key).call(value) : value
old_setter(key, coerced_value)
end | ruby | def []=(key, value)
coerced_value = coercion(key).present? ? coercion(key).call(value) : value
old_setter(key, coerced_value)
end | [
"def",
"[]=",
"(",
"key",
",",
"value",
")",
"coerced_value",
"=",
"coercion",
"(",
"key",
")",
".",
"present?",
"?",
"coercion",
"(",
"key",
")",
".",
"call",
"(",
"value",
")",
":",
"value",
"old_setter",
"(",
"key",
",",
"coerced_value",
")",
"end"
] | Override setter to coerce the given value if a coercion is defined | [
"Override",
"setter",
"to",
"coerce",
"the",
"given",
"value",
"if",
"a",
"coercion",
"is",
"defined"
] | ba88aff29bef4b2f56090a8ad1a4ba5a165786e8 | https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/hashie_ext/mash.rb#L23-L26 |
24,560 | movitto/reterm | lib/reterm/panel.rb | RETerm.Panel.show | def show
Ncurses::Panel.top_panel(@panel)
update_reterm
@@registry.values.each { |panel|
if panel == self
dispatch :panel_show
else
panel.dispatch :panel_hide
end
}
end | ruby | def show
Ncurses::Panel.top_panel(@panel)
update_reterm
@@registry.values.each { |panel|
if panel == self
dispatch :panel_show
else
panel.dispatch :panel_hide
end
}
end | [
"def",
"show",
"Ncurses",
"::",
"Panel",
".",
"top_panel",
"(",
"@panel",
")",
"update_reterm",
"@@registry",
".",
"values",
".",
"each",
"{",
"|",
"panel",
"|",
"if",
"panel",
"==",
"self",
"dispatch",
":panel_show",
"else",
"panel",
".",
"dispatch",
":panel_hide",
"end",
"}",
"end"
] | Initialize panel from the given window.
This maintains an internal registry of panels created
for event dispatching purposes
Render this panel by surfacing it ot hte top of the stack | [
"Initialize",
"panel",
"from",
"the",
"given",
"window",
"."
] | 3e78c64e677f69b22f00dc89c2b515b9188c5e15 | https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/panel.rb#L24-L35 |
24,561 | niho/related | lib/related/helpers.rb | Related.Helpers.generate_id | def generate_id
Base64.encode64(
Digest::MD5.digest("#{Time.now}-#{rand}")
).gsub('/','x').gsub('+','y').gsub('=','').strip
end | ruby | def generate_id
Base64.encode64(
Digest::MD5.digest("#{Time.now}-#{rand}")
).gsub('/','x').gsub('+','y').gsub('=','').strip
end | [
"def",
"generate_id",
"Base64",
".",
"encode64",
"(",
"Digest",
"::",
"MD5",
".",
"digest",
"(",
"\"#{Time.now}-#{rand}\"",
")",
")",
".",
"gsub",
"(",
"'/'",
",",
"'x'",
")",
".",
"gsub",
"(",
"'+'",
",",
"'y'",
")",
".",
"gsub",
"(",
"'='",
",",
"''",
")",
".",
"strip",
"end"
] | Generate a unique id | [
"Generate",
"a",
"unique",
"id"
] | c18d66911c4f08ed7422d2122bc2fbfdb0274c8f | https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/lib/related/helpers.rb#L8-L12 |
24,562 | reset/chozo | lib/chozo/mixin/params_validate.rb | Chozo::Mixin.ParamsValidate._pv_opts_lookup | def _pv_opts_lookup(opts, key)
if opts.has_key?(key.to_s)
opts[key.to_s]
elsif opts.has_key?(key.to_sym)
opts[key.to_sym]
else
nil
end
end | ruby | def _pv_opts_lookup(opts, key)
if opts.has_key?(key.to_s)
opts[key.to_s]
elsif opts.has_key?(key.to_sym)
opts[key.to_sym]
else
nil
end
end | [
"def",
"_pv_opts_lookup",
"(",
"opts",
",",
"key",
")",
"if",
"opts",
".",
"has_key?",
"(",
"key",
".",
"to_s",
")",
"opts",
"[",
"key",
".",
"to_s",
"]",
"elsif",
"opts",
".",
"has_key?",
"(",
"key",
".",
"to_sym",
")",
"opts",
"[",
"key",
".",
"to_sym",
"]",
"else",
"nil",
"end",
"end"
] | Return the value of a parameter, or nil if it doesn't exist. | [
"Return",
"the",
"value",
"of",
"a",
"parameter",
"or",
"nil",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | ba88aff29bef4b2f56090a8ad1a4ba5a165786e8 | https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/params_validate.rb#L91-L99 |
24,563 | reset/chozo | lib/chozo/mixin/params_validate.rb | Chozo::Mixin.ParamsValidate._pv_required | def _pv_required(opts, key, is_required=true)
if is_required
if (opts.has_key?(key.to_s) && !opts[key.to_s].nil?) ||
(opts.has_key?(key.to_sym) && !opts[key.to_sym].nil?)
true
else
raise ValidationFailed, "Required argument #{key} is missing!"
end
end
end | ruby | def _pv_required(opts, key, is_required=true)
if is_required
if (opts.has_key?(key.to_s) && !opts[key.to_s].nil?) ||
(opts.has_key?(key.to_sym) && !opts[key.to_sym].nil?)
true
else
raise ValidationFailed, "Required argument #{key} is missing!"
end
end
end | [
"def",
"_pv_required",
"(",
"opts",
",",
"key",
",",
"is_required",
"=",
"true",
")",
"if",
"is_required",
"if",
"(",
"opts",
".",
"has_key?",
"(",
"key",
".",
"to_s",
")",
"&&",
"!",
"opts",
"[",
"key",
".",
"to_s",
"]",
".",
"nil?",
")",
"||",
"(",
"opts",
".",
"has_key?",
"(",
"key",
".",
"to_sym",
")",
"&&",
"!",
"opts",
"[",
"key",
".",
"to_sym",
"]",
".",
"nil?",
")",
"true",
"else",
"raise",
"ValidationFailed",
",",
"\"Required argument #{key} is missing!\"",
"end",
"end",
"end"
] | Raise an exception if the parameter is not found. | [
"Raise",
"an",
"exception",
"if",
"the",
"parameter",
"is",
"not",
"found",
"."
] | ba88aff29bef4b2f56090a8ad1a4ba5a165786e8 | https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/params_validate.rb#L102-L111 |
24,564 | reset/chozo | lib/chozo/mixin/params_validate.rb | Chozo::Mixin.ParamsValidate._pv_respond_to | def _pv_respond_to(opts, key, method_name_list)
value = _pv_opts_lookup(opts, key)
unless value.nil?
Array(method_name_list).each do |method_name|
unless value.respond_to?(method_name)
raise ValidationFailed, "Option #{key} must have a #{method_name} method!"
end
end
end
end | ruby | def _pv_respond_to(opts, key, method_name_list)
value = _pv_opts_lookup(opts, key)
unless value.nil?
Array(method_name_list).each do |method_name|
unless value.respond_to?(method_name)
raise ValidationFailed, "Option #{key} must have a #{method_name} method!"
end
end
end
end | [
"def",
"_pv_respond_to",
"(",
"opts",
",",
"key",
",",
"method_name_list",
")",
"value",
"=",
"_pv_opts_lookup",
"(",
"opts",
",",
"key",
")",
"unless",
"value",
".",
"nil?",
"Array",
"(",
"method_name_list",
")",
".",
"each",
"do",
"|",
"method_name",
"|",
"unless",
"value",
".",
"respond_to?",
"(",
"method_name",
")",
"raise",
"ValidationFailed",
",",
"\"Option #{key} must have a #{method_name} method!\"",
"end",
"end",
"end",
"end"
] | Raise an exception if the parameter does not respond to a given set of methods. | [
"Raise",
"an",
"exception",
"if",
"the",
"parameter",
"does",
"not",
"respond",
"to",
"a",
"given",
"set",
"of",
"methods",
"."
] | ba88aff29bef4b2f56090a8ad1a4ba5a165786e8 | https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/params_validate.rb#L141-L150 |
24,565 | reset/chozo | lib/chozo/mixin/params_validate.rb | Chozo::Mixin.ParamsValidate._pv_default | def _pv_default(opts, key, default_value)
value = _pv_opts_lookup(opts, key)
if value == nil
opts[key] = default_value
end
end | ruby | def _pv_default(opts, key, default_value)
value = _pv_opts_lookup(opts, key)
if value == nil
opts[key] = default_value
end
end | [
"def",
"_pv_default",
"(",
"opts",
",",
"key",
",",
"default_value",
")",
"value",
"=",
"_pv_opts_lookup",
"(",
"opts",
",",
"key",
")",
"if",
"value",
"==",
"nil",
"opts",
"[",
"key",
"]",
"=",
"default_value",
"end",
"end"
] | Assign a default value to a parameter. | [
"Assign",
"a",
"default",
"value",
"to",
"a",
"parameter",
"."
] | ba88aff29bef4b2f56090a8ad1a4ba5a165786e8 | https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/params_validate.rb#L171-L176 |
24,566 | reset/chozo | lib/chozo/mixin/params_validate.rb | Chozo::Mixin.ParamsValidate._pv_regex | def _pv_regex(opts, key, regex)
value = _pv_opts_lookup(opts, key)
if value != nil
passes = false
[ regex ].flatten.each do |r|
if value != nil
if r.match(value.to_s)
passes = true
end
end
end
unless passes
raise ValidationFailed, "Option #{key}'s value #{value} does not match regular expression #{regex.inspect}"
end
end
end | ruby | def _pv_regex(opts, key, regex)
value = _pv_opts_lookup(opts, key)
if value != nil
passes = false
[ regex ].flatten.each do |r|
if value != nil
if r.match(value.to_s)
passes = true
end
end
end
unless passes
raise ValidationFailed, "Option #{key}'s value #{value} does not match regular expression #{regex.inspect}"
end
end
end | [
"def",
"_pv_regex",
"(",
"opts",
",",
"key",
",",
"regex",
")",
"value",
"=",
"_pv_opts_lookup",
"(",
"opts",
",",
"key",
")",
"if",
"value",
"!=",
"nil",
"passes",
"=",
"false",
"[",
"regex",
"]",
".",
"flatten",
".",
"each",
"do",
"|",
"r",
"|",
"if",
"value",
"!=",
"nil",
"if",
"r",
".",
"match",
"(",
"value",
".",
"to_s",
")",
"passes",
"=",
"true",
"end",
"end",
"end",
"unless",
"passes",
"raise",
"ValidationFailed",
",",
"\"Option #{key}'s value #{value} does not match regular expression #{regex.inspect}\"",
"end",
"end",
"end"
] | Check a parameter against a regular expression. | [
"Check",
"a",
"parameter",
"against",
"a",
"regular",
"expression",
"."
] | ba88aff29bef4b2f56090a8ad1a4ba5a165786e8 | https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/params_validate.rb#L179-L194 |
24,567 | reset/chozo | lib/chozo/mixin/params_validate.rb | Chozo::Mixin.ParamsValidate._pv_callbacks | def _pv_callbacks(opts, key, callbacks)
raise ArgumentError, "Callback list must be a hash!" unless callbacks.kind_of?(Hash)
value = _pv_opts_lookup(opts, key)
if value != nil
callbacks.each do |message, zeproc|
if zeproc.call(value) != true
raise ValidationFailed, "Option #{key}'s value #{value} #{message}!"
end
end
end
end | ruby | def _pv_callbacks(opts, key, callbacks)
raise ArgumentError, "Callback list must be a hash!" unless callbacks.kind_of?(Hash)
value = _pv_opts_lookup(opts, key)
if value != nil
callbacks.each do |message, zeproc|
if zeproc.call(value) != true
raise ValidationFailed, "Option #{key}'s value #{value} #{message}!"
end
end
end
end | [
"def",
"_pv_callbacks",
"(",
"opts",
",",
"key",
",",
"callbacks",
")",
"raise",
"ArgumentError",
",",
"\"Callback list must be a hash!\"",
"unless",
"callbacks",
".",
"kind_of?",
"(",
"Hash",
")",
"value",
"=",
"_pv_opts_lookup",
"(",
"opts",
",",
"key",
")",
"if",
"value",
"!=",
"nil",
"callbacks",
".",
"each",
"do",
"|",
"message",
",",
"zeproc",
"|",
"if",
"zeproc",
".",
"call",
"(",
"value",
")",
"!=",
"true",
"raise",
"ValidationFailed",
",",
"\"Option #{key}'s value #{value} #{message}!\"",
"end",
"end",
"end",
"end"
] | Check a parameter against a hash of proc's. | [
"Check",
"a",
"parameter",
"against",
"a",
"hash",
"of",
"proc",
"s",
"."
] | ba88aff29bef4b2f56090a8ad1a4ba5a165786e8 | https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/params_validate.rb#L197-L207 |
24,568 | reset/chozo | lib/chozo/mixin/params_validate.rb | Chozo::Mixin.ParamsValidate._pv_name_attribute | def _pv_name_attribute(opts, key, is_name_attribute=true)
if is_name_attribute
if opts[key] == nil
opts[key] = self.instance_variable_get("@name")
end
end
end | ruby | def _pv_name_attribute(opts, key, is_name_attribute=true)
if is_name_attribute
if opts[key] == nil
opts[key] = self.instance_variable_get("@name")
end
end
end | [
"def",
"_pv_name_attribute",
"(",
"opts",
",",
"key",
",",
"is_name_attribute",
"=",
"true",
")",
"if",
"is_name_attribute",
"if",
"opts",
"[",
"key",
"]",
"==",
"nil",
"opts",
"[",
"key",
"]",
"=",
"self",
".",
"instance_variable_get",
"(",
"\"@name\"",
")",
"end",
"end",
"end"
] | Allow a parameter to default to @name | [
"Allow",
"a",
"parameter",
"to",
"default",
"to"
] | ba88aff29bef4b2f56090a8ad1a4ba5a165786e8 | https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/params_validate.rb#L210-L216 |
24,569 | puppetlabs/beaker-answers | lib/beaker-answers/versions/version20162.rb | BeakerAnswers.Version20162.answer_hiera | def answer_hiera
# Render pretty JSON, because it is a subset of HOCON
json = JSON.pretty_generate(answers)
hocon = Hocon::Parser::ConfigDocumentFactory.parse_string(json)
hocon.render
end | ruby | def answer_hiera
# Render pretty JSON, because it is a subset of HOCON
json = JSON.pretty_generate(answers)
hocon = Hocon::Parser::ConfigDocumentFactory.parse_string(json)
hocon.render
end | [
"def",
"answer_hiera",
"# Render pretty JSON, because it is a subset of HOCON",
"json",
"=",
"JSON",
".",
"pretty_generate",
"(",
"answers",
")",
"hocon",
"=",
"Hocon",
"::",
"Parser",
"::",
"ConfigDocumentFactory",
".",
"parse_string",
"(",
"json",
")",
"hocon",
".",
"render",
"end"
] | This converts a data hash provided by answers, and returns a Puppet
Enterprise compatible hiera config file ready for use.
@return [String] a string of parseable hocon
@example Generating an answer file for a series of hosts
hosts.each do |host|
answers = Beaker::Answers.new("2.0", hosts, "master")
create_remote_file host, "/mypath/answer", answers.answer_hiera
end | [
"This",
"converts",
"a",
"data",
"hash",
"provided",
"by",
"answers",
"and",
"returns",
"a",
"Puppet",
"Enterprise",
"compatible",
"hiera",
"config",
"file",
"ready",
"for",
"use",
"."
] | 3193bf986fd1842f2c7d8940a88df36db4200f3f | https://github.com/puppetlabs/beaker-answers/blob/3193bf986fd1842f2c7d8940a88df36db4200f3f/lib/beaker-answers/versions/version20162.rb#L99-L104 |
24,570 | flyertools/tripit | lib/trip_it/base.rb | TripIt.Base.convertDT | def convertDT(tpitDT)
return nil if tpitDT.nil?
date = tpitDT["date"]
time = tpitDT["time"]
offset = tpitDT["utc_offset"]
if time.nil?
# Just return a date
Date.parse(date)
elsif date.nil?
# Or just a time
Time.parse(time)
else
# Ideally both
DateTime.parse("#{date}T#{time}#{offset}")
end
end | ruby | def convertDT(tpitDT)
return nil if tpitDT.nil?
date = tpitDT["date"]
time = tpitDT["time"]
offset = tpitDT["utc_offset"]
if time.nil?
# Just return a date
Date.parse(date)
elsif date.nil?
# Or just a time
Time.parse(time)
else
# Ideally both
DateTime.parse("#{date}T#{time}#{offset}")
end
end | [
"def",
"convertDT",
"(",
"tpitDT",
")",
"return",
"nil",
"if",
"tpitDT",
".",
"nil?",
"date",
"=",
"tpitDT",
"[",
"\"date\"",
"]",
"time",
"=",
"tpitDT",
"[",
"\"time\"",
"]",
"offset",
"=",
"tpitDT",
"[",
"\"utc_offset\"",
"]",
"if",
"time",
".",
"nil?",
"# Just return a date",
"Date",
".",
"parse",
"(",
"date",
")",
"elsif",
"date",
".",
"nil?",
"# Or just a time",
"Time",
".",
"parse",
"(",
"time",
")",
"else",
"# Ideally both",
"DateTime",
".",
"parse",
"(",
"\"#{date}T#{time}#{offset}\"",
")",
"end",
"end"
] | Convert a TripIt DateTime Object to a Ruby DateTime Object | [
"Convert",
"a",
"TripIt",
"DateTime",
"Object",
"to",
"a",
"Ruby",
"DateTime",
"Object"
] | 8d0c1d19c5c8ec22faafee73389e50c6da4d7a5a | https://github.com/flyertools/tripit/blob/8d0c1d19c5c8ec22faafee73389e50c6da4d7a5a/lib/trip_it/base.rb#L28-L43 |
24,571 | holtrop/rscons | lib/rscons/builder.rb | Rscons.Builder.standard_build | def standard_build(short_cmd_string, target, command, sources, env, cache)
unless cache.up_to_date?(target, command, sources, env)
unless Rscons.phony_target?(target)
cache.mkdir_p(File.dirname(target))
FileUtils.rm_f(target)
end
return false unless env.execute(short_cmd_string, command)
cache.register_build(target, command, sources, env)
end
target
end | ruby | def standard_build(short_cmd_string, target, command, sources, env, cache)
unless cache.up_to_date?(target, command, sources, env)
unless Rscons.phony_target?(target)
cache.mkdir_p(File.dirname(target))
FileUtils.rm_f(target)
end
return false unless env.execute(short_cmd_string, command)
cache.register_build(target, command, sources, env)
end
target
end | [
"def",
"standard_build",
"(",
"short_cmd_string",
",",
"target",
",",
"command",
",",
"sources",
",",
"env",
",",
"cache",
")",
"unless",
"cache",
".",
"up_to_date?",
"(",
"target",
",",
"command",
",",
"sources",
",",
"env",
")",
"unless",
"Rscons",
".",
"phony_target?",
"(",
"target",
")",
"cache",
".",
"mkdir_p",
"(",
"File",
".",
"dirname",
"(",
"target",
")",
")",
"FileUtils",
".",
"rm_f",
"(",
"target",
")",
"end",
"return",
"false",
"unless",
"env",
".",
"execute",
"(",
"short_cmd_string",
",",
"command",
")",
"cache",
".",
"register_build",
"(",
"target",
",",
"command",
",",
"sources",
",",
"env",
")",
"end",
"target",
"end"
] | Check if the cache is up to date for the target and if not execute the
build command. This method does not support parallelization.
@param short_cmd_string [String]
Short description of build action to be printed when env.echo ==
:short.
@param target [String] Name of the target file.
@param command [Array<String>]
The command to execute to build the target.
@param sources [Array<String>] Source file name(s).
@param env [Environment] The Environment executing the builder.
@param cache [Cache] The Cache object.
@return [String,false]
The name of the target on success or false on failure. | [
"Check",
"if",
"the",
"cache",
"is",
"up",
"to",
"date",
"for",
"the",
"target",
"and",
"if",
"not",
"execute",
"the",
"build",
"command",
".",
"This",
"method",
"does",
"not",
"support",
"parallelization",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/builder.rb#L207-L217 |
24,572 | movitto/reterm | lib/reterm/window.rb | RETerm.Window.finalize! | def finalize!
erase
@@registry.delete(self)
children.each { |c|
del_child c
}
cdk_scr.destroy if cdk?
component.finalize! if component?
end | ruby | def finalize!
erase
@@registry.delete(self)
children.each { |c|
del_child c
}
cdk_scr.destroy if cdk?
component.finalize! if component?
end | [
"def",
"finalize!",
"erase",
"@@registry",
".",
"delete",
"(",
"self",
")",
"children",
".",
"each",
"{",
"|",
"c",
"|",
"del_child",
"c",
"}",
"cdk_scr",
".",
"destroy",
"if",
"cdk?",
"component",
".",
"finalize!",
"if",
"component?",
"end"
] | Invoke window finalization routine by destroying it
and all children | [
"Invoke",
"window",
"finalization",
"routine",
"by",
"destroying",
"it",
"and",
"all",
"children"
] | 3e78c64e677f69b22f00dc89c2b515b9188c5e15 | https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/window.rb#L237-L247 |
24,573 | movitto/reterm | lib/reterm/window.rb | RETerm.Window.child_containing | def child_containing(x, y, z)
found = nil
children.find { |c|
next if found
# recursively descend into layout children
if c.component.kind_of?(Layout)
found = c.child_containing(x, y, z)
else
found =
c.total_x <= x && c.total_y <= y && # c.z >= z
(c.total_x + c.cols) >= x && (c.total_y + c.rows) >= y
found = c if found
end
}
found
end | ruby | def child_containing(x, y, z)
found = nil
children.find { |c|
next if found
# recursively descend into layout children
if c.component.kind_of?(Layout)
found = c.child_containing(x, y, z)
else
found =
c.total_x <= x && c.total_y <= y && # c.z >= z
(c.total_x + c.cols) >= x && (c.total_y + c.rows) >= y
found = c if found
end
}
found
end | [
"def",
"child_containing",
"(",
"x",
",",
"y",
",",
"z",
")",
"found",
"=",
"nil",
"children",
".",
"find",
"{",
"|",
"c",
"|",
"next",
"if",
"found",
"# recursively descend into layout children",
"if",
"c",
".",
"component",
".",
"kind_of?",
"(",
"Layout",
")",
"found",
"=",
"c",
".",
"child_containing",
"(",
"x",
",",
"y",
",",
"z",
")",
"else",
"found",
"=",
"c",
".",
"total_x",
"<=",
"x",
"&&",
"c",
".",
"total_y",
"<=",
"y",
"&&",
"# c.z >= z",
"(",
"c",
".",
"total_x",
"+",
"c",
".",
"cols",
")",
">=",
"x",
"&&",
"(",
"c",
".",
"total_y",
"+",
"c",
".",
"rows",
")",
">=",
"y",
"found",
"=",
"c",
"if",
"found",
"end",
"}",
"found",
"end"
] | Return child containing specified screen coordiantes, else nil | [
"Return",
"child",
"containing",
"specified",
"screen",
"coordiantes",
"else",
"nil"
] | 3e78c64e677f69b22f00dc89c2b515b9188c5e15 | https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/window.rb#L336-L354 |
24,574 | movitto/reterm | lib/reterm/window.rb | RETerm.Window.erase | def erase
children.each { |c|
c.erase
}
@win.werase if @win
component.component.erase if cdk? && component? && component.init?
end | ruby | def erase
children.each { |c|
c.erase
}
@win.werase if @win
component.component.erase if cdk? && component? && component.init?
end | [
"def",
"erase",
"children",
".",
"each",
"{",
"|",
"c",
"|",
"c",
".",
"erase",
"}",
"@win",
".",
"werase",
"if",
"@win",
"component",
".",
"component",
".",
"erase",
"if",
"cdk?",
"&&",
"component?",
"&&",
"component",
".",
"init?",
"end"
] | Erase window drawing area | [
"Erase",
"window",
"drawing",
"area"
] | 3e78c64e677f69b22f00dc89c2b515b9188c5e15 | https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/window.rb#L381-L389 |
24,575 | movitto/reterm | lib/reterm/window.rb | RETerm.Window.no_border! | def no_border!
@win.border(' '.ord, ' '.ord, ' '.ord, ' '.ord, ' '.ord, ' '.ord, ' '.ord, ' '.ord)
end | ruby | def no_border!
@win.border(' '.ord, ' '.ord, ' '.ord, ' '.ord, ' '.ord, ' '.ord, ' '.ord, ' '.ord)
end | [
"def",
"no_border!",
"@win",
".",
"border",
"(",
"' '",
".",
"ord",
",",
"' '",
".",
"ord",
",",
"' '",
".",
"ord",
",",
"' '",
".",
"ord",
",",
"' '",
".",
"ord",
",",
"' '",
".",
"ord",
",",
"' '",
".",
"ord",
",",
"' '",
".",
"ord",
")",
"end"
] | Remove Border around window | [
"Remove",
"Border",
"around",
"window"
] | 3e78c64e677f69b22f00dc89c2b515b9188c5e15 | https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/window.rb#L418-L420 |
24,576 | movitto/reterm | lib/reterm/window.rb | RETerm.Window.sync_getch | def sync_getch
return self.getch unless sync_enabled?
c = -1
while c == -1 && !shutdown?
c = self.getch
run_sync!
end
c
end | ruby | def sync_getch
return self.getch unless sync_enabled?
c = -1
while c == -1 && !shutdown?
c = self.getch
run_sync!
end
c
end | [
"def",
"sync_getch",
"return",
"self",
".",
"getch",
"unless",
"sync_enabled?",
"c",
"=",
"-",
"1",
"while",
"c",
"==",
"-",
"1",
"&&",
"!",
"shutdown?",
"c",
"=",
"self",
".",
"getch",
"run_sync!",
"end",
"c",
"end"
] | Normal getch unless sync enabled in which case,
timeout will be checked & components synchronized | [
"Normal",
"getch",
"unless",
"sync",
"enabled",
"in",
"which",
"case",
"timeout",
"will",
"be",
"checked",
"&",
"components",
"synchronized"
] | 3e78c64e677f69b22f00dc89c2b515b9188c5e15 | https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/window.rb#L434-L444 |
24,577 | movitto/reterm | lib/reterm/window.rb | RETerm.Window.colors= | def colors=(c)
@colors = c.is_a?(ColorPair) ? c : ColorPair.for(c).first
@win.bkgd(Ncurses.COLOR_PAIR(@colors.id)) unless @win.nil?
component.colors = @colors if component?
children.each { |ch|
ch.colors = c
}
end | ruby | def colors=(c)
@colors = c.is_a?(ColorPair) ? c : ColorPair.for(c).first
@win.bkgd(Ncurses.COLOR_PAIR(@colors.id)) unless @win.nil?
component.colors = @colors if component?
children.each { |ch|
ch.colors = c
}
end | [
"def",
"colors",
"=",
"(",
"c",
")",
"@colors",
"=",
"c",
".",
"is_a?",
"(",
"ColorPair",
")",
"?",
"c",
":",
"ColorPair",
".",
"for",
"(",
"c",
")",
".",
"first",
"@win",
".",
"bkgd",
"(",
"Ncurses",
".",
"COLOR_PAIR",
"(",
"@colors",
".",
"id",
")",
")",
"unless",
"@win",
".",
"nil?",
"component",
".",
"colors",
"=",
"@colors",
"if",
"component?",
"children",
".",
"each",
"{",
"|",
"ch",
"|",
"ch",
".",
"colors",
"=",
"c",
"}",
"end"
] | Set window color | [
"Set",
"window",
"color"
] | 3e78c64e677f69b22f00dc89c2b515b9188c5e15 | https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/window.rb#L493-L502 |
24,578 | movitto/reterm | lib/reterm/window.rb | RETerm.Window.dimensions | def dimensions
rows = []
cols = []
@win.getmaxyx(rows, cols)
rows = rows.first
cols = cols.first
[rows, cols]
end | ruby | def dimensions
rows = []
cols = []
@win.getmaxyx(rows, cols)
rows = rows.first
cols = cols.first
[rows, cols]
end | [
"def",
"dimensions",
"rows",
"=",
"[",
"]",
"cols",
"=",
"[",
"]",
"@win",
".",
"getmaxyx",
"(",
"rows",
",",
"cols",
")",
"rows",
"=",
"rows",
".",
"first",
"cols",
"=",
"cols",
".",
"first",
"[",
"rows",
",",
"cols",
"]",
"end"
] | Return window dimensions as an array containing rows & cols | [
"Return",
"window",
"dimensions",
"as",
"an",
"array",
"containing",
"rows",
"&",
"cols"
] | 3e78c64e677f69b22f00dc89c2b515b9188c5e15 | https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/window.rb#L505-L512 |
24,579 | chef-workflow/chef-workflow | lib/chef-workflow/support/ip.rb | ChefWorkflow.IPSupport.next_ip | def next_ip(arg)
octets = arg.split(/\./, 4).map(&:to_i)
octets[3] += 1
raise "out of ips!" if octets[3] > 255
return octets.map(&:to_s).join(".")
end | ruby | def next_ip(arg)
octets = arg.split(/\./, 4).map(&:to_i)
octets[3] += 1
raise "out of ips!" if octets[3] > 255
return octets.map(&:to_s).join(".")
end | [
"def",
"next_ip",
"(",
"arg",
")",
"octets",
"=",
"arg",
".",
"split",
"(",
"/",
"\\.",
"/",
",",
"4",
")",
".",
"map",
"(",
":to_i",
")",
"octets",
"[",
"3",
"]",
"+=",
"1",
"raise",
"\"out of ips!\"",
"if",
"octets",
"[",
"3",
"]",
">",
"255",
"return",
"octets",
".",
"map",
"(",
":to_s",
")",
".",
"join",
"(",
"\".\"",
")",
"end"
] | Gets the next unallocated IP, given an IP to start with. | [
"Gets",
"the",
"next",
"unallocated",
"IP",
"given",
"an",
"IP",
"to",
"start",
"with",
"."
] | 956c8f6cd694dacc25dfa405d70b05b12b7c1691 | https://github.com/chef-workflow/chef-workflow/blob/956c8f6cd694dacc25dfa405d70b05b12b7c1691/lib/chef-workflow/support/ip.rb#L44-L49 |
24,580 | devp/sanitize_attributes | lib/sanitize_attributes/instance_methods.rb | SanitizeAttributes.InstanceMethods.sanitize! | def sanitize!
self.class.sanitizable_attributes.each do |attr_name|
cleaned_text = process_text_via_sanitization_method(self.send(attr_name), attr_name)
self.send((attr_name.to_s + '='), cleaned_text)
end
end | ruby | def sanitize!
self.class.sanitizable_attributes.each do |attr_name|
cleaned_text = process_text_via_sanitization_method(self.send(attr_name), attr_name)
self.send((attr_name.to_s + '='), cleaned_text)
end
end | [
"def",
"sanitize!",
"self",
".",
"class",
".",
"sanitizable_attributes",
".",
"each",
"do",
"|",
"attr_name",
"|",
"cleaned_text",
"=",
"process_text_via_sanitization_method",
"(",
"self",
".",
"send",
"(",
"attr_name",
")",
",",
"attr_name",
")",
"self",
".",
"send",
"(",
"(",
"attr_name",
".",
"to_s",
"+",
"'='",
")",
",",
"cleaned_text",
")",
"end",
"end"
] | sanitize! is the method that is called when a model is saved.
It can be called to manually sanitize attributes. | [
"sanitize!",
"is",
"the",
"method",
"that",
"is",
"called",
"when",
"a",
"model",
"is",
"saved",
".",
"It",
"can",
"be",
"called",
"to",
"manually",
"sanitize",
"attributes",
"."
] | 75f482b58d0b82a84b70658dd752d4c5b6ea9f02 | https://github.com/devp/sanitize_attributes/blob/75f482b58d0b82a84b70658dd752d4c5b6ea9f02/lib/sanitize_attributes/instance_methods.rb#L6-L11 |
24,581 | kevgo/active_cucumber | lib/active_cucumber/creator.rb | ActiveCucumber.Creator.factorygirl_attributes | def factorygirl_attributes
symbolize_attributes!
@attributes.each do |key, value|
next unless respond_to?(method = method_name(key))
if (result = send method, value) || value.nil?
@attributes[key] = result if @attributes.key? key
else
@attributes.delete key
end
end
end | ruby | def factorygirl_attributes
symbolize_attributes!
@attributes.each do |key, value|
next unless respond_to?(method = method_name(key))
if (result = send method, value) || value.nil?
@attributes[key] = result if @attributes.key? key
else
@attributes.delete key
end
end
end | [
"def",
"factorygirl_attributes",
"symbolize_attributes!",
"@attributes",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"next",
"unless",
"respond_to?",
"(",
"method",
"=",
"method_name",
"(",
"key",
")",
")",
"if",
"(",
"result",
"=",
"send",
"method",
",",
"value",
")",
"||",
"value",
".",
"nil?",
"@attributes",
"[",
"key",
"]",
"=",
"result",
"if",
"@attributes",
".",
"key?",
"key",
"else",
"@attributes",
".",
"delete",
"key",
"end",
"end",
"end"
] | Returns the FactoryGirl version of this Creator's attributes | [
"Returns",
"the",
"FactoryGirl",
"version",
"of",
"this",
"Creator",
"s",
"attributes"
] | 9f3609abbfe2c4c3534c2c64d2f638a6bb6347cf | https://github.com/kevgo/active_cucumber/blob/9f3609abbfe2c4c3534c2c64d2f638a6bb6347cf/lib/active_cucumber/creator.rb#L18-L28 |
24,582 | jhass/configurate | lib/configurate/lookup_chain.rb | Configurate.LookupChain.add_provider | def add_provider(provider, *args)
unless provider.respond_to?(:instance_methods) && provider.instance_methods.include?(:lookup)
raise ArgumentError, "the given provider does not respond to lookup"
end
@provider << provider.new(*args)
end | ruby | def add_provider(provider, *args)
unless provider.respond_to?(:instance_methods) && provider.instance_methods.include?(:lookup)
raise ArgumentError, "the given provider does not respond to lookup"
end
@provider << provider.new(*args)
end | [
"def",
"add_provider",
"(",
"provider",
",",
"*",
"args",
")",
"unless",
"provider",
".",
"respond_to?",
"(",
":instance_methods",
")",
"&&",
"provider",
".",
"instance_methods",
".",
"include?",
"(",
":lookup",
")",
"raise",
"ArgumentError",
",",
"\"the given provider does not respond to lookup\"",
"end",
"@provider",
"<<",
"provider",
".",
"new",
"(",
"args",
")",
"end"
] | Adds a provider to the chain. Providers are tried in the order
they are added, so the order is important.
@param provider [#lookup]
@param *args the arguments passed to the providers constructor
@raise [ArgumentError] if an invalid provider is given
@return [void] | [
"Adds",
"a",
"provider",
"to",
"the",
"chain",
".",
"Providers",
"are",
"tried",
"in",
"the",
"order",
"they",
"are",
"added",
"so",
"the",
"order",
"is",
"important",
"."
] | ace8ef4705d81d4623a144db289051c16da58978 | https://github.com/jhass/configurate/blob/ace8ef4705d81d4623a144db289051c16da58978/lib/configurate/lookup_chain.rb#L16-L22 |
24,583 | jhass/configurate | lib/configurate/lookup_chain.rb | Configurate.LookupChain.lookup | def lookup(setting, *args)
setting = SettingPath.new setting if setting.is_a? String
@provider.each do |provider|
begin
return special_value_or_string(provider.lookup(setting.clone, *args))
rescue SettingNotFoundError; end
end
nil
end | ruby | def lookup(setting, *args)
setting = SettingPath.new setting if setting.is_a? String
@provider.each do |provider|
begin
return special_value_or_string(provider.lookup(setting.clone, *args))
rescue SettingNotFoundError; end
end
nil
end | [
"def",
"lookup",
"(",
"setting",
",",
"*",
"args",
")",
"setting",
"=",
"SettingPath",
".",
"new",
"setting",
"if",
"setting",
".",
"is_a?",
"String",
"@provider",
".",
"each",
"do",
"|",
"provider",
"|",
"begin",
"return",
"special_value_or_string",
"(",
"provider",
".",
"lookup",
"(",
"setting",
".",
"clone",
",",
"args",
")",
")",
"rescue",
"SettingNotFoundError",
";",
"end",
"end",
"nil",
"end"
] | Tries all providers in the order they were added to provide a response
for setting.
@param setting [SettingPath,String] nested settings as strings should
be separated by a dot
@param ... further args passed to the provider
@return [Array,Hash,String,Boolean,nil] whatever the responding
provider provides is casted to a {String}, except for some special values | [
"Tries",
"all",
"providers",
"in",
"the",
"order",
"they",
"were",
"added",
"to",
"provide",
"a",
"response",
"for",
"setting",
"."
] | ace8ef4705d81d4623a144db289051c16da58978 | https://github.com/jhass/configurate/blob/ace8ef4705d81d4623a144db289051c16da58978/lib/configurate/lookup_chain.rb#L32-L41 |
24,584 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.build_dir | def build_dir(src_dir, obj_dir)
if src_dir.is_a?(String)
src_dir = src_dir.gsub("\\", "/").sub(%r{/*$}, "")
end
@build_dirs.unshift([src_dir, obj_dir])
end | ruby | def build_dir(src_dir, obj_dir)
if src_dir.is_a?(String)
src_dir = src_dir.gsub("\\", "/").sub(%r{/*$}, "")
end
@build_dirs.unshift([src_dir, obj_dir])
end | [
"def",
"build_dir",
"(",
"src_dir",
",",
"obj_dir",
")",
"if",
"src_dir",
".",
"is_a?",
"(",
"String",
")",
"src_dir",
"=",
"src_dir",
".",
"gsub",
"(",
"\"\\\\\"",
",",
"\"/\"",
")",
".",
"sub",
"(",
"%r{",
"}",
",",
"\"\"",
")",
"end",
"@build_dirs",
".",
"unshift",
"(",
"[",
"src_dir",
",",
"obj_dir",
"]",
")",
"end"
] | Specify a build directory for this Environment.
Source files from src_dir will produce object files under obj_dir.
@param src_dir [String, Regexp]
Path to the source directory. If a Regexp is given, it will be matched
to source file names.
@param obj_dir [String]
Path to the object directory. If a Regexp is given as src_dir, then
obj_dir can contain backreferences to groups matched from the source
file name.
@return [void] | [
"Specify",
"a",
"build",
"directory",
"for",
"this",
"Environment",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L228-L233 |
24,585 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.process | def process
cache = Cache.instance
failure = nil
begin
while @job_set.size > 0 or @threaded_commands.size > 0
if failure
@job_set.clear!
job = nil
else
targets_still_building = @threaded_commands.map do |tc|
tc.build_operation[:target]
end
job = @job_set.get_next_job_to_run(targets_still_building)
end
# TODO: have Cache determine when checksums may be invalid based on
# file size and/or timestamp.
cache.clear_checksum_cache!
if job
result = run_builder(job[:builder],
job[:target],
job[:sources],
cache,
job[:vars],
allow_delayed_execution: true,
setup_info: job[:setup_info])
unless result
failure = "Failed to build #{job[:target]}"
Ansi.write($stderr, :red, failure, :reset, "\n")
next
end
end
completed_tcs = Set.new
# First do a non-blocking wait to pick up any threads that have
# completed since last time.
while tc = wait_for_threaded_commands(nonblock: true)
completed_tcs << tc
end
# If needed, do a blocking wait.
if (@threaded_commands.size > 0) and
((completed_tcs.empty? and job.nil?) or (@threaded_commands.size >= n_threads))
completed_tcs << wait_for_threaded_commands
end
# Process all completed {ThreadedCommand} objects.
completed_tcs.each do |tc|
result = finalize_builder(tc)
if result
@build_hooks[:post].each do |build_hook_block|
build_hook_block.call(tc.build_operation)
end
else
unless @echo == :command
print_failed_command(tc.command)
end
failure = "Failed to build #{tc.build_operation[:target]}"
Ansi.write($stderr, :red, failure, :reset, "\n")
break
end
end
end
ensure
cache.write
end
if failure
raise BuildError.new(failure)
end
end | ruby | def process
cache = Cache.instance
failure = nil
begin
while @job_set.size > 0 or @threaded_commands.size > 0
if failure
@job_set.clear!
job = nil
else
targets_still_building = @threaded_commands.map do |tc|
tc.build_operation[:target]
end
job = @job_set.get_next_job_to_run(targets_still_building)
end
# TODO: have Cache determine when checksums may be invalid based on
# file size and/or timestamp.
cache.clear_checksum_cache!
if job
result = run_builder(job[:builder],
job[:target],
job[:sources],
cache,
job[:vars],
allow_delayed_execution: true,
setup_info: job[:setup_info])
unless result
failure = "Failed to build #{job[:target]}"
Ansi.write($stderr, :red, failure, :reset, "\n")
next
end
end
completed_tcs = Set.new
# First do a non-blocking wait to pick up any threads that have
# completed since last time.
while tc = wait_for_threaded_commands(nonblock: true)
completed_tcs << tc
end
# If needed, do a blocking wait.
if (@threaded_commands.size > 0) and
((completed_tcs.empty? and job.nil?) or (@threaded_commands.size >= n_threads))
completed_tcs << wait_for_threaded_commands
end
# Process all completed {ThreadedCommand} objects.
completed_tcs.each do |tc|
result = finalize_builder(tc)
if result
@build_hooks[:post].each do |build_hook_block|
build_hook_block.call(tc.build_operation)
end
else
unless @echo == :command
print_failed_command(tc.command)
end
failure = "Failed to build #{tc.build_operation[:target]}"
Ansi.write($stderr, :red, failure, :reset, "\n")
break
end
end
end
ensure
cache.write
end
if failure
raise BuildError.new(failure)
end
end | [
"def",
"process",
"cache",
"=",
"Cache",
".",
"instance",
"failure",
"=",
"nil",
"begin",
"while",
"@job_set",
".",
"size",
">",
"0",
"or",
"@threaded_commands",
".",
"size",
">",
"0",
"if",
"failure",
"@job_set",
".",
"clear!",
"job",
"=",
"nil",
"else",
"targets_still_building",
"=",
"@threaded_commands",
".",
"map",
"do",
"|",
"tc",
"|",
"tc",
".",
"build_operation",
"[",
":target",
"]",
"end",
"job",
"=",
"@job_set",
".",
"get_next_job_to_run",
"(",
"targets_still_building",
")",
"end",
"# TODO: have Cache determine when checksums may be invalid based on",
"# file size and/or timestamp.",
"cache",
".",
"clear_checksum_cache!",
"if",
"job",
"result",
"=",
"run_builder",
"(",
"job",
"[",
":builder",
"]",
",",
"job",
"[",
":target",
"]",
",",
"job",
"[",
":sources",
"]",
",",
"cache",
",",
"job",
"[",
":vars",
"]",
",",
"allow_delayed_execution",
":",
"true",
",",
"setup_info",
":",
"job",
"[",
":setup_info",
"]",
")",
"unless",
"result",
"failure",
"=",
"\"Failed to build #{job[:target]}\"",
"Ansi",
".",
"write",
"(",
"$stderr",
",",
":red",
",",
"failure",
",",
":reset",
",",
"\"\\n\"",
")",
"next",
"end",
"end",
"completed_tcs",
"=",
"Set",
".",
"new",
"# First do a non-blocking wait to pick up any threads that have",
"# completed since last time.",
"while",
"tc",
"=",
"wait_for_threaded_commands",
"(",
"nonblock",
":",
"true",
")",
"completed_tcs",
"<<",
"tc",
"end",
"# If needed, do a blocking wait.",
"if",
"(",
"@threaded_commands",
".",
"size",
">",
"0",
")",
"and",
"(",
"(",
"completed_tcs",
".",
"empty?",
"and",
"job",
".",
"nil?",
")",
"or",
"(",
"@threaded_commands",
".",
"size",
">=",
"n_threads",
")",
")",
"completed_tcs",
"<<",
"wait_for_threaded_commands",
"end",
"# Process all completed {ThreadedCommand} objects.",
"completed_tcs",
".",
"each",
"do",
"|",
"tc",
"|",
"result",
"=",
"finalize_builder",
"(",
"tc",
")",
"if",
"result",
"@build_hooks",
"[",
":post",
"]",
".",
"each",
"do",
"|",
"build_hook_block",
"|",
"build_hook_block",
".",
"call",
"(",
"tc",
".",
"build_operation",
")",
"end",
"else",
"unless",
"@echo",
"==",
":command",
"print_failed_command",
"(",
"tc",
".",
"command",
")",
"end",
"failure",
"=",
"\"Failed to build #{tc.build_operation[:target]}\"",
"Ansi",
".",
"write",
"(",
"$stderr",
",",
":red",
",",
"failure",
",",
":reset",
",",
"\"\\n\"",
")",
"break",
"end",
"end",
"end",
"ensure",
"cache",
".",
"write",
"end",
"if",
"failure",
"raise",
"BuildError",
".",
"new",
"(",
"failure",
")",
"end",
"end"
] | Build all build targets specified in the Environment.
When a block is passed to Environment.new, this method is automatically
called after the block returns.
@return [void] | [
"Build",
"all",
"build",
"targets",
"specified",
"in",
"the",
"Environment",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L305-L377 |
24,586 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.expand_varref | def expand_varref(varref, extra_vars = nil)
vars = if extra_vars.nil?
@varset
else
@varset.merge(extra_vars)
end
lambda_args = [env: self, vars: vars]
vars.expand_varref(varref, lambda_args)
end | ruby | def expand_varref(varref, extra_vars = nil)
vars = if extra_vars.nil?
@varset
else
@varset.merge(extra_vars)
end
lambda_args = [env: self, vars: vars]
vars.expand_varref(varref, lambda_args)
end | [
"def",
"expand_varref",
"(",
"varref",
",",
"extra_vars",
"=",
"nil",
")",
"vars",
"=",
"if",
"extra_vars",
".",
"nil?",
"@varset",
"else",
"@varset",
".",
"merge",
"(",
"extra_vars",
")",
"end",
"lambda_args",
"=",
"[",
"env",
":",
"self",
",",
"vars",
":",
"vars",
"]",
"vars",
".",
"expand_varref",
"(",
"varref",
",",
"lambda_args",
")",
"end"
] | Expand a construction variable reference.
@param varref [nil, String, Array, Proc, Symbol, TrueClass, FalseClass] Variable reference to expand.
@param extra_vars [Hash, VarSet]
Extra variables to use in addition to (or replace) the Environment's
construction variables when expanding the variable reference.
@return [nil, String, Array, Symbol, TrueClass, FalseClass] Expansion of the variable reference. | [
"Expand",
"a",
"construction",
"variable",
"reference",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L394-L402 |
24,587 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.execute | def execute(short_desc, command, options = {})
print_builder_run_message(short_desc, command)
env_args = options[:env] ? [options[:env]] : []
options_args = options[:options] ? [options[:options]] : []
system(*env_args, *Rscons.command_executer, *command, *options_args).tap do |result|
unless result or @echo == :command
print_failed_command(command)
end
end
end | ruby | def execute(short_desc, command, options = {})
print_builder_run_message(short_desc, command)
env_args = options[:env] ? [options[:env]] : []
options_args = options[:options] ? [options[:options]] : []
system(*env_args, *Rscons.command_executer, *command, *options_args).tap do |result|
unless result or @echo == :command
print_failed_command(command)
end
end
end | [
"def",
"execute",
"(",
"short_desc",
",",
"command",
",",
"options",
"=",
"{",
"}",
")",
"print_builder_run_message",
"(",
"short_desc",
",",
"command",
")",
"env_args",
"=",
"options",
"[",
":env",
"]",
"?",
"[",
"options",
"[",
":env",
"]",
"]",
":",
"[",
"]",
"options_args",
"=",
"options",
"[",
":options",
"]",
"?",
"[",
"options",
"[",
":options",
"]",
"]",
":",
"[",
"]",
"system",
"(",
"env_args",
",",
"Rscons",
".",
"command_executer",
",",
"command",
",",
"options_args",
")",
".",
"tap",
"do",
"|",
"result",
"|",
"unless",
"result",
"or",
"@echo",
"==",
":command",
"print_failed_command",
"(",
"command",
")",
"end",
"end",
"end"
] | Execute a builder command.
@param short_desc [String] Message to print if the Environment's echo
mode is set to :short
@param command [Array] The command to execute.
@param options [Hash] Optional options, possible keys:
- :env - environment Hash to pass to Kernel#system.
- :options - options Hash to pass to Kernel#system.
@return [true,false,nil] Return value from Kernel.system(). | [
"Execute",
"a",
"builder",
"command",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L415-L424 |
24,588 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.method_missing | def method_missing(method, *args)
if @builders.has_key?(method.to_s)
target, sources, vars, *rest = args
vars ||= {}
unless vars.is_a?(Hash) or vars.is_a?(VarSet)
raise "Unexpected construction variable set: #{vars.inspect}"
end
builder = @builders[method.to_s]
target = expand_path(expand_varref(target))
sources = Array(sources).map do |source|
expand_path(expand_varref(source))
end.flatten
build_target = builder.create_build_target(env: self, target: target, sources: sources, vars: vars)
add_target(build_target.to_s, builder, sources, vars, rest)
build_target
else
super
end
end | ruby | def method_missing(method, *args)
if @builders.has_key?(method.to_s)
target, sources, vars, *rest = args
vars ||= {}
unless vars.is_a?(Hash) or vars.is_a?(VarSet)
raise "Unexpected construction variable set: #{vars.inspect}"
end
builder = @builders[method.to_s]
target = expand_path(expand_varref(target))
sources = Array(sources).map do |source|
expand_path(expand_varref(source))
end.flatten
build_target = builder.create_build_target(env: self, target: target, sources: sources, vars: vars)
add_target(build_target.to_s, builder, sources, vars, rest)
build_target
else
super
end
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
")",
"if",
"@builders",
".",
"has_key?",
"(",
"method",
".",
"to_s",
")",
"target",
",",
"sources",
",",
"vars",
",",
"*",
"rest",
"=",
"args",
"vars",
"||=",
"{",
"}",
"unless",
"vars",
".",
"is_a?",
"(",
"Hash",
")",
"or",
"vars",
".",
"is_a?",
"(",
"VarSet",
")",
"raise",
"\"Unexpected construction variable set: #{vars.inspect}\"",
"end",
"builder",
"=",
"@builders",
"[",
"method",
".",
"to_s",
"]",
"target",
"=",
"expand_path",
"(",
"expand_varref",
"(",
"target",
")",
")",
"sources",
"=",
"Array",
"(",
"sources",
")",
".",
"map",
"do",
"|",
"source",
"|",
"expand_path",
"(",
"expand_varref",
"(",
"source",
")",
")",
"end",
".",
"flatten",
"build_target",
"=",
"builder",
".",
"create_build_target",
"(",
"env",
":",
"self",
",",
"target",
":",
"target",
",",
"sources",
":",
"sources",
",",
"vars",
":",
"vars",
")",
"add_target",
"(",
"build_target",
".",
"to_s",
",",
"builder",
",",
"sources",
",",
"vars",
",",
"rest",
")",
"build_target",
"else",
"super",
"end",
"end"
] | Define a build target.
@param method [Symbol] Method name.
@param args [Array] Method arguments.
@return [BuildTarget]
The {BuildTarget} object registered, if the method called is a
{Builder}. | [
"Define",
"a",
"build",
"target",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L434-L452 |
24,589 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.depends | def depends(target, *user_deps)
target = expand_varref(target.to_s)
user_deps = user_deps.map {|ud| expand_varref(ud)}
@user_deps[target] ||= []
@user_deps[target] = (@user_deps[target] + user_deps).uniq
build_after(target, user_deps)
end | ruby | def depends(target, *user_deps)
target = expand_varref(target.to_s)
user_deps = user_deps.map {|ud| expand_varref(ud)}
@user_deps[target] ||= []
@user_deps[target] = (@user_deps[target] + user_deps).uniq
build_after(target, user_deps)
end | [
"def",
"depends",
"(",
"target",
",",
"*",
"user_deps",
")",
"target",
"=",
"expand_varref",
"(",
"target",
".",
"to_s",
")",
"user_deps",
"=",
"user_deps",
".",
"map",
"{",
"|",
"ud",
"|",
"expand_varref",
"(",
"ud",
")",
"}",
"@user_deps",
"[",
"target",
"]",
"||=",
"[",
"]",
"@user_deps",
"[",
"target",
"]",
"=",
"(",
"@user_deps",
"[",
"target",
"]",
"+",
"user_deps",
")",
".",
"uniq",
"build_after",
"(",
"target",
",",
"user_deps",
")",
"end"
] | Manually record a given target as depending on the specified files.
@param target [String,BuildTarget] Target file.
@param user_deps [Array<String>] Dependency files.
@return [void] | [
"Manually",
"record",
"a",
"given",
"target",
"as",
"depending",
"on",
"the",
"specified",
"files",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L460-L466 |
24,590 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.build_sources | def build_sources(sources, suffixes, cache, vars)
sources.map do |source|
if source.end_with?(*suffixes)
source
else
converted = nil
suffixes.each do |suffix|
converted_fname = get_build_fname(source, suffix)
if builder = find_builder_for(converted_fname, source, [])
converted = run_builder(builder, converted_fname, [source], cache, vars)
return nil unless converted
break
end
end
converted or raise "Could not find a builder to handle #{source.inspect}."
end
end
end | ruby | def build_sources(sources, suffixes, cache, vars)
sources.map do |source|
if source.end_with?(*suffixes)
source
else
converted = nil
suffixes.each do |suffix|
converted_fname = get_build_fname(source, suffix)
if builder = find_builder_for(converted_fname, source, [])
converted = run_builder(builder, converted_fname, [source], cache, vars)
return nil unless converted
break
end
end
converted or raise "Could not find a builder to handle #{source.inspect}."
end
end
end | [
"def",
"build_sources",
"(",
"sources",
",",
"suffixes",
",",
"cache",
",",
"vars",
")",
"sources",
".",
"map",
"do",
"|",
"source",
"|",
"if",
"source",
".",
"end_with?",
"(",
"suffixes",
")",
"source",
"else",
"converted",
"=",
"nil",
"suffixes",
".",
"each",
"do",
"|",
"suffix",
"|",
"converted_fname",
"=",
"get_build_fname",
"(",
"source",
",",
"suffix",
")",
"if",
"builder",
"=",
"find_builder_for",
"(",
"converted_fname",
",",
"source",
",",
"[",
"]",
")",
"converted",
"=",
"run_builder",
"(",
"builder",
",",
"converted_fname",
",",
"[",
"source",
"]",
",",
"cache",
",",
"vars",
")",
"return",
"nil",
"unless",
"converted",
"break",
"end",
"end",
"converted",
"or",
"raise",
"\"Could not find a builder to handle #{source.inspect}.\"",
"end",
"end",
"end"
] | Build a list of source files into files containing one of the suffixes
given by suffixes.
This method is used internally by Rscons builders.
@deprecated Use {#register_builds} instead.
@param sources [Array<String>] List of source files to build.
@param suffixes [Array<String>]
List of suffixes to try to convert source files into.
@param cache [Cache] The Cache.
@param vars [Hash] Extra variables to pass to the builder.
@return [Array<String>] List of the converted file name(s). | [
"Build",
"a",
"list",
"of",
"source",
"files",
"into",
"files",
"containing",
"one",
"of",
"the",
"suffixes",
"given",
"by",
"suffixes",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L551-L568 |
24,591 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.register_builds | def register_builds(target, sources, suffixes, vars, options = {})
options[:features] ||= []
@registered_build_dependencies[target] ||= Set.new
sources.map do |source|
if source.end_with?(*suffixes)
source
else
output_fname = nil
suffixes.each do |suffix|
attempt_output_fname = get_build_fname(source, suffix, features: options[:features])
if builder = find_builder_for(attempt_output_fname, source, options[:features])
output_fname = attempt_output_fname
self.__send__(builder.name, output_fname, source, vars)
@registered_build_dependencies[target] << output_fname
break
end
end
output_fname or raise "Could not find a builder for #{source.inspect}."
end
end
end | ruby | def register_builds(target, sources, suffixes, vars, options = {})
options[:features] ||= []
@registered_build_dependencies[target] ||= Set.new
sources.map do |source|
if source.end_with?(*suffixes)
source
else
output_fname = nil
suffixes.each do |suffix|
attempt_output_fname = get_build_fname(source, suffix, features: options[:features])
if builder = find_builder_for(attempt_output_fname, source, options[:features])
output_fname = attempt_output_fname
self.__send__(builder.name, output_fname, source, vars)
@registered_build_dependencies[target] << output_fname
break
end
end
output_fname or raise "Could not find a builder for #{source.inspect}."
end
end
end | [
"def",
"register_builds",
"(",
"target",
",",
"sources",
",",
"suffixes",
",",
"vars",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":features",
"]",
"||=",
"[",
"]",
"@registered_build_dependencies",
"[",
"target",
"]",
"||=",
"Set",
".",
"new",
"sources",
".",
"map",
"do",
"|",
"source",
"|",
"if",
"source",
".",
"end_with?",
"(",
"suffixes",
")",
"source",
"else",
"output_fname",
"=",
"nil",
"suffixes",
".",
"each",
"do",
"|",
"suffix",
"|",
"attempt_output_fname",
"=",
"get_build_fname",
"(",
"source",
",",
"suffix",
",",
"features",
":",
"options",
"[",
":features",
"]",
")",
"if",
"builder",
"=",
"find_builder_for",
"(",
"attempt_output_fname",
",",
"source",
",",
"options",
"[",
":features",
"]",
")",
"output_fname",
"=",
"attempt_output_fname",
"self",
".",
"__send__",
"(",
"builder",
".",
"name",
",",
"output_fname",
",",
"source",
",",
"vars",
")",
"@registered_build_dependencies",
"[",
"target",
"]",
"<<",
"output_fname",
"break",
"end",
"end",
"output_fname",
"or",
"raise",
"\"Could not find a builder for #{source.inspect}.\"",
"end",
"end",
"end"
] | Find and register builders to build source files into files containing
one of the suffixes given by suffixes.
This method is used internally by Rscons builders. It should be called
from the builder's #setup method.
@since 1.10.0
@param target [String]
The target that depends on these builds.
@param sources [Array<String>]
List of source file(s) to build.
@param suffixes [Array<String>]
List of suffixes to try to convert source files into.
@param vars [Hash]
Extra variables to pass to the builders.
@param options [Hash]
Extra options.
@option options [Array<String>] :features
Set of features the builder must provide. Each feature can be proceeded
by a "-" character to indicate that the builder must /not/ provide the
given feature.
* shared - builder builds a shared object/library
@return [Array<String>]
List of the output file name(s). | [
"Find",
"and",
"register",
"builders",
"to",
"build",
"source",
"files",
"into",
"files",
"containing",
"one",
"of",
"the",
"suffixes",
"given",
"by",
"suffixes",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L596-L616 |
24,592 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.run_builder | def run_builder(builder, target, sources, cache, vars, options = {})
vars = @varset.merge(vars)
build_operation = {
builder: builder,
target: target,
sources: sources,
cache: cache,
env: self,
vars: vars,
setup_info: options[:setup_info]
}
call_build_hooks = lambda do |sec|
@build_hooks[sec].each do |build_hook_block|
build_hook_block.call(build_operation)
end
end
# Invoke pre-build hooks.
call_build_hooks[:pre]
# Call the builder's #run method.
if builder.method(:run).arity == 5
rv = builder.run(*build_operation.values_at(:target, :sources, :cache, :env, :vars))
else
rv = builder.run(build_operation)
end
if rv.is_a?(ThreadedCommand)
# Store the build operation so the post-build hooks can be called
# with it when the threaded command completes.
rv.build_operation = build_operation
start_threaded_command(rv)
unless options[:allow_delayed_execution]
# Delayed command execution is not allowed, so we need to execute
# the command and finalize the builder now.
tc = wait_for_threaded_commands(which: [rv])
rv = finalize_builder(tc)
if rv
call_build_hooks[:post]
else
unless @echo == :command
print_failed_command(tc.command)
end
end
end
else
call_build_hooks[:post] if rv
end
rv
end | ruby | def run_builder(builder, target, sources, cache, vars, options = {})
vars = @varset.merge(vars)
build_operation = {
builder: builder,
target: target,
sources: sources,
cache: cache,
env: self,
vars: vars,
setup_info: options[:setup_info]
}
call_build_hooks = lambda do |sec|
@build_hooks[sec].each do |build_hook_block|
build_hook_block.call(build_operation)
end
end
# Invoke pre-build hooks.
call_build_hooks[:pre]
# Call the builder's #run method.
if builder.method(:run).arity == 5
rv = builder.run(*build_operation.values_at(:target, :sources, :cache, :env, :vars))
else
rv = builder.run(build_operation)
end
if rv.is_a?(ThreadedCommand)
# Store the build operation so the post-build hooks can be called
# with it when the threaded command completes.
rv.build_operation = build_operation
start_threaded_command(rv)
unless options[:allow_delayed_execution]
# Delayed command execution is not allowed, so we need to execute
# the command and finalize the builder now.
tc = wait_for_threaded_commands(which: [rv])
rv = finalize_builder(tc)
if rv
call_build_hooks[:post]
else
unless @echo == :command
print_failed_command(tc.command)
end
end
end
else
call_build_hooks[:post] if rv
end
rv
end | [
"def",
"run_builder",
"(",
"builder",
",",
"target",
",",
"sources",
",",
"cache",
",",
"vars",
",",
"options",
"=",
"{",
"}",
")",
"vars",
"=",
"@varset",
".",
"merge",
"(",
"vars",
")",
"build_operation",
"=",
"{",
"builder",
":",
"builder",
",",
"target",
":",
"target",
",",
"sources",
":",
"sources",
",",
"cache",
":",
"cache",
",",
"env",
":",
"self",
",",
"vars",
":",
"vars",
",",
"setup_info",
":",
"options",
"[",
":setup_info",
"]",
"}",
"call_build_hooks",
"=",
"lambda",
"do",
"|",
"sec",
"|",
"@build_hooks",
"[",
"sec",
"]",
".",
"each",
"do",
"|",
"build_hook_block",
"|",
"build_hook_block",
".",
"call",
"(",
"build_operation",
")",
"end",
"end",
"# Invoke pre-build hooks.",
"call_build_hooks",
"[",
":pre",
"]",
"# Call the builder's #run method.",
"if",
"builder",
".",
"method",
"(",
":run",
")",
".",
"arity",
"==",
"5",
"rv",
"=",
"builder",
".",
"run",
"(",
"build_operation",
".",
"values_at",
"(",
":target",
",",
":sources",
",",
":cache",
",",
":env",
",",
":vars",
")",
")",
"else",
"rv",
"=",
"builder",
".",
"run",
"(",
"build_operation",
")",
"end",
"if",
"rv",
".",
"is_a?",
"(",
"ThreadedCommand",
")",
"# Store the build operation so the post-build hooks can be called",
"# with it when the threaded command completes.",
"rv",
".",
"build_operation",
"=",
"build_operation",
"start_threaded_command",
"(",
"rv",
")",
"unless",
"options",
"[",
":allow_delayed_execution",
"]",
"# Delayed command execution is not allowed, so we need to execute",
"# the command and finalize the builder now.",
"tc",
"=",
"wait_for_threaded_commands",
"(",
"which",
":",
"[",
"rv",
"]",
")",
"rv",
"=",
"finalize_builder",
"(",
"tc",
")",
"if",
"rv",
"call_build_hooks",
"[",
":post",
"]",
"else",
"unless",
"@echo",
"==",
":command",
"print_failed_command",
"(",
"tc",
".",
"command",
")",
"end",
"end",
"end",
"else",
"call_build_hooks",
"[",
":post",
"]",
"if",
"rv",
"end",
"rv",
"end"
] | Invoke a builder to build the given target based on the given sources.
@param builder [Builder] The Builder to use.
@param target [String] The target output file.
@param sources [Array<String>] List of source files.
@param cache [Cache] The Cache.
@param vars [Hash] Extra variables to pass to the builder.
@param options [Hash]
@since 1.10.0
Options.
@option options [Boolean] :allow_delayed_execution
@since 1.10.0
Allow a threaded command to be scheduled but not yet completed before
this method returns.
@option options [Object] :setup_info
Arbitrary builder info returned by Builder#setup.
@return [String,false] Return value from the {Builder}'s +run+ method. | [
"Invoke",
"a",
"builder",
"to",
"build",
"the",
"given",
"target",
"based",
"on",
"the",
"given",
"sources",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L636-L686 |
24,593 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.expand_path | def expand_path(path)
if Rscons.phony_target?(path)
path
elsif path.is_a?(Array)
path.map do |path|
expand_path(path)
end
else
path.sub(%r{^\^(?=[\\/])}, @build_root).gsub("\\", "/")
end
end | ruby | def expand_path(path)
if Rscons.phony_target?(path)
path
elsif path.is_a?(Array)
path.map do |path|
expand_path(path)
end
else
path.sub(%r{^\^(?=[\\/])}, @build_root).gsub("\\", "/")
end
end | [
"def",
"expand_path",
"(",
"path",
")",
"if",
"Rscons",
".",
"phony_target?",
"(",
"path",
")",
"path",
"elsif",
"path",
".",
"is_a?",
"(",
"Array",
")",
"path",
".",
"map",
"do",
"|",
"path",
"|",
"expand_path",
"(",
"path",
")",
"end",
"else",
"path",
".",
"sub",
"(",
"%r{",
"\\^",
"\\\\",
"}",
",",
"@build_root",
")",
".",
"gsub",
"(",
"\"\\\\\"",
",",
"\"/\"",
")",
"end",
"end"
] | Expand a path to be relative to the Environment's build root.
Paths beginning with "^/" are expanded by replacing "^" with the
Environment's build root.
@param path [String, Array<String>]
The path(s) to expand.
@return [String, Array<String>]
The expanded path(s). | [
"Expand",
"a",
"path",
"to",
"be",
"relative",
"to",
"the",
"Environment",
"s",
"build",
"root",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L698-L708 |
24,594 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.shell | def shell(command)
shell_cmd =
if self["SHELL"]
flag = self["SHELLFLAG"] || (self["SHELL"] == "cmd" ? "/c" : "-c")
[self["SHELL"], flag]
else
Rscons.get_system_shell
end
IO.popen([*shell_cmd, command]) do |io|
io.read
end
end | ruby | def shell(command)
shell_cmd =
if self["SHELL"]
flag = self["SHELLFLAG"] || (self["SHELL"] == "cmd" ? "/c" : "-c")
[self["SHELL"], flag]
else
Rscons.get_system_shell
end
IO.popen([*shell_cmd, command]) do |io|
io.read
end
end | [
"def",
"shell",
"(",
"command",
")",
"shell_cmd",
"=",
"if",
"self",
"[",
"\"SHELL\"",
"]",
"flag",
"=",
"self",
"[",
"\"SHELLFLAG\"",
"]",
"||",
"(",
"self",
"[",
"\"SHELL\"",
"]",
"==",
"\"cmd\"",
"?",
"\"/c\"",
":",
"\"-c\"",
")",
"[",
"self",
"[",
"\"SHELL\"",
"]",
",",
"flag",
"]",
"else",
"Rscons",
".",
"get_system_shell",
"end",
"IO",
".",
"popen",
"(",
"[",
"shell_cmd",
",",
"command",
"]",
")",
"do",
"|",
"io",
"|",
"io",
".",
"read",
"end",
"end"
] | Execute a command using the system shell.
The shell is automatically determined but can be overridden by the SHELL
construction variable. If the SHELL construction variable is specified,
the flag to pass to the shell is automatically dtermined but can be
overridden by the SHELLFLAG construction variable.
@param command [String] Command to execute.
@return [String] The command's standard output. | [
"Execute",
"a",
"command",
"using",
"the",
"system",
"shell",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L720-L731 |
24,595 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.merge_flags | def merge_flags(flags)
flags.each_pair do |key, val|
if self[key].is_a?(Array) and val.is_a?(Array)
self[key] += val
else
self[key] = val
end
end
end | ruby | def merge_flags(flags)
flags.each_pair do |key, val|
if self[key].is_a?(Array) and val.is_a?(Array)
self[key] += val
else
self[key] = val
end
end
end | [
"def",
"merge_flags",
"(",
"flags",
")",
"flags",
".",
"each_pair",
"do",
"|",
"key",
",",
"val",
"|",
"if",
"self",
"[",
"key",
"]",
".",
"is_a?",
"(",
"Array",
")",
"and",
"val",
".",
"is_a?",
"(",
"Array",
")",
"self",
"[",
"key",
"]",
"+=",
"val",
"else",
"self",
"[",
"key",
"]",
"=",
"val",
"end",
"end",
"end"
] | Merge construction variable flags into this Environment's construction
variables.
This method does the same thing as {#append}, except that Array values in
+flags+ are appended to the end of Array construction variables instead
of replacing their contents.
@param flags [Hash]
Set of construction variables to merge into the current Environment.
This can be the value (or a modified version) returned by
{#parse_flags}.
@return [void] | [
"Merge",
"construction",
"variable",
"flags",
"into",
"this",
"Environment",
"s",
"construction",
"variables",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L849-L857 |
24,596 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.dump | def dump
varset_hash = @varset.to_h
varset_hash.keys.sort_by(&:to_s).each do |var|
var_str = var.is_a?(Symbol) ? var.inspect : var
Ansi.write($stdout, :cyan, var_str, :reset, " => #{varset_hash[var].inspect}\n")
end
end | ruby | def dump
varset_hash = @varset.to_h
varset_hash.keys.sort_by(&:to_s).each do |var|
var_str = var.is_a?(Symbol) ? var.inspect : var
Ansi.write($stdout, :cyan, var_str, :reset, " => #{varset_hash[var].inspect}\n")
end
end | [
"def",
"dump",
"varset_hash",
"=",
"@varset",
".",
"to_h",
"varset_hash",
".",
"keys",
".",
"sort_by",
"(",
":to_s",
")",
".",
"each",
"do",
"|",
"var",
"|",
"var_str",
"=",
"var",
".",
"is_a?",
"(",
"Symbol",
")",
"?",
"var",
".",
"inspect",
":",
"var",
"Ansi",
".",
"write",
"(",
"$stdout",
",",
":cyan",
",",
"var_str",
",",
":reset",
",",
"\" => #{varset_hash[var].inspect}\\n\"",
")",
"end",
"end"
] | Print the Environment's construction variables for debugging. | [
"Print",
"the",
"Environment",
"s",
"construction",
"variables",
"for",
"debugging",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L860-L866 |
24,597 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.print_builder_run_message | def print_builder_run_message(short_description, command)
case @echo
when :command
if command.is_a?(Array)
message = command_to_s(command)
elsif command.is_a?(String)
message = command
elsif short_description.is_a?(String)
message = short_description
end
when :short
message = short_description if short_description
end
Ansi.write($stdout, :cyan, message, :reset, "\n") if message
end | ruby | def print_builder_run_message(short_description, command)
case @echo
when :command
if command.is_a?(Array)
message = command_to_s(command)
elsif command.is_a?(String)
message = command
elsif short_description.is_a?(String)
message = short_description
end
when :short
message = short_description if short_description
end
Ansi.write($stdout, :cyan, message, :reset, "\n") if message
end | [
"def",
"print_builder_run_message",
"(",
"short_description",
",",
"command",
")",
"case",
"@echo",
"when",
":command",
"if",
"command",
".",
"is_a?",
"(",
"Array",
")",
"message",
"=",
"command_to_s",
"(",
"command",
")",
"elsif",
"command",
".",
"is_a?",
"(",
"String",
")",
"message",
"=",
"command",
"elsif",
"short_description",
".",
"is_a?",
"(",
"String",
")",
"message",
"=",
"short_description",
"end",
"when",
":short",
"message",
"=",
"short_description",
"if",
"short_description",
"end",
"Ansi",
".",
"write",
"(",
"$stdout",
",",
":cyan",
",",
"message",
",",
":reset",
",",
"\"\\n\"",
")",
"if",
"message",
"end"
] | Print the builder run message, depending on the Environment's echo mode.
@param short_description [String]
Builder short description, printed if the echo mode is :short.
@param command [Array<String>]
Builder command, printed if the echo mode is :command.
@return [void] | [
"Print",
"the",
"builder",
"run",
"message",
"depending",
"on",
"the",
"Environment",
"s",
"echo",
"mode",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L885-L899 |
24,598 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.add_target | def add_target(target, builder, sources, vars, args)
setup_info = builder.setup(
target: target,
sources: sources,
env: self,
vars: vars)
@job_set.add_job(
builder: builder,
target: target,
sources: sources,
vars: vars,
setup_info: setup_info)
end | ruby | def add_target(target, builder, sources, vars, args)
setup_info = builder.setup(
target: target,
sources: sources,
env: self,
vars: vars)
@job_set.add_job(
builder: builder,
target: target,
sources: sources,
vars: vars,
setup_info: setup_info)
end | [
"def",
"add_target",
"(",
"target",
",",
"builder",
",",
"sources",
",",
"vars",
",",
"args",
")",
"setup_info",
"=",
"builder",
".",
"setup",
"(",
"target",
":",
"target",
",",
"sources",
":",
"sources",
",",
"env",
":",
"self",
",",
"vars",
":",
"vars",
")",
"@job_set",
".",
"add_job",
"(",
"builder",
":",
"builder",
",",
"target",
":",
"target",
",",
"sources",
":",
"sources",
",",
"vars",
":",
"vars",
",",
"setup_info",
":",
"setup_info",
")",
"end"
] | Add a build target.
@param target [String] Build target file name.
@param builder [Builder] The {Builder} to use to build the target.
@param sources [Array<String>] Source file name(s).
@param vars [Hash] Construction variable overrides.
@param args [Object] Deprecated; unused.
@return [void] | [
"Add",
"a",
"build",
"target",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L922-L934 |
24,599 | holtrop/rscons | lib/rscons/environment.rb | Rscons.Environment.start_threaded_command | def start_threaded_command(tc)
print_builder_run_message(tc.short_description, tc.command)
env_args = tc.system_env ? [tc.system_env] : []
options_args = tc.system_options ? [tc.system_options] : []
system_args = [*env_args, *Rscons.command_executer, *tc.command, *options_args]
tc.thread = Thread.new do
system(*system_args)
end
@threaded_commands << tc
end | ruby | def start_threaded_command(tc)
print_builder_run_message(tc.short_description, tc.command)
env_args = tc.system_env ? [tc.system_env] : []
options_args = tc.system_options ? [tc.system_options] : []
system_args = [*env_args, *Rscons.command_executer, *tc.command, *options_args]
tc.thread = Thread.new do
system(*system_args)
end
@threaded_commands << tc
end | [
"def",
"start_threaded_command",
"(",
"tc",
")",
"print_builder_run_message",
"(",
"tc",
".",
"short_description",
",",
"tc",
".",
"command",
")",
"env_args",
"=",
"tc",
".",
"system_env",
"?",
"[",
"tc",
".",
"system_env",
"]",
":",
"[",
"]",
"options_args",
"=",
"tc",
".",
"system_options",
"?",
"[",
"tc",
".",
"system_options",
"]",
":",
"[",
"]",
"system_args",
"=",
"[",
"env_args",
",",
"Rscons",
".",
"command_executer",
",",
"tc",
".",
"command",
",",
"options_args",
"]",
"tc",
".",
"thread",
"=",
"Thread",
".",
"new",
"do",
"system",
"(",
"system_args",
")",
"end",
"@threaded_commands",
"<<",
"tc",
"end"
] | Start a threaded command in a new thread.
@param tc [ThreadedCommand]
The ThreadedCommand to start.
@return [void] | [
"Start",
"a",
"threaded",
"command",
"in",
"a",
"new",
"thread",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L942-L953 |
Subsets and Splits