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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
19,100
cxn03651/writeexcel
lib/writeexcel/worksheet.rb
Writeexcel.Worksheet.store_images
def store_images #:nodoc: # Skip this if there aren't any images. return if @images.array.empty? spid = @object_ids.spid @images.array.each_index do |i| @images.array[i].store_image_record(i, @images.array.size, charts_size, @filter_area.count, comments_size, spid) store_obj_image(i + 1) end @object_ids.spid = spid end
ruby
def store_images #:nodoc: # Skip this if there aren't any images. return if @images.array.empty? spid = @object_ids.spid @images.array.each_index do |i| @images.array[i].store_image_record(i, @images.array.size, charts_size, @filter_area.count, comments_size, spid) store_obj_image(i + 1) end @object_ids.spid = spid end
[ "def", "store_images", "#:nodoc:", "# Skip this if there aren't any images.", "return", "if", "@images", ".", "array", ".", "empty?", "spid", "=", "@object_ids", ".", "spid", "@images", ".", "array", ".", "each_index", "do", "|", "i", "|", "@images", ".", "array", "[", "i", "]", ".", "store_image_record", "(", "i", ",", "@images", ".", "array", ".", "size", ",", "charts_size", ",", "@filter_area", ".", "count", ",", "comments_size", ",", "spid", ")", "store_obj_image", "(", "i", "+", "1", ")", "end", "@object_ids", ".", "spid", "=", "spid", "end" ]
Store the collections of records that make up images.
[ "Store", "the", "collections", "of", "records", "that", "make", "up", "images", "." ]
d0345067c21b14a7141ba66b6752be8f4be379de
https://github.com/cxn03651/writeexcel/blob/d0345067c21b14a7141ba66b6752be8f4be379de/lib/writeexcel/worksheet.rb#L6614-L6626
19,101
cxn03651/writeexcel
lib/writeexcel/worksheet.rb
Writeexcel.Worksheet.store_charts
def store_charts #:nodoc: # Skip this if there aren't any charts. return if charts_size == 0 record = 0x00EC # Record identifier charts = @charts.array charts.each_index do |i| data = '' if i == 0 && images_size == 0 dg_length = 192 + 120 * (charts_size - 1) + 96 * filter_count + 128 * comments_size spgr_length = dg_length - 24 # Write the parent MSODRAWIING record. data += store_parent_mso_record(dg_length, spgr_length, @object_ids.spid) @object_ids.spid += 1 end data += store_mso_sp_container_sp(@object_ids.spid) data += store_mso_opt_chart_client_anchor_client_data(*charts[i].vertices) length = data.bytesize header = [record, length].pack("vv") append(header, data) store_obj_chart(images_size + i + 1) store_chart_binary(charts[i].chart) @object_ids.spid += 1 end # Simulate the EXTERNSHEET link between the chart and data using a formula # such as '=Sheet1!A1'. # TODO. Won't work for external data refs. Also should use a more direct # method. # store_formula("='#{@name}'!A1") end
ruby
def store_charts #:nodoc: # Skip this if there aren't any charts. return if charts_size == 0 record = 0x00EC # Record identifier charts = @charts.array charts.each_index do |i| data = '' if i == 0 && images_size == 0 dg_length = 192 + 120 * (charts_size - 1) + 96 * filter_count + 128 * comments_size spgr_length = dg_length - 24 # Write the parent MSODRAWIING record. data += store_parent_mso_record(dg_length, spgr_length, @object_ids.spid) @object_ids.spid += 1 end data += store_mso_sp_container_sp(@object_ids.spid) data += store_mso_opt_chart_client_anchor_client_data(*charts[i].vertices) length = data.bytesize header = [record, length].pack("vv") append(header, data) store_obj_chart(images_size + i + 1) store_chart_binary(charts[i].chart) @object_ids.spid += 1 end # Simulate the EXTERNSHEET link between the chart and data using a formula # such as '=Sheet1!A1'. # TODO. Won't work for external data refs. Also should use a more direct # method. # store_formula("='#{@name}'!A1") end
[ "def", "store_charts", "#:nodoc:", "# Skip this if there aren't any charts.", "return", "if", "charts_size", "==", "0", "record", "=", "0x00EC", "# Record identifier", "charts", "=", "@charts", ".", "array", "charts", ".", "each_index", "do", "|", "i", "|", "data", "=", "''", "if", "i", "==", "0", "&&", "images_size", "==", "0", "dg_length", "=", "192", "+", "120", "*", "(", "charts_size", "-", "1", ")", "+", "96", "*", "filter_count", "+", "128", "*", "comments_size", "spgr_length", "=", "dg_length", "-", "24", "# Write the parent MSODRAWIING record.", "data", "+=", "store_parent_mso_record", "(", "dg_length", ",", "spgr_length", ",", "@object_ids", ".", "spid", ")", "@object_ids", ".", "spid", "+=", "1", "end", "data", "+=", "store_mso_sp_container_sp", "(", "@object_ids", ".", "spid", ")", "data", "+=", "store_mso_opt_chart_client_anchor_client_data", "(", "charts", "[", "i", "]", ".", "vertices", ")", "length", "=", "data", ".", "bytesize", "header", "=", "[", "record", ",", "length", "]", ".", "pack", "(", "\"vv\"", ")", "append", "(", "header", ",", "data", ")", "store_obj_chart", "(", "images_size", "+", "i", "+", "1", ")", "store_chart_binary", "(", "charts", "[", "i", "]", ".", "chart", ")", "@object_ids", ".", "spid", "+=", "1", "end", "# Simulate the EXTERNSHEET link between the chart and data using a formula", "# such as '=Sheet1!A1'.", "# TODO. Won't work for external data refs. Also should use a more direct", "# method.", "#", "store_formula", "(", "\"='#{@name}'!A1\"", ")", "end" ]
Store the collections of records that make up charts.
[ "Store", "the", "collections", "of", "records", "that", "make", "up", "charts", "." ]
d0345067c21b14a7141ba66b6752be8f4be379de
https://github.com/cxn03651/writeexcel/blob/d0345067c21b14a7141ba66b6752be8f4be379de/lib/writeexcel/worksheet.rb#L6639-L6674
19,102
cxn03651/writeexcel
lib/writeexcel/worksheet.rb
Writeexcel.Worksheet.store_comments
def store_comments #:nodoc: return if @comments.array.empty? spid = @object_ids.spid num_comments = comments_size # Number of objects written so far. num_objects = images_size + @filter_area.count + charts_size @comments.array.each_index { |i| spid = @comments.array[i].store_comment_record(i, num_objects, num_comments, spid) } # Write the NOTE records after MSODRAWIING records. @comments.array.each_index { |i| @comments.array[i].store_note_record(num_objects + i + 1) } end
ruby
def store_comments #:nodoc: return if @comments.array.empty? spid = @object_ids.spid num_comments = comments_size # Number of objects written so far. num_objects = images_size + @filter_area.count + charts_size @comments.array.each_index { |i| spid = @comments.array[i].store_comment_record(i, num_objects, num_comments, spid) } # Write the NOTE records after MSODRAWIING records. @comments.array.each_index { |i| @comments.array[i].store_note_record(num_objects + i + 1) } end
[ "def", "store_comments", "#:nodoc:", "return", "if", "@comments", ".", "array", ".", "empty?", "spid", "=", "@object_ids", ".", "spid", "num_comments", "=", "comments_size", "# Number of objects written so far.", "num_objects", "=", "images_size", "+", "@filter_area", ".", "count", "+", "charts_size", "@comments", ".", "array", ".", "each_index", "{", "|", "i", "|", "spid", "=", "@comments", ".", "array", "[", "i", "]", ".", "store_comment_record", "(", "i", ",", "num_objects", ",", "num_comments", ",", "spid", ")", "}", "# Write the NOTE records after MSODRAWIING records.", "@comments", ".", "array", ".", "each_index", "{", "|", "i", "|", "@comments", ".", "array", "[", "i", "]", ".", "store_note_record", "(", "num_objects", "+", "i", "+", "1", ")", "}", "end" ]
Store the collections of records that make up cell comments. NOTE: We write the comment objects last since that makes it a little easier to write the NOTE records directly after the MSODRAWIING records.
[ "Store", "the", "collections", "of", "records", "that", "make", "up", "cell", "comments", "." ]
d0345067c21b14a7141ba66b6752be8f4be379de
https://github.com/cxn03651/writeexcel/blob/d0345067c21b14a7141ba66b6752be8f4be379de/lib/writeexcel/worksheet.rb#L6728-L6741
19,103
cxn03651/writeexcel
lib/writeexcel/worksheet.rb
Writeexcel.Worksheet.store_mso_dg_container
def store_mso_dg_container(length) #:nodoc: type = 0xF002 version = 15 instance = 0 data = '' add_mso_generic(type, version, instance, data, length) end
ruby
def store_mso_dg_container(length) #:nodoc: type = 0xF002 version = 15 instance = 0 data = '' add_mso_generic(type, version, instance, data, length) end
[ "def", "store_mso_dg_container", "(", "length", ")", "#:nodoc:", "type", "=", "0xF002", "version", "=", "15", "instance", "=", "0", "data", "=", "''", "add_mso_generic", "(", "type", ",", "version", ",", "instance", ",", "data", ",", "length", ")", "end" ]
Write the Escher DgContainer record that is part of MSODRAWING.
[ "Write", "the", "Escher", "DgContainer", "record", "that", "is", "part", "of", "MSODRAWING", "." ]
d0345067c21b14a7141ba66b6752be8f4be379de
https://github.com/cxn03651/writeexcel/blob/d0345067c21b14a7141ba66b6752be8f4be379de/lib/writeexcel/worksheet.rb#L6746-L6752
19,104
cxn03651/writeexcel
lib/writeexcel/worksheet.rb
Writeexcel.Worksheet.store_mso_dg
def store_mso_dg #:nodoc: type = 0xF008 version = 0 length = 8 data = [@object_ids.num_shapes, @object_ids.max_spid].pack("VV") add_mso_generic(type, version, @object_ids.drawings_saved, data, length) end
ruby
def store_mso_dg #:nodoc: type = 0xF008 version = 0 length = 8 data = [@object_ids.num_shapes, @object_ids.max_spid].pack("VV") add_mso_generic(type, version, @object_ids.drawings_saved, data, length) end
[ "def", "store_mso_dg", "#:nodoc:", "type", "=", "0xF008", "version", "=", "0", "length", "=", "8", "data", "=", "[", "@object_ids", ".", "num_shapes", ",", "@object_ids", ".", "max_spid", "]", ".", "pack", "(", "\"VV\"", ")", "add_mso_generic", "(", "type", ",", "version", ",", "@object_ids", ".", "drawings_saved", ",", "data", ",", "length", ")", "end" ]
Write the Escher Dg record that is part of MSODRAWING.
[ "Write", "the", "Escher", "Dg", "record", "that", "is", "part", "of", "MSODRAWING", "." ]
d0345067c21b14a7141ba66b6752be8f4be379de
https://github.com/cxn03651/writeexcel/blob/d0345067c21b14a7141ba66b6752be8f4be379de/lib/writeexcel/worksheet.rb#L6757-L6764
19,105
cxn03651/writeexcel
lib/writeexcel/worksheet.rb
Writeexcel.Worksheet.store_mso_spgr_container
def store_mso_spgr_container(length) #:nodoc: type = 0xF003 version = 15 instance = 0 data = '' add_mso_generic(type, version, instance, data, length) end
ruby
def store_mso_spgr_container(length) #:nodoc: type = 0xF003 version = 15 instance = 0 data = '' add_mso_generic(type, version, instance, data, length) end
[ "def", "store_mso_spgr_container", "(", "length", ")", "#:nodoc:", "type", "=", "0xF003", "version", "=", "15", "instance", "=", "0", "data", "=", "''", "add_mso_generic", "(", "type", ",", "version", ",", "instance", ",", "data", ",", "length", ")", "end" ]
Write the Escher SpgrContainer record that is part of MSODRAWING.
[ "Write", "the", "Escher", "SpgrContainer", "record", "that", "is", "part", "of", "MSODRAWING", "." ]
d0345067c21b14a7141ba66b6752be8f4be379de
https://github.com/cxn03651/writeexcel/blob/d0345067c21b14a7141ba66b6752be8f4be379de/lib/writeexcel/worksheet.rb#L6769-L6776
19,106
cxn03651/writeexcel
lib/writeexcel/worksheet.rb
Writeexcel.Worksheet.store_mso_spgr
def store_mso_spgr #:nodoc: type = 0xF009 version = 1 instance = 0 data = [0, 0, 0, 0].pack("VVVV") length = 16 add_mso_generic(type, version, instance, data, length) end
ruby
def store_mso_spgr #:nodoc: type = 0xF009 version = 1 instance = 0 data = [0, 0, 0, 0].pack("VVVV") length = 16 add_mso_generic(type, version, instance, data, length) end
[ "def", "store_mso_spgr", "#:nodoc:", "type", "=", "0xF009", "version", "=", "1", "instance", "=", "0", "data", "=", "[", "0", ",", "0", ",", "0", ",", "0", "]", ".", "pack", "(", "\"VVVV\"", ")", "length", "=", "16", "add_mso_generic", "(", "type", ",", "version", ",", "instance", ",", "data", ",", "length", ")", "end" ]
Write the Escher Spgr record that is part of MSODRAWING.
[ "Write", "the", "Escher", "Spgr", "record", "that", "is", "part", "of", "MSODRAWING", "." ]
d0345067c21b14a7141ba66b6752be8f4be379de
https://github.com/cxn03651/writeexcel/blob/d0345067c21b14a7141ba66b6752be8f4be379de/lib/writeexcel/worksheet.rb#L6781-L6789
19,107
cxn03651/writeexcel
lib/writeexcel/format.rb
Writeexcel.Format.get_font
def get_font # :nodoc: # my $record; # Record identifier # my $length; # Record length # my $dyHeight; # Height of font (1/20 of a point) # my $grbit; # Font attributes # my $icv; # Index to color palette # my $bls; # Bold style # my $sss; # Superscript/subscript # my $uls; # Underline # my $bFamily; # Font family # my $bCharSet; # Character set # my $reserved; # Reserved # my $cch; # Length of font name # my $rgch; # Font name # my $encoding; # Font name character encoding dyHeight = @size * 20 icv = @color bls = @bold sss = @font_script uls = @underline bFamily = @font_family bCharSet = @font_charset rgch = @font encoding = @font_encoding ruby_19 { rgch = convert_to_ascii_if_ascii(rgch) } # Handle utf8 strings if is_utf8?(rgch) rgch = utf8_to_16be(rgch) encoding = 1 end cch = rgch.bytesize # # Handle Unicode font names. if (encoding == 1) raise "Uneven number of bytes in Unicode font name" if cch % 2 != 0 cch /= 2 if encoding !=0 rgch = utf16be_to_16le(rgch) end record = 0x31 length = 0x10 + rgch.bytesize reserved = 0x00 grbit = 0x00 grbit |= 0x02 if @italic != 0 grbit |= 0x08 if @font_strikeout != 0 grbit |= 0x10 if @font_outline != 0 grbit |= 0x20 if @font_shadow != 0 header = [record, length].pack("vv") data = [dyHeight, grbit, icv, bls, sss, uls, bFamily, bCharSet, reserved, cch, encoding].pack('vvvvvCCCCCC') header + data + rgch end
ruby
def get_font # :nodoc: # my $record; # Record identifier # my $length; # Record length # my $dyHeight; # Height of font (1/20 of a point) # my $grbit; # Font attributes # my $icv; # Index to color palette # my $bls; # Bold style # my $sss; # Superscript/subscript # my $uls; # Underline # my $bFamily; # Font family # my $bCharSet; # Character set # my $reserved; # Reserved # my $cch; # Length of font name # my $rgch; # Font name # my $encoding; # Font name character encoding dyHeight = @size * 20 icv = @color bls = @bold sss = @font_script uls = @underline bFamily = @font_family bCharSet = @font_charset rgch = @font encoding = @font_encoding ruby_19 { rgch = convert_to_ascii_if_ascii(rgch) } # Handle utf8 strings if is_utf8?(rgch) rgch = utf8_to_16be(rgch) encoding = 1 end cch = rgch.bytesize # # Handle Unicode font names. if (encoding == 1) raise "Uneven number of bytes in Unicode font name" if cch % 2 != 0 cch /= 2 if encoding !=0 rgch = utf16be_to_16le(rgch) end record = 0x31 length = 0x10 + rgch.bytesize reserved = 0x00 grbit = 0x00 grbit |= 0x02 if @italic != 0 grbit |= 0x08 if @font_strikeout != 0 grbit |= 0x10 if @font_outline != 0 grbit |= 0x20 if @font_shadow != 0 header = [record, length].pack("vv") data = [dyHeight, grbit, icv, bls, sss, uls, bFamily, bCharSet, reserved, cch, encoding].pack('vvvvvCCCCCC') header + data + rgch end
[ "def", "get_font", "# :nodoc:", "# my $record; # Record identifier", "# my $length; # Record length", "# my $dyHeight; # Height of font (1/20 of a point)", "# my $grbit; # Font attributes", "# my $icv; # Index to color palette", "# my $bls; # Bold style", "# my $sss; # Superscript/subscript", "# my $uls; # Underline", "# my $bFamily; # Font family", "# my $bCharSet; # Character set", "# my $reserved; # Reserved", "# my $cch; # Length of font name", "# my $rgch; # Font name", "# my $encoding; # Font name character encoding", "dyHeight", "=", "@size", "*", "20", "icv", "=", "@color", "bls", "=", "@bold", "sss", "=", "@font_script", "uls", "=", "@underline", "bFamily", "=", "@font_family", "bCharSet", "=", "@font_charset", "rgch", "=", "@font", "encoding", "=", "@font_encoding", "ruby_19", "{", "rgch", "=", "convert_to_ascii_if_ascii", "(", "rgch", ")", "}", "# Handle utf8 strings", "if", "is_utf8?", "(", "rgch", ")", "rgch", "=", "utf8_to_16be", "(", "rgch", ")", "encoding", "=", "1", "end", "cch", "=", "rgch", ".", "bytesize", "#", "# Handle Unicode font names.", "if", "(", "encoding", "==", "1", ")", "raise", "\"Uneven number of bytes in Unicode font name\"", "if", "cch", "%", "2", "!=", "0", "cch", "/=", "2", "if", "encoding", "!=", "0", "rgch", "=", "utf16be_to_16le", "(", "rgch", ")", "end", "record", "=", "0x31", "length", "=", "0x10", "+", "rgch", ".", "bytesize", "reserved", "=", "0x00", "grbit", "=", "0x00", "grbit", "|=", "0x02", "if", "@italic", "!=", "0", "grbit", "|=", "0x08", "if", "@font_strikeout", "!=", "0", "grbit", "|=", "0x10", "if", "@font_outline", "!=", "0", "grbit", "|=", "0x20", "if", "@font_shadow", "!=", "0", "header", "=", "[", "record", ",", "length", "]", ".", "pack", "(", "\"vv\"", ")", "data", "=", "[", "dyHeight", ",", "grbit", ",", "icv", ",", "bls", ",", "sss", ",", "uls", ",", "bFamily", ",", "bCharSet", ",", "reserved", ",", "cch", ",", "encoding", "]", ".", "pack", "(", "'vvvvvCCCCCC'", ")", "header", "+", "data", "+", "rgch", "end" ]
Generate an Excel BIFF FONT record.
[ "Generate", "an", "Excel", "BIFF", "FONT", "record", "." ]
d0345067c21b14a7141ba66b6752be8f4be379de
https://github.com/cxn03651/writeexcel/blob/d0345067c21b14a7141ba66b6752be8f4be379de/lib/writeexcel/format.rb#L336-L399
19,108
cxn03651/writeexcel
lib/writeexcel/format.rb
Writeexcel.Format.set_border
def set_border(style) set_bottom(style) set_top(style) set_left(style) set_right(style) end
ruby
def set_border(style) set_bottom(style) set_top(style) set_left(style) set_right(style) end
[ "def", "set_border", "(", "style", ")", "set_bottom", "(", "style", ")", "set_top", "(", "style", ")", "set_left", "(", "style", ")", "set_right", "(", "style", ")", "end" ]
Set cells borders to the same style Also applies to: set_bottom() set_top() set_left() set_right() Default state: Border is off Default action: Set border type 1 Valid args: 0-13, See below. A cell border is comprised of a border on the bottom, top, left and right. These can be set to the same value using set_border() or individually using the relevant method calls shown above. The following shows the border styles sorted by WriteExcel index number: Index Name Weight Style ===== ============= ====== =========== 0 None 0 1 Continuous 1 ----------- 2 Continuous 2 ----------- 3 Dash 1 - - - - - - 4 Dot 1 . . . . . . 5 Continuous 3 ----------- 6 Double 3 =========== 7 Continuous 0 ----------- 8 Dash 2 - - - - - - 9 Dash Dot 1 - . - . - . 10 Dash Dot 2 - . - . - . 11 Dash Dot Dot 1 - . . - . . 12 Dash Dot Dot 2 - . . - . . 13 SlantDash Dot 2 / - . / - . The following shows the borders sorted by style: Name Weight Style Index ============= ====== =========== ===== Continuous 0 ----------- 7 Continuous 1 ----------- 1 Continuous 2 ----------- 2 Continuous 3 ----------- 5 Dash 1 - - - - - - 3 Dash 2 - - - - - - 8 Dash Dot 1 - . - . - . 9 Dash Dot 2 - . - . - . 10 Dash Dot Dot 1 - . . - . . 11 Dash Dot Dot 2 - . . - . . 12 Dot 1 . . . . . . 4 Double 3 =========== 6 None 0 0 SlantDash Dot 2 / - . / - . 13 The following shows the borders in the order shown in the Excel Dialog. Index Style Index Style ===== ===== ===== ===== 0 None 12 - . . - . . 7 ----------- 13 / - . / - . 4 . . . . . . 10 - . - . - . 11 - . . - . . 8 - - - - - - 9 - . - . - . 2 ----------- 3 - - - - - - 5 ----------- 1 ----------- 6 =========== Examples of the available border styles are shown in the 'Borders' worksheet created by formats.rb.
[ "Set", "cells", "borders", "to", "the", "same", "style" ]
d0345067c21b14a7141ba66b6752be8f4be379de
https://github.com/cxn03651/writeexcel/blob/d0345067c21b14a7141ba66b6752be8f4be379de/lib/writeexcel/format.rb#L1106-L1111
19,109
cxn03651/writeexcel
lib/writeexcel/format.rb
Writeexcel.Format.set_border_color
def set_border_color(color) set_bottom_color(color) set_top_color(color) set_left_color(color) set_right_color(color) end
ruby
def set_border_color(color) set_bottom_color(color) set_top_color(color) set_left_color(color) set_right_color(color) end
[ "def", "set_border_color", "(", "color", ")", "set_bottom_color", "(", "color", ")", "set_top_color", "(", "color", ")", "set_left_color", "(", "color", ")", "set_right_color", "(", "color", ")", "end" ]
Set cells border to the same color Also applies to: set_bottom_color() set_top_color() set_left_color() set_right_color() Default state: Color is off Default action: Undefined Valid args: See set_color() Set the colour of the cell borders. A cell border is comprised of a border on the bottom, top, left and right. These can be set to the same colour using set_border_color() or individually using the relevant method calls shown above. Examples of the border styles and colours are shown in the 'Borders' worksheet created by formats.rb.
[ "Set", "cells", "border", "to", "the", "same", "color" ]
d0345067c21b14a7141ba66b6752be8f4be379de
https://github.com/cxn03651/writeexcel/blob/d0345067c21b14a7141ba66b6752be8f4be379de/lib/writeexcel/format.rb#L1163-L1168
19,110
cxn03651/writeexcel
lib/writeexcel/format.rb
Writeexcel.Format.method_missing
def method_missing(name, *args) # :nodoc: # -- original perl comment -- # There are two types of set methods: set_property() and # set_property_color(). When a method is AUTOLOADED we store a new anonymous # sub in the appropriate slot in the symbol table. The speeds up subsequent # calls to the same method. method = "#{name}" # Check for a valid method names, i.e. "set_xxx_yyy". method =~ /set_(\w+)/ or raise "Unknown method: #{method}\n" # Match the attribute, i.e. "@xxx_yyy". attribute = "@#{$1}" # Check that the attribute exists # ........ if method =~ /set\w+color$/ # for "set_property_color" methods value = get_color(args[0]) else # for "set_xxx" methods value = args[0].nil? ? 1 : args[0] end if value.respond_to?(:to_str) || !value.respond_to?(:+) s = %Q!#{attribute} = "#{value.to_s}"! else s = %Q!#{attribute} = #{value.to_s}! end eval s end
ruby
def method_missing(name, *args) # :nodoc: # -- original perl comment -- # There are two types of set methods: set_property() and # set_property_color(). When a method is AUTOLOADED we store a new anonymous # sub in the appropriate slot in the symbol table. The speeds up subsequent # calls to the same method. method = "#{name}" # Check for a valid method names, i.e. "set_xxx_yyy". method =~ /set_(\w+)/ or raise "Unknown method: #{method}\n" # Match the attribute, i.e. "@xxx_yyy". attribute = "@#{$1}" # Check that the attribute exists # ........ if method =~ /set\w+color$/ # for "set_property_color" methods value = get_color(args[0]) else # for "set_xxx" methods value = args[0].nil? ? 1 : args[0] end if value.respond_to?(:to_str) || !value.respond_to?(:+) s = %Q!#{attribute} = "#{value.to_s}"! else s = %Q!#{attribute} = #{value.to_s}! end eval s end
[ "def", "method_missing", "(", "name", ",", "*", "args", ")", "# :nodoc:", "# -- original perl comment --", "# There are two types of set methods: set_property() and", "# set_property_color(). When a method is AUTOLOADED we store a new anonymous", "# sub in the appropriate slot in the symbol table. The speeds up subsequent", "# calls to the same method.", "method", "=", "\"#{name}\"", "# Check for a valid method names, i.e. \"set_xxx_yyy\".", "method", "=~", "/", "\\w", "/", "or", "raise", "\"Unknown method: #{method}\\n\"", "# Match the attribute, i.e. \"@xxx_yyy\".", "attribute", "=", "\"@#{$1}\"", "# Check that the attribute exists", "# ........", "if", "method", "=~", "/", "\\w", "/", "# for \"set_property_color\" methods", "value", "=", "get_color", "(", "args", "[", "0", "]", ")", "else", "# for \"set_xxx\" methods", "value", "=", "args", "[", "0", "]", ".", "nil?", "?", "1", ":", "args", "[", "0", "]", "end", "if", "value", ".", "respond_to?", "(", ":to_str", ")", "||", "!", "value", ".", "respond_to?", "(", ":+", ")", "s", "=", "%Q!#{attribute} = \"#{value.to_s}\"!", "else", "s", "=", "%Q!#{attribute} = #{value.to_s}!", "end", "eval", "s", "end" ]
Dynamically create set methods that aren't already defined.
[ "Dynamically", "create", "set", "methods", "that", "aren", "t", "already", "defined", "." ]
d0345067c21b14a7141ba66b6752be8f4be379de
https://github.com/cxn03651/writeexcel/blob/d0345067c21b14a7141ba66b6752be8f4be379de/lib/writeexcel/format.rb#L1543-L1571
19,111
cxn03651/writeexcel
lib/writeexcel/image.rb
Writeexcel.Image.process_jpg
def process_jpg(data) @type = 5 # Excel Blip type (MSOBLIPTYPE). offset = 2 data_length = data.bytesize # Search through the image data to find the 0xFFC0 marker. The height and # width are contained in the data for that sub element. while offset < data_length marker = data[offset, 2].unpack("n") marker = marker[0] length = data[offset+2, 2].unpack("n") length = length[0] if marker == 0xFFC0 || marker == 0xFFC2 height = data[offset+5, 2].unpack("n") @height = height[0] width = data[offset+7, 2].unpack("n") @width = width[0] break end offset += length + 2 break if marker == 0xFFDA end raise "#{@filename}: no size data found in jpeg image.\n" unless @height end
ruby
def process_jpg(data) @type = 5 # Excel Blip type (MSOBLIPTYPE). offset = 2 data_length = data.bytesize # Search through the image data to find the 0xFFC0 marker. The height and # width are contained in the data for that sub element. while offset < data_length marker = data[offset, 2].unpack("n") marker = marker[0] length = data[offset+2, 2].unpack("n") length = length[0] if marker == 0xFFC0 || marker == 0xFFC2 height = data[offset+5, 2].unpack("n") @height = height[0] width = data[offset+7, 2].unpack("n") @width = width[0] break end offset += length + 2 break if marker == 0xFFDA end raise "#{@filename}: no size data found in jpeg image.\n" unless @height end
[ "def", "process_jpg", "(", "data", ")", "@type", "=", "5", "# Excel Blip type (MSOBLIPTYPE).", "offset", "=", "2", "data_length", "=", "data", ".", "bytesize", "# Search through the image data to find the 0xFFC0 marker. The height and", "# width are contained in the data for that sub element.", "while", "offset", "<", "data_length", "marker", "=", "data", "[", "offset", ",", "2", "]", ".", "unpack", "(", "\"n\"", ")", "marker", "=", "marker", "[", "0", "]", "length", "=", "data", "[", "offset", "+", "2", ",", "2", "]", ".", "unpack", "(", "\"n\"", ")", "length", "=", "length", "[", "0", "]", "if", "marker", "==", "0xFFC0", "||", "marker", "==", "0xFFC2", "height", "=", "data", "[", "offset", "+", "5", ",", "2", "]", ".", "unpack", "(", "\"n\"", ")", "@height", "=", "height", "[", "0", "]", "width", "=", "data", "[", "offset", "+", "7", ",", "2", "]", ".", "unpack", "(", "\"n\"", ")", "@width", "=", "width", "[", "0", "]", "break", "end", "offset", "+=", "length", "+", "2", "break", "if", "marker", "==", "0xFFDA", "end", "raise", "\"#{@filename}: no size data found in jpeg image.\\n\"", "unless", "@height", "end" ]
Extract width and height information from a JPEG file.
[ "Extract", "width", "and", "height", "information", "from", "a", "JPEG", "file", "." ]
d0345067c21b14a7141ba66b6752be8f4be379de
https://github.com/cxn03651/writeexcel/blob/d0345067c21b14a7141ba66b6752be8f4be379de/lib/writeexcel/image.rb#L119-L146
19,112
burtlo/yard-cucumber
lib/yard/code_objects/step_transformer.rb
YARD::CodeObjects.StepTransformerObject.value
def value unless @processed @processed = true until (nested = constants_from_value).empty? nested.each {|n| @value.gsub!(value_regex(n),find_value_for_constant(n)) } end end @value end
ruby
def value unless @processed @processed = true until (nested = constants_from_value).empty? nested.each {|n| @value.gsub!(value_regex(n),find_value_for_constant(n)) } end end @value end
[ "def", "value", "unless", "@processed", "@processed", "=", "true", "until", "(", "nested", "=", "constants_from_value", ")", ".", "empty?", "nested", ".", "each", "{", "|", "n", "|", "@value", ".", "gsub!", "(", "value_regex", "(", "n", ")", ",", "find_value_for_constant", "(", "n", ")", ")", "}", "end", "end", "@value", "end" ]
When requesting a step tranformer object value, process it, if it hasn't alredy been processed, replacing any constants that may be lurking within the value. Processing it means looking for any escaped characters that happen to be CONSTANTS that could be matched and then replaced. This is done recursively as CONSTANTS can be defined with more CONSTANTS.
[ "When", "requesting", "a", "step", "tranformer", "object", "value", "process", "it", "if", "it", "hasn", "t", "alredy", "been", "processed", "replacing", "any", "constants", "that", "may", "be", "lurking", "within", "the", "value", "." ]
177e5ad17aa4973660ce646b398118a6408d8913
https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/code_objects/step_transformer.rb#L31-L40
19,113
burtlo/yard-cucumber
lib/yard/code_objects/step_transformer.rb
YARD::CodeObjects.StepTransformerObject.constants_from_value
def constants_from_value(data=@value) data.scan(escape_pattern).flatten.collect { |value| value.strip } end
ruby
def constants_from_value(data=@value) data.scan(escape_pattern).flatten.collect { |value| value.strip } end
[ "def", "constants_from_value", "(", "data", "=", "@value", ")", "data", ".", "scan", "(", "escape_pattern", ")", ".", "flatten", ".", "collect", "{", "|", "value", "|", "value", ".", "strip", "}", "end" ]
Look through the specified data for the escape pattern and return an array of those constants found. This defaults to the @value within step transformer as it is used internally, however, it can be called externally if it's needed somewhere.
[ "Look", "through", "the", "specified", "data", "for", "the", "escape", "pattern", "and", "return", "an", "array", "of", "those", "constants", "found", ".", "This", "defaults", "to", "the" ]
177e5ad17aa4973660ce646b398118a6408d8913
https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/code_objects/step_transformer.rb#L68-L70
19,114
burtlo/yard-cucumber
lib/yard/code_objects/step_transformer.rb
YARD::CodeObjects.StepTransformerObject.find_value_for_constant
def find_value_for_constant(name) constant = YARD::Registry.all(:constant).find{|c| c.name == name.to_sym } log.warn "StepTransformer#find_value_for_constant : Could not find the CONSTANT [#{name}] using the string value." unless constant constant ? strip_regex_from(constant.value) : name end
ruby
def find_value_for_constant(name) constant = YARD::Registry.all(:constant).find{|c| c.name == name.to_sym } log.warn "StepTransformer#find_value_for_constant : Could not find the CONSTANT [#{name}] using the string value." unless constant constant ? strip_regex_from(constant.value) : name end
[ "def", "find_value_for_constant", "(", "name", ")", "constant", "=", "YARD", "::", "Registry", ".", "all", "(", ":constant", ")", ".", "find", "{", "|", "c", "|", "c", ".", "name", "==", "name", ".", "to_sym", "}", "log", ".", "warn", "\"StepTransformer#find_value_for_constant : Could not find the CONSTANT [#{name}] using the string value.\"", "unless", "constant", "constant", "?", "strip_regex_from", "(", "constant", ".", "value", ")", ":", "name", "end" ]
Looking through all the constants in the registry and returning the value with the regex items replaced from the constnat if present
[ "Looking", "through", "all", "the", "constants", "in", "the", "registry", "and", "returning", "the", "value", "with", "the", "regex", "items", "replaced", "from", "the", "constnat", "if", "present" ]
177e5ad17aa4973660ce646b398118a6408d8913
https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/code_objects/step_transformer.rb#L78-L82
19,115
burtlo/yard-cucumber
lib/yard/parser/cucumber/feature.rb
YARD::Parser::Cucumber.FeatureParser.parse
def parse begin @parser.parse(@source) @feature = @builder.ast return nil if @feature.nil? # Nothing matched # The parser used the following keywords when parsing the feature # @feature.language = @parser.i18n_language.get_code_keywords.map {|word| word } rescue Gherkin::ParserError => e e.message.insert(0, "#{@file}: ") warn e end self end
ruby
def parse begin @parser.parse(@source) @feature = @builder.ast return nil if @feature.nil? # Nothing matched # The parser used the following keywords when parsing the feature # @feature.language = @parser.i18n_language.get_code_keywords.map {|word| word } rescue Gherkin::ParserError => e e.message.insert(0, "#{@file}: ") warn e end self end
[ "def", "parse", "begin", "@parser", ".", "parse", "(", "@source", ")", "@feature", "=", "@builder", ".", "ast", "return", "nil", "if", "@feature", ".", "nil?", "# Nothing matched", "# The parser used the following keywords when parsing the feature", "# @feature.language = @parser.i18n_language.get_code_keywords.map {|word| word }", "rescue", "Gherkin", "::", "ParserError", "=>", "e", "e", ".", "message", ".", "insert", "(", "0", ",", "\"#{@file}: \"", ")", "warn", "e", "end", "self", "end" ]
Each found feature found is creates a new FeatureParser This logic was copied from the logic found in Cucumber to create the builder and then set up the formatter and parser. The difference is really the custom Cucumber::Parser::CityBuilder that is being used to parse the elements of the feature into YARD::CodeObjects. @param [<String>] source containing the string conents of the feauture file @param [<String>] file the filename that contains the source When parse is called, the gherkin parser is executed and all the feature elements that are found are sent to the various methods in the Cucumber::Parser::CityBuilder. The result of which is the feature element that contains all the scenarios, steps, etc. associated with that feature. @see Cucumber::Parser::CityBuilder
[ "Each", "found", "feature", "found", "is", "creates", "a", "new", "FeatureParser" ]
177e5ad17aa4973660ce646b398118a6408d8913
https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/parser/cucumber/feature.rb#L35-L50
19,116
hidroh/cucumber-api
lib/cucumber-api/response.rb
CucumberApi.Response.has
def has json_path, json=nil if json.nil? json = JSON.parse body end not JsonPath.new(json_path).on(json).empty? end
ruby
def has json_path, json=nil if json.nil? json = JSON.parse body end not JsonPath.new(json_path).on(json).empty? end
[ "def", "has", "json_path", ",", "json", "=", "nil", "if", "json", ".", "nil?", "json", "=", "JSON", ".", "parse", "body", "end", "not", "JsonPath", ".", "new", "(", "json_path", ")", ".", "on", "(", "json", ")", ".", "empty?", "end" ]
Check if given JSON path exists @param json_path [String] a valid JSON path expression @param json [String] optional JSON from which to check JSON path, default to response body @return [true, false] true if JSON path is valid and exists, false otherwise
[ "Check", "if", "given", "JSON", "path", "exists" ]
8d101d166b5eb0dd2f9f6eee5019e062bc3d4f11
https://github.com/hidroh/cucumber-api/blob/8d101d166b5eb0dd2f9f6eee5019e062bc3d4f11/lib/cucumber-api/response.rb#L22-L27
19,117
hidroh/cucumber-api
lib/cucumber-api/response.rb
CucumberApi.Response.get
def get json_path, json=nil if json.nil? json = JSON.parse body end results = JsonPath.new(json_path).on(json) if results.empty? raise %/Expected json path '#{json_path}' not found\n#{to_json_s}/ end results.first end
ruby
def get json_path, json=nil if json.nil? json = JSON.parse body end results = JsonPath.new(json_path).on(json) if results.empty? raise %/Expected json path '#{json_path}' not found\n#{to_json_s}/ end results.first end
[ "def", "get", "json_path", ",", "json", "=", "nil", "if", "json", ".", "nil?", "json", "=", "JSON", ".", "parse", "body", "end", "results", "=", "JsonPath", ".", "new", "(", "json_path", ")", ".", "on", "(", "json", ")", "if", "results", ".", "empty?", "raise", "%/Expected json path '#{json_path}' not found\\n#{to_json_s}/", "end", "results", ".", "first", "end" ]
Retrieve value of the first JSON element with given JSON path @param json_path [String] a valid JSON path expression @param json [String] optional JSON from which to apply JSON path, default to response body @return [Object] value of first retrieved JSON element in form of Ruby object @raise [Exception] if JSON path is invalid or no matching JSON element found
[ "Retrieve", "value", "of", "the", "first", "JSON", "element", "with", "given", "JSON", "path" ]
8d101d166b5eb0dd2f9f6eee5019e062bc3d4f11
https://github.com/hidroh/cucumber-api/blob/8d101d166b5eb0dd2f9f6eee5019e062bc3d4f11/lib/cucumber-api/response.rb#L34-L43
19,118
hidroh/cucumber-api
lib/cucumber-api/response.rb
CucumberApi.Response.get_as_type
def get_as_type json_path, type, json=nil value = get json_path, json case type when 'numeric' valid = value.is_a? Numeric when 'array' valid = value.is_a? Array when 'string' valid = value.is_a? String when 'boolean' valid = !!value == value when 'numeric_string' valid = value.is_a?(Numeric) or value.is_a?(String) when 'object' valid = value.is_a? Hash else raise %/Invalid expected type '#{type}'/ end unless valid raise %/Expect '#{json_path}' as a '#{type}' but was '#{value.class}'\n#{to_json_s}/ end value end
ruby
def get_as_type json_path, type, json=nil value = get json_path, json case type when 'numeric' valid = value.is_a? Numeric when 'array' valid = value.is_a? Array when 'string' valid = value.is_a? String when 'boolean' valid = !!value == value when 'numeric_string' valid = value.is_a?(Numeric) or value.is_a?(String) when 'object' valid = value.is_a? Hash else raise %/Invalid expected type '#{type}'/ end unless valid raise %/Expect '#{json_path}' as a '#{type}' but was '#{value.class}'\n#{to_json_s}/ end value end
[ "def", "get_as_type", "json_path", ",", "type", ",", "json", "=", "nil", "value", "=", "get", "json_path", ",", "json", "case", "type", "when", "'numeric'", "valid", "=", "value", ".", "is_a?", "Numeric", "when", "'array'", "valid", "=", "value", ".", "is_a?", "Array", "when", "'string'", "valid", "=", "value", ".", "is_a?", "String", "when", "'boolean'", "valid", "=", "!", "!", "value", "==", "value", "when", "'numeric_string'", "valid", "=", "value", ".", "is_a?", "(", "Numeric", ")", "or", "value", ".", "is_a?", "(", "String", ")", "when", "'object'", "valid", "=", "value", ".", "is_a?", "Hash", "else", "raise", "%/Invalid expected type '#{type}'/", "end", "unless", "valid", "raise", "%/Expect '#{json_path}' as a '#{type}' but was '#{value.class}'\\n#{to_json_s}/", "end", "value", "end" ]
Retrieve value of the first JSON element with given JSON path as given type @param json_path [String] a valid JSON path expression @param type [String] required type, possible values are 'numeric', 'array', 'string', 'boolean', 'numeric_string' or 'object' @param json [String] optional JSON from which to apply JSON path, default to response body @return [Object] value of first retrieved JSON element in form of given type @raise [Exception] if JSON path is invalid or no matching JSON element found or matching element does not match required type
[ "Retrieve", "value", "of", "the", "first", "JSON", "element", "with", "given", "JSON", "path", "as", "given", "type" ]
8d101d166b5eb0dd2f9f6eee5019e062bc3d4f11
https://github.com/hidroh/cucumber-api/blob/8d101d166b5eb0dd2f9f6eee5019e062bc3d4f11/lib/cucumber-api/response.rb#L53-L76
19,119
hidroh/cucumber-api
lib/cucumber-api/response.rb
CucumberApi.Response.get_as_type_or_null
def get_as_type_or_null json_path, type, json=nil value = get json_path, json value.nil? ? value : get_as_type(json_path, type, json) end
ruby
def get_as_type_or_null json_path, type, json=nil value = get json_path, json value.nil? ? value : get_as_type(json_path, type, json) end
[ "def", "get_as_type_or_null", "json_path", ",", "type", ",", "json", "=", "nil", "value", "=", "get", "json_path", ",", "json", "value", ".", "nil?", "?", "value", ":", "get_as_type", "(", "json_path", ",", "type", ",", "json", ")", "end" ]
Retrieve value of the first JSON element with given JSON path as given type, with nil value allowed @param json_path [String] a valid JSON path expression @param type [String] required type, possible values are 'numeric', 'array', 'string', 'boolean', 'numeric_string' or 'object' @param json [String] optional JSON from which to apply JSON path, default to response body @return [Object] value of first retrieved JSON element in form of given type or nil @raise [Exception] if JSON path is invalid or no matching JSON element found or matching element does not match required type
[ "Retrieve", "value", "of", "the", "first", "JSON", "element", "with", "given", "JSON", "path", "as", "given", "type", "with", "nil", "value", "allowed" ]
8d101d166b5eb0dd2f9f6eee5019e062bc3d4f11
https://github.com/hidroh/cucumber-api/blob/8d101d166b5eb0dd2f9f6eee5019e062bc3d4f11/lib/cucumber-api/response.rb#L86-L89
19,120
hidroh/cucumber-api
lib/cucumber-api/response.rb
CucumberApi.Response.get_as_type_and_check_value
def get_as_type_and_check_value json_path, type, value, json=nil v = get_as_type json_path, type, json if value != v.to_s raise %/Expect '#{json_path}' to be '#{value}' but was '#{v}'\n#{to_json_s}/ end end
ruby
def get_as_type_and_check_value json_path, type, value, json=nil v = get_as_type json_path, type, json if value != v.to_s raise %/Expect '#{json_path}' to be '#{value}' but was '#{v}'\n#{to_json_s}/ end end
[ "def", "get_as_type_and_check_value", "json_path", ",", "type", ",", "value", ",", "json", "=", "nil", "v", "=", "get_as_type", "json_path", ",", "type", ",", "json", "if", "value", "!=", "v", ".", "to_s", "raise", "%/Expect '#{json_path}' to be '#{value}' but was '#{v}'\\n#{to_json_s}/", "end", "end" ]
Retrieve value of the first JSON element with given JSON path as given type, and check for a given value @param json_path [String] a valid JSON path expression @param type [String] required type, possible values are 'numeric', 'string', 'boolean', or 'numeric_string' @param value [String] value to check for @param json [String] optional JSON from which to apply JSON path, default to response body @return [Object] value of first retrieved JSON element in form of given type or nil @raise [Exception] if JSON path is invalid or no matching JSON element found or matching element does not match required type or value
[ "Retrieve", "value", "of", "the", "first", "JSON", "element", "with", "given", "JSON", "path", "as", "given", "type", "and", "check", "for", "a", "given", "value" ]
8d101d166b5eb0dd2f9f6eee5019e062bc3d4f11
https://github.com/hidroh/cucumber-api/blob/8d101d166b5eb0dd2f9f6eee5019e062bc3d4f11/lib/cucumber-api/response.rb#L99-L104
19,121
square/rails-auth
lib/rails/auth/helpers.rb
Rails.Auth.authorized!
def authorized!(rack_env, allowed_by) Env.new(rack_env).tap do |env| env.authorize(allowed_by) end.to_rack end
ruby
def authorized!(rack_env, allowed_by) Env.new(rack_env).tap do |env| env.authorize(allowed_by) end.to_rack end
[ "def", "authorized!", "(", "rack_env", ",", "allowed_by", ")", "Env", ".", "new", "(", "rack_env", ")", ".", "tap", "do", "|", "env", "|", "env", ".", "authorize", "(", "allowed_by", ")", "end", ".", "to_rack", "end" ]
Mark a request as externally authorized. Causes ACL checks to be skipped. @param [Hash] :rack_env Rack environment @param [String] :allowed_by what allowed the request
[ "Mark", "a", "request", "as", "externally", "authorized", ".", "Causes", "ACL", "checks", "to", "be", "skipped", "." ]
7cac4119c043f7de923f67255d1789ea70aeba5d
https://github.com/square/rails-auth/blob/7cac4119c043f7de923f67255d1789ea70aeba5d/lib/rails/auth/helpers.rb#L11-L15
19,122
square/rails-auth
lib/rails/auth/helpers.rb
Rails.Auth.set_allowed_by
def set_allowed_by(rack_env, allowed_by) Env.new(rack_env).tap do |env| env.allowed_by = allowed_by end.to_rack end
ruby
def set_allowed_by(rack_env, allowed_by) Env.new(rack_env).tap do |env| env.allowed_by = allowed_by end.to_rack end
[ "def", "set_allowed_by", "(", "rack_env", ",", "allowed_by", ")", "Env", ".", "new", "(", "rack_env", ")", ".", "tap", "do", "|", "env", "|", "env", ".", "allowed_by", "=", "allowed_by", "end", ".", "to_rack", "end" ]
Mark what authorized the request in the Rack environment @param [Hash] :rack_env Rack environment @param [String] :allowed_by what allowed this request
[ "Mark", "what", "authorized", "the", "request", "in", "the", "Rack", "environment" ]
7cac4119c043f7de923f67255d1789ea70aeba5d
https://github.com/square/rails-auth/blob/7cac4119c043f7de923f67255d1789ea70aeba5d/lib/rails/auth/helpers.rb#L29-L33
19,123
square/rails-auth
lib/rails/auth/helpers.rb
Rails.Auth.add_credential
def add_credential(rack_env, type, credential) Env.new(rack_env).tap do |env| env.credentials[type] = credential end.to_rack end
ruby
def add_credential(rack_env, type, credential) Env.new(rack_env).tap do |env| env.credentials[type] = credential end.to_rack end
[ "def", "add_credential", "(", "rack_env", ",", "type", ",", "credential", ")", "Env", ".", "new", "(", "rack_env", ")", ".", "tap", "do", "|", "env", "|", "env", ".", "credentials", "[", "type", "]", "=", "credential", "end", ".", "to_rack", "end" ]
Add a credential to the Rack environment @param [Hash] :rack_env Rack environment @param [String] :type credential type to add to the environment @param [Object] :credential object to add to the environment
[ "Add", "a", "credential", "to", "the", "Rack", "environment" ]
7cac4119c043f7de923f67255d1789ea70aeba5d
https://github.com/square/rails-auth/blob/7cac4119c043f7de923f67255d1789ea70aeba5d/lib/rails/auth/helpers.rb#L58-L62
19,124
cristibalan/braid
lib/braid/config.rb
Braid.Config.write_db
def write_db new_db = {} @db.keys.sort.each do |key| new_db[key] = {} Braid::Mirror::ATTRIBUTES.each do |k| new_db[key][k] = @db[key][k] if @db[key].has_key?(k) end end new_data = { 'config_version' => CURRENT_CONFIG_VERSION, 'mirrors' => new_db } File.open(@config_file, 'wb') do |f| f.write JSON.pretty_generate(new_data) f.write "\n" end end
ruby
def write_db new_db = {} @db.keys.sort.each do |key| new_db[key] = {} Braid::Mirror::ATTRIBUTES.each do |k| new_db[key][k] = @db[key][k] if @db[key].has_key?(k) end end new_data = { 'config_version' => CURRENT_CONFIG_VERSION, 'mirrors' => new_db } File.open(@config_file, 'wb') do |f| f.write JSON.pretty_generate(new_data) f.write "\n" end end
[ "def", "write_db", "new_db", "=", "{", "}", "@db", ".", "keys", ".", "sort", ".", "each", "do", "|", "key", "|", "new_db", "[", "key", "]", "=", "{", "}", "Braid", "::", "Mirror", "::", "ATTRIBUTES", ".", "each", "do", "|", "k", "|", "new_db", "[", "key", "]", "[", "k", "]", "=", "@db", "[", "key", "]", "[", "k", "]", "if", "@db", "[", "key", "]", ".", "has_key?", "(", "k", ")", "end", "end", "new_data", "=", "{", "'config_version'", "=>", "CURRENT_CONFIG_VERSION", ",", "'mirrors'", "=>", "new_db", "}", "File", ".", "open", "(", "@config_file", ",", "'wb'", ")", "do", "|", "f", "|", "f", ".", "write", "JSON", ".", "pretty_generate", "(", "new_data", ")", "f", ".", "write", "\"\\n\"", "end", "end" ]
Public for upgrade-config command only.
[ "Public", "for", "upgrade", "-", "config", "command", "only", "." ]
d5eba17bb2905e75227e36858709b0a49b988b9e
https://github.com/cristibalan/braid/blob/d5eba17bb2905e75227e36858709b0a49b988b9e/lib/braid/config.rb#L194-L210
19,125
michaelherold/benchmark-memory
lib/benchmark/memory.rb
Benchmark.Memory.memory
def memory(quiet: false) raise ConfigurationError unless block_given? job = Job.new(quiet: quiet) yield job job.run job.run_comparison job.full_report end
ruby
def memory(quiet: false) raise ConfigurationError unless block_given? job = Job.new(quiet: quiet) yield job job.run job.run_comparison job.full_report end
[ "def", "memory", "(", "quiet", ":", "false", ")", "raise", "ConfigurationError", "unless", "block_given?", "job", "=", "Job", ".", "new", "(", "quiet", ":", "quiet", ")", "yield", "job", "job", ".", "run", "job", ".", "run_comparison", "job", ".", "full_report", "end" ]
Measure memory usage in report blocks. @param quiet [Boolean] A flag to toggle benchmark output. @return [Report]
[ "Measure", "memory", "usage", "in", "report", "blocks", "." ]
cd91f5ba81e20cbcea583f305a5b9b9d77cecdd3
https://github.com/michaelherold/benchmark-memory/blob/cd91f5ba81e20cbcea583f305a5b9b9d77cecdd3/lib/benchmark/memory.rb#L15-L25
19,126
ryanb/populator
lib/populator/factory.rb
Populator.Factory.populate
def populate(amount, options = {}, &block) self.class.remember_depth do build_records(Populator.interpret_value(amount), options[:per_query] || DEFAULT_RECORDS_PER_QUERY, &block) end end
ruby
def populate(amount, options = {}, &block) self.class.remember_depth do build_records(Populator.interpret_value(amount), options[:per_query] || DEFAULT_RECORDS_PER_QUERY, &block) end end
[ "def", "populate", "(", "amount", ",", "options", "=", "{", "}", ",", "&", "block", ")", "self", ".", "class", ".", "remember_depth", "do", "build_records", "(", "Populator", ".", "interpret_value", "(", "amount", ")", ",", "options", "[", ":per_query", "]", "||", "DEFAULT_RECORDS_PER_QUERY", ",", "block", ")", "end", "end" ]
Use for_model instead of instatiating a record directly. Entry method for building records. Delegates to build_records after remember_depth.
[ "Use", "for_model", "instead", "of", "instatiating", "a", "record", "directly", ".", "Entry", "method", "for", "building", "records", ".", "Delegates", "to", "build_records", "after", "remember_depth", "." ]
cd1373d8c0a89709a892db9abb2517a87646ed41
https://github.com/ryanb/populator/blob/cd1373d8c0a89709a892db9abb2517a87646ed41/lib/populator/factory.rb#L41-L45
19,127
ryanb/populator
lib/populator/factory.rb
Populator.Factory.save_records
def save_records unless @records.empty? @model_class.connection.populate(@model_class.quoted_table_name, columns_sql, rows_sql_arr, "#{@model_class.name} Populate") @last_id_in_database = @records.last.id @records.clear end end
ruby
def save_records unless @records.empty? @model_class.connection.populate(@model_class.quoted_table_name, columns_sql, rows_sql_arr, "#{@model_class.name} Populate") @last_id_in_database = @records.last.id @records.clear end end
[ "def", "save_records", "unless", "@records", ".", "empty?", "@model_class", ".", "connection", ".", "populate", "(", "@model_class", ".", "quoted_table_name", ",", "columns_sql", ",", "rows_sql_arr", ",", "\"#{@model_class.name} Populate\"", ")", "@last_id_in_database", "=", "@records", ".", "last", ".", "id", "@records", ".", "clear", "end", "end" ]
Saves the records to the database by calling populate on the current database adapter.
[ "Saves", "the", "records", "to", "the", "database", "by", "calling", "populate", "on", "the", "current", "database", "adapter", "." ]
cd1373d8c0a89709a892db9abb2517a87646ed41
https://github.com/ryanb/populator/blob/cd1373d8c0a89709a892db9abb2517a87646ed41/lib/populator/factory.rb#L60-L66
19,128
ryanb/populator
lib/populator/model_additions.rb
Populator.ModelAdditions.populate
def populate(amount, options = {}, &block) Factory.for_model(self).populate(amount, options, &block) end
ruby
def populate(amount, options = {}, &block) Factory.for_model(self).populate(amount, options, &block) end
[ "def", "populate", "(", "amount", ",", "options", "=", "{", "}", ",", "&", "block", ")", "Factory", ".", "for_model", "(", "self", ")", ".", "populate", "(", "amount", ",", "options", ",", "block", ")", "end" ]
Call populate on any ActiveRecord model to fill it with data. Pass the number of records you want to create, and a block to set the attributes. You can nest calls to handle associations and use ranges or arrays to randomize the values. Person.populate(3000) do |person| person.name = "John Doe" person.gender = ['male', 'female'] Project.populate(10..30, :per_query => 100) do |project| project.person_id = person.id project.due_at = 5.days.from_now..2.years.from_now project.name = Populator.words(1..3).titleize project.description = Populator.sentences(2..10) end end The following options are supported. * <tt>:per_query</tt> - limit how many records are inserted per query, defaults to 1000 Populator::Factory is where all the work happens.
[ "Call", "populate", "on", "any", "ActiveRecord", "model", "to", "fill", "it", "with", "data", ".", "Pass", "the", "number", "of", "records", "you", "want", "to", "create", "and", "a", "block", "to", "set", "the", "attributes", ".", "You", "can", "nest", "calls", "to", "handle", "associations", "and", "use", "ranges", "or", "arrays", "to", "randomize", "the", "values", "." ]
cd1373d8c0a89709a892db9abb2517a87646ed41
https://github.com/ryanb/populator/blob/cd1373d8c0a89709a892db9abb2517a87646ed41/lib/populator/model_additions.rb#L24-L26
19,129
ryanb/populator
lib/populator/random.rb
Populator.Random.value_in_range
def value_in_range(range) case range.first when Integer then number_in_range(range) when Time then time_in_range(range) when Date then date_in_range(range) else range.to_a[rand(range.to_a.size)] end end
ruby
def value_in_range(range) case range.first when Integer then number_in_range(range) when Time then time_in_range(range) when Date then date_in_range(range) else range.to_a[rand(range.to_a.size)] end end
[ "def", "value_in_range", "(", "range", ")", "case", "range", ".", "first", "when", "Integer", "then", "number_in_range", "(", "range", ")", "when", "Time", "then", "time_in_range", "(", "range", ")", "when", "Date", "then", "date_in_range", "(", "range", ")", "else", "range", ".", "to_a", "[", "rand", "(", "range", ".", "to_a", ".", "size", ")", "]", "end", "end" ]
Pick a random value out of a given range.
[ "Pick", "a", "random", "value", "out", "of", "a", "given", "range", "." ]
cd1373d8c0a89709a892db9abb2517a87646ed41
https://github.com/ryanb/populator/blob/cd1373d8c0a89709a892db9abb2517a87646ed41/lib/populator/random.rb#L8-L15
19,130
sophsec/ruby-nmap
lib/nmap/program.rb
Nmap.Program.scan
def scan(options={},exec_options={},&block) run_task(Task.new(options,&block),exec_options) end
ruby
def scan(options={},exec_options={},&block) run_task(Task.new(options,&block),exec_options) end
[ "def", "scan", "(", "options", "=", "{", "}", ",", "exec_options", "=", "{", "}", ",", "&", "block", ")", "run_task", "(", "Task", ".", "new", "(", "options", ",", "block", ")", ",", "exec_options", ")", "end" ]
Performs a scan. @param [Hash{Symbol => Object}] options Additional options for nmap. @param [Hash{Symbol => Object}] exec_options Additional exec-options. @yield [task] If a block is given, it will be passed a task object used to specify options for nmap. @yieldparam [Task] task The nmap task object. @return [Boolean] Specifies whether the command exited normally. @see http://rubydoc.info/gems/rprogram/0.3.0/RProgram/Program#run-instance_method For additional exec-options.
[ "Performs", "a", "scan", "." ]
f6060a7b2238872357622572145add88fc2ba412
https://github.com/sophsec/ruby-nmap/blob/f6060a7b2238872357622572145add88fc2ba412/lib/nmap/program.rb#L86-L88
19,131
sophsec/ruby-nmap
lib/nmap/program.rb
Nmap.Program.sudo_scan
def sudo_scan(options={},exec_options={},&block) sudo_task(Task.new(options,&block),exec_options) end
ruby
def sudo_scan(options={},exec_options={},&block) sudo_task(Task.new(options,&block),exec_options) end
[ "def", "sudo_scan", "(", "options", "=", "{", "}", ",", "exec_options", "=", "{", "}", ",", "&", "block", ")", "sudo_task", "(", "Task", ".", "new", "(", "options", ",", "block", ")", ",", "exec_options", ")", "end" ]
Performs a scan and runs `nmap` under `sudo`. @see #scan @since 0.8.0
[ "Performs", "a", "scan", "and", "runs", "nmap", "under", "sudo", "." ]
f6060a7b2238872357622572145add88fc2ba412
https://github.com/sophsec/ruby-nmap/blob/f6060a7b2238872357622572145add88fc2ba412/lib/nmap/program.rb#L97-L99
19,132
sophsec/ruby-nmap
lib/nmap/xml.rb
Nmap.XML.scanner
def scanner @scanner ||= Scanner.new( @doc.root['scanner'], @doc.root['version'], @doc.root['args'], Time.at(@doc.root['start'].to_i) ) end
ruby
def scanner @scanner ||= Scanner.new( @doc.root['scanner'], @doc.root['version'], @doc.root['args'], Time.at(@doc.root['start'].to_i) ) end
[ "def", "scanner", "@scanner", "||=", "Scanner", ".", "new", "(", "@doc", ".", "root", "[", "'scanner'", "]", ",", "@doc", ".", "root", "[", "'version'", "]", ",", "@doc", ".", "root", "[", "'args'", "]", ",", "Time", ".", "at", "(", "@doc", ".", "root", "[", "'start'", "]", ".", "to_i", ")", ")", "end" ]
Parses the scanner information. @return [Scanner] The scanner that was used and generated the scan file.
[ "Parses", "the", "scanner", "information", "." ]
f6060a7b2238872357622572145add88fc2ba412
https://github.com/sophsec/ruby-nmap/blob/f6060a7b2238872357622572145add88fc2ba412/lib/nmap/xml.rb#L99-L106
19,133
sophsec/ruby-nmap
lib/nmap/xml.rb
Nmap.XML.scan_info
def scan_info @doc.xpath('/nmaprun/scaninfo').map do |scaninfo| Scan.new( scaninfo['type'].to_sym, scaninfo['protocol'].to_sym, scaninfo['services'].split(',').map { |ports| if ports.include?('-') Range.new(*(ports.split('-',2))) else ports.to_i end } ) end end
ruby
def scan_info @doc.xpath('/nmaprun/scaninfo').map do |scaninfo| Scan.new( scaninfo['type'].to_sym, scaninfo['protocol'].to_sym, scaninfo['services'].split(',').map { |ports| if ports.include?('-') Range.new(*(ports.split('-',2))) else ports.to_i end } ) end end
[ "def", "scan_info", "@doc", ".", "xpath", "(", "'/nmaprun/scaninfo'", ")", ".", "map", "do", "|", "scaninfo", "|", "Scan", ".", "new", "(", "scaninfo", "[", "'type'", "]", ".", "to_sym", ",", "scaninfo", "[", "'protocol'", "]", ".", "to_sym", ",", "scaninfo", "[", "'services'", "]", ".", "split", "(", "','", ")", ".", "map", "{", "|", "ports", "|", "if", "ports", ".", "include?", "(", "'-'", ")", "Range", ".", "new", "(", "(", "ports", ".", "split", "(", "'-'", ",", "2", ")", ")", ")", "else", "ports", ".", "to_i", "end", "}", ")", "end", "end" ]
Parses the scan information. @return [Array<Scan>] The scan information.
[ "Parses", "the", "scan", "information", "." ]
f6060a7b2238872357622572145add88fc2ba412
https://github.com/sophsec/ruby-nmap/blob/f6060a7b2238872357622572145add88fc2ba412/lib/nmap/xml.rb#L124-L138
19,134
sophsec/ruby-nmap
lib/nmap/xml.rb
Nmap.XML.each_run_stat
def each_run_stat return enum_for(__method__) unless block_given? @doc.xpath('/nmaprun/runstats/finished').each do |run_stat| yield RunStat.new( Time.at(run_stat['time'].to_i), run_stat['elapsed'], run_stat['summary'], run_stat['exit'] ) end return self end
ruby
def each_run_stat return enum_for(__method__) unless block_given? @doc.xpath('/nmaprun/runstats/finished').each do |run_stat| yield RunStat.new( Time.at(run_stat['time'].to_i), run_stat['elapsed'], run_stat['summary'], run_stat['exit'] ) end return self end
[ "def", "each_run_stat", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "@doc", ".", "xpath", "(", "'/nmaprun/runstats/finished'", ")", ".", "each", "do", "|", "run_stat", "|", "yield", "RunStat", ".", "new", "(", "Time", ".", "at", "(", "run_stat", "[", "'time'", "]", ".", "to_i", ")", ",", "run_stat", "[", "'elapsed'", "]", ",", "run_stat", "[", "'summary'", "]", ",", "run_stat", "[", "'exit'", "]", ")", "end", "return", "self", "end" ]
Parses the essential runstats information. @yield [run_stat] The given block will be passed each runstat. @yieldparam [RunStat] run_stat A runstat. @return [Enumerator] If no block is given, an enumerator will be returned. @since 0.7.0
[ "Parses", "the", "essential", "runstats", "information", "." ]
f6060a7b2238872357622572145add88fc2ba412
https://github.com/sophsec/ruby-nmap/blob/f6060a7b2238872357622572145add88fc2ba412/lib/nmap/xml.rb#L154-L167
19,135
sophsec/ruby-nmap
lib/nmap/xml.rb
Nmap.XML.each_task
def each_task return enum_for(__method__) unless block_given? @doc.xpath('/nmaprun/taskbegin').each do |task_begin| task_end = task_begin.xpath('following-sibling::taskend').first yield ScanTask.new( task_begin['task'], Time.at(task_begin['time'].to_i), Time.at(task_end['time'].to_i), task_end['extrainfo'] ) end return self end
ruby
def each_task return enum_for(__method__) unless block_given? @doc.xpath('/nmaprun/taskbegin').each do |task_begin| task_end = task_begin.xpath('following-sibling::taskend').first yield ScanTask.new( task_begin['task'], Time.at(task_begin['time'].to_i), Time.at(task_end['time'].to_i), task_end['extrainfo'] ) end return self end
[ "def", "each_task", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "@doc", ".", "xpath", "(", "'/nmaprun/taskbegin'", ")", ".", "each", "do", "|", "task_begin", "|", "task_end", "=", "task_begin", ".", "xpath", "(", "'following-sibling::taskend'", ")", ".", "first", "yield", "ScanTask", ".", "new", "(", "task_begin", "[", "'task'", "]", ",", "Time", ".", "at", "(", "task_begin", "[", "'time'", "]", ".", "to_i", ")", ",", "Time", ".", "at", "(", "task_end", "[", "'time'", "]", ".", "to_i", ")", ",", "task_end", "[", "'extrainfo'", "]", ")", "end", "return", "self", "end" ]
Parses the tasks of the scan. @yield [task] The given block will be passed each scan task. @yieldparam [ScanTask] task A task from the scan. @return [Enumerator] If no block is given, an enumerator will be returned. @since 0.7.0
[ "Parses", "the", "tasks", "of", "the", "scan", "." ]
f6060a7b2238872357622572145add88fc2ba412
https://github.com/sophsec/ruby-nmap/blob/f6060a7b2238872357622572145add88fc2ba412/lib/nmap/xml.rb#L215-L230
19,136
sophsec/ruby-nmap
lib/nmap/xml.rb
Nmap.XML.each_up_host
def each_up_host return enum_for(__method__) unless block_given? @doc.xpath("/nmaprun/host[status[@state='up']]").each do |host| yield Host.new(host) end return self end
ruby
def each_up_host return enum_for(__method__) unless block_given? @doc.xpath("/nmaprun/host[status[@state='up']]").each do |host| yield Host.new(host) end return self end
[ "def", "each_up_host", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "@doc", ".", "xpath", "(", "\"/nmaprun/host[status[@state='up']]\"", ")", ".", "each", "do", "|", "host", "|", "yield", "Host", ".", "new", "(", "host", ")", "end", "return", "self", "end" ]
Parses the hosts that were found to be up during the scan. @yield [host] Each host will be passed to a given block. @yieldparam [Host] host A host in the scan. @return [XML, Enumerator] The XML parser. If no block was given, an enumerator object will be returned.
[ "Parses", "the", "hosts", "that", "were", "found", "to", "be", "up", "during", "the", "scan", "." ]
f6060a7b2238872357622572145add88fc2ba412
https://github.com/sophsec/ruby-nmap/blob/f6060a7b2238872357622572145add88fc2ba412/lib/nmap/xml.rb#L381-L389
19,137
sophsec/ruby-nmap
lib/nmap/host.rb
Nmap.Host.each_address
def each_address return enum_for(__method__) unless block_given? @node.xpath("address[@addr]").each do |addr| address = Address.new( addr['addrtype'].to_sym, addr['addr'], addr['vendor'] ) yield address end return self end
ruby
def each_address return enum_for(__method__) unless block_given? @node.xpath("address[@addr]").each do |addr| address = Address.new( addr['addrtype'].to_sym, addr['addr'], addr['vendor'] ) yield address end return self end
[ "def", "each_address", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "@node", ".", "xpath", "(", "\"address[@addr]\"", ")", ".", "each", "do", "|", "addr", "|", "address", "=", "Address", ".", "new", "(", "addr", "[", "'addrtype'", "]", ".", "to_sym", ",", "addr", "[", "'addr'", "]", ",", "addr", "[", "'vendor'", "]", ")", "yield", "address", "end", "return", "self", "end" ]
Parses each address of the host. @yield [addr] Each parsed address will be pass to a given block. @yieldparam [Address] addr A address of the host. @return [Host, Enumerator] The host. If no block was given, an enumerator will be returned.
[ "Parses", "each", "address", "of", "the", "host", "." ]
f6060a7b2238872357622572145add88fc2ba412
https://github.com/sophsec/ruby-nmap/blob/f6060a7b2238872357622572145add88fc2ba412/lib/nmap/host.rb#L90-L104
19,138
sophsec/ruby-nmap
lib/nmap/host.rb
Nmap.Host.each_hostname
def each_hostname return enum_for(__method__) unless block_given? @node.xpath("hostnames/hostname[@name]").each do |host| yield Hostname.new(host['type'],host['name']) end return self end
ruby
def each_hostname return enum_for(__method__) unless block_given? @node.xpath("hostnames/hostname[@name]").each do |host| yield Hostname.new(host['type'],host['name']) end return self end
[ "def", "each_hostname", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "@node", ".", "xpath", "(", "\"hostnames/hostname[@name]\"", ")", ".", "each", "do", "|", "host", "|", "yield", "Hostname", ".", "new", "(", "host", "[", "'type'", "]", ",", "host", "[", "'name'", "]", ")", "end", "return", "self", "end" ]
Parses the hostnames of the host. @yield [host] Each parsed hostname will be passed to the given block. @yieldparam [Hostname] host A hostname of the host. @return [Host, Enumerator] The host. If no block was given, an enumerator will be returned.
[ "Parses", "the", "hostnames", "of", "the", "host", "." ]
f6060a7b2238872357622572145add88fc2ba412
https://github.com/sophsec/ruby-nmap/blob/f6060a7b2238872357622572145add88fc2ba412/lib/nmap/host.rb#L199-L207
19,139
sophsec/ruby-nmap
lib/nmap/host.rb
Nmap.Host.uptime
def uptime @uptime ||= if (uptime = @node.at_xpath('uptime')) Uptime.new( uptime['seconds'].to_i, Time.parse(uptime['lastboot']) ) end yield @uptime if (@uptime && block_given?) return @uptime end
ruby
def uptime @uptime ||= if (uptime = @node.at_xpath('uptime')) Uptime.new( uptime['seconds'].to_i, Time.parse(uptime['lastboot']) ) end yield @uptime if (@uptime && block_given?) return @uptime end
[ "def", "uptime", "@uptime", "||=", "if", "(", "uptime", "=", "@node", ".", "at_xpath", "(", "'uptime'", ")", ")", "Uptime", ".", "new", "(", "uptime", "[", "'seconds'", "]", ".", "to_i", ",", "Time", ".", "parse", "(", "uptime", "[", "'lastboot'", "]", ")", ")", "end", "yield", "@uptime", "if", "(", "@uptime", "&&", "block_given?", ")", "return", "@uptime", "end" ]
Parses the Uptime analysis of the host. @yield [uptime] If a block is given, it will be passed the resulting object @yieldparam [Uptime] Uptime value. @return [Uptime] The parsed object. @since 0.7.0
[ "Parses", "the", "Uptime", "analysis", "of", "the", "host", "." ]
f6060a7b2238872357622572145add88fc2ba412
https://github.com/sophsec/ruby-nmap/blob/f6060a7b2238872357622572145add88fc2ba412/lib/nmap/host.rb#L265-L275
19,140
sophsec/ruby-nmap
lib/nmap/host.rb
Nmap.Host.each_tcp_port
def each_tcp_port return enum_for(__method__) unless block_given? @node.xpath("ports/port[@protocol='tcp']").each do |port| yield Port.new(port) end return self end
ruby
def each_tcp_port return enum_for(__method__) unless block_given? @node.xpath("ports/port[@protocol='tcp']").each do |port| yield Port.new(port) end return self end
[ "def", "each_tcp_port", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "@node", ".", "xpath", "(", "\"ports/port[@protocol='tcp']\"", ")", ".", "each", "do", "|", "port", "|", "yield", "Port", ".", "new", "(", "port", ")", "end", "return", "self", "end" ]
Parses the TCP ports of the host. @yield [port] Each TCP port of the host. @yieldparam [Port] port An TCP scanned port of the host. @return [Host, Enumerator] The host. If no block was given, an enumerator will be returned.
[ "Parses", "the", "TCP", "ports", "of", "the", "host", "." ]
f6060a7b2238872357622572145add88fc2ba412
https://github.com/sophsec/ruby-nmap/blob/f6060a7b2238872357622572145add88fc2ba412/lib/nmap/host.rb#L446-L454
19,141
sophsec/ruby-nmap
lib/nmap/scripts.rb
Nmap.Scripts.script_data
def script_data unless @script_data @script_data = {} traverse = lambda do |node| case node.name when 'script', 'table' unless node.xpath('*[@key]').empty? hash = {} node.elements.each do |element| hash[element['key']] = traverse.call(element) end hash else array = [] node.elements.each do |element| array << traverse.call(element) end array end when 'elem' node.inner_text else raise(NotImplementedError,"unrecognized XML NSE element: #{node}") end end @node.xpath('script').each do |script| @script_data[script['id']] = traverse.call(script) end end return @script_data end
ruby
def script_data unless @script_data @script_data = {} traverse = lambda do |node| case node.name when 'script', 'table' unless node.xpath('*[@key]').empty? hash = {} node.elements.each do |element| hash[element['key']] = traverse.call(element) end hash else array = [] node.elements.each do |element| array << traverse.call(element) end array end when 'elem' node.inner_text else raise(NotImplementedError,"unrecognized XML NSE element: #{node}") end end @node.xpath('script').each do |script| @script_data[script['id']] = traverse.call(script) end end return @script_data end
[ "def", "script_data", "unless", "@script_data", "@script_data", "=", "{", "}", "traverse", "=", "lambda", "do", "|", "node", "|", "case", "node", ".", "name", "when", "'script'", ",", "'table'", "unless", "node", ".", "xpath", "(", "'*[@key]'", ")", ".", "empty?", "hash", "=", "{", "}", "node", ".", "elements", ".", "each", "do", "|", "element", "|", "hash", "[", "element", "[", "'key'", "]", "]", "=", "traverse", ".", "call", "(", "element", ")", "end", "hash", "else", "array", "=", "[", "]", "node", ".", "elements", ".", "each", "do", "|", "element", "|", "array", "<<", "traverse", ".", "call", "(", "element", ")", "end", "array", "end", "when", "'elem'", "node", ".", "inner_text", "else", "raise", "(", "NotImplementedError", ",", "\"unrecognized XML NSE element: #{node}\"", ")", "end", "end", "@node", ".", "xpath", "(", "'script'", ")", ".", "each", "do", "|", "script", "|", "@script_data", "[", "script", "[", "'id'", "]", "]", "=", "traverse", ".", "call", "(", "script", ")", "end", "end", "return", "@script_data", "end" ]
The structured output of the NSE scripts. @return [Hash{String => Hash{String => Array<String>}}] The NSE script names and their structured output. @since 0.9.0
[ "The", "structured", "output", "of", "the", "NSE", "scripts", "." ]
f6060a7b2238872357622572145add88fc2ba412
https://github.com/sophsec/ruby-nmap/blob/f6060a7b2238872357622572145add88fc2ba412/lib/nmap/scripts.rb#L31-L68
19,142
sophsec/ruby-nmap
lib/nmap/traceroute.rb
Nmap.Traceroute.each
def each return enum_for(__method__) unless block_given? @node.xpath('hop').each do |hop| yield Hop.new(hop['ipaddr'],hop['host'],hop['ttl'],hop['rtt']) end return self end
ruby
def each return enum_for(__method__) unless block_given? @node.xpath('hop').each do |hop| yield Hop.new(hop['ipaddr'],hop['host'],hop['ttl'],hop['rtt']) end return self end
[ "def", "each", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "@node", ".", "xpath", "(", "'hop'", ")", ".", "each", "do", "|", "hop", "|", "yield", "Hop", ".", "new", "(", "hop", "[", "'ipaddr'", "]", ",", "hop", "[", "'host'", "]", ",", "hop", "[", "'ttl'", "]", ",", "hop", "[", "'rtt'", "]", ")", "end", "return", "self", "end" ]
Parses the traceroute information for the host. @yield [hop] Each hop to the host. @yieldparam [Hop] hop A hop to the host. @return [Traceroute, Enumerator] The traceroute. If no block was given, an enumerator will be returned.
[ "Parses", "the", "traceroute", "information", "for", "the", "host", "." ]
f6060a7b2238872357622572145add88fc2ba412
https://github.com/sophsec/ruby-nmap/blob/f6060a7b2238872357622572145add88fc2ba412/lib/nmap/traceroute.rb#L60-L68
19,143
sophsec/ruby-nmap
lib/nmap/os.rb
Nmap.OS.each_class
def each_class return enum_for(__method__) unless block_given? @node.xpath("osmatch/osclass").each do |osclass| yield OSClass.new(osclass) end return self end
ruby
def each_class return enum_for(__method__) unless block_given? @node.xpath("osmatch/osclass").each do |osclass| yield OSClass.new(osclass) end return self end
[ "def", "each_class", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "@node", ".", "xpath", "(", "\"osmatch/osclass\"", ")", ".", "each", "do", "|", "osclass", "|", "yield", "OSClass", ".", "new", "(", "osclass", ")", "end", "return", "self", "end" ]
Creates a new OS object. @param [Nokogiri::XML::Node] node The node that contains the OS guessing information. Parses the OS class information. @yield [class] Passes each OS class to the given block. @yieldparam [OSClass] class The OS class information. @return [OS, Enumerator] The OS information. If no block was given, an enumerator object will be returned.
[ "Creates", "a", "new", "OS", "object", "." ]
f6060a7b2238872357622572145add88fc2ba412
https://github.com/sophsec/ruby-nmap/blob/f6060a7b2238872357622572145add88fc2ba412/lib/nmap/os.rb#L35-L43
19,144
sophsec/ruby-nmap
lib/nmap/os.rb
Nmap.OS.each_match
def each_match return enum_for(__method__) unless block_given? @node.xpath("osmatch").map do |osclass| os_match = OSMatch.new( osclass['name'], osclass['accuracy'].to_i ) yield os_match end return self end
ruby
def each_match return enum_for(__method__) unless block_given? @node.xpath("osmatch").map do |osclass| os_match = OSMatch.new( osclass['name'], osclass['accuracy'].to_i ) yield os_match end return self end
[ "def", "each_match", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "@node", ".", "xpath", "(", "\"osmatch\"", ")", ".", "map", "do", "|", "osclass", "|", "os_match", "=", "OSMatch", ".", "new", "(", "osclass", "[", "'name'", "]", ",", "osclass", "[", "'accuracy'", "]", ".", "to_i", ")", "yield", "os_match", "end", "return", "self", "end" ]
Parses the OS match information. @yield [match] Passes each OS match to the given block. @yieldparam [OSMatch] class The OS match information. @return [OS, Enumerator] The OS information. If no block was given, an enumerator object will be returned.
[ "Parses", "the", "OS", "match", "information", "." ]
f6060a7b2238872357622572145add88fc2ba412
https://github.com/sophsec/ruby-nmap/blob/f6060a7b2238872357622572145add88fc2ba412/lib/nmap/os.rb#L68-L81
19,145
veger/ruby-bbcode
lib/ruby-bbcode/bbtree.rb
RubyBBCode.BBTree.retrogress_bbtree
def retrogress_bbtree if @tags_list[-1].definition[:self_closable] # It is possible that the next (self_closable) tag is on the next line # Remove newline of current tag and parent tag as they are (probably) not intented as an actual newline here but as tag separator @tags_list[-1][:nodes][0][:text].chomp! unless @tags_list[-1][:nodes][0][:text].nil? @tags_list[-2][:nodes][0][:text].chomp! unless @tags_list.length < 2 or @tags_list[-2][:nodes][0][:text].nil? end @tags_list.pop # remove latest tag in tags_list since it's closed now... # The parsed data manifests in @bbtree.current_node.children << TagNode.new(element) which I think is more confusing than needed if within_open_tag? @current_node = @tags_list[-1] else # If we're still at the root of the BBTree or have returned back to the root via encountring closing tags... @current_node = TagNode.new({:nodes => self.nodes}) # Note: just passing in self works too... end end
ruby
def retrogress_bbtree if @tags_list[-1].definition[:self_closable] # It is possible that the next (self_closable) tag is on the next line # Remove newline of current tag and parent tag as they are (probably) not intented as an actual newline here but as tag separator @tags_list[-1][:nodes][0][:text].chomp! unless @tags_list[-1][:nodes][0][:text].nil? @tags_list[-2][:nodes][0][:text].chomp! unless @tags_list.length < 2 or @tags_list[-2][:nodes][0][:text].nil? end @tags_list.pop # remove latest tag in tags_list since it's closed now... # The parsed data manifests in @bbtree.current_node.children << TagNode.new(element) which I think is more confusing than needed if within_open_tag? @current_node = @tags_list[-1] else # If we're still at the root of the BBTree or have returned back to the root via encountring closing tags... @current_node = TagNode.new({:nodes => self.nodes}) # Note: just passing in self works too... end end
[ "def", "retrogress_bbtree", "if", "@tags_list", "[", "-", "1", "]", ".", "definition", "[", ":self_closable", "]", "# It is possible that the next (self_closable) tag is on the next line", "# Remove newline of current tag and parent tag as they are (probably) not intented as an actual newline here but as tag separator", "@tags_list", "[", "-", "1", "]", "[", ":nodes", "]", "[", "0", "]", "[", ":text", "]", ".", "chomp!", "unless", "@tags_list", "[", "-", "1", "]", "[", ":nodes", "]", "[", "0", "]", "[", ":text", "]", ".", "nil?", "@tags_list", "[", "-", "2", "]", "[", ":nodes", "]", "[", "0", "]", "[", ":text", "]", ".", "chomp!", "unless", "@tags_list", ".", "length", "<", "2", "or", "@tags_list", "[", "-", "2", "]", "[", ":nodes", "]", "[", "0", "]", "[", ":text", "]", ".", "nil?", "end", "@tags_list", ".", "pop", "# remove latest tag in tags_list since it's closed now...", "# The parsed data manifests in @bbtree.current_node.children << TagNode.new(element) which I think is more confusing than needed", "if", "within_open_tag?", "@current_node", "=", "@tags_list", "[", "-", "1", "]", "else", "# If we're still at the root of the BBTree or have returned back to the root via encountring closing tags...", "@current_node", "=", "TagNode", ".", "new", "(", "{", ":nodes", "=>", "self", ".", "nodes", "}", ")", "# Note: just passing in self works too...", "end", "end" ]
Step down the bbtree a notch because we've reached a closing tag
[ "Step", "down", "the", "bbtree", "a", "notch", "because", "we", "ve", "reached", "a", "closing", "tag" ]
0b9ea504060f3e5b1ae9c3e5d9586a5672ec5fc7
https://github.com/veger/ruby-bbcode/blob/0b9ea504060f3e5b1ae9c3e5d9586a5672ec5fc7/lib/ruby-bbcode/bbtree.rb#L48-L64
19,146
veger/ruby-bbcode
lib/ruby-bbcode/tag_sifter.rb
RubyBBCode.TagSifter.get_formatted_between
def get_formatted_between between = @ti[:text] # perform special formatting for cenrtain tags between = match_url_id(between, @bbtree.current_node.definition[:url_matches]) if @bbtree.current_node.definition[:url_matches] return between end
ruby
def get_formatted_between between = @ti[:text] # perform special formatting for cenrtain tags between = match_url_id(between, @bbtree.current_node.definition[:url_matches]) if @bbtree.current_node.definition[:url_matches] return between end
[ "def", "get_formatted_between", "between", "=", "@ti", "[", ":text", "]", "# perform special formatting for cenrtain tags", "between", "=", "match_url_id", "(", "between", ",", "@bbtree", ".", "current_node", ".", "definition", "[", ":url_matches", "]", ")", "if", "@bbtree", ".", "current_node", ".", "definition", "[", ":url_matches", "]", "return", "between", "end" ]
Get 'between tag' for tag
[ "Get", "between", "tag", "for", "tag" ]
0b9ea504060f3e5b1ae9c3e5d9586a5672ec5fc7
https://github.com/veger/ruby-bbcode/blob/0b9ea504060f3e5b1ae9c3e5d9586a5672ec5fc7/lib/ruby-bbcode/tag_sifter.rb#L139-L144
19,147
xeger/docker-compose
lib/docker/compose/session.rb
Docker::Compose.Session.up
def up(*services, abort_on_container_exit: false, detached: false, timeout: 10, build: false, exit_code_from: nil, no_build: false, no_deps: false, no_start: false) o = opts( abort_on_container_exit: [abort_on_container_exit, false], d: [detached, false], timeout: [timeout, 10], build: [build, false], exit_code_from: [exit_code_from, nil], no_build: [no_build, false], no_deps: [no_deps, false], no_start: [no_start, false] ) run!('up', o, services) true end
ruby
def up(*services, abort_on_container_exit: false, detached: false, timeout: 10, build: false, exit_code_from: nil, no_build: false, no_deps: false, no_start: false) o = opts( abort_on_container_exit: [abort_on_container_exit, false], d: [detached, false], timeout: [timeout, 10], build: [build, false], exit_code_from: [exit_code_from, nil], no_build: [no_build, false], no_deps: [no_deps, false], no_start: [no_start, false] ) run!('up', o, services) true end
[ "def", "up", "(", "*", "services", ",", "abort_on_container_exit", ":", "false", ",", "detached", ":", "false", ",", "timeout", ":", "10", ",", "build", ":", "false", ",", "exit_code_from", ":", "nil", ",", "no_build", ":", "false", ",", "no_deps", ":", "false", ",", "no_start", ":", "false", ")", "o", "=", "opts", "(", "abort_on_container_exit", ":", "[", "abort_on_container_exit", ",", "false", "]", ",", "d", ":", "[", "detached", ",", "false", "]", ",", "timeout", ":", "[", "timeout", ",", "10", "]", ",", "build", ":", "[", "build", ",", "false", "]", ",", "exit_code_from", ":", "[", "exit_code_from", ",", "nil", "]", ",", "no_build", ":", "[", "no_build", ",", "false", "]", ",", "no_deps", ":", "[", "no_deps", ",", "false", "]", ",", "no_start", ":", "[", "no_start", ",", "false", "]", ")", "run!", "(", "'up'", ",", "o", ",", "services", ")", "true", "end" ]
Idempotently up the given services in the project. @param [Array] services list of String service names to run @param [Boolean] detached if true, to start services in the background; otherwise, monitor logs in the foreground and shutdown on Ctrl+C @param [Integer] timeout how long to wait for each service to start @param [Boolean] build if true, build images before starting containers @param [Boolean] no_build if true, don't build images, even if they're missing @param [Boolean] no_deps if true, just run specified services without running the services that they depend on @return [true] always returns true @raise [Error] if command fails
[ "Idempotently", "up", "the", "given", "services", "in", "the", "project", "." ]
c1428491b686a33cbafdc26e609e6a863e2ec6fa
https://github.com/xeger/docker-compose/blob/c1428491b686a33cbafdc26e609e6a863e2ec6fa/lib/docker/compose/session.rb#L83-L100
19,148
xeger/docker-compose
lib/docker/compose/session.rb
Docker::Compose.Session.scale
def scale(container_count, timeout: 10) args = container_count.map {|service, count| "#{service}=#{count}"} o = opts(timeout: [timeout, 10]) run!('scale', o, *args) end
ruby
def scale(container_count, timeout: 10) args = container_count.map {|service, count| "#{service}=#{count}"} o = opts(timeout: [timeout, 10]) run!('scale', o, *args) end
[ "def", "scale", "(", "container_count", ",", "timeout", ":", "10", ")", "args", "=", "container_count", ".", "map", "{", "|", "service", ",", "count", "|", "\"#{service}=#{count}\"", "}", "o", "=", "opts", "(", "timeout", ":", "[", "timeout", ",", "10", "]", ")", "run!", "(", "'scale'", ",", "o", ",", "args", ")", "end" ]
Idempotently scales the number of containers for given services in the project. @param [Hash] container_count per service, e.g. {web: 2, worker: 3} @param [Integer] timeout how long to wait for each service to scale
[ "Idempotently", "scales", "the", "number", "of", "containers", "for", "given", "services", "in", "the", "project", "." ]
c1428491b686a33cbafdc26e609e6a863e2ec6fa
https://github.com/xeger/docker-compose/blob/c1428491b686a33cbafdc26e609e6a863e2ec6fa/lib/docker/compose/session.rb#L105-L109
19,149
xeger/docker-compose
lib/docker/compose/session.rb
Docker::Compose.Session.run
def run(service, *cmd, detached: false, no_deps: false, volumes: [], env: [], rm: false, no_tty: false, user: nil, service_ports: false) o = opts(d: [detached, false], no_deps: [no_deps, false], rm: [rm, false], T: [no_tty, false], u: [user, nil], service_ports: [service_ports, false]) env_params = env.map { |v| { e: v } } volume_params = volumes.map { |v| { v: v } } run!('run', o, *env_params, *volume_params, service, cmd) end
ruby
def run(service, *cmd, detached: false, no_deps: false, volumes: [], env: [], rm: false, no_tty: false, user: nil, service_ports: false) o = opts(d: [detached, false], no_deps: [no_deps, false], rm: [rm, false], T: [no_tty, false], u: [user, nil], service_ports: [service_ports, false]) env_params = env.map { |v| { e: v } } volume_params = volumes.map { |v| { v: v } } run!('run', o, *env_params, *volume_params, service, cmd) end
[ "def", "run", "(", "service", ",", "*", "cmd", ",", "detached", ":", "false", ",", "no_deps", ":", "false", ",", "volumes", ":", "[", "]", ",", "env", ":", "[", "]", ",", "rm", ":", "false", ",", "no_tty", ":", "false", ",", "user", ":", "nil", ",", "service_ports", ":", "false", ")", "o", "=", "opts", "(", "d", ":", "[", "detached", ",", "false", "]", ",", "no_deps", ":", "[", "no_deps", ",", "false", "]", ",", "rm", ":", "[", "rm", ",", "false", "]", ",", "T", ":", "[", "no_tty", ",", "false", "]", ",", "u", ":", "[", "user", ",", "nil", "]", ",", "service_ports", ":", "[", "service_ports", ",", "false", "]", ")", "env_params", "=", "env", ".", "map", "{", "|", "v", "|", "{", "e", ":", "v", "}", "}", "volume_params", "=", "volumes", ".", "map", "{", "|", "v", "|", "{", "v", ":", "v", "}", "}", "run!", "(", "'run'", ",", "o", ",", "env_params", ",", "volume_params", ",", "service", ",", "cmd", ")", "end" ]
Idempotently run an arbitrary command with a service container. @param [String] service name to run @param [String] cmd command statement to run @param [Boolean] detached if true, to start services in the background; otherwise, monitor logs in the foreground and shutdown on Ctrl+C @param [Boolean] no_deps if true, just run specified services without running the services that they depend on @param [Array] env a list of environment variables (see: -e flag) @param [Array] volumes a list of volumes to bind mount (see: -v flag) @param [Boolean] rm remove the container when done @param [Boolean] no_tty disable pseudo-tty allocation (see: -T flag) @param [String] user run as specified username or uid (see: -u flag) @raise [Error] if command fails
[ "Idempotently", "run", "an", "arbitrary", "command", "with", "a", "service", "container", "." ]
c1428491b686a33cbafdc26e609e6a863e2ec6fa
https://github.com/xeger/docker-compose/blob/c1428491b686a33cbafdc26e609e6a863e2ec6fa/lib/docker/compose/session.rb#L140-L145
19,150
xeger/docker-compose
lib/docker/compose/session.rb
Docker::Compose.Session.stop
def stop(*services, timeout: 10) o = opts(timeout: [timeout, 10]) run!('stop', o, services) end
ruby
def stop(*services, timeout: 10) o = opts(timeout: [timeout, 10]) run!('stop', o, services) end
[ "def", "stop", "(", "*", "services", ",", "timeout", ":", "10", ")", "o", "=", "opts", "(", "timeout", ":", "[", "timeout", ",", "10", "]", ")", "run!", "(", "'stop'", ",", "o", ",", "services", ")", "end" ]
Stop running services. @param [Array] services list of String service names to stop @param [Integer] timeout how long to wait for each service to stop @raise [Error] if command fails
[ "Stop", "running", "services", "." ]
c1428491b686a33cbafdc26e609e6a863e2ec6fa
https://github.com/xeger/docker-compose/blob/c1428491b686a33cbafdc26e609e6a863e2ec6fa/lib/docker/compose/session.rb#L168-L171
19,151
xeger/docker-compose
lib/docker/compose/session.rb
Docker::Compose.Session.kill
def kill(*services, signal: 'KILL') o = opts(signal: [signal, 'KILL']) run!('kill', o, services) end
ruby
def kill(*services, signal: 'KILL') o = opts(signal: [signal, 'KILL']) run!('kill', o, services) end
[ "def", "kill", "(", "*", "services", ",", "signal", ":", "'KILL'", ")", "o", "=", "opts", "(", "signal", ":", "[", "signal", ",", "'KILL'", "]", ")", "run!", "(", "'kill'", ",", "o", ",", "services", ")", "end" ]
Forcibly stop running services. @param [Array] services list of String service names to stop @param [String] name of murderous signal to use, default is 'KILL' @see Signal.list for a list of acceptable signal names
[ "Forcibly", "stop", "running", "services", "." ]
c1428491b686a33cbafdc26e609e6a863e2ec6fa
https://github.com/xeger/docker-compose/blob/c1428491b686a33cbafdc26e609e6a863e2ec6fa/lib/docker/compose/session.rb#L177-L180
19,152
xeger/docker-compose
lib/docker/compose/session.rb
Docker::Compose.Session.version
def version(short: false) o = opts(short: [short, false]) result = run!('version', o, file: false, dir: false) if short result.strip else lines = result.split(/[\r\n]+/) lines.inject({}) do |h, line| kv = line.split(/: +/, 2) h[kv.first] = kv.last h end end end
ruby
def version(short: false) o = opts(short: [short, false]) result = run!('version', o, file: false, dir: false) if short result.strip else lines = result.split(/[\r\n]+/) lines.inject({}) do |h, line| kv = line.split(/: +/, 2) h[kv.first] = kv.last h end end end
[ "def", "version", "(", "short", ":", "false", ")", "o", "=", "opts", "(", "short", ":", "[", "short", ",", "false", "]", ")", "result", "=", "run!", "(", "'version'", ",", "o", ",", "file", ":", "false", ",", "dir", ":", "false", ")", "if", "short", "result", ".", "strip", "else", "lines", "=", "result", ".", "split", "(", "/", "\\r", "\\n", "/", ")", "lines", ".", "inject", "(", "{", "}", ")", "do", "|", "h", ",", "line", "|", "kv", "=", "line", ".", "split", "(", "/", "/", ",", "2", ")", "h", "[", "kv", ".", "first", "]", "=", "kv", ".", "last", "h", "end", "end", "end" ]
Determine the installed version of docker-compose. @param [Boolean] short whether to return terse version information @return [String, Hash] if short==true, returns a version string; otherwise, returns a Hash of component-name strings to version strings @raise [Error] if command fails
[ "Determine", "the", "installed", "version", "of", "docker", "-", "compose", "." ]
c1428491b686a33cbafdc26e609e6a863e2ec6fa
https://github.com/xeger/docker-compose/blob/c1428491b686a33cbafdc26e609e6a863e2ec6fa/lib/docker/compose/session.rb#L220-L234
19,153
xeger/docker-compose
lib/docker/compose/session.rb
Docker::Compose.Session.run!
def run!(*args) file_args = case @file when 'docker-compose.yml' [] when Array # backticks sugar can't handle array values; build a list of hashes # IMPORTANT: preserve the order of the files so overrides work correctly file_args = @file.map { |filepath| { :file => filepath } } else # a single String (or Pathname, etc); use normal sugar to add it [{ file: @file.to_s }] end @shell.chdir = dir @last_command = @shell.run('docker-compose', *file_args, *args).join status = @last_command.status out = @last_command.captured_output err = @last_command.captured_error status.success? || fail(Error.new(args.first, status, out+err)) out end
ruby
def run!(*args) file_args = case @file when 'docker-compose.yml' [] when Array # backticks sugar can't handle array values; build a list of hashes # IMPORTANT: preserve the order of the files so overrides work correctly file_args = @file.map { |filepath| { :file => filepath } } else # a single String (or Pathname, etc); use normal sugar to add it [{ file: @file.to_s }] end @shell.chdir = dir @last_command = @shell.run('docker-compose', *file_args, *args).join status = @last_command.status out = @last_command.captured_output err = @last_command.captured_error status.success? || fail(Error.new(args.first, status, out+err)) out end
[ "def", "run!", "(", "*", "args", ")", "file_args", "=", "case", "@file", "when", "'docker-compose.yml'", "[", "]", "when", "Array", "# backticks sugar can't handle array values; build a list of hashes", "# IMPORTANT: preserve the order of the files so overrides work correctly", "file_args", "=", "@file", ".", "map", "{", "|", "filepath", "|", "{", ":file", "=>", "filepath", "}", "}", "else", "# a single String (or Pathname, etc); use normal sugar to add it", "[", "{", "file", ":", "@file", ".", "to_s", "}", "]", "end", "@shell", ".", "chdir", "=", "dir", "@last_command", "=", "@shell", ".", "run", "(", "'docker-compose'", ",", "file_args", ",", "args", ")", ".", "join", "status", "=", "@last_command", ".", "status", "out", "=", "@last_command", ".", "captured_output", "err", "=", "@last_command", ".", "captured_error", "status", ".", "success?", "||", "fail", "(", "Error", ".", "new", "(", "args", ".", "first", ",", "status", ",", "out", "+", "err", ")", ")", "out", "end" ]
Run a docker-compose command without validating that the CLI parameters make sense. Prepend project and file options if suitable. @see Docker::Compose::Shell#command @param [Array] args command-line arguments in the format accepted by Backticks::Runner#command @return [String] output of the command @raise [Error] if command fails
[ "Run", "a", "docker", "-", "compose", "command", "without", "validating", "that", "the", "CLI", "parameters", "make", "sense", ".", "Prepend", "project", "and", "file", "options", "if", "suitable", "." ]
c1428491b686a33cbafdc26e609e6a863e2ec6fa
https://github.com/xeger/docker-compose/blob/c1428491b686a33cbafdc26e609e6a863e2ec6fa/lib/docker/compose/session.rb#L252-L272
19,154
xeger/docker-compose
lib/docker/compose/session.rb
Docker::Compose.Session.parse
def parse(str) fields = [] nest = 0 field = '' str.each_char do |ch| got = false if nest == 0 if ch == '(' nest += 1 end else if ch == '(' nest += 1 field << ch elsif ch == ')' nest -= 1 if nest == 0 got = true else field << ch end else field << ch end end if got fields << field field = '' end end fields end
ruby
def parse(str) fields = [] nest = 0 field = '' str.each_char do |ch| got = false if nest == 0 if ch == '(' nest += 1 end else if ch == '(' nest += 1 field << ch elsif ch == ')' nest -= 1 if nest == 0 got = true else field << ch end else field << ch end end if got fields << field field = '' end end fields end
[ "def", "parse", "(", "str", ")", "fields", "=", "[", "]", "nest", "=", "0", "field", "=", "''", "str", ".", "each_char", "do", "|", "ch", "|", "got", "=", "false", "if", "nest", "==", "0", "if", "ch", "==", "'('", "nest", "+=", "1", "end", "else", "if", "ch", "==", "'('", "nest", "+=", "1", "field", "<<", "ch", "elsif", "ch", "==", "')'", "nest", "-=", "1", "if", "nest", "==", "0", "got", "=", "true", "else", "field", "<<", "ch", "end", "else", "field", "<<", "ch", "end", "end", "if", "got", "fields", "<<", "field", "field", "=", "''", "end", "end", "fields", "end" ]
Parse a string that consists of a sequence of values enclosed within parentheses. Ignore any bytes that are outside of parentheses. Values may include nested parentheses. @param [String] str e.g. "(foo) ((bar)) ... (baz)" @return [Array] e.g. ["foo", "bar", "baz"]
[ "Parse", "a", "string", "that", "consists", "of", "a", "sequence", "of", "values", "enclosed", "within", "parentheses", ".", "Ignore", "any", "bytes", "that", "are", "outside", "of", "parentheses", ".", "Values", "may", "include", "nested", "parentheses", "." ]
c1428491b686a33cbafdc26e609e6a863e2ec6fa
https://github.com/xeger/docker-compose/blob/c1428491b686a33cbafdc26e609e6a863e2ec6fa/lib/docker/compose/session.rb#L310-L343
19,155
xeger/docker-compose
lib/docker/compose/rake_tasks.rb
Docker::Compose.RakeTasks.export_env
def export_env(print:) Docker::Compose::Mapper.map(host_env, session: @session, net_info: @net_info) do |k, v| ENV[k] = serialize_for_env(v) print_env(k, ENV[k]) if print end extra_host_env.each do |k, v| ENV[k] = serialize_for_env(v) print_env(k, ENV[k]) if print end end
ruby
def export_env(print:) Docker::Compose::Mapper.map(host_env, session: @session, net_info: @net_info) do |k, v| ENV[k] = serialize_for_env(v) print_env(k, ENV[k]) if print end extra_host_env.each do |k, v| ENV[k] = serialize_for_env(v) print_env(k, ENV[k]) if print end end
[ "def", "export_env", "(", "print", ":", ")", "Docker", "::", "Compose", "::", "Mapper", ".", "map", "(", "host_env", ",", "session", ":", "@session", ",", "net_info", ":", "@net_info", ")", "do", "|", "k", ",", "v", "|", "ENV", "[", "k", "]", "=", "serialize_for_env", "(", "v", ")", "print_env", "(", "k", ",", "ENV", "[", "k", "]", ")", "if", "print", "end", "extra_host_env", ".", "each", "do", "|", "k", ",", "v", "|", "ENV", "[", "k", "]", "=", "serialize_for_env", "(", "v", ")", "print_env", "(", "k", ",", "ENV", "[", "k", "]", ")", "if", "print", "end", "end" ]
Substitute and set environment variables that point to network ports published by docker-compose services. Optionally also print bash export statements so this information can be made available to a user's shell.
[ "Substitute", "and", "set", "environment", "variables", "that", "point", "to", "network", "ports", "published", "by", "docker", "-", "compose", "services", ".", "Optionally", "also", "print", "bash", "export", "statements", "so", "this", "information", "can", "be", "made", "available", "to", "a", "user", "s", "shell", "." ]
c1428491b686a33cbafdc26e609e6a863e2ec6fa
https://github.com/xeger/docker-compose/blob/c1428491b686a33cbafdc26e609e6a863e2ec6fa/lib/docker/compose/rake_tasks.rb#L111-L123
19,156
xeger/docker-compose
lib/docker/compose/rake_tasks.rb
Docker::Compose.RakeTasks.serialize_for_env
def serialize_for_env(v) case v when String v when NilClass nil when Array JSON.dump(v) else fail ArgumentError, "Can't represent a #{v.class} in the environment" end end
ruby
def serialize_for_env(v) case v when String v when NilClass nil when Array JSON.dump(v) else fail ArgumentError, "Can't represent a #{v.class} in the environment" end end
[ "def", "serialize_for_env", "(", "v", ")", "case", "v", "when", "String", "v", "when", "NilClass", "nil", "when", "Array", "JSON", ".", "dump", "(", "v", ")", "else", "fail", "ArgumentError", ",", "\"Can't represent a #{v.class} in the environment\"", "end", "end" ]
Transform a Ruby value into a String that can be stored in the environment. This accepts nil, String, or Array and returns nil, String or JSON-serialized Array.
[ "Transform", "a", "Ruby", "value", "into", "a", "String", "that", "can", "be", "stored", "in", "the", "environment", ".", "This", "accepts", "nil", "String", "or", "Array", "and", "returns", "nil", "String", "or", "JSON", "-", "serialized", "Array", "." ]
c1428491b686a33cbafdc26e609e6a863e2ec6fa
https://github.com/xeger/docker-compose/blob/c1428491b686a33cbafdc26e609e6a863e2ec6fa/lib/docker/compose/rake_tasks.rb#L129-L140
19,157
xeger/docker-compose
lib/docker/compose/rake_tasks.rb
Docker::Compose.RakeTasks.print_env
def print_env(k, v) if v puts @shell_printer.export(k, v) else puts @shell_printer.unset(k) end end
ruby
def print_env(k, v) if v puts @shell_printer.export(k, v) else puts @shell_printer.unset(k) end end
[ "def", "print_env", "(", "k", ",", "v", ")", "if", "v", "puts", "@shell_printer", ".", "export", "(", "k", ",", "v", ")", "else", "puts", "@shell_printer", ".", "unset", "(", "k", ")", "end", "end" ]
Print an export or unset statement suitable for user's shell
[ "Print", "an", "export", "or", "unset", "statement", "suitable", "for", "user", "s", "shell" ]
c1428491b686a33cbafdc26e609e6a863e2ec6fa
https://github.com/xeger/docker-compose/blob/c1428491b686a33cbafdc26e609e6a863e2ec6fa/lib/docker/compose/rake_tasks.rb#L144-L150
19,158
xeger/docker-compose
lib/docker/compose/net_info.rb
Docker::Compose.NetInfo.docker_routable_ip
def docker_routable_ip case @docker_url.scheme when 'tcp', 'http', 'https' docker_dns = @docker_url.host docker_port = @docker_url.port || 2376 else # Cheap trick: for unix, file or other protocols, assume docker ports # are proxied to localhost in addition to other interfaces docker_dns = 'localhost' docker_port = 2376 end addr = Addrinfo.getaddrinfo( docker_dns, docker_port, Socket::AF_INET, Socket::SOCK_STREAM).first addr && addr.ip_address end
ruby
def docker_routable_ip case @docker_url.scheme when 'tcp', 'http', 'https' docker_dns = @docker_url.host docker_port = @docker_url.port || 2376 else # Cheap trick: for unix, file or other protocols, assume docker ports # are proxied to localhost in addition to other interfaces docker_dns = 'localhost' docker_port = 2376 end addr = Addrinfo.getaddrinfo( docker_dns, docker_port, Socket::AF_INET, Socket::SOCK_STREAM).first addr && addr.ip_address end
[ "def", "docker_routable_ip", "case", "@docker_url", ".", "scheme", "when", "'tcp'", ",", "'http'", ",", "'https'", "docker_dns", "=", "@docker_url", ".", "host", "docker_port", "=", "@docker_url", ".", "port", "||", "2376", "else", "# Cheap trick: for unix, file or other protocols, assume docker ports", "# are proxied to localhost in addition to other interfaces", "docker_dns", "=", "'localhost'", "docker_port", "=", "2376", "end", "addr", "=", "Addrinfo", ".", "getaddrinfo", "(", "docker_dns", ",", "docker_port", ",", "Socket", "::", "AF_INET", ",", "Socket", "::", "SOCK_STREAM", ")", ".", "first", "addr", "&&", "addr", ".", "ip_address", "end" ]
Figure out the likely IP address of the host pointed to by self.docker_url. @return [String] host-reachable IPv4 address of docker host
[ "Figure", "out", "the", "likely", "IP", "address", "of", "the", "host", "pointed", "to", "by", "self", ".", "docker_url", "." ]
c1428491b686a33cbafdc26e609e6a863e2ec6fa
https://github.com/xeger/docker-compose/blob/c1428491b686a33cbafdc26e609e6a863e2ec6fa/lib/docker/compose/net_info.rb#L70-L87
19,159
xeger/docker-compose
lib/docker/compose/mapper.rb
Docker::Compose.Mapper.map
def map(value) if value.respond_to?(:map) value.map { |e| map_scalar(e) } else map_scalar(value) end end
ruby
def map(value) if value.respond_to?(:map) value.map { |e| map_scalar(e) } else map_scalar(value) end end
[ "def", "map", "(", "value", ")", "if", "value", ".", "respond_to?", "(", ":map", ")", "value", ".", "map", "{", "|", "e", "|", "map_scalar", "(", "e", ")", "}", "else", "map_scalar", "(", "value", ")", "end", "end" ]
Create an instance of Mapper @param [Docker::Compose::Session] session @param [NetInfo] net_info Substitute service hostnames and ports that appear in a URL or a host:port string. If either component of a host:port string is surrounded by square brackets, "elide" that component, removing it from the result but using it to find the correct service and port. @example map MySQL on local docker host with 3306 published to 13847 map("tcp://db:3306") # => "tcp://127.0.0.1:13847" @example map just the hostname of MySQL on local docker host map("db:[3306]") # => "127.0.0.1" @example map just the port of MySQL on local docker host map("[db]:3306") # => "13847" @example map an array of database hosts map(["[db1]:3306", "[db2]:3306"]) @param [String,#map] value a URI, host:port pair, or an array of either @return [String,Array] the mapped value with container-names and ports substituted @raise [BadSubstitution] if a substitution string can't be parsed @raise [NoService] if service is not up or does not publish port
[ "Create", "an", "instance", "of", "Mapper" ]
c1428491b686a33cbafdc26e609e6a863e2ec6fa
https://github.com/xeger/docker-compose/blob/c1428491b686a33cbafdc26e609e6a863e2ec6fa/lib/docker/compose/mapper.rb#L88-L94
19,160
xeger/docker-compose
lib/docker/compose/mapper.rb
Docker::Compose.Mapper.map_scalar
def map_scalar(value) uri = begin URI.parse(value) rescue nil end pair = value.split(':') if uri && uri.scheme && uri.host # absolute URI with scheme, authority, etc uri.host, uri.port = host_and_port(uri.host, uri.port) return uri.to_s elsif pair.size == 2 # "host:port" pair; three sub-cases... if pair.first =~ ELIDED # output only the port service = pair.first.gsub(REMOVE_ELIDED, '') _, port = host_and_port(service, pair.last) return port.to_s elsif pair.last =~ ELIDED # output only the hostname; resolve the port anyway to ensure that # the service is running. service = pair.first port = pair.last.gsub(REMOVE_ELIDED, '') host, = host_and_port(service, port) return host else # output port:hostname pair host, port = host_and_port(pair.first, pair.last) return "#{host}:#{port}" end else fail BadSubstitution, "Can't understand '#{value}'" end end
ruby
def map_scalar(value) uri = begin URI.parse(value) rescue nil end pair = value.split(':') if uri && uri.scheme && uri.host # absolute URI with scheme, authority, etc uri.host, uri.port = host_and_port(uri.host, uri.port) return uri.to_s elsif pair.size == 2 # "host:port" pair; three sub-cases... if pair.first =~ ELIDED # output only the port service = pair.first.gsub(REMOVE_ELIDED, '') _, port = host_and_port(service, pair.last) return port.to_s elsif pair.last =~ ELIDED # output only the hostname; resolve the port anyway to ensure that # the service is running. service = pair.first port = pair.last.gsub(REMOVE_ELIDED, '') host, = host_and_port(service, port) return host else # output port:hostname pair host, port = host_and_port(pair.first, pair.last) return "#{host}:#{port}" end else fail BadSubstitution, "Can't understand '#{value}'" end end
[ "def", "map_scalar", "(", "value", ")", "uri", "=", "begin", "URI", ".", "parse", "(", "value", ")", "rescue", "nil", "end", "pair", "=", "value", ".", "split", "(", "':'", ")", "if", "uri", "&&", "uri", ".", "scheme", "&&", "uri", ".", "host", "# absolute URI with scheme, authority, etc", "uri", ".", "host", ",", "uri", ".", "port", "=", "host_and_port", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "return", "uri", ".", "to_s", "elsif", "pair", ".", "size", "==", "2", "# \"host:port\" pair; three sub-cases...", "if", "pair", ".", "first", "=~", "ELIDED", "# output only the port", "service", "=", "pair", ".", "first", ".", "gsub", "(", "REMOVE_ELIDED", ",", "''", ")", "_", ",", "port", "=", "host_and_port", "(", "service", ",", "pair", ".", "last", ")", "return", "port", ".", "to_s", "elsif", "pair", ".", "last", "=~", "ELIDED", "# output only the hostname; resolve the port anyway to ensure that", "# the service is running.", "service", "=", "pair", ".", "first", "port", "=", "pair", ".", "last", ".", "gsub", "(", "REMOVE_ELIDED", ",", "''", ")", "host", ",", "=", "host_and_port", "(", "service", ",", "port", ")", "return", "host", "else", "# output port:hostname pair", "host", ",", "port", "=", "host_and_port", "(", "pair", ".", "first", ",", "pair", ".", "last", ")", "return", "\"#{host}:#{port}\"", "end", "else", "fail", "BadSubstitution", ",", "\"Can't understand '#{value}'\"", "end", "end" ]
Map a single string, replacing service names with IPs and container ports with the host ports that they have been mapped to. @param [String] value @return [String]
[ "Map", "a", "single", "string", "replacing", "service", "names", "with", "IPs", "and", "container", "ports", "with", "the", "host", "ports", "that", "they", "have", "been", "mapped", "to", "." ]
c1428491b686a33cbafdc26e609e6a863e2ec6fa
https://github.com/xeger/docker-compose/blob/c1428491b686a33cbafdc26e609e6a863e2ec6fa/lib/docker/compose/mapper.rb#L122-L156
19,161
sue445/rubicure
lib/rubicure/girl.rb
Rubicure.Girl.birthday?
def birthday?(date = Date.today) return false unless have_birthday? # NOTE: birthday is "mm/dd" month, day = birthday.split("/") birthday_date = Date.new(date.year, month.to_i, day.to_i) birthday_date == date end
ruby
def birthday?(date = Date.today) return false unless have_birthday? # NOTE: birthday is "mm/dd" month, day = birthday.split("/") birthday_date = Date.new(date.year, month.to_i, day.to_i) birthday_date == date end
[ "def", "birthday?", "(", "date", "=", "Date", ".", "today", ")", "return", "false", "unless", "have_birthday?", "# NOTE: birthday is \"mm/dd\"", "month", ",", "day", "=", "birthday", ".", "split", "(", "\"/\"", ")", "birthday_date", "=", "Date", ".", "new", "(", "date", ".", "year", ",", "month", ".", "to_i", ",", "day", ".", "to_i", ")", "birthday_date", "==", "date", "end" ]
Whether `date` is her birthday @param date [Date] @return [Boolean] @example Cure.twinkle.birthday?(Date.parse("2015-9-12")) #=> true
[ "Whether", "date", "is", "her", "birthday" ]
bdd5efc2127774a0620399e779b076d9f8f4aeab
https://github.com/sue445/rubicure/blob/bdd5efc2127774a0620399e779b076d9f8f4aeab/lib/rubicure/girl.rb#L131-L140
19,162
sue445/rubicure
lib/rubicure/core.rb
Rubicure.Core.all_stars
def all_stars(arg = Time.current) extra_girls = [] # args is Time or Date date = to_date(arg) if date last_all_stars_date = Rubicure::Movie.find(:stmm).started_date if date > last_all_stars_date date = last_all_stars_date end else # args is movie name movie = Rubicure::Movie.find(arg.to_sym) date = movie.started_date if movie.has_key?(:extra_girls) extra_girls = movie.extra_girls.map {|girl_name| Rubicure::Girl.find(girl_name.to_sym) } end end all_girls(date) - [Cure.echo] + extra_girls end
ruby
def all_stars(arg = Time.current) extra_girls = [] # args is Time or Date date = to_date(arg) if date last_all_stars_date = Rubicure::Movie.find(:stmm).started_date if date > last_all_stars_date date = last_all_stars_date end else # args is movie name movie = Rubicure::Movie.find(arg.to_sym) date = movie.started_date if movie.has_key?(:extra_girls) extra_girls = movie.extra_girls.map {|girl_name| Rubicure::Girl.find(girl_name.to_sym) } end end all_girls(date) - [Cure.echo] + extra_girls end
[ "def", "all_stars", "(", "arg", "=", "Time", ".", "current", ")", "extra_girls", "=", "[", "]", "# args is Time or Date", "date", "=", "to_date", "(", "arg", ")", "if", "date", "last_all_stars_date", "=", "Rubicure", "::", "Movie", ".", "find", "(", ":stmm", ")", ".", "started_date", "if", "date", ">", "last_all_stars_date", "date", "=", "last_all_stars_date", "end", "else", "# args is movie name", "movie", "=", "Rubicure", "::", "Movie", ".", "find", "(", "arg", ".", "to_sym", ")", "date", "=", "movie", ".", "started_date", "if", "movie", ".", "has_key?", "(", ":extra_girls", ")", "extra_girls", "=", "movie", ".", "extra_girls", ".", "map", "{", "|", "girl_name", "|", "Rubicure", "::", "Girl", ".", "find", "(", "girl_name", ".", "to_sym", ")", "}", "end", "end", "all_girls", "(", "date", ")", "-", "[", "Cure", ".", "echo", "]", "+", "extra_girls", "end" ]
Get precure all stars @param [Time,Date,String,Symbol] arg Time, Date or date like String (ex. "2013-12-16") @return [Array<Rubicure::Girl>] @example precure all stars Precure.all_stars.count Precure.all_stars.map(&:precure_name) # returns current precure count and names Precure.all_stars.include?(Cure.echo) #=> false Precure.all_stars("2013-10-26").count #=> 33 Precure.all_stars(:dx).count #=> 14 Precure.all_stars(:dx2).count #=> 17 Precure.all_stars(:dx3).count #=> 21 Precure.all_stars(:new_stage).count #=> 29 Precure.all_stars(:new_stage).include?(Cure.echo) #=> true Precure.all_stars(:new_stage2).count #=> 32 Precure.all_stars(:new_stage3).count #=> 37 Precure.all_stars(:new_stage3).include?(Cure.echo) #=> true Precure.all_stars(:spring_carnival).count #=> 40 Precure.all_stars(:sing_together_miracle_magic).count #=> 44 Precure.all_stars(:sing_together_miracle_magic).include?(Cure.echo) #=> true
[ "Get", "precure", "all", "stars" ]
bdd5efc2127774a0620399e779b076d9f8f4aeab
https://github.com/sue445/rubicure/blob/bdd5efc2127774a0620399e779b076d9f8f4aeab/lib/rubicure/core.rb#L98-L120
19,163
sue445/rubicure
lib/rubicure/core.rb
Rubicure.Core.all_girls
def all_girls(arg = Time.current) date = to_date(arg) unless @all_girls @all_girls = [] Rubicure::Girl.names.each do |girl_name| @all_girls << Rubicure::Girl.find(girl_name) end @all_girls.uniq!(&:human_name) end @all_girls.select {|girl| girl.created_date && girl.created_date <= date } end
ruby
def all_girls(arg = Time.current) date = to_date(arg) unless @all_girls @all_girls = [] Rubicure::Girl.names.each do |girl_name| @all_girls << Rubicure::Girl.find(girl_name) end @all_girls.uniq!(&:human_name) end @all_girls.select {|girl| girl.created_date && girl.created_date <= date } end
[ "def", "all_girls", "(", "arg", "=", "Time", ".", "current", ")", "date", "=", "to_date", "(", "arg", ")", "unless", "@all_girls", "@all_girls", "=", "[", "]", "Rubicure", "::", "Girl", ".", "names", ".", "each", "do", "|", "girl_name", "|", "@all_girls", "<<", "Rubicure", "::", "Girl", ".", "find", "(", "girl_name", ")", "end", "@all_girls", ".", "uniq!", "(", ":human_name", ")", "end", "@all_girls", ".", "select", "{", "|", "girl", "|", "girl", ".", "created_date", "&&", "girl", ".", "created_date", "<=", "date", "}", "end" ]
Get all precures @param [Time,Date] arg Time, Date or date like String (ex. "2013-12-16") @return [Array<Rubicure::Girl>] all precures @example Precure.all_girls.count Precure.all_girls.map(&:precure_name) # returns current precure count and names Precure.all_girls("2013-10-26").count #=> 33 Precure.all_girls.include?(Cure.echo) #=> true
[ "Get", "all", "precures" ]
bdd5efc2127774a0620399e779b076d9f8f4aeab
https://github.com/sue445/rubicure/blob/bdd5efc2127774a0620399e779b076d9f8f4aeab/lib/rubicure/core.rb#L138-L151
19,164
sue445/rubicure
lib/rubicure/core.rb
Rubicure.Core.dream_stars
def dream_stars return @dream_stars if @dream_stars girls = Precure.go_princess.girls + Precure.maho_girls.girls + Precure.a_la_mode.girls dream_stars_date = Rubicure::Movie.find(:dream_stars).started_date @dream_stars = girls.select {|girl| girl.created_date && girl.created_date <= dream_stars_date } @dream_stars end
ruby
def dream_stars return @dream_stars if @dream_stars girls = Precure.go_princess.girls + Precure.maho_girls.girls + Precure.a_la_mode.girls dream_stars_date = Rubicure::Movie.find(:dream_stars).started_date @dream_stars = girls.select {|girl| girl.created_date && girl.created_date <= dream_stars_date } @dream_stars end
[ "def", "dream_stars", "return", "@dream_stars", "if", "@dream_stars", "girls", "=", "Precure", ".", "go_princess", ".", "girls", "+", "Precure", ".", "maho_girls", ".", "girls", "+", "Precure", ".", "a_la_mode", ".", "girls", "dream_stars_date", "=", "Rubicure", "::", "Movie", ".", "find", "(", ":dream_stars", ")", ".", "started_date", "@dream_stars", "=", "girls", ".", "select", "{", "|", "girl", "|", "girl", ".", "created_date", "&&", "girl", ".", "created_date", "<=", "dream_stars_date", "}", "@dream_stars", "end" ]
Get precure dream stars @return [Array<Rubicure::Girl>] precure dream stars @example Precure.dream_stars.count #=> 12 Precure.dream_stars.map(&:precure_name) #=> ["キュアフローラ", "キュアマーメイド", "キュアトゥインクル", "キュアスカーレット", "キュアミラクル", "キュアマジカル", "キュアフェリーチェ", "キュアホイップ", "キュアカスタード", "キュアジェラート", "キュアマカロン", "キュアショコラ"]
[ "Get", "precure", "dream", "stars" ]
bdd5efc2127774a0620399e779b076d9f8f4aeab
https://github.com/sue445/rubicure/blob/bdd5efc2127774a0620399e779b076d9f8f4aeab/lib/rubicure/core.rb#L165-L174
19,165
sue445/rubicure
lib/rubicure/core.rb
Rubicure.Core.super_stars
def super_stars return @super_stars if @super_stars girls = Precure.maho_girls.girls + Precure.a_la_mode.girls + Precure.hugtto.girls super_stars_date = Rubicure::Movie.find(:super_stars).started_date @super_stars = girls.select {|girl| girl.created_date && girl.created_date <= super_stars_date } @super_stars end
ruby
def super_stars return @super_stars if @super_stars girls = Precure.maho_girls.girls + Precure.a_la_mode.girls + Precure.hugtto.girls super_stars_date = Rubicure::Movie.find(:super_stars).started_date @super_stars = girls.select {|girl| girl.created_date && girl.created_date <= super_stars_date } @super_stars end
[ "def", "super_stars", "return", "@super_stars", "if", "@super_stars", "girls", "=", "Precure", ".", "maho_girls", ".", "girls", "+", "Precure", ".", "a_la_mode", ".", "girls", "+", "Precure", ".", "hugtto", ".", "girls", "super_stars_date", "=", "Rubicure", "::", "Movie", ".", "find", "(", ":super_stars", ")", ".", "started_date", "@super_stars", "=", "girls", ".", "select", "{", "|", "girl", "|", "girl", ".", "created_date", "&&", "girl", ".", "created_date", "<=", "super_stars_date", "}", "@super_stars", "end" ]
Get precure super stars @return [Array<Rubicure::Girl>] precure super stars @example Precure.super_stars.count #=> 12 Precure.super_stars.map(&:precure_name) #=> ["キュアミラクル", "キュアマジカル", "キュアフェリーチェ", "キュアホイップ", "キュアカスタード", "キュアジェラート", "キュアマカロン", "キュアショコラ", "キュアパルフェ", "キュアエール", "キュアアンジュ", "キュアエトワール"]
[ "Get", "precure", "super", "stars" ]
bdd5efc2127774a0620399e779b076d9f8f4aeab
https://github.com/sue445/rubicure/blob/bdd5efc2127774a0620399e779b076d9f8f4aeab/lib/rubicure/core.rb#L186-L195
19,166
pinnymz/migration_comments
lib/migration_comments/active_record/connection_adapters/postgresql_adapter.rb
MigrationComments::ActiveRecord::ConnectionAdapters.PostgreSQLAdapter.set_column_comment
def set_column_comment(table_name, column_name, comment_text) execute comment_sql(CommentDefinition.new(table_name, column_name, comment_text)) end
ruby
def set_column_comment(table_name, column_name, comment_text) execute comment_sql(CommentDefinition.new(table_name, column_name, comment_text)) end
[ "def", "set_column_comment", "(", "table_name", ",", "column_name", ",", "comment_text", ")", "execute", "comment_sql", "(", "CommentDefinition", ".", "new", "(", "table_name", ",", "column_name", ",", "comment_text", ")", ")", "end" ]
Set a comment on a column
[ "Set", "a", "comment", "on", "a", "column" ]
2b62e5291deb982a5034052504fdf30cb20450bc
https://github.com/pinnymz/migration_comments/blob/2b62e5291deb982a5034052504fdf30cb20450bc/lib/migration_comments/active_record/connection_adapters/postgresql_adapter.rb#L18-L20
19,167
microformats/microformats-ruby
lib/microformats/format_parser.rb
Microformats.FormatParser.imply_dates
def imply_dates return unless !@properties['end'].nil? && !@properties['start'].nil? start_date = nil @properties['start'].each do |start_val| if start_val =~ /^(\d{4}-[01]\d-[0-3]\d)/ start_date = Regexp.last_match(1) if start_date.nil? elsif start_val =~ /^(\d{4}-[0-3]\d\d)/ start_date = Regexp.last_match(1) if start_date.nil? end end unless start_date.nil? @properties['end'].map! do |end_val| if end_val.match?(/^\d{4}-[01]\d-[0-3]\d/) end_val elsif end_val.match?(/^\d{4}-[0-3]\d\d/) end_val else start_date + ' ' + end_val end end end end
ruby
def imply_dates return unless !@properties['end'].nil? && !@properties['start'].nil? start_date = nil @properties['start'].each do |start_val| if start_val =~ /^(\d{4}-[01]\d-[0-3]\d)/ start_date = Regexp.last_match(1) if start_date.nil? elsif start_val =~ /^(\d{4}-[0-3]\d\d)/ start_date = Regexp.last_match(1) if start_date.nil? end end unless start_date.nil? @properties['end'].map! do |end_val| if end_val.match?(/^\d{4}-[01]\d-[0-3]\d/) end_val elsif end_val.match?(/^\d{4}-[0-3]\d\d/) end_val else start_date + ' ' + end_val end end end end
[ "def", "imply_dates", "return", "unless", "!", "@properties", "[", "'end'", "]", ".", "nil?", "&&", "!", "@properties", "[", "'start'", "]", ".", "nil?", "start_date", "=", "nil", "@properties", "[", "'start'", "]", ".", "each", "do", "|", "start_val", "|", "if", "start_val", "=~", "/", "\\d", "\\d", "\\d", "/", "start_date", "=", "Regexp", ".", "last_match", "(", "1", ")", "if", "start_date", ".", "nil?", "elsif", "start_val", "=~", "/", "\\d", "\\d", "\\d", "/", "start_date", "=", "Regexp", ".", "last_match", "(", "1", ")", "if", "start_date", ".", "nil?", "end", "end", "unless", "start_date", ".", "nil?", "@properties", "[", "'end'", "]", ".", "map!", "do", "|", "end_val", "|", "if", "end_val", ".", "match?", "(", "/", "\\d", "\\d", "\\d", "/", ")", "end_val", "elsif", "end_val", ".", "match?", "(", "/", "\\d", "\\d", "\\d", "/", ")", "end_val", "else", "start_date", "+", "' '", "+", "end_val", "end", "end", "end", "end" ]
imply date for dt-end if dt-start is defined with a date
[ "imply", "date", "for", "dt", "-", "end", "if", "dt", "-", "start", "is", "defined", "with", "a", "date" ]
d0841b2489ce7bf6fbae03d3e3aa1ecfbf56e98b
https://github.com/microformats/microformats-ruby/blob/d0841b2489ce7bf6fbae03d3e3aa1ecfbf56e98b/lib/microformats/format_parser.rb#L323-L347
19,168
justindomingue/markov_chains
lib/markov_chains/generator.rb
MarkovChains.Generator.get_sentences
def get_sentences(n) sentences = [] n.times do sentence = @dict.get_start_words while nw = @dict.get(sentence[-@dict.order, @dict.order]) sentence << nw end sentences << (sentence[0...-1].join(" ").gsub(/\s([,;:])/, '\1') << sentence.last) end sentences end
ruby
def get_sentences(n) sentences = [] n.times do sentence = @dict.get_start_words while nw = @dict.get(sentence[-@dict.order, @dict.order]) sentence << nw end sentences << (sentence[0...-1].join(" ").gsub(/\s([,;:])/, '\1') << sentence.last) end sentences end
[ "def", "get_sentences", "(", "n", ")", "sentences", "=", "[", "]", "n", ".", "times", "do", "sentence", "=", "@dict", ".", "get_start_words", "while", "nw", "=", "@dict", ".", "get", "(", "sentence", "[", "-", "@dict", ".", "order", ",", "@dict", ".", "order", "]", ")", "sentence", "<<", "nw", "end", "sentences", "<<", "(", "sentence", "[", "0", "...", "-", "1", "]", ".", "join", "(", "\" \"", ")", ".", "gsub", "(", "/", "\\s", "/", ",", "'\\1'", ")", "<<", "sentence", ".", "last", ")", "end", "sentences", "end" ]
Initializes the generator @example Create a new generator MarkovChains::Generator.new(text) @param Text source to generate sentences from Returns a given number of randonly generated sentences @example Get 5 sentences get_sentences(5) @param n [int] number of sentences to generate @return Array conataining generated sentences
[ "Initializes", "the", "generator" ]
cc94beb2ad17bea13db6cb9dacaa5bf23e7274e8
https://github.com/justindomingue/markov_chains/blob/cc94beb2ad17bea13db6cb9dacaa5bf23e7274e8/lib/markov_chains/generator.rb#L23-L37
19,169
codez/dry_crud
app/controllers/dry_crud/nestable.rb
DryCrud.Nestable.parents
def parents @parents ||= Array(nesting).map do |p| if p.is_a?(Class) && p < ActiveRecord::Base parent_entry(p) else p end end end
ruby
def parents @parents ||= Array(nesting).map do |p| if p.is_a?(Class) && p < ActiveRecord::Base parent_entry(p) else p end end end
[ "def", "parents", "@parents", "||=", "Array", "(", "nesting", ")", ".", "map", "do", "|", "p", "|", "if", "p", ".", "is_a?", "(", "Class", ")", "&&", "p", "<", "ActiveRecord", "::", "Base", "parent_entry", "(", "p", ")", "else", "p", "end", "end", "end" ]
Returns the parent entries of the current request, if any. These are ActiveRecords or namespace symbols, corresponding to the defined nesting attribute.
[ "Returns", "the", "parent", "entries", "of", "the", "current", "request", "if", "any", ".", "These", "are", "ActiveRecords", "or", "namespace", "symbols", "corresponding", "to", "the", "defined", "nesting", "attribute", "." ]
2d034b25fe3fc2a096c602f59a29fe7be152b050
https://github.com/codez/dry_crud/blob/2d034b25fe3fc2a096c602f59a29fe7be152b050/app/controllers/dry_crud/nestable.rb#L30-L38
19,170
nccgroup/BinProxy
lib/binproxy/proxy_message.rb
BinProxy.ProxyMessage.headers
def headers super.merge({ size: @raw.length, # HACK - this will prevent errors, but will mangle anything that isn't # actually utf8. We should try to handle this upstream where we might # know what the actual encoding is. summary: @message.summary.force_encoding('UTF-8').scrub, message_class: @message_class.to_s, }) end
ruby
def headers super.merge({ size: @raw.length, # HACK - this will prevent errors, but will mangle anything that isn't # actually utf8. We should try to handle this upstream where we might # know what the actual encoding is. summary: @message.summary.force_encoding('UTF-8').scrub, message_class: @message_class.to_s, }) end
[ "def", "headers", "super", ".", "merge", "(", "{", "size", ":", "@raw", ".", "length", ",", "# HACK - this will prevent errors, but will mangle anything that isn't", "# actually utf8. We should try to handle this upstream where we might", "# know what the actual encoding is.", "summary", ":", "@message", ".", "summary", ".", "force_encoding", "(", "'UTF-8'", ")", ".", "scrub", ",", "message_class", ":", "@message_class", ".", "to_s", ",", "}", ")", "end" ]
The next two methods are the last stop before JSON encoding, so all strings in the returned hash must be UTF-8 compatible.
[ "The", "next", "two", "methods", "are", "the", "last", "stop", "before", "JSON", "encoding", "so", "all", "strings", "in", "the", "returned", "hash", "must", "be", "UTF", "-", "8", "compatible", "." ]
d02fce91a1bd5aa0bd4b99a6f60f65ddc9d33c27
https://github.com/nccgroup/BinProxy/blob/d02fce91a1bd5aa0bd4b99a6f60f65ddc9d33c27/lib/binproxy/proxy_message.rb#L106-L115
19,171
nccgroup/BinProxy
lib/binproxy/parser.rb
BinProxy.Parser.parse
def parse(raw_buffer, peer) start_pos = nil loop do break if raw_buffer.eof? start_pos = raw_buffer.pos log.debug "at #{start_pos} of #{raw_buffer.length} in buffer" read_fn = lambda { message_class.new(src: peer.to_s, protocol_state: @protocol_state).read(raw_buffer) } message = if log.debug? BinData::trace_reading &read_fn else read_fn.call end bytes_read = raw_buffer.pos - start_pos log.debug "read #{bytes_read} bytes" # Go back and grab raw bytes for validation of serialization raw_buffer.pos = start_pos raw_m = raw_buffer.read bytes_read @protocol_state = message.update_state log.debug "protocol state is now #{@protocol_state.inspect}" pm = ProxyMessage.new(raw_m, message) pm.src = peer yield pm end rescue EOFError, IOError log.info "Hit end of buffer while parsing. Consumed #{raw_buffer.pos - start_pos} bytes." raw_buffer.pos = start_pos #rewind partial read #todo, warn to client if validate flag set? rescue Exception => e log.err_trace(e, 'parsing message (probably an issue with user BinData class)', ::Logger::WARN) self.class.proxy.on_bindata_error('parsing', e) end
ruby
def parse(raw_buffer, peer) start_pos = nil loop do break if raw_buffer.eof? start_pos = raw_buffer.pos log.debug "at #{start_pos} of #{raw_buffer.length} in buffer" read_fn = lambda { message_class.new(src: peer.to_s, protocol_state: @protocol_state).read(raw_buffer) } message = if log.debug? BinData::trace_reading &read_fn else read_fn.call end bytes_read = raw_buffer.pos - start_pos log.debug "read #{bytes_read} bytes" # Go back and grab raw bytes for validation of serialization raw_buffer.pos = start_pos raw_m = raw_buffer.read bytes_read @protocol_state = message.update_state log.debug "protocol state is now #{@protocol_state.inspect}" pm = ProxyMessage.new(raw_m, message) pm.src = peer yield pm end rescue EOFError, IOError log.info "Hit end of buffer while parsing. Consumed #{raw_buffer.pos - start_pos} bytes." raw_buffer.pos = start_pos #rewind partial read #todo, warn to client if validate flag set? rescue Exception => e log.err_trace(e, 'parsing message (probably an issue with user BinData class)', ::Logger::WARN) self.class.proxy.on_bindata_error('parsing', e) end
[ "def", "parse", "(", "raw_buffer", ",", "peer", ")", "start_pos", "=", "nil", "loop", "do", "break", "if", "raw_buffer", ".", "eof?", "start_pos", "=", "raw_buffer", ".", "pos", "log", ".", "debug", "\"at #{start_pos} of #{raw_buffer.length} in buffer\"", "read_fn", "=", "lambda", "{", "message_class", ".", "new", "(", "src", ":", "peer", ".", "to_s", ",", "protocol_state", ":", "@protocol_state", ")", ".", "read", "(", "raw_buffer", ")", "}", "message", "=", "if", "log", ".", "debug?", "BinData", "::", "trace_reading", "read_fn", "else", "read_fn", ".", "call", "end", "bytes_read", "=", "raw_buffer", ".", "pos", "-", "start_pos", "log", ".", "debug", "\"read #{bytes_read} bytes\"", "# Go back and grab raw bytes for validation of serialization", "raw_buffer", ".", "pos", "=", "start_pos", "raw_m", "=", "raw_buffer", ".", "read", "bytes_read", "@protocol_state", "=", "message", ".", "update_state", "log", ".", "debug", "\"protocol state is now #{@protocol_state.inspect}\"", "pm", "=", "ProxyMessage", ".", "new", "(", "raw_m", ",", "message", ")", "pm", ".", "src", "=", "peer", "yield", "pm", "end", "rescue", "EOFError", ",", "IOError", "log", ".", "info", "\"Hit end of buffer while parsing. Consumed #{raw_buffer.pos - start_pos} bytes.\"", "raw_buffer", ".", "pos", "=", "start_pos", "#rewind partial read", "#todo, warn to client if validate flag set?", "rescue", "Exception", "=>", "e", "log", ".", "err_trace", "(", "e", ",", "'parsing message (probably an issue with user BinData class)'", ",", "::", "Logger", "::", "WARN", ")", "self", ".", "class", ".", "proxy", ".", "on_bindata_error", "(", "'parsing'", ",", "e", ")", "end" ]
Try to parse one or more messages from the buffer, and yield them
[ "Try", "to", "parse", "one", "or", "more", "messages", "from", "the", "buffer", "and", "yield", "them" ]
d02fce91a1bd5aa0bd4b99a6f60f65ddc9d33c27
https://github.com/nccgroup/BinProxy/blob/d02fce91a1bd5aa0bd4b99a6f60f65ddc9d33c27/lib/binproxy/parser.rb#L36-L74
19,172
nccgroup/BinProxy
lib/binproxy/connection.rb
BinProxy.Connection.connect
def connect(host=nil, port=nil, &cb) host ||= opts[:upstream_host] || raise('no upstream host') port ||= opts[:upstream_port] || raise('no upstream port') cb ||= lambda { |conn| opts[:session_callback].call(self, conn) } log.debug "Making upstream connection to #{host}:#{port}" EM.connect(host, port, Connection, opts[:upstream_args], &cb) end
ruby
def connect(host=nil, port=nil, &cb) host ||= opts[:upstream_host] || raise('no upstream host') port ||= opts[:upstream_port] || raise('no upstream port') cb ||= lambda { |conn| opts[:session_callback].call(self, conn) } log.debug "Making upstream connection to #{host}:#{port}" EM.connect(host, port, Connection, opts[:upstream_args], &cb) end
[ "def", "connect", "(", "host", "=", "nil", ",", "port", "=", "nil", ",", "&", "cb", ")", "host", "||=", "opts", "[", ":upstream_host", "]", "||", "raise", "(", "'no upstream host'", ")", "port", "||=", "opts", "[", ":upstream_port", "]", "||", "raise", "(", "'no upstream port'", ")", "cb", "||=", "lambda", "{", "|", "conn", "|", "opts", "[", ":session_callback", "]", ".", "call", "(", "self", ",", "conn", ")", "}", "log", ".", "debug", "\"Making upstream connection to #{host}:#{port}\"", "EM", ".", "connect", "(", "host", ",", "port", ",", "Connection", ",", "opts", "[", ":upstream_args", "]", ",", "cb", ")", "end" ]
Used by filters to initiate upstream connection in response to inbound connection
[ "Used", "by", "filters", "to", "initiate", "upstream", "connection", "in", "response", "to", "inbound", "connection" ]
d02fce91a1bd5aa0bd4b99a6f60f65ddc9d33c27
https://github.com/nccgroup/BinProxy/blob/d02fce91a1bd5aa0bd4b99a6f60f65ddc9d33c27/lib/binproxy/connection.rb#L37-L43
19,173
nccgroup/BinProxy
lib/binproxy/connection.rb
BinProxy.Connection.send_message
def send_message(pm) log.error "OOPS! message going the wrong way (to #{peer})" if pm.dest != peer data = pm.to_binary_s @filters.each do |f| data = f.write data return if data.nil? or data == '' end send_data(data) end
ruby
def send_message(pm) log.error "OOPS! message going the wrong way (to #{peer})" if pm.dest != peer data = pm.to_binary_s @filters.each do |f| data = f.write data return if data.nil? or data == '' end send_data(data) end
[ "def", "send_message", "(", "pm", ")", "log", ".", "error", "\"OOPS! message going the wrong way (to #{peer})\"", "if", "pm", ".", "dest", "!=", "peer", "data", "=", "pm", ".", "to_binary_s", "@filters", ".", "each", "do", "|", "f", "|", "data", "=", "f", ".", "write", "data", "return", "if", "data", ".", "nil?", "or", "data", "==", "''", "end", "send_data", "(", "data", ")", "end" ]
called with a ProxyMessage
[ "called", "with", "a", "ProxyMessage" ]
d02fce91a1bd5aa0bd4b99a6f60f65ddc9d33c27
https://github.com/nccgroup/BinProxy/blob/d02fce91a1bd5aa0bd4b99a6f60f65ddc9d33c27/lib/binproxy/connection.rb#L84-L93
19,174
nccgroup/BinProxy
lib/binproxy/parsers/zmq.rb
ZMQ.Message.update_state
def update_state current_state.dup.tap do |s| src = eval_parameter :src s[src] = next_state s[src] end end
ruby
def update_state current_state.dup.tap do |s| src = eval_parameter :src s[src] = next_state s[src] end end
[ "def", "update_state", "current_state", ".", "dup", ".", "tap", "do", "|", "s", "|", "src", "=", "eval_parameter", ":src", "s", "[", "src", "]", "=", "next_state", "s", "[", "src", "]", "end", "end" ]
Protocol is symmetrical. Each endpoint has its own state. This is a bit clunky and maybe should be abstracted into a module? Or update parser.rb to differentiate between proto-shared and endpoint-separate state?
[ "Protocol", "is", "symmetrical", ".", "Each", "endpoint", "has", "its", "own", "state", ".", "This", "is", "a", "bit", "clunky", "and", "maybe", "should", "be", "abstracted", "into", "a", "module?", "Or", "update", "parser", ".", "rb", "to", "differentiate", "between", "proto", "-", "shared", "and", "endpoint", "-", "separate", "state?" ]
d02fce91a1bd5aa0bd4b99a6f60f65ddc9d33c27
https://github.com/nccgroup/BinProxy/blob/d02fce91a1bd5aa0bd4b99a6f60f65ddc9d33c27/lib/binproxy/parsers/zmq.rb#L47-L52
19,175
couchbase/couchbase-ruby-client
lib/couchbase/cluster.rb
Couchbase.Cluster.create_bucket
def create_bucket(name, options = {}) defaults = { :type => "couchbase", :ram_quota => 100, :replica_number => 1, :auth_type => "sasl", :sasl_password => "", :proxy_port => nil, :flush_enabled => false, :replica_index => true, :parallel_db_and_view_compaction => false } options = defaults.merge(options) params = {"name" => name} params["bucketType"] = options[:type] params["ramQuotaMB"] = options[:ram_quota] params["replicaNumber"] = options[:replica_number] params["authType"] = options[:auth_type] params["saslPassword"] = options[:sasl_password] params["proxyPort"] = options[:proxy_port] params["flushEnabled"] = options[:flush_enabled] ? 1 : 0 params["replicaIndex"] = options[:replica_index] ? 1 : 0 params["parallelDBAndViewCompaction"] = !!options[:parallel_db_and_view_compaction] payload = Utils.encode_params(params.reject! { |_k, v| v.nil? }) response = @connection.send(:__http_query, :management, :post, "/pools/default/buckets", payload, "application/x-www-form-urlencoded", nil, nil, nil) Result.new(response.merge(:operation => :create_bucket)) end
ruby
def create_bucket(name, options = {}) defaults = { :type => "couchbase", :ram_quota => 100, :replica_number => 1, :auth_type => "sasl", :sasl_password => "", :proxy_port => nil, :flush_enabled => false, :replica_index => true, :parallel_db_and_view_compaction => false } options = defaults.merge(options) params = {"name" => name} params["bucketType"] = options[:type] params["ramQuotaMB"] = options[:ram_quota] params["replicaNumber"] = options[:replica_number] params["authType"] = options[:auth_type] params["saslPassword"] = options[:sasl_password] params["proxyPort"] = options[:proxy_port] params["flushEnabled"] = options[:flush_enabled] ? 1 : 0 params["replicaIndex"] = options[:replica_index] ? 1 : 0 params["parallelDBAndViewCompaction"] = !!options[:parallel_db_and_view_compaction] payload = Utils.encode_params(params.reject! { |_k, v| v.nil? }) response = @connection.send(:__http_query, :management, :post, "/pools/default/buckets", payload, "application/x-www-form-urlencoded", nil, nil, nil) Result.new(response.merge(:operation => :create_bucket)) end
[ "def", "create_bucket", "(", "name", ",", "options", "=", "{", "}", ")", "defaults", "=", "{", ":type", "=>", "\"couchbase\"", ",", ":ram_quota", "=>", "100", ",", ":replica_number", "=>", "1", ",", ":auth_type", "=>", "\"sasl\"", ",", ":sasl_password", "=>", "\"\"", ",", ":proxy_port", "=>", "nil", ",", ":flush_enabled", "=>", "false", ",", ":replica_index", "=>", "true", ",", ":parallel_db_and_view_compaction", "=>", "false", "}", "options", "=", "defaults", ".", "merge", "(", "options", ")", "params", "=", "{", "\"name\"", "=>", "name", "}", "params", "[", "\"bucketType\"", "]", "=", "options", "[", ":type", "]", "params", "[", "\"ramQuotaMB\"", "]", "=", "options", "[", ":ram_quota", "]", "params", "[", "\"replicaNumber\"", "]", "=", "options", "[", ":replica_number", "]", "params", "[", "\"authType\"", "]", "=", "options", "[", ":auth_type", "]", "params", "[", "\"saslPassword\"", "]", "=", "options", "[", ":sasl_password", "]", "params", "[", "\"proxyPort\"", "]", "=", "options", "[", ":proxy_port", "]", "params", "[", "\"flushEnabled\"", "]", "=", "options", "[", ":flush_enabled", "]", "?", "1", ":", "0", "params", "[", "\"replicaIndex\"", "]", "=", "options", "[", ":replica_index", "]", "?", "1", ":", "0", "params", "[", "\"parallelDBAndViewCompaction\"", "]", "=", "!", "!", "options", "[", ":parallel_db_and_view_compaction", "]", "payload", "=", "Utils", ".", "encode_params", "(", "params", ".", "reject!", "{", "|", "_k", ",", "v", "|", "v", ".", "nil?", "}", ")", "response", "=", "@connection", ".", "send", "(", ":__http_query", ",", ":management", ",", ":post", ",", "\"/pools/default/buckets\"", ",", "payload", ",", "\"application/x-www-form-urlencoded\"", ",", "nil", ",", "nil", ",", "nil", ")", "Result", ".", "new", "(", "response", ".", "merge", "(", ":operation", "=>", ":create_bucket", ")", ")", "end" ]
Establish connection to the cluster for administration @param [String] connstr ("couchbasae://localhost") connection string @param [Hash] options The connection parameter @option options [String] :username The username @option options [String] :password The password Create data bucket @param [String] name The name of the bucket @param [Hash] options The bucket parameters @option options [String] :bucket_type ("couchbase") The type of the bucket. Possible values are "memcached" and "couchbase". @option options [Fixnum] :ram_quota (100) The RAM quota in megabytes. @option options [Fixnum] :replica_number (1) The number of replicas of each document. Minimum 0, maximum 3. @option options [String] :auth_type ("sasl") The authentication type. Possible values are "sasl" and "none". Note you should specify free port for "none" @option options [Fixnum] :proxy_port The port for moxi @option options [true, false] :replica_index (true) Disable or enable indexes for bucket replicas @option options [true, false] :flush_enabled (false) Enables the 'flush all' functionality on the specified bucket. @option options [true, false] :parallel_db_and_view_compaction (false) Indicates whether database and view files on disk can be compacted simultaneously
[ "Establish", "connection", "to", "the", "cluster", "for", "administration" ]
ecce41a5996d9a97d6182e120bd9b5296707b353
https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/cluster.rb#L54-L82
19,176
couchbase/couchbase-ruby-client
lib/couchbase/dns.rb
Couchbase.DNS.locate
def locate(name, bootstrap_protocol = :http) service = case bootstrap_protocol when :http "_cbhttp" when :cccp "_cbmcd" else raise ArgumentError, "unknown bootstrap protocol: #{bootstrap_transports}" end hosts = [] Resolv::DNS.open do |dns| resources = dns.getresources("#{service}._tcp.#{name}", Resolv::DNS::Resource::IN::SRV) hosts = resources.sort_by(&:priority).map { |res| "#{res.target}:#{res.port}" } end hosts end
ruby
def locate(name, bootstrap_protocol = :http) service = case bootstrap_protocol when :http "_cbhttp" when :cccp "_cbmcd" else raise ArgumentError, "unknown bootstrap protocol: #{bootstrap_transports}" end hosts = [] Resolv::DNS.open do |dns| resources = dns.getresources("#{service}._tcp.#{name}", Resolv::DNS::Resource::IN::SRV) hosts = resources.sort_by(&:priority).map { |res| "#{res.target}:#{res.port}" } end hosts end
[ "def", "locate", "(", "name", ",", "bootstrap_protocol", "=", ":http", ")", "service", "=", "case", "bootstrap_protocol", "when", ":http", "\"_cbhttp\"", "when", ":cccp", "\"_cbmcd\"", "else", "raise", "ArgumentError", ",", "\"unknown bootstrap protocol: #{bootstrap_transports}\"", "end", "hosts", "=", "[", "]", "Resolv", "::", "DNS", ".", "open", "do", "|", "dns", "|", "resources", "=", "dns", ".", "getresources", "(", "\"#{service}._tcp.#{name}\"", ",", "Resolv", "::", "DNS", "::", "Resource", "::", "IN", "::", "SRV", ")", "hosts", "=", "resources", ".", "sort_by", "(", ":priority", ")", ".", "map", "{", "|", "res", "|", "\"#{res.target}:#{res.port}\"", "}", "end", "hosts", "end" ]
Locate bootstrap nodes from a DNS SRV record. @note This is experimental interface. It might change in future (e.g. service identifiers) The DNS SRV records need to be configured on a reachable DNS server. An example configuration could look like the following: _cbmcd._tcp.example.com. 0 IN SRV 20 0 11210 node2.example.com. _cbmcd._tcp.example.com. 0 IN SRV 10 0 11210 node1.example.com. _cbmcd._tcp.example.com. 0 IN SRV 30 0 11210 node3.example.com. _cbhttp._tcp.example.com. 0 IN SRV 20 0 8091 node2.example.com. _cbhttp._tcp.example.com. 0 IN SRV 10 0 8091 node1.example.com. _cbhttp._tcp.example.com. 0 IN SRV 30 0 8091 node3.example.com. Now if "example.com" is passed in as the argument, the three nodes configured will be parsed and put in the returned URI list. Note that the priority is respected (in this example, node1 will be the first one in the list, followed by node2 and node3). As of now, weighting is not supported. @param name the DNS name where SRV records configured @param bootstrap_protocol (Symbol) the desired protocol for bootstrapping. See +bootstrap_protocols+ option to {Couchbase::Bucket#new}. Allowed values +:http, :cccp+ @return a list of ordered boostrap URIs by their weight. @example Initialize connection using DNS SRV records nodes = Couchbase::DNS.locate('example.com', :http) if nodes.empty? nodes = ["example.com:8091"] end Couchbase.connect(:node_list => nodes)
[ "Locate", "bootstrap", "nodes", "from", "a", "DNS", "SRV", "record", "." ]
ecce41a5996d9a97d6182e120bd9b5296707b353
https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/dns.rb#L57-L72
19,177
couchbase/couchbase-ruby-client
lib/couchbase/view.rb
Couchbase.View.fetch
def fetch(params = {}) params = @params.merge(params) options = {} options[:include_docs] = params.delete(:include_docs) if params.key?(:include_docs) options[:format] = params.delete(:format) if params.key?(:format) options[:transcoder] = params.delete(:transcoder) if params.key?(:transcoder) options[:spatial] = params.delete(:spatial) if params.key?(:spatial) body = params.delete(:body) || {} body = MultiJson.dump(body) unless body.is_a?(String) res = @bucket.send(:__view_query, @ddoc, @view, Utils.encode_params(params), body, options) raise res[:error] if res[:error] meta = MultiJson.load(res[:meta]) send_error(meta[S_ERRORS][S_FROM], meta[S_ERRORS][S_REASON]) if meta[S_ERRORS] if block_given? res[:rows].each do |row| yield @wrapper_class.wrap(row) end else rows = res[:rows].map { |row| @wrapper_class.wrap(row) } ArrayWithTotalRows.new(rows, meta[S_TOTAL_ROWS]) end end
ruby
def fetch(params = {}) params = @params.merge(params) options = {} options[:include_docs] = params.delete(:include_docs) if params.key?(:include_docs) options[:format] = params.delete(:format) if params.key?(:format) options[:transcoder] = params.delete(:transcoder) if params.key?(:transcoder) options[:spatial] = params.delete(:spatial) if params.key?(:spatial) body = params.delete(:body) || {} body = MultiJson.dump(body) unless body.is_a?(String) res = @bucket.send(:__view_query, @ddoc, @view, Utils.encode_params(params), body, options) raise res[:error] if res[:error] meta = MultiJson.load(res[:meta]) send_error(meta[S_ERRORS][S_FROM], meta[S_ERRORS][S_REASON]) if meta[S_ERRORS] if block_given? res[:rows].each do |row| yield @wrapper_class.wrap(row) end else rows = res[:rows].map { |row| @wrapper_class.wrap(row) } ArrayWithTotalRows.new(rows, meta[S_TOTAL_ROWS]) end end
[ "def", "fetch", "(", "params", "=", "{", "}", ")", "params", "=", "@params", ".", "merge", "(", "params", ")", "options", "=", "{", "}", "options", "[", ":include_docs", "]", "=", "params", ".", "delete", "(", ":include_docs", ")", "if", "params", ".", "key?", "(", ":include_docs", ")", "options", "[", ":format", "]", "=", "params", ".", "delete", "(", ":format", ")", "if", "params", ".", "key?", "(", ":format", ")", "options", "[", ":transcoder", "]", "=", "params", ".", "delete", "(", ":transcoder", ")", "if", "params", ".", "key?", "(", ":transcoder", ")", "options", "[", ":spatial", "]", "=", "params", ".", "delete", "(", ":spatial", ")", "if", "params", ".", "key?", "(", ":spatial", ")", "body", "=", "params", ".", "delete", "(", ":body", ")", "||", "{", "}", "body", "=", "MultiJson", ".", "dump", "(", "body", ")", "unless", "body", ".", "is_a?", "(", "String", ")", "res", "=", "@bucket", ".", "send", "(", ":__view_query", ",", "@ddoc", ",", "@view", ",", "Utils", ".", "encode_params", "(", "params", ")", ",", "body", ",", "options", ")", "raise", "res", "[", ":error", "]", "if", "res", "[", ":error", "]", "meta", "=", "MultiJson", ".", "load", "(", "res", "[", ":meta", "]", ")", "send_error", "(", "meta", "[", "S_ERRORS", "]", "[", "S_FROM", "]", ",", "meta", "[", "S_ERRORS", "]", "[", "S_REASON", "]", ")", "if", "meta", "[", "S_ERRORS", "]", "if", "block_given?", "res", "[", ":rows", "]", ".", "each", "do", "|", "row", "|", "yield", "@wrapper_class", ".", "wrap", "(", "row", ")", "end", "else", "rows", "=", "res", "[", ":rows", "]", ".", "map", "{", "|", "row", "|", "@wrapper_class", ".", "wrap", "(", "row", ")", "}", "ArrayWithTotalRows", ".", "new", "(", "rows", ",", "meta", "[", "S_TOTAL_ROWS", "]", ")", "end", "end" ]
Performs query to Couchbase view. This method will stream results if block given or return complete result set otherwise. In latter case it defines method +total_rows+ returning corresponding entry from Couchbase result object. @note Avoid using +$+ symbol as prefix for properties in your documents, because server marks with it meta fields like flags and expiration, therefore dollar prefix is some kind of reserved. It won't hurt your application. Currently the {ViewRow} class extracts +$flags+, +$cas+ and +$expiration+ properties from the document and store them in {ViewRow#meta} hash. @param [Hash] params parameters for Couchbase query. @option params [true, false] :include_docs (false) Include the full content of the documents in the return. Note that the document is fetched from the in memory cache where it may have been changed or even deleted. See also +:quiet+ parameter below to control error reporting during fetch. @option params [true, false] :quiet (true) Do not raise error if associated document not found in the memory. If the parameter +true+ will use +nil+ value instead. @option params [true, false] :descending (false) Return the documents in descending by key order @option params [String, Fixnum, Hash, Array] :key Return only documents that match the specified key. Will be JSON encoded. @option params [Array] :keys The same as +:key+, but will work for set of keys. Will be JSON encoded. @option params [String, Fixnum, Hash, Array] :startkey Return records starting with the specified key. +:start_key+ option should also work here. Will be JSON encoded. @option params [String] :startkey_docid Document id to start with (to allow pagination for duplicate startkeys). +:start_key_doc_id+ also should work. @option params [String, Fixnum, Hash, Array] :endkey Stop returning records when the specified key is reached. +:end_key+ option should also work here. Will be JSON encoded. @option params [String] :endkey_docid Last document id to include in the output (to allow pagination for duplicate startkeys). +:end_key_doc_id+ also should work. @option params [true, false] :inclusive_end (true) Specifies whether the specified end key should be included in the result @option params [Fixnum] :limit Limit the number of documents in the output. @option params [Fixnum] :skip Skip this number of records before starting to return the results. @option params [String, Symbol] :on_error (:continue) Sets the response in the event of an error. Supported values: :continue:: Continue to generate view information in the event of an error, including the error information in the view response stream. :stop:: Stop immediately when an error condition occurs. No further view information will be returned. @option params [Fixnum] :connection_timeout (75000) Timeout before the view request is dropped (milliseconds) @option params [true, false] :reduce (true) Use the reduction function @option params [true, false] :group (false) Group the results using the reduce function to a group or single row. @option params [Fixnum] :group_level Specify the group level to be used. @option params [String, Symbol, false] :stale (:update_after) Allow the results from a stale view to be used. Supported values: false:: Force a view update before returning data :ok:: Allow stale views :update_after:: Allow stale view, update view after it has been accessed @option params [Hash] :body Accepts the same parameters, except +:body+ of course, but sends them in POST body instead of query string. It could be useful for really large and complex parameters. @yieldparam [Couchbase::ViewRow] document @return [Array] with documents. There will be +total_entries+ method defined on this array if it's possible. @raise [Couchbase::Error::View] when +on_error+ callback is nil and error object found in the result stream. @example Query +recent_posts+ view with key filter doc.recent_posts(:body => {:keys => ["key1", "key2"]}) @example Fetch second page of result set (splitted in 10 items per page) page = 2 per_page = 10 doc.recent_posts(:skip => (page - 1) * per_page, :limit => per_page) @example Simple join using Map/Reduce # Given the bucket with Posts(:id, :type, :title, :body) and # Comments(:id, :type, :post_id, :author, :body). The map function # below (in javascript) will build the View index called # "recent_posts_with_comments" which will behave like left inner join. # function(doc) { # switch (doc.type) { # case "Post": # emit([doc.id, 0], null); # break; # case "Comment": # emit([doc.post_id, 1], null); # break; # } # } post_id = 42 doc.recent_posts_with_comments(:start_key => [post_id, 0], :end_key => [post_id, 1], :include_docs => true)
[ "Performs", "query", "to", "Couchbase", "view", ".", "This", "method", "will", "stream", "results", "if", "block", "given", "or", "return", "complete", "result", "set", "otherwise", ".", "In", "latter", "case", "it", "defines", "method", "+", "total_rows", "+", "returning", "corresponding", "entry", "from", "Couchbase", "result", "object", "." ]
ecce41a5996d9a97d6182e120bd9b5296707b353
https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/view.rb#L271-L293
19,178
couchbase/couchbase-ruby-client
lib/couchbase/view_row.rb
Couchbase.DesignDoc.method_missing
def method_missing(meth, *args) name, options = @all_views[meth.to_s] if name View.new(@bucket, @id, name, (args[0] || {}).merge(options)) else super end end
ruby
def method_missing(meth, *args) name, options = @all_views[meth.to_s] if name View.new(@bucket, @id, name, (args[0] || {}).merge(options)) else super end end
[ "def", "method_missing", "(", "meth", ",", "*", "args", ")", "name", ",", "options", "=", "@all_views", "[", "meth", ".", "to_s", "]", "if", "name", "View", ".", "new", "(", "@bucket", ",", "@id", ",", "name", ",", "(", "args", "[", "0", "]", "||", "{", "}", ")", ".", "merge", "(", "options", ")", ")", "else", "super", "end", "end" ]
Initialize the design doc instance @since 1.2.1 It takes reference to the bucket, data hash. It will define view methods if the data object looks like design document. @param [Couchbase::Bucket] bucket the reference to connection @param [Hash] data the data hash, which was built from JSON document representation
[ "Initialize", "the", "design", "doc", "instance" ]
ecce41a5996d9a97d6182e120bd9b5296707b353
https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/view_row.rb#L198-L205
19,179
couchbase/couchbase-ruby-client
lib/couchbase/bucket.rb
Couchbase.Bucket.cas
def cas(key, options = {}) retries_remaining = options.delete(:retry) || 0 loop do res = get(key, options) val = yield(res.value) # get new value from caller res = set(key, val, options.merge(:cas => res.cas)) if res.error && res.error.code == Couchbase::LibraryError::LCB_KEY_EEXISTS if retries_remaining > 0 retries_remaining -= 1 next end end return res end end
ruby
def cas(key, options = {}) retries_remaining = options.delete(:retry) || 0 loop do res = get(key, options) val = yield(res.value) # get new value from caller res = set(key, val, options.merge(:cas => res.cas)) if res.error && res.error.code == Couchbase::LibraryError::LCB_KEY_EEXISTS if retries_remaining > 0 retries_remaining -= 1 next end end return res end end
[ "def", "cas", "(", "key", ",", "options", "=", "{", "}", ")", "retries_remaining", "=", "options", ".", "delete", "(", ":retry", ")", "||", "0", "loop", "do", "res", "=", "get", "(", "key", ",", "options", ")", "val", "=", "yield", "(", "res", ".", "value", ")", "# get new value from caller", "res", "=", "set", "(", "key", ",", "val", ",", "options", ".", "merge", "(", ":cas", "=>", "res", ".", "cas", ")", ")", "if", "res", ".", "error", "&&", "res", ".", "error", ".", "code", "==", "Couchbase", "::", "LibraryError", "::", "LCB_KEY_EEXISTS", "if", "retries_remaining", ">", "0", "retries_remaining", "-=", "1", "next", "end", "end", "return", "res", "end", "end" ]
Compare and swap value. @since 1.0.0 Reads a key's value from the server and yields it to a block. Replaces the key's value with the result of the block as long as the key hasn't been updated in the meantime, otherwise raises {Couchbase::Error::KeyExists}. CAS stands for "compare and swap", and avoids the need for manual key mutexing. Read more info here: @see http://couchbase.com/docs/memcached-api/memcached-api-protocol-text_cas.html Setting the +:retry+ option to a positive number will cause this method to rescue the {Couchbase::Error::KeyExists} error that happens when an update collision is detected, and automatically get a fresh copy of the value and retry the block. This will repeat as long as there continues to be conflicts, up to the maximum number of retries specified. @param [String, Symbol] key @param [Hash] options the options for "swap" part @option options [Fixnum] :ttl (self.default_ttl) the time to live of this key @option options [Symbol] :format (self.default_format) format of the value @option options [Fixnum] :flags (self.default_flags) flags for this key @option options [Fixnum] :retry (0) maximum number of times to autmatically retry upon update collision @yieldparam [Object] value old value @yieldreturn [Object] new value. @raise [Couchbase::Error::KeyExists] if the key was updated before the the code in block has been completed (the CAS value has been changed). @example Implement append to JSON encoded value c.default_format = :document c.set("foo", {"bar" => 1}) c.cas("foo") do |val| val["baz"] = 2 val end c.get("foo") #=> {"bar" => 1, "baz" => 2} @return [Fixnum] the CAS of new value
[ "Compare", "and", "swap", "value", "." ]
ecce41a5996d9a97d6182e120bd9b5296707b353
https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/bucket.rb#L63-L77
19,180
couchbase/couchbase-ruby-client
lib/couchbase/bucket.rb
Couchbase.Bucket.design_docs
def design_docs req = __http_query(:management, :get, "/pools/default/buckets/#{bucket}/ddocs", nil, nil, nil, nil, nil) docmap = {} res = MultiJson.load(req[:chunks].join) res["rows"].each do |obj| obj['doc']['value'] = obj['doc'].delete('json') if obj['doc'] doc = DesignDoc.new(self, obj) next if environment == :production && doc.id =~ /dev_/ docmap[doc.id] = doc end docmap end
ruby
def design_docs req = __http_query(:management, :get, "/pools/default/buckets/#{bucket}/ddocs", nil, nil, nil, nil, nil) docmap = {} res = MultiJson.load(req[:chunks].join) res["rows"].each do |obj| obj['doc']['value'] = obj['doc'].delete('json') if obj['doc'] doc = DesignDoc.new(self, obj) next if environment == :production && doc.id =~ /dev_/ docmap[doc.id] = doc end docmap end
[ "def", "design_docs", "req", "=", "__http_query", "(", ":management", ",", ":get", ",", "\"/pools/default/buckets/#{bucket}/ddocs\"", ",", "nil", ",", "nil", ",", "nil", ",", "nil", ",", "nil", ")", "docmap", "=", "{", "}", "res", "=", "MultiJson", ".", "load", "(", "req", "[", ":chunks", "]", ".", "join", ")", "res", "[", "\"rows\"", "]", ".", "each", "do", "|", "obj", "|", "obj", "[", "'doc'", "]", "[", "'value'", "]", "=", "obj", "[", "'doc'", "]", ".", "delete", "(", "'json'", ")", "if", "obj", "[", "'doc'", "]", "doc", "=", "DesignDoc", ".", "new", "(", "self", ",", "obj", ")", "next", "if", "environment", "==", ":production", "&&", "doc", ".", "id", "=~", "/", "/", "docmap", "[", "doc", ".", "id", "]", "=", "doc", "end", "docmap", "end" ]
Fetch design docs stored in current bucket @since 1.2.0 @return [Hash]
[ "Fetch", "design", "docs", "stored", "in", "current", "bucket" ]
ecce41a5996d9a97d6182e120bd9b5296707b353
https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/bucket.rb#L85-L96
19,181
couchbase/couchbase-ruby-client
lib/couchbase/bucket.rb
Couchbase.Bucket.save_design_doc
def save_design_doc(data) attrs = case data when String MultiJson.load(data) when IO MultiJson.load(data.read) when Hash data else raise ArgumentError, "Document should be Hash, String or IO instance" end id = attrs.delete('_id').to_s attrs['language'] ||= 'javascript' raise ArgumentError, "'_id' key must be set and start with '_design/'." if id !~ /\A_design\// res = __http_query(:view, :put, "/#{id}", MultiJson.dump(attrs), 'application/json', nil, nil, nil) return true if res[:status] == 201 val = MultiJson.load(res[:chunks].join) raise Error::View.new("save_design_doc", val['error']) end
ruby
def save_design_doc(data) attrs = case data when String MultiJson.load(data) when IO MultiJson.load(data.read) when Hash data else raise ArgumentError, "Document should be Hash, String or IO instance" end id = attrs.delete('_id').to_s attrs['language'] ||= 'javascript' raise ArgumentError, "'_id' key must be set and start with '_design/'." if id !~ /\A_design\// res = __http_query(:view, :put, "/#{id}", MultiJson.dump(attrs), 'application/json', nil, nil, nil) return true if res[:status] == 201 val = MultiJson.load(res[:chunks].join) raise Error::View.new("save_design_doc", val['error']) end
[ "def", "save_design_doc", "(", "data", ")", "attrs", "=", "case", "data", "when", "String", "MultiJson", ".", "load", "(", "data", ")", "when", "IO", "MultiJson", ".", "load", "(", "data", ".", "read", ")", "when", "Hash", "data", "else", "raise", "ArgumentError", ",", "\"Document should be Hash, String or IO instance\"", "end", "id", "=", "attrs", ".", "delete", "(", "'_id'", ")", ".", "to_s", "attrs", "[", "'language'", "]", "||=", "'javascript'", "raise", "ArgumentError", ",", "\"'_id' key must be set and start with '_design/'.\"", "if", "id", "!~", "/", "\\A", "\\/", "/", "res", "=", "__http_query", "(", ":view", ",", ":put", ",", "\"/#{id}\"", ",", "MultiJson", ".", "dump", "(", "attrs", ")", ",", "'application/json'", ",", "nil", ",", "nil", ",", "nil", ")", "return", "true", "if", "res", "[", ":status", "]", "==", "201", "val", "=", "MultiJson", ".", "load", "(", "res", "[", ":chunks", "]", ".", "join", ")", "raise", "Error", "::", "View", ".", "new", "(", "\"save_design_doc\"", ",", "val", "[", "'error'", "]", ")", "end" ]
Update or create design doc with supplied views @since 1.2.0 @param [Hash, IO, String] data The source object containing JSON encoded design document. It must have +_id+ key set, this key should start with +_design/+. @return [true, false]
[ "Update", "or", "create", "design", "doc", "with", "supplied", "views" ]
ecce41a5996d9a97d6182e120bd9b5296707b353
https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/bucket.rb#L107-L125
19,182
couchbase/couchbase-ruby-client
lib/couchbase/bucket.rb
Couchbase.Bucket.delete_design_doc
def delete_design_doc(id, rev = nil) ddoc = design_docs[id.sub(/^_design\//, '')] return false unless ddoc path = Utils.build_query(ddoc.id, :rev => rev || ddoc.meta['rev']) res = __http_query(:view, :delete, path, nil, nil, nil, nil, nil) return true if res[:status] == 200 val = MultiJson.load(res[:chunks].join) raise Error::View.new("delete_design_doc", val['error']) end
ruby
def delete_design_doc(id, rev = nil) ddoc = design_docs[id.sub(/^_design\//, '')] return false unless ddoc path = Utils.build_query(ddoc.id, :rev => rev || ddoc.meta['rev']) res = __http_query(:view, :delete, path, nil, nil, nil, nil, nil) return true if res[:status] == 200 val = MultiJson.load(res[:chunks].join) raise Error::View.new("delete_design_doc", val['error']) end
[ "def", "delete_design_doc", "(", "id", ",", "rev", "=", "nil", ")", "ddoc", "=", "design_docs", "[", "id", ".", "sub", "(", "/", "\\/", "/", ",", "''", ")", "]", "return", "false", "unless", "ddoc", "path", "=", "Utils", ".", "build_query", "(", "ddoc", ".", "id", ",", ":rev", "=>", "rev", "||", "ddoc", ".", "meta", "[", "'rev'", "]", ")", "res", "=", "__http_query", "(", ":view", ",", ":delete", ",", "path", ",", "nil", ",", "nil", ",", "nil", ",", "nil", ",", "nil", ")", "return", "true", "if", "res", "[", ":status", "]", "==", "200", "val", "=", "MultiJson", ".", "load", "(", "res", "[", ":chunks", "]", ".", "join", ")", "raise", "Error", "::", "View", ".", "new", "(", "\"delete_design_doc\"", ",", "val", "[", "'error'", "]", ")", "end" ]
Delete design doc with given id and revision. @since 1.2.0 @param [String] id Design document id. It might have '_design/' prefix. @param [String] rev Document revision. It uses latest revision if +rev+ parameter is nil. @return [true, false]
[ "Delete", "design", "doc", "with", "given", "id", "and", "revision", "." ]
ecce41a5996d9a97d6182e120bd9b5296707b353
https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/bucket.rb#L138-L146
19,183
couchbase/couchbase-ruby-client
lib/couchbase/bucket.rb
Couchbase.Bucket.observe_and_wait
def observe_and_wait(*keys, &block) options = {:timeout => default_observe_timeout} options.update(keys.pop) if keys.size > 1 && keys.last.is_a?(Hash) verify_observe_options(options) raise ArgumentError, "at least one key is required" if keys.empty? key_cas = if keys.size == 1 && keys[0].is_a?(Hash) keys[0] else keys.flatten.each_with_object({}) do |kk, h| h[kk] = nil # set CAS to nil end end res = do_observe_and_wait(key_cas, options, &block) while res.nil? return res.values.first if keys.size == 1 && (keys[0].is_a?(String) || keys[0].is_a?(Symbol)) return res end
ruby
def observe_and_wait(*keys, &block) options = {:timeout => default_observe_timeout} options.update(keys.pop) if keys.size > 1 && keys.last.is_a?(Hash) verify_observe_options(options) raise ArgumentError, "at least one key is required" if keys.empty? key_cas = if keys.size == 1 && keys[0].is_a?(Hash) keys[0] else keys.flatten.each_with_object({}) do |kk, h| h[kk] = nil # set CAS to nil end end res = do_observe_and_wait(key_cas, options, &block) while res.nil? return res.values.first if keys.size == 1 && (keys[0].is_a?(String) || keys[0].is_a?(Symbol)) return res end
[ "def", "observe_and_wait", "(", "*", "keys", ",", "&", "block", ")", "options", "=", "{", ":timeout", "=>", "default_observe_timeout", "}", "options", ".", "update", "(", "keys", ".", "pop", ")", "if", "keys", ".", "size", ">", "1", "&&", "keys", ".", "last", ".", "is_a?", "(", "Hash", ")", "verify_observe_options", "(", "options", ")", "raise", "ArgumentError", ",", "\"at least one key is required\"", "if", "keys", ".", "empty?", "key_cas", "=", "if", "keys", ".", "size", "==", "1", "&&", "keys", "[", "0", "]", ".", "is_a?", "(", "Hash", ")", "keys", "[", "0", "]", "else", "keys", ".", "flatten", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "kk", ",", "h", "|", "h", "[", "kk", "]", "=", "nil", "# set CAS to nil", "end", "end", "res", "=", "do_observe_and_wait", "(", "key_cas", ",", "options", ",", "block", ")", "while", "res", ".", "nil?", "return", "res", ".", "values", ".", "first", "if", "keys", ".", "size", "==", "1", "&&", "(", "keys", "[", "0", "]", ".", "is_a?", "(", "String", ")", "||", "keys", "[", "0", "]", ".", "is_a?", "(", "Symbol", ")", ")", "return", "res", "end" ]
Wait for persistence condition @since 1.2.0.dp6 This operation is useful when some confidence needed regarding the state of the keys. With two parameters +:replicated+ and +:persisted+ it allows to set up the waiting rule. @param [String, Symbol, Array, Hash] keys The list of the keys to observe. Full form is hash with key-cas value pairs, but there are also shortcuts like just Array of keys or single key. CAS value needed to when you need to ensure that the storage persisted exactly the same version of the key you are asking to observe. @param [Hash] options The options for operation @option options [Fixnum] :timeout The timeout in microseconds @option options [Fixnum] :replicated How many replicas should receive the copy of the key. @option options [Fixnum] :persisted How many nodes should store the key on the disk. @raise [Couchbase::Error::Timeout] if the given time is up @return [Fixnum, Hash<String, Fixnum>] will return CAS value just like mutators or pairs key-cas in case of multiple keys.
[ "Wait", "for", "persistence", "condition" ]
ecce41a5996d9a97d6182e120bd9b5296707b353
https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/bucket.rb#L194-L209
19,184
code-and-effect/effective_resources
app/controllers/concerns/effective/crud_controller.rb
Effective.CrudController.resource_scope
def resource_scope # Thing @_effective_resource_relation ||= ( relation = case @_effective_resource_scope # If this was initialized by the resource_scope before_filter when ActiveRecord::Relation @_effective_resource_scope when Hash effective_resource.klass.where(@_effective_resource_scope) when Symbol effective_resource.klass.send(@_effective_resource_scope) when nil effective_resource.klass.respond_to?(:all) ? effective_resource.klass.all : effective_resource.klass else raise "expected resource_scope method to return an ActiveRecord::Relation or Hash" end unless relation.kind_of?(ActiveRecord::Relation) || effective_resource.active_model? raise("unable to build resource_scope for #{effective_resource.klass || 'unknown klass'}. Please name your controller to match an existing model, or manually define a resource_scope.") end relation ) end
ruby
def resource_scope # Thing @_effective_resource_relation ||= ( relation = case @_effective_resource_scope # If this was initialized by the resource_scope before_filter when ActiveRecord::Relation @_effective_resource_scope when Hash effective_resource.klass.where(@_effective_resource_scope) when Symbol effective_resource.klass.send(@_effective_resource_scope) when nil effective_resource.klass.respond_to?(:all) ? effective_resource.klass.all : effective_resource.klass else raise "expected resource_scope method to return an ActiveRecord::Relation or Hash" end unless relation.kind_of?(ActiveRecord::Relation) || effective_resource.active_model? raise("unable to build resource_scope for #{effective_resource.klass || 'unknown klass'}. Please name your controller to match an existing model, or manually define a resource_scope.") end relation ) end
[ "def", "resource_scope", "# Thing", "@_effective_resource_relation", "||=", "(", "relation", "=", "case", "@_effective_resource_scope", "# If this was initialized by the resource_scope before_filter", "when", "ActiveRecord", "::", "Relation", "@_effective_resource_scope", "when", "Hash", "effective_resource", ".", "klass", ".", "where", "(", "@_effective_resource_scope", ")", "when", "Symbol", "effective_resource", ".", "klass", ".", "send", "(", "@_effective_resource_scope", ")", "when", "nil", "effective_resource", ".", "klass", ".", "respond_to?", "(", ":all", ")", "?", "effective_resource", ".", "klass", ".", "all", ":", "effective_resource", ".", "klass", "else", "raise", "\"expected resource_scope method to return an ActiveRecord::Relation or Hash\"", "end", "unless", "relation", ".", "kind_of?", "(", "ActiveRecord", "::", "Relation", ")", "||", "effective_resource", ".", "active_model?", "raise", "(", "\"unable to build resource_scope for #{effective_resource.klass || 'unknown klass'}. Please name your controller to match an existing model, or manually define a resource_scope.\"", ")", "end", "relation", ")", "end" ]
Returns an ActiveRecord relation based on the computed value of `resource_scope` dsl method
[ "Returns", "an", "ActiveRecord", "relation", "based", "on", "the", "computed", "value", "of", "resource_scope", "dsl", "method" ]
eb201dedb4d1480081f8fc466decf6873c1f5bef
https://github.com/code-and-effect/effective_resources/blob/eb201dedb4d1480081f8fc466decf6873c1f5bef/app/controllers/concerns/effective/crud_controller.rb#L83-L104
19,185
tbpgr/tbpgr_utils
lib/template_methodable.rb
TemplateMethodable.ClassMethods.must_impl
def must_impl(*methods) return if methods.nil? fail TypeError, "invalid args type #{methods.class}. you must use Array or Symbol" unless methods.class.any_of? Array, Symbol methods = (methods.class.is_a? Symbol) ? [methods] : methods methods.each do |method_name| fail TypeError, "invalid args type #{method_name.class}. you must use Symbol" unless method_name.is_a? Symbol define_method method_name do |*args| fail NotImplementedError.new end end end
ruby
def must_impl(*methods) return if methods.nil? fail TypeError, "invalid args type #{methods.class}. you must use Array or Symbol" unless methods.class.any_of? Array, Symbol methods = (methods.class.is_a? Symbol) ? [methods] : methods methods.each do |method_name| fail TypeError, "invalid args type #{method_name.class}. you must use Symbol" unless method_name.is_a? Symbol define_method method_name do |*args| fail NotImplementedError.new end end end
[ "def", "must_impl", "(", "*", "methods", ")", "return", "if", "methods", ".", "nil?", "fail", "TypeError", ",", "\"invalid args type #{methods.class}. you must use Array or Symbol\"", "unless", "methods", ".", "class", ".", "any_of?", "Array", ",", "Symbol", "methods", "=", "(", "methods", ".", "class", ".", "is_a?", "Symbol", ")", "?", "[", "methods", "]", ":", "methods", "methods", ".", "each", "do", "|", "method_name", "|", "fail", "TypeError", ",", "\"invalid args type #{method_name.class}. you must use Symbol\"", "unless", "method_name", ".", "is_a?", "Symbol", "define_method", "method_name", "do", "|", "*", "args", "|", "fail", "NotImplementedError", ".", "new", "end", "end", "end" ]
template method force class macro concrete class must define *methods. if not define '*method', raise NotImplementedError. sample BaseClass require "template_methodable" class BaseDeveloper include TemplateMethodable must_impl :easy_coding, :difficult_coding, :normal_coding module DIFFICILTY EASY = 1 NORMAL = 2 DIFFICILT = 3 end def coding(difficulty) ret = [] ret << "start coding" case difficulty when DIFFICILTY::EASY ret << easy_coding("hoge", "hige") when DIFFICILTY::NORMAL ret << normal_coding("hoge", "hige") when DIFFICILTY::DIFFICILT ret << difficult_coding("hoge", "hige") else fail 'error' end ret << "finish coding" ret.join("\n") end end sample Concrete Class. if you don't define xxxx_coding method, it raises NotImplementedError. class StarDeveloper < BaseDeveloper def easy_coding(hoge, hige) "complete 1 minutes" end def normal_coding(hoge, hige) "complete 10 minutes" end def difficult_coding(hoge, hige) "complete 59 minutes" end end
[ "template", "method", "force", "class", "macro" ]
0f7c44478692ada3e1e94ce4aa5182896c4389f1
https://github.com/tbpgr/tbpgr_utils/blob/0f7c44478692ada3e1e94ce4aa5182896c4389f1/lib/template_methodable.rb#L54-L64
19,186
code-and-effect/effective_resources
app/models/effective/code_reader.rb
Effective.CodeReader.each_with_depth
def each_with_depth(from: nil, to: nil, &block) Array(lines).each_with_index do |line, index| next if index < (from || 0) depth = line.length - line.lstrip.length block.call(line.strip, depth, index) break if to == index end nil end
ruby
def each_with_depth(from: nil, to: nil, &block) Array(lines).each_with_index do |line, index| next if index < (from || 0) depth = line.length - line.lstrip.length block.call(line.strip, depth, index) break if to == index end nil end
[ "def", "each_with_depth", "(", "from", ":", "nil", ",", "to", ":", "nil", ",", "&", "block", ")", "Array", "(", "lines", ")", ".", "each_with_index", "do", "|", "line", ",", "index", "|", "next", "if", "index", "<", "(", "from", "||", "0", ")", "depth", "=", "line", ".", "length", "-", "line", ".", "lstrip", ".", "length", "block", ".", "call", "(", "line", ".", "strip", ",", "depth", ",", "index", ")", "break", "if", "to", "==", "index", "end", "nil", "end" ]
Iterate over the lines with a depth, and passed the stripped line to the passed block
[ "Iterate", "over", "the", "lines", "with", "a", "depth", "and", "passed", "the", "stripped", "line", "to", "the", "passed", "block" ]
eb201dedb4d1480081f8fc466decf6873c1f5bef
https://github.com/code-and-effect/effective_resources/blob/eb201dedb4d1480081f8fc466decf6873c1f5bef/app/models/effective/code_reader.rb#L11-L22
19,187
code-and-effect/effective_resources
app/models/effective/code_reader.rb
Effective.CodeReader.index
def index(from: nil, to: nil, &block) each_with_depth(from: from, to: to) do |line, depth, index| return index if block.call(line, depth, index) end end
ruby
def index(from: nil, to: nil, &block) each_with_depth(from: from, to: to) do |line, depth, index| return index if block.call(line, depth, index) end end
[ "def", "index", "(", "from", ":", "nil", ",", "to", ":", "nil", ",", "&", "block", ")", "each_with_depth", "(", "from", ":", "from", ",", "to", ":", "to", ")", "do", "|", "line", ",", "depth", ",", "index", "|", "return", "index", "if", "block", ".", "call", "(", "line", ",", "depth", ",", "index", ")", "end", "end" ]
Returns the index of the first line where the passed block returns true
[ "Returns", "the", "index", "of", "the", "first", "line", "where", "the", "passed", "block", "returns", "true" ]
eb201dedb4d1480081f8fc466decf6873c1f5bef
https://github.com/code-and-effect/effective_resources/blob/eb201dedb4d1480081f8fc466decf6873c1f5bef/app/models/effective/code_reader.rb#L25-L29
19,188
code-and-effect/effective_resources
app/models/effective/code_reader.rb
Effective.CodeReader.last
def last(from: nil, to: nil, &block) retval = nil each_with_depth(from: from, to: nil) do |line, depth, index| retval = line if block.call(line, depth, index) end retval end
ruby
def last(from: nil, to: nil, &block) retval = nil each_with_depth(from: from, to: nil) do |line, depth, index| retval = line if block.call(line, depth, index) end retval end
[ "def", "last", "(", "from", ":", "nil", ",", "to", ":", "nil", ",", "&", "block", ")", "retval", "=", "nil", "each_with_depth", "(", "from", ":", "from", ",", "to", ":", "nil", ")", "do", "|", "line", ",", "depth", ",", "index", "|", "retval", "=", "line", "if", "block", ".", "call", "(", "line", ",", "depth", ",", "index", ")", "end", "retval", "end" ]
Returns the stripped contents of the last line where the passed block returns true
[ "Returns", "the", "stripped", "contents", "of", "the", "last", "line", "where", "the", "passed", "block", "returns", "true" ]
eb201dedb4d1480081f8fc466decf6873c1f5bef
https://github.com/code-and-effect/effective_resources/blob/eb201dedb4d1480081f8fc466decf6873c1f5bef/app/models/effective/code_reader.rb#L40-L48
19,189
code-and-effect/effective_resources
app/models/effective/code_reader.rb
Effective.CodeReader.select
def select(from: nil, to: nil, &block) retval = [] each_with_depth(from: from, to: to) do |line, depth, index| retval << line if (block_given? == false || block.call(line, depth, index)) end retval end
ruby
def select(from: nil, to: nil, &block) retval = [] each_with_depth(from: from, to: to) do |line, depth, index| retval << line if (block_given? == false || block.call(line, depth, index)) end retval end
[ "def", "select", "(", "from", ":", "nil", ",", "to", ":", "nil", ",", "&", "block", ")", "retval", "=", "[", "]", "each_with_depth", "(", "from", ":", "from", ",", "to", ":", "to", ")", "do", "|", "line", ",", "depth", ",", "index", "|", "retval", "<<", "line", "if", "(", "block_given?", "==", "false", "||", "block", ".", "call", "(", "line", ",", "depth", ",", "index", ")", ")", "end", "retval", "end" ]
Returns an array of stripped lines for each line where the passed block returns true
[ "Returns", "an", "array", "of", "stripped", "lines", "for", "each", "line", "where", "the", "passed", "block", "returns", "true" ]
eb201dedb4d1480081f8fc466decf6873c1f5bef
https://github.com/code-and-effect/effective_resources/blob/eb201dedb4d1480081f8fc466decf6873c1f5bef/app/models/effective/code_reader.rb#L51-L59
19,190
code-and-effect/effective_resources
app/models/concerns/acts_as_statused.rb
ActsAsStatused.CanCan.acts_as_statused
def acts_as_statused(klass, only: nil, except: nil) raise "klass does not implement acts_as_statused" unless klass.acts_as_statused? statuses = klass.const_get(:STATUSES) instance = klass.new only = Array(only).compact except = Array(except).compact statuses.each_with_index do |status, index| action = status_active_verb(status, instance) next if action.blank? next if only.present? && !only.include?(action) next if except.present? && except.include?(action) if index == 0 can(action, klass) and next end if status == :approved && statuses.include?(:declined) if (position = statuses.index { |status| (status == :approved || status == :declined) }) > 0 can(action, klass) { |obj| obj.public_send("#{statuses[position-1]}?") || obj.declined? } next end end if status == :declined && statuses.include?(:approved) if (position = statuses.index { |status| (status == :approved || status == :declined) }) > 0 can(action, klass) { |obj| obj.public_send("#{statuses[position-1]}?") } next end end can(action, klass) { |obj| obj.public_send("#{statuses[index-1]}?") } end end
ruby
def acts_as_statused(klass, only: nil, except: nil) raise "klass does not implement acts_as_statused" unless klass.acts_as_statused? statuses = klass.const_get(:STATUSES) instance = klass.new only = Array(only).compact except = Array(except).compact statuses.each_with_index do |status, index| action = status_active_verb(status, instance) next if action.blank? next if only.present? && !only.include?(action) next if except.present? && except.include?(action) if index == 0 can(action, klass) and next end if status == :approved && statuses.include?(:declined) if (position = statuses.index { |status| (status == :approved || status == :declined) }) > 0 can(action, klass) { |obj| obj.public_send("#{statuses[position-1]}?") || obj.declined? } next end end if status == :declined && statuses.include?(:approved) if (position = statuses.index { |status| (status == :approved || status == :declined) }) > 0 can(action, klass) { |obj| obj.public_send("#{statuses[position-1]}?") } next end end can(action, klass) { |obj| obj.public_send("#{statuses[index-1]}?") } end end
[ "def", "acts_as_statused", "(", "klass", ",", "only", ":", "nil", ",", "except", ":", "nil", ")", "raise", "\"klass does not implement acts_as_statused\"", "unless", "klass", ".", "acts_as_statused?", "statuses", "=", "klass", ".", "const_get", "(", ":STATUSES", ")", "instance", "=", "klass", ".", "new", "only", "=", "Array", "(", "only", ")", ".", "compact", "except", "=", "Array", "(", "except", ")", ".", "compact", "statuses", ".", "each_with_index", "do", "|", "status", ",", "index", "|", "action", "=", "status_active_verb", "(", "status", ",", "instance", ")", "next", "if", "action", ".", "blank?", "next", "if", "only", ".", "present?", "&&", "!", "only", ".", "include?", "(", "action", ")", "next", "if", "except", ".", "present?", "&&", "except", ".", "include?", "(", "action", ")", "if", "index", "==", "0", "can", "(", "action", ",", "klass", ")", "and", "next", "end", "if", "status", "==", ":approved", "&&", "statuses", ".", "include?", "(", ":declined", ")", "if", "(", "position", "=", "statuses", ".", "index", "{", "|", "status", "|", "(", "status", "==", ":approved", "||", "status", "==", ":declined", ")", "}", ")", ">", "0", "can", "(", "action", ",", "klass", ")", "{", "|", "obj", "|", "obj", ".", "public_send", "(", "\"#{statuses[position-1]}?\"", ")", "||", "obj", ".", "declined?", "}", "next", "end", "end", "if", "status", "==", ":declined", "&&", "statuses", ".", "include?", "(", ":approved", ")", "if", "(", "position", "=", "statuses", ".", "index", "{", "|", "status", "|", "(", "status", "==", ":approved", "||", "status", "==", ":declined", ")", "}", ")", ">", "0", "can", "(", "action", ",", "klass", ")", "{", "|", "obj", "|", "obj", ".", "public_send", "(", "\"#{statuses[position-1]}?\"", ")", "}", "next", "end", "end", "can", "(", "action", ",", "klass", ")", "{", "|", "obj", "|", "obj", ".", "public_send", "(", "\"#{statuses[index-1]}?\"", ")", "}", "end", "end" ]
The idea here is you can go forward but you can't go back.
[ "The", "idea", "here", "is", "you", "can", "go", "forward", "but", "you", "can", "t", "go", "back", "." ]
eb201dedb4d1480081f8fc466decf6873c1f5bef
https://github.com/code-and-effect/effective_resources/blob/eb201dedb4d1480081f8fc466decf6873c1f5bef/app/models/concerns/acts_as_statused.rb#L29-L65
19,191
code-and-effect/effective_resources
app/models/concerns/acts_as_statused.rb
ActsAsStatused.CanCan.status_active_verb
def status_active_verb(status, instance) status = status.to_s.strip if status.end_with?('ied') action = status[0...-3] + 'y' return action.to_sym if instance.respond_to?(action + '!') end # ed, e, ing [-1, -2, -3].each do |index| action = status[0...index] return action.to_sym if instance.respond_to?(action + '!') end nil end
ruby
def status_active_verb(status, instance) status = status.to_s.strip if status.end_with?('ied') action = status[0...-3] + 'y' return action.to_sym if instance.respond_to?(action + '!') end # ed, e, ing [-1, -2, -3].each do |index| action = status[0...index] return action.to_sym if instance.respond_to?(action + '!') end nil end
[ "def", "status_active_verb", "(", "status", ",", "instance", ")", "status", "=", "status", ".", "to_s", ".", "strip", "if", "status", ".", "end_with?", "(", "'ied'", ")", "action", "=", "status", "[", "0", "...", "-", "3", "]", "+", "'y'", "return", "action", ".", "to_sym", "if", "instance", ".", "respond_to?", "(", "action", "+", "'!'", ")", "end", "# ed, e, ing", "[", "-", "1", ",", "-", "2", ",", "-", "3", "]", ".", "each", "do", "|", "index", "|", "action", "=", "status", "[", "0", "...", "index", "]", "return", "action", ".", "to_sym", "if", "instance", ".", "respond_to?", "(", "action", "+", "'!'", ")", "end", "nil", "end" ]
requested -> request, approved -> approve, declined -> decline, pending -> pending
[ "requested", "-", ">", "request", "approved", "-", ">", "approve", "declined", "-", ">", "decline", "pending", "-", ">", "pending" ]
eb201dedb4d1480081f8fc466decf6873c1f5bef
https://github.com/code-and-effect/effective_resources/blob/eb201dedb4d1480081f8fc466decf6873c1f5bef/app/models/concerns/acts_as_statused.rb#L70-L85
19,192
mlipper/runt
lib/runt/schedule.rb
Runt.Schedule.dates
def dates(event, date_range) result=[] date_range.each do |date| result.push date if include?(event,date) end result end
ruby
def dates(event, date_range) result=[] date_range.each do |date| result.push date if include?(event,date) end result end
[ "def", "dates", "(", "event", ",", "date_range", ")", "result", "=", "[", "]", "date_range", ".", "each", "do", "|", "date", "|", "result", ".", "push", "date", "if", "include?", "(", "event", ",", "date", ")", "end", "result", "end" ]
For the given date range, returns an Array of PDate objects at which the supplied event is scheduled to occur.
[ "For", "the", "given", "date", "range", "returns", "an", "Array", "of", "PDate", "objects", "at", "which", "the", "supplied", "event", "is", "scheduled", "to", "occur", "." ]
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/lib/runt/schedule.rb#L26-L32
19,193
mlipper/runt
lib/runt/schedule.rb
Runt.Schedule.include?
def include?(event, date) return false unless @elems.include?(event) return 0<(self.select{|ev,xpr| ev.eql?(event)&&xpr.include?(date);}).size end
ruby
def include?(event, date) return false unless @elems.include?(event) return 0<(self.select{|ev,xpr| ev.eql?(event)&&xpr.include?(date);}).size end
[ "def", "include?", "(", "event", ",", "date", ")", "return", "false", "unless", "@elems", ".", "include?", "(", "event", ")", "return", "0", "<", "(", "self", ".", "select", "{", "|", "ev", ",", "xpr", "|", "ev", ".", "eql?", "(", "event", ")", "&&", "xpr", ".", "include?", "(", "date", ")", ";", "}", ")", ".", "size", "end" ]
Return true or false depend on if the supplied event is scheduled to occur on the given date.
[ "Return", "true", "or", "false", "depend", "on", "if", "the", "supplied", "event", "is", "scheduled", "to", "occur", "on", "the", "given", "date", "." ]
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/lib/runt/schedule.rb#L40-L43
19,194
Chetane/fixy
lib/fixy/record.rb
Fixy.Record.generate
def generate(debug = false) decorator = debug ? Fixy::Decorator::Debug : Fixy::Decorator::Default output = '' current_position = 1 current_record = 1 while current_position <= self.class.record_length do field = record_fields[current_position] raise StandardError, "Undefined field for position #{current_position}" unless field # We will first retrieve the value, then format it method = field[:name] value = send(method) formatted_value = format_value(value, field[:size], field[:type]) formatted_value = decorator.field(formatted_value, current_record, current_position, method, field[:size], field[:type]) output << formatted_value current_position = field[:to] + 1 current_record += 1 end # Documentation mandates that every record ends with new line. output << line_ending # All ready. In the words of Mr. Peters: "Take it and go!" decorator.record(output) end
ruby
def generate(debug = false) decorator = debug ? Fixy::Decorator::Debug : Fixy::Decorator::Default output = '' current_position = 1 current_record = 1 while current_position <= self.class.record_length do field = record_fields[current_position] raise StandardError, "Undefined field for position #{current_position}" unless field # We will first retrieve the value, then format it method = field[:name] value = send(method) formatted_value = format_value(value, field[:size], field[:type]) formatted_value = decorator.field(formatted_value, current_record, current_position, method, field[:size], field[:type]) output << formatted_value current_position = field[:to] + 1 current_record += 1 end # Documentation mandates that every record ends with new line. output << line_ending # All ready. In the words of Mr. Peters: "Take it and go!" decorator.record(output) end
[ "def", "generate", "(", "debug", "=", "false", ")", "decorator", "=", "debug", "?", "Fixy", "::", "Decorator", "::", "Debug", ":", "Fixy", "::", "Decorator", "::", "Default", "output", "=", "''", "current_position", "=", "1", "current_record", "=", "1", "while", "current_position", "<=", "self", ".", "class", ".", "record_length", "do", "field", "=", "record_fields", "[", "current_position", "]", "raise", "StandardError", ",", "\"Undefined field for position #{current_position}\"", "unless", "field", "# We will first retrieve the value, then format it", "method", "=", "field", "[", ":name", "]", "value", "=", "send", "(", "method", ")", "formatted_value", "=", "format_value", "(", "value", ",", "field", "[", ":size", "]", ",", "field", "[", ":type", "]", ")", "formatted_value", "=", "decorator", ".", "field", "(", "formatted_value", ",", "current_record", ",", "current_position", ",", "method", ",", "field", "[", ":size", "]", ",", "field", "[", ":type", "]", ")", "output", "<<", "formatted_value", "current_position", "=", "field", "[", ":to", "]", "+", "1", "current_record", "+=", "1", "end", "# Documentation mandates that every record ends with new line.", "output", "<<", "line_ending", "# All ready. In the words of Mr. Peters: \"Take it and go!\"", "decorator", ".", "record", "(", "output", ")", "end" ]
Generate the entry based on the record structure
[ "Generate", "the", "entry", "based", "on", "the", "record", "structure" ]
aa5cf89e56cf592fabf5c5695d5d213af157a283
https://github.com/Chetane/fixy/blob/aa5cf89e56cf592fabf5c5695d5d213af157a283/lib/fixy/record.rb#L122-L149
19,195
walle/gas
lib/gas/users.rb
Gas.Users.exists?
def exists?(nickname) users.each do |user| if user.nickname == nickname return true; end end false end
ruby
def exists?(nickname) users.each do |user| if user.nickname == nickname return true; end end false end
[ "def", "exists?", "(", "nickname", ")", "users", ".", "each", "do", "|", "user", "|", "if", "user", ".", "nickname", "==", "nickname", "return", "true", ";", "end", "end", "false", "end" ]
Initializes the object. If no users are supplied we look for a config file, if none then create it, and parse it to load users @param [String] config_file The path to the file that stores users Checks if a user with _nickname_ exists @param [String] nickname @return [Boolean]
[ "Initializes", "the", "object", ".", "If", "no", "users", "are", "supplied", "we", "look", "for", "a", "config", "file", "if", "none", "then", "create", "it", "and", "parse", "it", "to", "load", "users" ]
b27ee21681c1ddbaa15b64ca1b4f359bc26d4876
https://github.com/walle/gas/blob/b27ee21681c1ddbaa15b64ca1b4f359bc26d4876/lib/gas/users.rb#L21-L29
19,196
walle/gas
lib/gas/users.rb
Gas.Users.get
def get(nickname) users.each do |user| if user.nickname == nickname.to_s return user end end nil end
ruby
def get(nickname) users.each do |user| if user.nickname == nickname.to_s return user end end nil end
[ "def", "get", "(", "nickname", ")", "users", ".", "each", "do", "|", "user", "|", "if", "user", ".", "nickname", "==", "nickname", ".", "to_s", "return", "user", "end", "end", "nil", "end" ]
Returns the user with nickname nil if no such user exists @param [String|Symbol] nickname @return [User|nil]
[ "Returns", "the", "user", "with", "nickname", "nil", "if", "no", "such", "user", "exists" ]
b27ee21681c1ddbaa15b64ca1b4f359bc26d4876
https://github.com/walle/gas/blob/b27ee21681c1ddbaa15b64ca1b4f359bc26d4876/lib/gas/users.rb#L34-L42
19,197
walle/gas
lib/gas/users.rb
Gas.Users.to_s
def to_s current_user = GitConfig.current_user users.map do |user| if current_user == user " ==> #{user.to_s[5,user.to_s.length]}" else user.to_s end end.join "\n" end
ruby
def to_s current_user = GitConfig.current_user users.map do |user| if current_user == user " ==> #{user.to_s[5,user.to_s.length]}" else user.to_s end end.join "\n" end
[ "def", "to_s", "current_user", "=", "GitConfig", ".", "current_user", "users", ".", "map", "do", "|", "user", "|", "if", "current_user", "==", "user", "\" ==> #{user.to_s[5,user.to_s.length]}\"", "else", "user", ".", "to_s", "end", "end", ".", "join", "\"\\n\"", "end" ]
Override to_s to output correct format
[ "Override", "to_s", "to", "output", "correct", "format" ]
b27ee21681c1ddbaa15b64ca1b4f359bc26d4876
https://github.com/walle/gas/blob/b27ee21681c1ddbaa15b64ca1b4f359bc26d4876/lib/gas/users.rb#L73-L82
19,198
dbalmain/ferret
ruby/lib/ferret/field_symbol.rb
Ferret.FieldSymbolMethods.desc
def desc fsym = FieldSymbol.new(self, respond_to?(:desc?) ? !desc? : true) fsym.type = respond_to?(:type) ? type : nil fsym end
ruby
def desc fsym = FieldSymbol.new(self, respond_to?(:desc?) ? !desc? : true) fsym.type = respond_to?(:type) ? type : nil fsym end
[ "def", "desc", "fsym", "=", "FieldSymbol", ".", "new", "(", "self", ",", "respond_to?", "(", ":desc?", ")", "?", "!", "desc?", ":", "true", ")", "fsym", ".", "type", "=", "respond_to?", "(", ":type", ")", "?", "type", ":", "nil", "fsym", "end" ]
Set a field to be a descending field. This only makes sense in sort specifications.
[ "Set", "a", "field", "to", "be", "a", "descending", "field", ".", "This", "only", "makes", "sense", "in", "sort", "specifications", "." ]
2451bc48c3aa162cbb87659b0f460b7821590cd1
https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/field_symbol.rb#L58-L62
19,199
dbalmain/ferret
ruby/lib/ferret/document.rb
Ferret.Document.to_s
def to_s buf = ["Document {"] self.keys.sort_by {|key| key.to_s}.each do |key| val = self[key] val_str = if val.instance_of? Array then %{["#{val.join('", "')}"]} elsif val.is_a? Field then val.to_s else %{"#{val.to_s}"} end buf << " :#{key} => #{val_str}" end buf << ["}#{@boost == 1.0 ? "" : "^" + @boost.to_s}"] return buf.join("\n") end
ruby
def to_s buf = ["Document {"] self.keys.sort_by {|key| key.to_s}.each do |key| val = self[key] val_str = if val.instance_of? Array then %{["#{val.join('", "')}"]} elsif val.is_a? Field then val.to_s else %{"#{val.to_s}"} end buf << " :#{key} => #{val_str}" end buf << ["}#{@boost == 1.0 ? "" : "^" + @boost.to_s}"] return buf.join("\n") end
[ "def", "to_s", "buf", "=", "[", "\"Document {\"", "]", "self", ".", "keys", ".", "sort_by", "{", "|", "key", "|", "key", ".", "to_s", "}", ".", "each", "do", "|", "key", "|", "val", "=", "self", "[", "key", "]", "val_str", "=", "if", "val", ".", "instance_of?", "Array", "then", "%{[\"#{val.join('\", \"')}\"]}", "elsif", "val", ".", "is_a?", "Field", "then", "val", ".", "to_s", "else", "%{\"#{val.to_s}\"}", "end", "buf", "<<", "\" :#{key} => #{val_str}\"", "end", "buf", "<<", "[", "\"}#{@boost == 1.0 ? \"\" : \"^\" + @boost.to_s}\"", "]", "return", "buf", ".", "join", "(", "\"\\n\"", ")", "end" ]
Create a string representation of the document
[ "Create", "a", "string", "representation", "of", "the", "document" ]
2451bc48c3aa162cbb87659b0f460b7821590cd1
https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/document.rb#L61-L73