repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
mare-imbrium/canis
lib/canis/core/widgets/rwidget.rb
Canis.Field.position_label
def position_label $log.debug "XXX: LABEL row #{@label.row}, #{@label.col} " @label.row @row unless @label.row #if @label.row == -1 @label.col @col-(@label.name.length+1) unless @label.col #if @label.col == -1 @label.label_for(self) # this line got deleted when we redid stuff ! $log.debug " XXX: LABEL row #{@label.row}, #{@label.col} " end
ruby
def position_label $log.debug "XXX: LABEL row #{@label.row}, #{@label.col} " @label.row @row unless @label.row #if @label.row == -1 @label.col @col-(@label.name.length+1) unless @label.col #if @label.col == -1 @label.label_for(self) # this line got deleted when we redid stuff ! $log.debug " XXX: LABEL row #{@label.row}, #{@label.col} " end
[ "def", "position_label", "$log", ".", "debug", "\"XXX: LABEL row #{@label.row}, #{@label.col} \"", "@label", ".", "row", "@row", "unless", "@label", ".", "row", "@label", ".", "col", "@col", "-", "(", "@label", ".", "name", ".", "length", "+", "1", ")", "unless", "@label", ".", "col", "@label", ".", "label_for", "(", "self", ")", "$log", ".", "debug", "\" XXX: LABEL row #{@label.row}, #{@label.col} \"", "end" ]
FIXME this may not work since i have disabled -1, now i do not set row and col
[ "FIXME", "this", "may", "not", "work", "since", "i", "have", "disabled", "-", "1", "now", "i", "do", "not", "set", "row", "and", "col" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/rwidget.rb#L2505-L2511
train
mare-imbrium/canis
lib/canis/core/widgets/rwidget.rb
Canis.Field.cursor_end
def cursor_end blen = @buffer.rstrip.length if blen < @width set_form_col blen else # there is a problem here FIXME. @pcol = blen-@width #set_form_col @width-1 set_form_col blen end @curpos = blen # this is position in array where editing or motion is to happen regardless of what you see # regardless of pcol (panning) # $log.debug " crusor END cp:#{@curpos} pcol:#{@pcol} b.l:#{@buffer.length} d_l:#{@width} fc:#{@form.col}" #set_form_col @buffer.length end
ruby
def cursor_end blen = @buffer.rstrip.length if blen < @width set_form_col blen else # there is a problem here FIXME. @pcol = blen-@width #set_form_col @width-1 set_form_col blen end @curpos = blen # this is position in array where editing or motion is to happen regardless of what you see # regardless of pcol (panning) # $log.debug " crusor END cp:#{@curpos} pcol:#{@pcol} b.l:#{@buffer.length} d_l:#{@width} fc:#{@form.col}" #set_form_col @buffer.length end
[ "def", "cursor_end", "blen", "=", "@buffer", ".", "rstrip", ".", "length", "if", "blen", "<", "@width", "set_form_col", "blen", "else", "@pcol", "=", "blen", "-", "@width", "set_form_col", "blen", "end", "@curpos", "=", "blen", "end" ]
goto end of field, "end" is a keyword so could not use it.
[ "goto", "end", "of", "field", "end", "is", "a", "keyword", "so", "could", "not", "use", "it", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/rwidget.rb#L2618-L2632
train
mare-imbrium/canis
lib/canis/core/widgets/rwidget.rb
Canis.Field.set_form_col
def set_form_col col1=@curpos @curpos = col1 || 0 # NOTE we set the index of cursor here c = @col + @col_offset + @curpos - @pcol min = @col + @col_offset max = min + @width c = min if c < min c = max if c > max #$log.debug " #{@name} FIELD set_form_col #{c}, curpos #{@curpos} , #{@col} + #{@col_offset} pcol:#{@pcol} " setrowcol nil, c end
ruby
def set_form_col col1=@curpos @curpos = col1 || 0 # NOTE we set the index of cursor here c = @col + @col_offset + @curpos - @pcol min = @col + @col_offset max = min + @width c = min if c < min c = max if c > max #$log.debug " #{@name} FIELD set_form_col #{c}, curpos #{@curpos} , #{@col} + #{@col_offset} pcol:#{@pcol} " setrowcol nil, c end
[ "def", "set_form_col", "col1", "=", "@curpos", "@curpos", "=", "col1", "||", "0", "c", "=", "@col", "+", "@col_offset", "+", "@curpos", "-", "@pcol", "min", "=", "@col", "+", "@col_offset", "max", "=", "min", "+", "@width", "c", "=", "min", "if", "c", "<", "min", "c", "=", "max", "if", "c", ">", "max", "setrowcol", "nil", ",", "c", "end" ]
sets the visual cursor on the window at correct place added here since we need to account for pcol. 2011-12-7 NOTE be careful of curpos - pcol being less than 0
[ "sets", "the", "visual", "cursor", "on", "the", "window", "at", "correct", "place", "added", "here", "since", "we", "need", "to", "account", "for", "pcol", ".", "2011", "-", "12", "-", "7", "NOTE", "be", "careful", "of", "curpos", "-", "pcol", "being", "less", "than", "0" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/rwidget.rb#L2636-L2645
train
mare-imbrium/canis
lib/canis/core/widgets/rwidget.rb
Canis.Field.in_range?
def in_range?( val ) val = val.to_i (@above.nil? or val > @above) and (@below.nil? or val < @below) and (@valid_range.nil? or @valid_range.include?(val)) end
ruby
def in_range?( val ) val = val.to_i (@above.nil? or val > @above) and (@below.nil? or val < @below) and (@valid_range.nil? or @valid_range.include?(val)) end
[ "def", "in_range?", "(", "val", ")", "val", "=", "val", ".", "to_i", "(", "@above", ".", "nil?", "or", "val", ">", "@above", ")", "and", "(", "@below", ".", "nil?", "or", "val", "<", "@below", ")", "and", "(", "@valid_range", ".", "nil?", "or", "@valid_range", ".", "include?", "(", "val", ")", ")", "end" ]
checks field against +valid_range+, +above+ and +below+ , returning +true+ if it passes set attributes, +false+ if it fails any one.
[ "checks", "field", "against", "+", "valid_range", "+", "+", "above", "+", "and", "+", "below", "+", "returning", "+", "true", "+", "if", "it", "passes", "set", "attributes", "+", "false", "+", "if", "it", "fails", "any", "one", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/rwidget.rb#L2752-L2757
train
mare-imbrium/canis
lib/canis/core/widgets/rwidget.rb
Canis.LabeledField.repaint
def repaint return unless @repaint_required _lrow = @lrow || @row # the next was nice, but in some cases this goes out of screen. and the container # only sets row and col for whatever is added, it does not know that lcol has to be # taken into account #_lcol = @lcol || (@col - @label.length - 2) unless @lcol @lcol = @col @col = @lcol + @label.length + 2 end _lcol = @lcol @graphic = @form.window if @graphic.nil? lcolor = @label_color_pair || $datacolor # this should be the same color as window bg XXX lattr = @label_attr || NORMAL @graphic.printstring _lrow, _lcol, @label, lcolor, lattr ##c += @label.length + 2 #@col_offset = c-@col # required so cursor lands in right place super end
ruby
def repaint return unless @repaint_required _lrow = @lrow || @row # the next was nice, but in some cases this goes out of screen. and the container # only sets row and col for whatever is added, it does not know that lcol has to be # taken into account #_lcol = @lcol || (@col - @label.length - 2) unless @lcol @lcol = @col @col = @lcol + @label.length + 2 end _lcol = @lcol @graphic = @form.window if @graphic.nil? lcolor = @label_color_pair || $datacolor # this should be the same color as window bg XXX lattr = @label_attr || NORMAL @graphic.printstring _lrow, _lcol, @label, lcolor, lattr ##c += @label.length + 2 #@col_offset = c-@col # required so cursor lands in right place super end
[ "def", "repaint", "return", "unless", "@repaint_required", "_lrow", "=", "@lrow", "||", "@row", "unless", "@lcol", "@lcol", "=", "@col", "@col", "=", "@lcol", "+", "@label", ".", "length", "+", "2", "end", "_lcol", "=", "@lcol", "@graphic", "=", "@form", ".", "window", "if", "@graphic", ".", "nil?", "lcolor", "=", "@label_color_pair", "||", "$datacolor", "lattr", "=", "@label_attr", "||", "NORMAL", "@graphic", ".", "printstring", "_lrow", ",", "_lcol", ",", "@label", ",", "lcolor", ",", "lattr", "super", "end" ]
label of field Unused earlier, now will print
[ "label", "of", "field", "Unused", "earlier", "now", "will", "print" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/rwidget.rb#L2817-L2836
train
mare-imbrium/canis
lib/canis/core/widgets/rwidget.rb
Canis.Label.bind_hotkey
def bind_hotkey if @mnemonic ch = @mnemonic.downcase()[0].ord ## 1.9 DONE # meta key mch = ?\M-a.getbyte(0) + (ch - ?a.getbyte(0)) ## 1.9 if (@label_for.is_a? Canis::Button ) && (@label_for.respond_to? :fire) @form.bind_key(mch, "hotkey for button #{@label_for.text} ") { |_form, _butt| @label_for.fire } else $log.debug " bind_hotkey label for: #{@label_for}" @form.bind_key(mch, "hotkey for label #{text} ") { |_form, _field| @label_for.focus } end end end
ruby
def bind_hotkey if @mnemonic ch = @mnemonic.downcase()[0].ord ## 1.9 DONE # meta key mch = ?\M-a.getbyte(0) + (ch - ?a.getbyte(0)) ## 1.9 if (@label_for.is_a? Canis::Button ) && (@label_for.respond_to? :fire) @form.bind_key(mch, "hotkey for button #{@label_for.text} ") { |_form, _butt| @label_for.fire } else $log.debug " bind_hotkey label for: #{@label_for}" @form.bind_key(mch, "hotkey for label #{text} ") { |_form, _field| @label_for.focus } end end end
[ "def", "bind_hotkey", "if", "@mnemonic", "ch", "=", "@mnemonic", ".", "downcase", "(", ")", "[", "0", "]", ".", "ord", "mch", "=", "?\\M-a", ".", "getbyte", "(", "0", ")", "+", "(", "ch", "-", "?a", ".", "getbyte", "(", "0", ")", ")", "if", "(", "@label_for", ".", "is_a?", "Canis", "::", "Button", ")", "&&", "(", "@label_for", ".", "respond_to?", ":fire", ")", "@form", ".", "bind_key", "(", "mch", ",", "\"hotkey for button #{@label_for.text} \"", ")", "{", "|", "_form", ",", "_butt", "|", "@label_for", ".", "fire", "}", "else", "$log", ".", "debug", "\" bind_hotkey label for: #{@label_for}\"", "@form", ".", "bind_key", "(", "mch", ",", "\"hotkey for label #{text} \"", ")", "{", "|", "_form", ",", "_field", "|", "@label_for", ".", "focus", "}", "end", "end", "end" ]
for a button, fire it when label invoked without changing focus for other widgets, attempt to change focus to that field
[ "for", "a", "button", "fire", "it", "when", "label", "invoked", "without", "changing", "focus", "for", "other", "widgets", "attempt", "to", "change", "focus", "to", "that", "field" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/rwidget.rb#L3001-L3013
train
mare-imbrium/canis
lib/canis/core/widgets/rwidget.rb
Canis.Label.repaint
def repaint return unless @repaint_required raise "Label row or col nil #{@row} , #{@col}, #{@text} " if @row.nil? || @col.nil? r,c = rowcol #@bgcolor ||= $def_bg_color #@color ||= $def_fg_color _bgcolor = bgcolor() _color = color() # value often nil so putting blank, but usually some application error value = getvalue_for_paint || "" if value.is_a? Array value = value.join " " end # ensure we do not exceed if @width if value.length > @width value = value[0..@width-1] end end len = @width || value.length #acolor = get_color $datacolor # the user could have set color_pair, use that, else determine color # This implies that if he sets cp, then changing col and bg won't have an effect ! # A general routine that only changes color will not work here. acolor = @color_pair || get_color($datacolor, _color, _bgcolor) #$log.debug "label :#{@text}, #{value}, r #{r}, c #{c} col= #{@color}, #{@bgcolor} acolor #{acolor} j:#{@justify} dlL: #{@width} " str = @justify.to_sym == :right ? "%*s" : "%-*s" # added 2008-12-22 19:05 @graphic ||= @form.window # clear the area @graphic.printstring r, c, " " * len , acolor, attr() if @justify.to_sym == :center padding = (@width - value.length)/2 value = " "*padding + value + " "*padding # so its cleared if we change it midway end @graphic.printstring r, c, str % [len, value], acolor, attr() if @mnemonic ulindex = value.index(@mnemonic) || value.index(@mnemonic.swapcase) @graphic.mvchgat(y=r, x=c+ulindex, max=1, Ncurses::A_BOLD|Ncurses::A_UNDERLINE, acolor, nil) end @repaint_required = false end
ruby
def repaint return unless @repaint_required raise "Label row or col nil #{@row} , #{@col}, #{@text} " if @row.nil? || @col.nil? r,c = rowcol #@bgcolor ||= $def_bg_color #@color ||= $def_fg_color _bgcolor = bgcolor() _color = color() # value often nil so putting blank, but usually some application error value = getvalue_for_paint || "" if value.is_a? Array value = value.join " " end # ensure we do not exceed if @width if value.length > @width value = value[0..@width-1] end end len = @width || value.length #acolor = get_color $datacolor # the user could have set color_pair, use that, else determine color # This implies that if he sets cp, then changing col and bg won't have an effect ! # A general routine that only changes color will not work here. acolor = @color_pair || get_color($datacolor, _color, _bgcolor) #$log.debug "label :#{@text}, #{value}, r #{r}, c #{c} col= #{@color}, #{@bgcolor} acolor #{acolor} j:#{@justify} dlL: #{@width} " str = @justify.to_sym == :right ? "%*s" : "%-*s" # added 2008-12-22 19:05 @graphic ||= @form.window # clear the area @graphic.printstring r, c, " " * len , acolor, attr() if @justify.to_sym == :center padding = (@width - value.length)/2 value = " "*padding + value + " "*padding # so its cleared if we change it midway end @graphic.printstring r, c, str % [len, value], acolor, attr() if @mnemonic ulindex = value.index(@mnemonic) || value.index(@mnemonic.swapcase) @graphic.mvchgat(y=r, x=c+ulindex, max=1, Ncurses::A_BOLD|Ncurses::A_UNDERLINE, acolor, nil) end @repaint_required = false end
[ "def", "repaint", "return", "unless", "@repaint_required", "raise", "\"Label row or col nil #{@row} , #{@col}, #{@text} \"", "if", "@row", ".", "nil?", "||", "@col", ".", "nil?", "r", ",", "c", "=", "rowcol", "_bgcolor", "=", "bgcolor", "(", ")", "_color", "=", "color", "(", ")", "value", "=", "getvalue_for_paint", "||", "\"\"", "if", "value", ".", "is_a?", "Array", "value", "=", "value", ".", "join", "\" \"", "end", "if", "@width", "if", "value", ".", "length", ">", "@width", "value", "=", "value", "[", "0", "..", "@width", "-", "1", "]", "end", "end", "len", "=", "@width", "||", "value", ".", "length", "acolor", "=", "@color_pair", "||", "get_color", "(", "$datacolor", ",", "_color", ",", "_bgcolor", ")", "str", "=", "@justify", ".", "to_sym", "==", ":right", "?", "\"%*s\"", ":", "\"%-*s\"", "@graphic", "||=", "@form", ".", "window", "@graphic", ".", "printstring", "r", ",", "c", ",", "\" \"", "*", "len", ",", "acolor", ",", "attr", "(", ")", "if", "@justify", ".", "to_sym", "==", ":center", "padding", "=", "(", "@width", "-", "value", ".", "length", ")", "/", "2", "value", "=", "\" \"", "*", "padding", "+", "value", "+", "\" \"", "*", "padding", "end", "@graphic", ".", "printstring", "r", ",", "c", ",", "str", "%", "[", "len", ",", "value", "]", ",", "acolor", ",", "attr", "(", ")", "if", "@mnemonic", "ulindex", "=", "value", ".", "index", "(", "@mnemonic", ")", "||", "value", ".", "index", "(", "@mnemonic", ".", "swapcase", ")", "@graphic", ".", "mvchgat", "(", "y", "=", "r", ",", "x", "=", "c", "+", "ulindex", ",", "max", "=", "1", ",", "Ncurses", "::", "A_BOLD", "|", "Ncurses", "::", "A_UNDERLINE", ",", "acolor", ",", "nil", ")", "end", "@repaint_required", "=", "false", "end" ]
label's repaint - I am removing wrapping and Array stuff and making it simple 2011-11-12
[ "label", "s", "repaint", "-", "I", "am", "removing", "wrapping", "and", "Array", "stuff", "and", "making", "it", "simple", "2011", "-", "11", "-", "12" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/rwidget.rb#L3017-L3060
train
mare-imbrium/canis
lib/canis/core/widgets/rwidget.rb
Canis.Button.action
def action a text a.name mnemonic a.mnemonic unless a.mnemonic.nil? command { a.call } end
ruby
def action a text a.name mnemonic a.mnemonic unless a.mnemonic.nil? command { a.call } end
[ "def", "action", "a", "text", "a", ".", "name", "mnemonic", "a", ".", "mnemonic", "unless", "a", ".", "mnemonic", ".", "nil?", "command", "{", "a", ".", "call", "}", "end" ]
set button based on Action
[ "set", "button", "based", "on", "Action" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/rwidget.rb#L3106-L3110
train
mare-imbrium/canis
lib/canis/core/widgets/rwidget.rb
Canis.Button.repaint
def repaint # button #@bgcolor ||= $def_bg_color #@color ||= $def_fg_color $log.debug("BUTTON repaint : #{self} r:#{@row} c:#{@col} , #{@color} , #{@bgcolor} , #{getvalue_for_paint}" ) r,c = @row, @col #rowcol include offset for putting cursor # NOTE: please override both (if using a string), or else it won't work # These are both colorpairs not colors ??? 2014-05-31 - 11:58 _highlight_color = @highlight_color || $reversecolor _highlight_bgcolor = @highlight_bgcolor || 0 _bgcolor = bgcolor() _color = color() if @state == :HIGHLIGHTED _bgcolor = @state==:HIGHLIGHTED ? _highlight_bgcolor : _bgcolor _color = @state==:HIGHLIGHTED ? _highlight_color : _color elsif selected? # only for certain buttons lie toggle and radio _bgcolor = @selected_bgcolor || _bgcolor _color = @selected_color || _color end $log.debug "XXX: button #{text} STATE is #{@state} color #{_color} , bg: #{_bgcolor} " if _bgcolor.is_a?( Integer) && _color.is_a?( Integer) # i think this means they are colorpairs not colors, but what if we use colors on the 256 scale ? # i don;t like this at all. else _color = get_color($datacolor, _color, _bgcolor) end value = getvalue_for_paint $log.debug("button repaint :#{self} r:#{r} c:#{c} col:#{_color} bg #{_bgcolor} v: #{value} ul #{@underline} mnem #{@mnemonic} datacolor #{$datacolor} ") len = @width || value.length @graphic = @form.window if @graphic.nil? ## cell editor listbox hack @graphic.printstring r, c, "%-*s" % [len, value], _color, attr() # @form.window.mvchgat(y=r, x=c, max=len, Ncurses::A_NORMAL, bgcolor, nil) # in toggle buttons the underline can change as the text toggles if @underline || @mnemonic uline = @underline && (@underline + @text_offset) || value.index(@mnemonic) || value.index(@mnemonic.swapcase) # if the char is not found don't print it if uline y=r #[email protected] x=c+uline #[email protected] # # NOTE: often values go below zero since root windows are defined # with 0 w and h, and then i might use that value for calcaluting # $log.error "XXX button underline location error #{x} , #{y} " if x < 0 or c < 0 raise " #{r} #{c} #{uline} button underline location error x:#{x} , y:#{y}. left #{@graphic.left} top:#{@graphic.top} " if x < 0 or c < 0 @graphic.mvchgat(y, x, max=1, Ncurses::A_BOLD|Ncurses::A_UNDERLINE, _color, nil) end end end
ruby
def repaint # button #@bgcolor ||= $def_bg_color #@color ||= $def_fg_color $log.debug("BUTTON repaint : #{self} r:#{@row} c:#{@col} , #{@color} , #{@bgcolor} , #{getvalue_for_paint}" ) r,c = @row, @col #rowcol include offset for putting cursor # NOTE: please override both (if using a string), or else it won't work # These are both colorpairs not colors ??? 2014-05-31 - 11:58 _highlight_color = @highlight_color || $reversecolor _highlight_bgcolor = @highlight_bgcolor || 0 _bgcolor = bgcolor() _color = color() if @state == :HIGHLIGHTED _bgcolor = @state==:HIGHLIGHTED ? _highlight_bgcolor : _bgcolor _color = @state==:HIGHLIGHTED ? _highlight_color : _color elsif selected? # only for certain buttons lie toggle and radio _bgcolor = @selected_bgcolor || _bgcolor _color = @selected_color || _color end $log.debug "XXX: button #{text} STATE is #{@state} color #{_color} , bg: #{_bgcolor} " if _bgcolor.is_a?( Integer) && _color.is_a?( Integer) # i think this means they are colorpairs not colors, but what if we use colors on the 256 scale ? # i don;t like this at all. else _color = get_color($datacolor, _color, _bgcolor) end value = getvalue_for_paint $log.debug("button repaint :#{self} r:#{r} c:#{c} col:#{_color} bg #{_bgcolor} v: #{value} ul #{@underline} mnem #{@mnemonic} datacolor #{$datacolor} ") len = @width || value.length @graphic = @form.window if @graphic.nil? ## cell editor listbox hack @graphic.printstring r, c, "%-*s" % [len, value], _color, attr() # @form.window.mvchgat(y=r, x=c, max=len, Ncurses::A_NORMAL, bgcolor, nil) # in toggle buttons the underline can change as the text toggles if @underline || @mnemonic uline = @underline && (@underline + @text_offset) || value.index(@mnemonic) || value.index(@mnemonic.swapcase) # if the char is not found don't print it if uline y=r #[email protected] x=c+uline #[email protected] # # NOTE: often values go below zero since root windows are defined # with 0 w and h, and then i might use that value for calcaluting # $log.error "XXX button underline location error #{x} , #{y} " if x < 0 or c < 0 raise " #{r} #{c} #{uline} button underline location error x:#{x} , y:#{y}. left #{@graphic.left} top:#{@graphic.top} " if x < 0 or c < 0 @graphic.mvchgat(y, x, max=1, Ncurses::A_BOLD|Ncurses::A_UNDERLINE, _color, nil) end end end
[ "def", "repaint", "$log", ".", "debug", "(", "\"BUTTON repaint : #{self} r:#{@row} c:#{@col} , #{@color} , #{@bgcolor} , #{getvalue_for_paint}\"", ")", "r", ",", "c", "=", "@row", ",", "@col", "_highlight_color", "=", "@highlight_color", "||", "$reversecolor", "_highlight_bgcolor", "=", "@highlight_bgcolor", "||", "0", "_bgcolor", "=", "bgcolor", "(", ")", "_color", "=", "color", "(", ")", "if", "@state", "==", ":HIGHLIGHTED", "_bgcolor", "=", "@state", "==", ":HIGHLIGHTED", "?", "_highlight_bgcolor", ":", "_bgcolor", "_color", "=", "@state", "==", ":HIGHLIGHTED", "?", "_highlight_color", ":", "_color", "elsif", "selected?", "_bgcolor", "=", "@selected_bgcolor", "||", "_bgcolor", "_color", "=", "@selected_color", "||", "_color", "end", "$log", ".", "debug", "\"XXX: button #{text} STATE is #{@state} color #{_color} , bg: #{_bgcolor} \"", "if", "_bgcolor", ".", "is_a?", "(", "Integer", ")", "&&", "_color", ".", "is_a?", "(", "Integer", ")", "else", "_color", "=", "get_color", "(", "$datacolor", ",", "_color", ",", "_bgcolor", ")", "end", "value", "=", "getvalue_for_paint", "$log", ".", "debug", "(", "\"button repaint :#{self} r:#{r} c:#{c} col:#{_color} bg #{_bgcolor} v: #{value} ul #{@underline} mnem #{@mnemonic} datacolor #{$datacolor} \"", ")", "len", "=", "@width", "||", "value", ".", "length", "@graphic", "=", "@form", ".", "window", "if", "@graphic", ".", "nil?", "@graphic", ".", "printstring", "r", ",", "c", ",", "\"%-*s\"", "%", "[", "len", ",", "value", "]", ",", "_color", ",", "attr", "(", ")", "if", "@underline", "||", "@mnemonic", "uline", "=", "@underline", "&&", "(", "@underline", "+", "@text_offset", ")", "||", "value", ".", "index", "(", "@mnemonic", ")", "||", "value", ".", "index", "(", "@mnemonic", ".", "swapcase", ")", "if", "uline", "y", "=", "r", "x", "=", "c", "+", "uline", "$log", ".", "error", "\"XXX button underline location error #{x} , #{y} \"", "if", "x", "<", "0", "or", "c", "<", "0", "raise", "\" #{r} #{c} #{uline} button underline location error x:#{x} , y:#{y}. left #{@graphic.left} top:#{@graphic.top} \"", "if", "x", "<", "0", "or", "c", "<", "0", "@graphic", ".", "mvchgat", "(", "y", ",", "x", ",", "max", "=", "1", ",", "Ncurses", "::", "A_BOLD", "|", "Ncurses", "::", "A_UNDERLINE", ",", "_color", ",", "nil", ")", "end", "end", "end" ]
FIXME 2014-05-31 since form checks for highlight color and sets repaint on on_enter, we shoul not set it. but what if it is set at form level ? also it is not correct to set colors now that form's defaults are taken
[ "FIXME", "2014", "-", "05", "-", "31", "since", "form", "checks", "for", "highlight", "color", "and", "sets", "repaint", "on", "on_enter", "we", "shoul", "not", "set", "it", ".", "but", "what", "if", "it", "is", "set", "at", "form", "level", "?", "also", "it", "is", "not", "correct", "to", "set", "colors", "now", "that", "form", "s", "defaults", "are", "taken" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/rwidget.rb#L3207-L3256
train
mare-imbrium/canis
lib/canis/core/widgets/rwidget.rb
Canis.ItemEvent.set
def set state, item_first=-1, item_last=-1, param_string=nil @state, @item_first, @item_last, @param_string = state, item_first, item_last, param_string @param_string = "Item event fired: #{item}, #{state}" if param_string.nil? end
ruby
def set state, item_first=-1, item_last=-1, param_string=nil @state, @item_first, @item_last, @param_string = state, item_first, item_last, param_string @param_string = "Item event fired: #{item}, #{state}" if param_string.nil? end
[ "def", "set", "state", ",", "item_first", "=", "-", "1", ",", "item_last", "=", "-", "1", ",", "param_string", "=", "nil", "@state", ",", "@item_first", ",", "@item_last", ",", "@param_string", "=", "state", ",", "item_first", ",", "item_last", ",", "param_string", "@param_string", "=", "\"Item event fired: #{item}, #{state}\"", "if", "param_string", ".", "nil?", "end" ]
for debugging etc =begin def initialize item, item_selectable, state, item_first=-1, item_last=-1, paramstring=nil @item, @item_selectable, @state, @item_first, @item_last = item, item_selectable, state, item_first, item_last @param_string = "Item event fired: #{item}, #{state}" end =end i think only one is needed per object, so create once only
[ "for", "debugging", "etc", "=", "begin", "def", "initialize", "item", "item_selectable", "state", "item_first", "=", "-", "1", "item_last", "=", "-", "1", "paramstring", "=", "nil" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/rwidget.rb#L3355-L3359
train
mare-imbrium/canis
lib/canis/core/widgets/rwidget.rb
Canis.ButtonGroup.select
def select button if button.is_a? String ; else button = button.value end set_value button end
ruby
def select button if button.is_a? String ; else button = button.value end set_value button end
[ "def", "select", "button", "if", "button", ".", "is_a?", "String", ";", "else", "button", "=", "button", ".", "value", "end", "set_value", "button", "end" ]
select the given button or value. This may be called by user programs to programmatically select a button
[ "select", "the", "given", "button", "or", "value", ".", "This", "may", "be", "called", "by", "user", "programs", "to", "programmatically", "select", "a", "button" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/rwidget.rb#L3544-L3551
train
mare-imbrium/canis
lib/canis/core/include/widgetmenu.rb
Canis.WidgetMenu._show_menu
def _show_menu return if @_menuitems.nil? || @_menuitems.empty? list = @_menuitems menu = PromptMenu.new self do |m| list.each { |e| m.add *e } end menu.display_new :title => 'Widget Menu (Press letter)' end
ruby
def _show_menu return if @_menuitems.nil? || @_menuitems.empty? list = @_menuitems menu = PromptMenu.new self do |m| list.each { |e| m.add *e } end menu.display_new :title => 'Widget Menu (Press letter)' end
[ "def", "_show_menu", "return", "if", "@_menuitems", ".", "nil?", "||", "@_menuitems", ".", "empty?", "list", "=", "@_menuitems", "menu", "=", "PromptMenu", ".", "new", "self", "do", "|", "m", "|", "list", ".", "each", "{", "|", "e", "|", "m", ".", "add", "*", "e", "}", "end", "menu", ".", "display_new", ":title", "=>", "'Widget Menu (Press letter)'", "end" ]
popup the hist
[ "popup", "the", "hist" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/include/widgetmenu.rb#L55-L64
train
mare-imbrium/canis
lib/canis/core/include/deprecated/listscrollable.rb
Canis.ListScrollable.bounds_check
def bounds_check h = scrollatrow() rc = row_count @old_toprow = @toprow @_header_adjustment ||= 0 @current_index = 0 if @current_index < 0 # not lt 0 @current_index = rc-1 if @current_index >= rc && rc>0 # not gt rowcount @toprow = rc-h-1 if rc > h && @toprow > rc - h - 1 # toprow shows full page if possible # curr has gone below table, move toprow forward if @current_index - @toprow > h @toprow = @current_index - h elsif @current_index < @toprow # curr has gone above table, move toprow up # sometimes current row gets hidden below header line @toprow = @current_index - (@_header_adjustment ||0) # prev line can make top row -1, however, if we are going back, lets # put it at start of page, so first or second row is not hidden @toprow = 0 if @toprow < h end @row_changed = false if @oldrow != @current_index on_leave_row @oldrow if respond_to? :on_leave_row # to be defined by widget that has included this on_enter_row @current_index if respond_to? :on_enter_row # to be defined by widget that has included this set_form_row @row_changed = true end #set_form_row # 2011-10-13 if @old_toprow != @toprow # only if scrolling has happened should we repaint @repaint_required = true #if @old_toprow != @toprow # only if scrolling has happened should we repaint @widget_scrolled = true end end
ruby
def bounds_check h = scrollatrow() rc = row_count @old_toprow = @toprow @_header_adjustment ||= 0 @current_index = 0 if @current_index < 0 # not lt 0 @current_index = rc-1 if @current_index >= rc && rc>0 # not gt rowcount @toprow = rc-h-1 if rc > h && @toprow > rc - h - 1 # toprow shows full page if possible # curr has gone below table, move toprow forward if @current_index - @toprow > h @toprow = @current_index - h elsif @current_index < @toprow # curr has gone above table, move toprow up # sometimes current row gets hidden below header line @toprow = @current_index - (@_header_adjustment ||0) # prev line can make top row -1, however, if we are going back, lets # put it at start of page, so first or second row is not hidden @toprow = 0 if @toprow < h end @row_changed = false if @oldrow != @current_index on_leave_row @oldrow if respond_to? :on_leave_row # to be defined by widget that has included this on_enter_row @current_index if respond_to? :on_enter_row # to be defined by widget that has included this set_form_row @row_changed = true end #set_form_row # 2011-10-13 if @old_toprow != @toprow # only if scrolling has happened should we repaint @repaint_required = true #if @old_toprow != @toprow # only if scrolling has happened should we repaint @widget_scrolled = true end end
[ "def", "bounds_check", "h", "=", "scrollatrow", "(", ")", "rc", "=", "row_count", "@old_toprow", "=", "@toprow", "@_header_adjustment", "||=", "0", "@current_index", "=", "0", "if", "@current_index", "<", "0", "@current_index", "=", "rc", "-", "1", "if", "@current_index", ">=", "rc", "&&", "rc", ">", "0", "@toprow", "=", "rc", "-", "h", "-", "1", "if", "rc", ">", "h", "&&", "@toprow", ">", "rc", "-", "h", "-", "1", "if", "@current_index", "-", "@toprow", ">", "h", "@toprow", "=", "@current_index", "-", "h", "elsif", "@current_index", "<", "@toprow", "@toprow", "=", "@current_index", "-", "(", "@_header_adjustment", "||", "0", ")", "@toprow", "=", "0", "if", "@toprow", "<", "h", "end", "@row_changed", "=", "false", "if", "@oldrow", "!=", "@current_index", "on_leave_row", "@oldrow", "if", "respond_to?", ":on_leave_row", "on_enter_row", "@current_index", "if", "respond_to?", ":on_enter_row", "set_form_row", "@row_changed", "=", "true", "end", "if", "@old_toprow", "!=", "@toprow", "@repaint_required", "=", "true", "@widget_scrolled", "=", "true", "end", "end" ]
please set oldrow before calling this. Store current_index as oldrow before changing. NOTE
[ "please", "set", "oldrow", "before", "calling", "this", ".", "Store", "current_index", "as", "oldrow", "before", "changing", ".", "NOTE" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/include/deprecated/listscrollable.rb#L83-L117
train
mare-imbrium/canis
lib/canis/core/include/deprecated/listscrollable.rb
Canis.ListScrollable.show_caret_func
def show_caret_func return unless @show_caret # trying highlighting cursor 2010-01-23 19:07 TABBEDPANE TRYING # TODO take into account rows_panned etc ? I don't think so. @rows_panned ||= 0 r,c = rowcol yy = r + @current_index - @toprow - @win_top #xx = @form.col # how do we know what value has been set earlier ? yy = r + @current_index - @toprow #- @win_top yy = @row_offset + @current_index - @toprow #- @win_top xx = @col_offset + @curpos || 0 #yy = @row_offset if yy < @row_offset # sometimes r is 0, we are missing something in tabbedpane+scroll #xx = @col_offset if xx < @col_offset #xx = 0 if xx < 0 $log.debug " #{@name} printing CARET at #{yy},#{xx}: fwt:- #{@win_top} r:#{@row} tr:-#{@toprow}+ci:#{@current_index},+r #{r} " if [email protected]? @graphic.mvchgat(y=@oldcursorrow, x=@oldcursorcol, 1, Ncurses::A_NORMAL, $datacolor, NIL) end @oldcursorrow = yy @oldcursorcol = xx @graphic.mvchgat(y=yy, x=xx, 1, Ncurses::A_NORMAL, $reversecolor, nil) @buffer_modified = true end
ruby
def show_caret_func return unless @show_caret # trying highlighting cursor 2010-01-23 19:07 TABBEDPANE TRYING # TODO take into account rows_panned etc ? I don't think so. @rows_panned ||= 0 r,c = rowcol yy = r + @current_index - @toprow - @win_top #xx = @form.col # how do we know what value has been set earlier ? yy = r + @current_index - @toprow #- @win_top yy = @row_offset + @current_index - @toprow #- @win_top xx = @col_offset + @curpos || 0 #yy = @row_offset if yy < @row_offset # sometimes r is 0, we are missing something in tabbedpane+scroll #xx = @col_offset if xx < @col_offset #xx = 0 if xx < 0 $log.debug " #{@name} printing CARET at #{yy},#{xx}: fwt:- #{@win_top} r:#{@row} tr:-#{@toprow}+ci:#{@current_index},+r #{r} " if [email protected]? @graphic.mvchgat(y=@oldcursorrow, x=@oldcursorcol, 1, Ncurses::A_NORMAL, $datacolor, NIL) end @oldcursorrow = yy @oldcursorcol = xx @graphic.mvchgat(y=yy, x=xx, 1, Ncurses::A_NORMAL, $reversecolor, nil) @buffer_modified = true end
[ "def", "show_caret_func", "return", "unless", "@show_caret", "@rows_panned", "||=", "0", "r", ",", "c", "=", "rowcol", "yy", "=", "r", "+", "@current_index", "-", "@toprow", "-", "@win_top", "yy", "=", "r", "+", "@current_index", "-", "@toprow", "yy", "=", "@row_offset", "+", "@current_index", "-", "@toprow", "xx", "=", "@col_offset", "+", "@curpos", "||", "0", "$log", ".", "debug", "\" #{@name} printing CARET at #{yy},#{xx}: fwt:- #{@win_top} r:#{@row} tr:-#{@toprow}+ci:#{@current_index},+r #{r} \"", "if", "!", "@oldcursorrow", ".", "nil?", "@graphic", ".", "mvchgat", "(", "y", "=", "@oldcursorrow", ",", "x", "=", "@oldcursorcol", ",", "1", ",", "Ncurses", "::", "A_NORMAL", ",", "$datacolor", ",", "NIL", ")", "end", "@oldcursorrow", "=", "yy", "@oldcursorcol", "=", "xx", "@graphic", ".", "mvchgat", "(", "y", "=", "yy", ",", "x", "=", "xx", ",", "1", ",", "Ncurses", "::", "A_NORMAL", ",", "$reversecolor", ",", "nil", ")", "@buffer_modified", "=", "true", "end" ]
In many situations like placing a textarea or textview inside a splitpane + or scrollpane there have been issues getting the cursor at the right point, + since there are multiple buffers. Finally in tabbedpanes, i am pretty + lost getting the correct position, and i feel we should set the cursor + internally once and for all. So here's an attempt paint the cursor ourselves on the widget, rather than rely on getting to the top window with the correct coordinates. I do need to erase cursor too. Can be dicey, but is worth the attempt. This works perfectly, except for when placed in a Tabbedpane since that prints the form with a row offset + of 2 and the widget does not know of the offset. cursor gets it correct since the form has an add_row.
[ "In", "many", "situations", "like", "placing", "a", "textarea", "or", "textview", "inside", "a", "splitpane", "+", "or", "scrollpane", "there", "have", "been", "issues", "getting", "the", "cursor", "at", "the", "right", "point", "+", "since", "there", "are", "multiple", "buffers", ".", "Finally", "in", "tabbedpanes", "i", "am", "pretty", "+", "lost", "getting", "the", "correct", "position", "and", "i", "feel", "we", "should", "set", "the", "cursor", "+", "internally", "once", "and", "for", "all", ".", "So", "here", "s", "an", "attempt", "paint", "the", "cursor", "ourselves", "on", "the", "widget", "rather", "than", "rely", "on", "getting", "to", "the", "top", "window", "with", "the", "correct", "coordinates", ".", "I", "do", "need", "to", "erase", "cursor", "too", ".", "Can", "be", "dicey", "but", "is", "worth", "the", "attempt", ".", "This", "works", "perfectly", "except", "for", "when", "placed", "in", "a", "Tabbedpane", "since", "that", "prints", "the", "form", "with", "a", "row", "offset", "+", "of", "2", "and", "the", "widget", "does", "not", "know", "of", "the", "offset", ".", "cursor", "gets", "it", "correct", "since", "the", "form", "has", "an", "add_row", "." ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/include/deprecated/listscrollable.rb#L146-L169
train
mare-imbrium/canis
lib/canis/core/include/deprecated/listscrollable.rb
Canis.ListScrollable.next_match
def next_match char data = get_content row = focussed_index + 1 row.upto(data.length-1) do |ix| #val = data[ix].chomp rescue return # 2010-01-05 15:28 crashed on trueclass val = data[ix].to_s rescue return # 2010-01-05 15:28 crashed on trueclass #if val[0,1] == char #and val != currval if val[0,1].casecmp(char) == 0 #AND VAL != CURRval return ix end end row = focussed_index - 1 0.upto(row) do |ix| #val = data[ix].chomp val = data[ix].to_s #if val[0,1] == char #and val != currval if val[0,1].casecmp(char) == 0 #and val != currval return ix end end return -1 end
ruby
def next_match char data = get_content row = focussed_index + 1 row.upto(data.length-1) do |ix| #val = data[ix].chomp rescue return # 2010-01-05 15:28 crashed on trueclass val = data[ix].to_s rescue return # 2010-01-05 15:28 crashed on trueclass #if val[0,1] == char #and val != currval if val[0,1].casecmp(char) == 0 #AND VAL != CURRval return ix end end row = focussed_index - 1 0.upto(row) do |ix| #val = data[ix].chomp val = data[ix].to_s #if val[0,1] == char #and val != currval if val[0,1].casecmp(char) == 0 #and val != currval return ix end end return -1 end
[ "def", "next_match", "char", "data", "=", "get_content", "row", "=", "focussed_index", "+", "1", "row", ".", "upto", "(", "data", ".", "length", "-", "1", ")", "do", "|", "ix", "|", "val", "=", "data", "[", "ix", "]", ".", "to_s", "rescue", "return", "if", "val", "[", "0", ",", "1", "]", ".", "casecmp", "(", "char", ")", "==", "0", "return", "ix", "end", "end", "row", "=", "focussed_index", "-", "1", "0", ".", "upto", "(", "row", ")", "do", "|", "ix", "|", "val", "=", "data", "[", "ix", "]", ".", "to_s", "if", "val", "[", "0", ",", "1", "]", ".", "casecmp", "(", "char", ")", "==", "0", "return", "ix", "end", "end", "return", "-", "1", "end" ]
finds the next match for the char pressed returning the index If we are only checking first char, then why chomp ? Please note that this is used now by tree, and list can have non-strings, so use to_s
[ "finds", "the", "next", "match", "for", "the", "char", "pressed", "returning", "the", "index", "If", "we", "are", "only", "checking", "first", "char", "then", "why", "chomp", "?", "Please", "note", "that", "this", "is", "used", "now", "by", "tree", "and", "list", "can", "have", "non", "-", "strings", "so", "use", "to_s" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/include/deprecated/listscrollable.rb#L218-L239
train
mare-imbrium/canis
lib/canis/core/include/deprecated/listscrollable.rb
Canis.ListScrollable._find_next
def _find_next regex=@last_regex, start = @search_found_ix, first_time = false #raise "No previous search" if regex.nil? warn "No previous search" and return if regex.nil? #$log.debug " _find_next #{@search_found_ix} : #{@current_index}" extra = 1 # first time search on current line, next time skip current line or else we get stuck. extra = 0 if first_time start ||= 0 fend = @list.size-1 if start != fend start += extra unless start == fend # used to be +=1 so we don't get stuck in same row @last_regex = regex @search_start_ix = start regex = Regexp.new(regex, Regexp::IGNORECASE) if @search_case start.upto(fend) do |ix| row1 = @list[ix].to_s # 2011-09-29 crashing on a character F3 in log file # 2013-03-20 - 18:25 187compat if row1.respond_to? :encode row = row1.encode("ASCII-8BIT", :invalid => :replace, :undef => :replace, :replace => "?") else row = row1 end m=row.match(regex) if !m.nil? @find_offset = m.offset(0)[0] @find_offset1 = m.offset(0)[1] ix += (@_header_adjustment || 0) @search_found_ix = ix return ix end end end fend = start-1 start = 0 if @search_wrap start.upto(fend) do |ix| row = @list[ix].to_s m=row.match(regex) if !m.nil? @find_offset = m.offset(0)[0] @find_offset1 = m.offset(0)[1] ix += (@_header_adjustment || 0) @search_found_ix = ix return ix end end end return nil end
ruby
def _find_next regex=@last_regex, start = @search_found_ix, first_time = false #raise "No previous search" if regex.nil? warn "No previous search" and return if regex.nil? #$log.debug " _find_next #{@search_found_ix} : #{@current_index}" extra = 1 # first time search on current line, next time skip current line or else we get stuck. extra = 0 if first_time start ||= 0 fend = @list.size-1 if start != fend start += extra unless start == fend # used to be +=1 so we don't get stuck in same row @last_regex = regex @search_start_ix = start regex = Regexp.new(regex, Regexp::IGNORECASE) if @search_case start.upto(fend) do |ix| row1 = @list[ix].to_s # 2011-09-29 crashing on a character F3 in log file # 2013-03-20 - 18:25 187compat if row1.respond_to? :encode row = row1.encode("ASCII-8BIT", :invalid => :replace, :undef => :replace, :replace => "?") else row = row1 end m=row.match(regex) if !m.nil? @find_offset = m.offset(0)[0] @find_offset1 = m.offset(0)[1] ix += (@_header_adjustment || 0) @search_found_ix = ix return ix end end end fend = start-1 start = 0 if @search_wrap start.upto(fend) do |ix| row = @list[ix].to_s m=row.match(regex) if !m.nil? @find_offset = m.offset(0)[0] @find_offset1 = m.offset(0)[1] ix += (@_header_adjustment || 0) @search_found_ix = ix return ix end end end return nil end
[ "def", "_find_next", "regex", "=", "@last_regex", ",", "start", "=", "@search_found_ix", ",", "first_time", "=", "false", "warn", "\"No previous search\"", "and", "return", "if", "regex", ".", "nil?", "extra", "=", "1", "extra", "=", "0", "if", "first_time", "start", "||=", "0", "fend", "=", "@list", ".", "size", "-", "1", "if", "start", "!=", "fend", "start", "+=", "extra", "unless", "start", "==", "fend", "@last_regex", "=", "regex", "@search_start_ix", "=", "start", "regex", "=", "Regexp", ".", "new", "(", "regex", ",", "Regexp", "::", "IGNORECASE", ")", "if", "@search_case", "start", ".", "upto", "(", "fend", ")", "do", "|", "ix", "|", "row1", "=", "@list", "[", "ix", "]", ".", "to_s", "if", "row1", ".", "respond_to?", ":encode", "row", "=", "row1", ".", "encode", "(", "\"ASCII-8BIT\"", ",", ":invalid", "=>", ":replace", ",", ":undef", "=>", ":replace", ",", ":replace", "=>", "\"?\"", ")", "else", "row", "=", "row1", "end", "m", "=", "row", ".", "match", "(", "regex", ")", "if", "!", "m", ".", "nil?", "@find_offset", "=", "m", ".", "offset", "(", "0", ")", "[", "0", "]", "@find_offset1", "=", "m", ".", "offset", "(", "0", ")", "[", "1", "]", "ix", "+=", "(", "@_header_adjustment", "||", "0", ")", "@search_found_ix", "=", "ix", "return", "ix", "end", "end", "end", "fend", "=", "start", "-", "1", "start", "=", "0", "if", "@search_wrap", "start", ".", "upto", "(", "fend", ")", "do", "|", "ix", "|", "row", "=", "@list", "[", "ix", "]", ".", "to_s", "m", "=", "row", ".", "match", "(", "regex", ")", "if", "!", "m", ".", "nil?", "@find_offset", "=", "m", ".", "offset", "(", "0", ")", "[", "0", "]", "@find_offset1", "=", "m", ".", "offset", "(", "0", ")", "[", "1", "]", "ix", "+=", "(", "@_header_adjustment", "||", "0", ")", "@search_found_ix", "=", "ix", "return", "ix", "end", "end", "end", "return", "nil", "end" ]
find forwards Using this to start a search or continue search
[ "find", "forwards", "Using", "this", "to", "start", "a", "search", "or", "continue", "search" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/include/deprecated/listscrollable.rb#L328-L378
train
mare-imbrium/canis
lib/canis/core/include/deprecated/listscrollable.rb
Canis.ListScrollable._find_prev
def _find_prev regex=@last_regex, start = @search_found_ix, first_time = false #TODO the firsttime part, see find_next #raise "No previous search" if regex.nil? warn "No previous search" and return if regex.nil? #$log.debug " _find_prev #{@search_found_ix} : #{@current_index}" if start != 0 start -= 1 unless start == 0 @last_regex = regex @search_start_ix = start regex = Regexp.new(regex, Regexp::IGNORECASE) if @search_case start.downto(0) do |ix| row = @list[ix].to_s m=row.match(regex) if !m.nil? @find_offset = m.offset(0)[0] @find_offset1 = m.offset(0)[1] ix += (@_header_adjustment || 0) @search_found_ix = ix return ix end end end fend = start-1 start = @list.size-1 if @search_wrap start.downto(fend) do |ix| row = @list[ix].to_s m=row.match(regex) if !m.nil? @find_offset = m.offset(0)[0] @find_offset1 = m.offset(0)[1] ix += (@_header_adjustment || 0) @search_found_ix = ix return ix end end end return nil end
ruby
def _find_prev regex=@last_regex, start = @search_found_ix, first_time = false #TODO the firsttime part, see find_next #raise "No previous search" if regex.nil? warn "No previous search" and return if regex.nil? #$log.debug " _find_prev #{@search_found_ix} : #{@current_index}" if start != 0 start -= 1 unless start == 0 @last_regex = regex @search_start_ix = start regex = Regexp.new(regex, Regexp::IGNORECASE) if @search_case start.downto(0) do |ix| row = @list[ix].to_s m=row.match(regex) if !m.nil? @find_offset = m.offset(0)[0] @find_offset1 = m.offset(0)[1] ix += (@_header_adjustment || 0) @search_found_ix = ix return ix end end end fend = start-1 start = @list.size-1 if @search_wrap start.downto(fend) do |ix| row = @list[ix].to_s m=row.match(regex) if !m.nil? @find_offset = m.offset(0)[0] @find_offset1 = m.offset(0)[1] ix += (@_header_adjustment || 0) @search_found_ix = ix return ix end end end return nil end
[ "def", "_find_prev", "regex", "=", "@last_regex", ",", "start", "=", "@search_found_ix", ",", "first_time", "=", "false", "warn", "\"No previous search\"", "and", "return", "if", "regex", ".", "nil?", "if", "start", "!=", "0", "start", "-=", "1", "unless", "start", "==", "0", "@last_regex", "=", "regex", "@search_start_ix", "=", "start", "regex", "=", "Regexp", ".", "new", "(", "regex", ",", "Regexp", "::", "IGNORECASE", ")", "if", "@search_case", "start", ".", "downto", "(", "0", ")", "do", "|", "ix", "|", "row", "=", "@list", "[", "ix", "]", ".", "to_s", "m", "=", "row", ".", "match", "(", "regex", ")", "if", "!", "m", ".", "nil?", "@find_offset", "=", "m", ".", "offset", "(", "0", ")", "[", "0", "]", "@find_offset1", "=", "m", ".", "offset", "(", "0", ")", "[", "1", "]", "ix", "+=", "(", "@_header_adjustment", "||", "0", ")", "@search_found_ix", "=", "ix", "return", "ix", "end", "end", "end", "fend", "=", "start", "-", "1", "start", "=", "@list", ".", "size", "-", "1", "if", "@search_wrap", "start", ".", "downto", "(", "fend", ")", "do", "|", "ix", "|", "row", "=", "@list", "[", "ix", "]", ".", "to_s", "m", "=", "row", ".", "match", "(", "regex", ")", "if", "!", "m", ".", "nil?", "@find_offset", "=", "m", ".", "offset", "(", "0", ")", "[", "0", "]", "@find_offset1", "=", "m", ".", "offset", "(", "0", ")", "[", "1", "]", "ix", "+=", "(", "@_header_adjustment", "||", "0", ")", "@search_found_ix", "=", "ix", "return", "ix", "end", "end", "end", "return", "nil", "end" ]
find backwards Using this to start a search or continue search
[ "find", "backwards", "Using", "this", "to", "start", "a", "search", "or", "continue", "search" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/include/deprecated/listscrollable.rb#L412-L450
train
mare-imbrium/canis
lib/canis/core/include/deprecated/listscrollable.rb
Canis.ListScrollable.sanitize
def sanitize content #:nodoc: if content.is_a? String content.chomp! # 2013-03-20 - 18:29 187compat if content.respond_to? :encode content.replace(content.encode("ASCII-8BIT", :invalid => :replace, :undef => :replace, :replace => "?")) end content.gsub!(/[\t\r\n]/, ' ') # don't display tab, newline content.gsub!(/\n/, ' ') # don't display tab, newline content.gsub!(/[^[:print:]]/, '') # don't display non print characters else content end end
ruby
def sanitize content #:nodoc: if content.is_a? String content.chomp! # 2013-03-20 - 18:29 187compat if content.respond_to? :encode content.replace(content.encode("ASCII-8BIT", :invalid => :replace, :undef => :replace, :replace => "?")) end content.gsub!(/[\t\r\n]/, ' ') # don't display tab, newline content.gsub!(/\n/, ' ') # don't display tab, newline content.gsub!(/[^[:print:]]/, '') # don't display non print characters else content end end
[ "def", "sanitize", "content", "if", "content", ".", "is_a?", "String", "content", ".", "chomp!", "if", "content", ".", "respond_to?", ":encode", "content", ".", "replace", "(", "content", ".", "encode", "(", "\"ASCII-8BIT\"", ",", ":invalid", "=>", ":replace", ",", ":undef", "=>", ":replace", ",", ":replace", "=>", "\"?\"", ")", ")", "end", "content", ".", "gsub!", "(", "/", "\\t", "\\r", "\\n", "/", ",", "' '", ")", "content", ".", "gsub!", "(", "/", "\\n", "/", ",", "' '", ")", "content", ".", "gsub!", "(", "/", "/", ",", "''", ")", "else", "content", "end", "end" ]
takes a block, this way anyone extending this class can just pass a block to do his job This modifies the string
[ "takes", "a", "block", "this", "way", "anyone", "extending", "this", "class", "can", "just", "pass", "a", "block", "to", "do", "his", "job", "This", "modifies", "the", "string" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/include/deprecated/listscrollable.rb#L572-L585
train
mare-imbrium/canis
lib/canis/core/include/deprecated/listscrollable.rb
Canis.ListScrollable._convert_index_to_printable_row
def _convert_index_to_printable_row index=@current_index r,c = rowcol pos = _convert_index_to_visible_row(index) return nil unless pos pos = r + pos return pos end
ruby
def _convert_index_to_printable_row index=@current_index r,c = rowcol pos = _convert_index_to_visible_row(index) return nil unless pos pos = r + pos return pos end
[ "def", "_convert_index_to_printable_row", "index", "=", "@current_index", "r", ",", "c", "=", "rowcol", "pos", "=", "_convert_index_to_visible_row", "(", "index", ")", "return", "nil", "unless", "pos", "pos", "=", "r", "+", "pos", "return", "pos", "end" ]
actual position to write on window NOTE can return nil, if user scrolls forward or backward
[ "actual", "position", "to", "write", "on", "window", "NOTE", "can", "return", "nil", "if", "user", "scrolls", "forward", "or", "backward" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/include/deprecated/listscrollable.rb#L623-L629
train
mare-imbrium/canis
lib/canis/core/widgets/tree.rb
Canis.Tree.data
def data alist=nil # if nothing passed, print an empty root, rather than crashing alist = [] if alist.nil? @data = alist # data given by user case alist when Array @treemodel = Canis::DefaultTreeModel.new("/") @treemodel.root.add alist when Hash @treemodel = Canis::DefaultTreeModel.new("/") @treemodel.root.add alist when TreeNode # this is a root node @treemodel = Canis::DefaultTreeModel.new(alist) when DefaultTreeModel @treemodel = alist else if alist.is_a? DefaultTreeModel @treemodel = alist else raise ArgumentError, "Tree does not know how to handle #{alist.class} " end end # we now have a tree raise "I still don't have a tree" unless @treemodel set_expanded_state(@treemodel.root, true) convert_to_list @treemodel # added on 2009-01-13 23:19 since updates are not automatic now #@list.bind(:LIST_DATA_EVENT) { |e| list_data_changed() } #create_default_list_selection_model TODO fire_dimension_changed self end
ruby
def data alist=nil # if nothing passed, print an empty root, rather than crashing alist = [] if alist.nil? @data = alist # data given by user case alist when Array @treemodel = Canis::DefaultTreeModel.new("/") @treemodel.root.add alist when Hash @treemodel = Canis::DefaultTreeModel.new("/") @treemodel.root.add alist when TreeNode # this is a root node @treemodel = Canis::DefaultTreeModel.new(alist) when DefaultTreeModel @treemodel = alist else if alist.is_a? DefaultTreeModel @treemodel = alist else raise ArgumentError, "Tree does not know how to handle #{alist.class} " end end # we now have a tree raise "I still don't have a tree" unless @treemodel set_expanded_state(@treemodel.root, true) convert_to_list @treemodel # added on 2009-01-13 23:19 since updates are not automatic now #@list.bind(:LIST_DATA_EVENT) { |e| list_data_changed() } #create_default_list_selection_model TODO fire_dimension_changed self end
[ "def", "data", "alist", "=", "nil", "alist", "=", "[", "]", "if", "alist", ".", "nil?", "@data", "=", "alist", "case", "alist", "when", "Array", "@treemodel", "=", "Canis", "::", "DefaultTreeModel", ".", "new", "(", "\"/\"", ")", "@treemodel", ".", "root", ".", "add", "alist", "when", "Hash", "@treemodel", "=", "Canis", "::", "DefaultTreeModel", ".", "new", "(", "\"/\"", ")", "@treemodel", ".", "root", ".", "add", "alist", "when", "TreeNode", "@treemodel", "=", "Canis", "::", "DefaultTreeModel", ".", "new", "(", "alist", ")", "when", "DefaultTreeModel", "@treemodel", "=", "alist", "else", "if", "alist", ".", "is_a?", "DefaultTreeModel", "@treemodel", "=", "alist", "else", "raise", "ArgumentError", ",", "\"Tree does not know how to handle #{alist.class} \"", "end", "end", "raise", "\"I still don't have a tree\"", "unless", "@treemodel", "set_expanded_state", "(", "@treemodel", ".", "root", ",", "true", ")", "convert_to_list", "@treemodel", "fire_dimension_changed", "self", "end" ]
pass data to create this tree model used to be list
[ "pass", "data", "to", "create", "this", "tree", "model", "used", "to", "be", "list" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/tree.rb#L252-L285
train
mare-imbrium/canis
lib/canis/core/widgets/tree.rb
Canis.Tree.XXXpadrefresh
def XXXpadrefresh top = @window.top left = @window.left sr = @startrow + top sc = @startcol + left # first do header always in first row retval = FFI::NCurses.prefresh(@pad,0,@pcol, sr , sc , 2 , @cols+ sc ); # now print rest of data # h is header_adjustment h = 1 retval = FFI::NCurses.prefresh(@pad,@prow + h,@pcol, sr + h , sc , @rows + sr , @cols+ sc ); $log.warn "XXX: PADREFRESH #{retval}, #{@prow}, #{@pcol}, #{sr}, #{sc}, #{@rows+sr}, #{@cols+sc}." if retval == -1 # padrefresh can fail if width is greater than NCurses.COLS end
ruby
def XXXpadrefresh top = @window.top left = @window.left sr = @startrow + top sc = @startcol + left # first do header always in first row retval = FFI::NCurses.prefresh(@pad,0,@pcol, sr , sc , 2 , @cols+ sc ); # now print rest of data # h is header_adjustment h = 1 retval = FFI::NCurses.prefresh(@pad,@prow + h,@pcol, sr + h , sc , @rows + sr , @cols+ sc ); $log.warn "XXX: PADREFRESH #{retval}, #{@prow}, #{@pcol}, #{sr}, #{sc}, #{@rows+sr}, #{@cols+sc}." if retval == -1 # padrefresh can fail if width is greater than NCurses.COLS end
[ "def", "XXXpadrefresh", "top", "=", "@window", ".", "top", "left", "=", "@window", ".", "left", "sr", "=", "@startrow", "+", "top", "sc", "=", "@startcol", "+", "left", "retval", "=", "FFI", "::", "NCurses", ".", "prefresh", "(", "@pad", ",", "0", ",", "@pcol", ",", "sr", ",", "sc", ",", "2", ",", "@cols", "+", "sc", ")", ";", "h", "=", "1", "retval", "=", "FFI", "::", "NCurses", ".", "prefresh", "(", "@pad", ",", "@prow", "+", "h", ",", "@pcol", ",", "sr", "+", "h", ",", "sc", ",", "@rows", "+", "sr", ",", "@cols", "+", "sc", ")", ";", "$log", ".", "warn", "\"XXX: PADREFRESH #{retval}, #{@prow}, #{@pcol}, #{sr}, #{sc}, #{@rows+sr}, #{@cols+sc}.\"", "if", "retval", "==", "-", "1", "end" ]
refresh pad onto window overrides super due to header_adjustment and the header too
[ "refresh", "pad", "onto", "window", "overrides", "super", "due", "to", "header_adjustment", "and", "the", "header", "too" ]
8bce60ff9dad321e299a6124620deb4771740b0b
https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/tree.rb#L418-L431
train
kristianmandrup/cream
lib/cream/view/role_area.rb
Cream::View.Role.area_for_roles
def area_for_roles(*user_roles, &block) options = last_option(user_roles) return area(&block) if user_roles.empty? not_for_roles(user_roles, &block) if user_roles.first == false for_roles user_roles do area(options, &block) end end
ruby
def area_for_roles(*user_roles, &block) options = last_option(user_roles) return area(&block) if user_roles.empty? not_for_roles(user_roles, &block) if user_roles.first == false for_roles user_roles do area(options, &block) end end
[ "def", "area_for_roles", "(", "*", "user_roles", ",", "&", "block", ")", "options", "=", "last_option", "(", "user_roles", ")", "return", "area", "(", "&", "block", ")", "if", "user_roles", ".", "empty?", "not_for_roles", "(", "user_roles", ",", "&", "block", ")", "if", "user_roles", ".", "first", "==", "false", "for_roles", "user_roles", "do", "area", "(", "options", ",", "&", "block", ")", "end", "end" ]
for users WITH the given roles create a div area with optional class given in options hash and render block within this div
[ "for", "users", "WITH", "the", "given", "roles", "create", "a", "div", "area", "with", "optional", "class", "given", "in", "options", "hash", "and", "render", "block", "within", "this", "div" ]
6edbdc8796b4a942e11d1054649b2e058c90c9d8
https://github.com/kristianmandrup/cream/blob/6edbdc8796b4a942e11d1054649b2e058c90c9d8/lib/cream/view/role_area.rb#L8-L18
train
kristianmandrup/cream
lib/cream/view/role_area.rb
Cream::View.Role.area_not_for_roles
def area_not_for_roles(*user_roles, &block) options = last_option(user_roles) not_for_roles user_roles do clazz = options[:class] || 'special' area(:class => clazz, &block) end end
ruby
def area_not_for_roles(*user_roles, &block) options = last_option(user_roles) not_for_roles user_roles do clazz = options[:class] || 'special' area(:class => clazz, &block) end end
[ "def", "area_not_for_roles", "(", "*", "user_roles", ",", "&", "block", ")", "options", "=", "last_option", "(", "user_roles", ")", "not_for_roles", "user_roles", "do", "clazz", "=", "options", "[", ":class", "]", "||", "'special'", "area", "(", ":class", "=>", "clazz", ",", "&", "block", ")", "end", "end" ]
for users WITHOUT the given roles create a div area with optional class given in options hash and render block within this div
[ "for", "users", "WITHOUT", "the", "given", "roles", "create", "a", "div", "area", "with", "optional", "class", "given", "in", "options", "hash", "and", "render", "block", "within", "this", "div" ]
6edbdc8796b4a942e11d1054649b2e058c90c9d8
https://github.com/kristianmandrup/cream/blob/6edbdc8796b4a942e11d1054649b2e058c90c9d8/lib/cream/view/role_area.rb#L24-L30
train
takanamito/openapi2ruby
lib/openapi2ruby/generator.rb
Openapi2ruby.Generator.generate
def generate(output_path, template_path) template_path = TEMPLATE_PATH if template_path.nil? template = File.read(template_path) generated_class = ERB.new(template, nil, '-').result(binding) output_file = Pathname.new(output_path).join("#{@schema.name.underscore}_serializer.rb") File.open(output_file.to_s, 'w') { |file| file << generated_class } output_file.to_s end
ruby
def generate(output_path, template_path) template_path = TEMPLATE_PATH if template_path.nil? template = File.read(template_path) generated_class = ERB.new(template, nil, '-').result(binding) output_file = Pathname.new(output_path).join("#{@schema.name.underscore}_serializer.rb") File.open(output_file.to_s, 'w') { |file| file << generated_class } output_file.to_s end
[ "def", "generate", "(", "output_path", ",", "template_path", ")", "template_path", "=", "TEMPLATE_PATH", "if", "template_path", ".", "nil?", "template", "=", "File", ".", "read", "(", "template_path", ")", "generated_class", "=", "ERB", ".", "new", "(", "template", ",", "nil", ",", "'-'", ")", ".", "result", "(", "binding", ")", "output_file", "=", "Pathname", ".", "new", "(", "output_path", ")", ".", "join", "(", "\"#{@schema.name.underscore}_serializer.rb\"", ")", "File", ".", "open", "(", "output_file", ".", "to_s", ",", "'w'", ")", "{", "|", "file", "|", "file", "<<", "generated_class", "}", "output_file", ".", "to_s", "end" ]
Generate ruby class from OpenAPI schema @param output_path [String] parsed OpenAPI YAML @param template_path [String] original template path
[ "Generate", "ruby", "class", "from", "OpenAPI", "schema" ]
1c971a814248600bd302809a912a527328164dc5
https://github.com/takanamito/openapi2ruby/blob/1c971a814248600bd302809a912a527328164dc5/lib/openapi2ruby/generator.rb#L24-L32
train
bguthrie/handshake
lib/handshake/clause_methods.rb
Handshake.ClauseMethods.responds_to?
def responds_to?(*methods) respond_assertions = methods.map do |m| clause("responds to #{m}") { |o| o.respond_to? m } end all?(*respond_assertions) end
ruby
def responds_to?(*methods) respond_assertions = methods.map do |m| clause("responds to #{m}") { |o| o.respond_to? m } end all?(*respond_assertions) end
[ "def", "responds_to?", "(", "*", "methods", ")", "respond_assertions", "=", "methods", ".", "map", "do", "|", "m", "|", "clause", "(", "\"responds to #{m}\"", ")", "{", "|", "o", "|", "o", ".", "respond_to?", "m", "}", "end", "all?", "(", "*", "respond_assertions", ")", "end" ]
Passes if argument responds to all of the given methods.
[ "Passes", "if", "argument", "responds", "to", "all", "of", "the", "given", "methods", "." ]
5fd50a814be5c1df02854fb62d851584273ce813
https://github.com/bguthrie/handshake/blob/5fd50a814be5c1df02854fb62d851584273ce813/lib/handshake/clause_methods.rb#L150-L155
train
takanamito/openapi2ruby
lib/openapi2ruby/openapi.rb
Openapi2ruby.Openapi.schemas
def schemas @content['components']['schemas'].each_with_object([]) do |(key, value), results| schema_content = { name: key, definition: value} schema = Openapi2ruby::Openapi::Schema.new(schema_content) results << schema unless schema.properties.empty? end end
ruby
def schemas @content['components']['schemas'].each_with_object([]) do |(key, value), results| schema_content = { name: key, definition: value} schema = Openapi2ruby::Openapi::Schema.new(schema_content) results << schema unless schema.properties.empty? end end
[ "def", "schemas", "@content", "[", "'components'", "]", "[", "'schemas'", "]", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "(", "key", ",", "value", ")", ",", "results", "|", "schema_content", "=", "{", "name", ":", "key", ",", "definition", ":", "value", "}", "schema", "=", "Openapi2ruby", "::", "Openapi", "::", "Schema", ".", "new", "(", "schema_content", ")", "results", "<<", "schema", "unless", "schema", ".", "properties", ".", "empty?", "end", "end" ]
Creates OpenAPI Schema array @return [Array[Openapi2ruby::Openapi::Schema]]
[ "Creates", "OpenAPI", "Schema", "array" ]
1c971a814248600bd302809a912a527328164dc5
https://github.com/takanamito/openapi2ruby/blob/1c971a814248600bd302809a912a527328164dc5/lib/openapi2ruby/openapi.rb#L9-L15
train
bguthrie/handshake
lib/handshake/block_contract.rb
Handshake.ClauseMethods.Block
def Block(contract_hash) pc = Handshake::ProcContract.new pc.signature = contract_hash pc end
ruby
def Block(contract_hash) pc = Handshake::ProcContract.new pc.signature = contract_hash pc end
[ "def", "Block", "(", "contract_hash", ")", "pc", "=", "Handshake", "::", "ProcContract", ".", "new", "pc", ".", "signature", "=", "contract_hash", "pc", "end" ]
Block signature definition. Returns a ProcContract with the given attributes
[ "Block", "signature", "definition", ".", "Returns", "a", "ProcContract", "with", "the", "given", "attributes" ]
5fd50a814be5c1df02854fb62d851584273ce813
https://github.com/bguthrie/handshake/blob/5fd50a814be5c1df02854fb62d851584273ce813/lib/handshake/block_contract.rb#L41-L45
train
takanamito/openapi2ruby
lib/openapi2ruby/openapi/schema.rb
Openapi2ruby.Openapi::Schema.properties
def properties return [] if @definition['properties'].nil? @definition['properties'].each_with_object([]) do |(key, value), results| content = { name: key, definition: value } results << Openapi2ruby::Openapi::Schema::Property.new(content) end end
ruby
def properties return [] if @definition['properties'].nil? @definition['properties'].each_with_object([]) do |(key, value), results| content = { name: key, definition: value } results << Openapi2ruby::Openapi::Schema::Property.new(content) end end
[ "def", "properties", "return", "[", "]", "if", "@definition", "[", "'properties'", "]", ".", "nil?", "@definition", "[", "'properties'", "]", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "(", "key", ",", "value", ")", ",", "results", "|", "content", "=", "{", "name", ":", "key", ",", "definition", ":", "value", "}", "results", "<<", "Openapi2ruby", "::", "Openapi", "::", "Schema", "::", "Property", ".", "new", "(", "content", ")", "end", "end" ]
OpenAPI schema properties @return [Array[Openapi2ruby::Openapi::Schema]]
[ "OpenAPI", "schema", "properties" ]
1c971a814248600bd302809a912a527328164dc5
https://github.com/takanamito/openapi2ruby/blob/1c971a814248600bd302809a912a527328164dc5/lib/openapi2ruby/openapi/schema.rb#L22-L28
train
gstark/tesla-api
lib/tesla-api/connection.rb
TeslaAPI.Connection.vehicles
def vehicles @vehicles ||= begin _, json = get_json("/vehicles") json.map { |data| Vehicle.new(self, data) } end end
ruby
def vehicles @vehicles ||= begin _, json = get_json("/vehicles") json.map { |data| Vehicle.new(self, data) } end end
[ "def", "vehicles", "@vehicles", "||=", "begin", "_", ",", "json", "=", "get_json", "(", "\"/vehicles\"", ")", "json", ".", "map", "{", "|", "data", "|", "Vehicle", ".", "new", "(", "self", ",", "data", ")", "}", "end", "end" ]
Returns Vehicle objects for all vehicles the account contains
[ "Returns", "Vehicle", "objects", "for", "all", "vehicles", "the", "account", "contains" ]
b094ec01232415c3b6a1777fa875e4e53fecb7b4
https://github.com/gstark/tesla-api/blob/b094ec01232415c3b6a1777fa875e4e53fecb7b4/lib/tesla-api/connection.rb#L40-L45
train
Digi-Cazter/omniship
lib/omniship/carrier.rb
Omniship.Carrier.valid_credentials?
def valid_credentials? location = self.class.default_location find_rates(location,location,Package.new(100, [5,15,30]), :test => test_mode) rescue Omniship::ResponseError false else true end
ruby
def valid_credentials? location = self.class.default_location find_rates(location,location,Package.new(100, [5,15,30]), :test => test_mode) rescue Omniship::ResponseError false else true end
[ "def", "valid_credentials?", "location", "=", "self", ".", "class", ".", "default_location", "find_rates", "(", "location", ",", "location", ",", "Package", ".", "new", "(", "100", ",", "[", "5", ",", "15", ",", "30", "]", ")", ",", ":test", "=>", "test_mode", ")", "rescue", "Omniship", "::", "ResponseError", "false", "else", "true", "end" ]
Validate credentials with a call to the API. By default this just does a find_rates call with the orgin and destination both as the carrier's default_location. Override to provide alternate functionality, such as checking for test_mode to use test servers, etc.
[ "Validate", "credentials", "with", "a", "call", "to", "the", "API", ".", "By", "default", "this", "just", "does", "a", "find_rates", "call", "with", "the", "orgin", "and", "destination", "both", "as", "the", "carrier", "s", "default_location", ".", "Override", "to", "provide", "alternate", "functionality", "such", "as", "checking", "for", "test_mode", "to", "use", "test", "servers", "etc", "." ]
a8c3ffca548fc2f00a06e4593d363439512ce6ae
https://github.com/Digi-Cazter/omniship/blob/a8c3ffca548fc2f00a06e4593d363439512ce6ae/lib/omniship/carrier.rb#L33-L40
train
pius/rdf-mongo
lib/rdf/mongo.rb
RDF.Statement.to_mongo
def to_mongo self.to_hash.inject({}) do |hash, (place_in_statement, entity)| hash.merge(RDF::Mongo::Conversion.to_mongo(entity, place_in_statement)) end end
ruby
def to_mongo self.to_hash.inject({}) do |hash, (place_in_statement, entity)| hash.merge(RDF::Mongo::Conversion.to_mongo(entity, place_in_statement)) end end
[ "def", "to_mongo", "self", ".", "to_hash", ".", "inject", "(", "{", "}", ")", "do", "|", "hash", ",", "(", "place_in_statement", ",", "entity", ")", "|", "hash", ".", "merge", "(", "RDF", "::", "Mongo", "::", "Conversion", ".", "to_mongo", "(", "entity", ",", "place_in_statement", ")", ")", "end", "end" ]
Creates a BSON representation of the statement. @return [Hash]
[ "Creates", "a", "BSON", "representation", "of", "the", "statement", "." ]
bd877be4e902496c8b5625d9d293d4b8cd1bc8cc
https://github.com/pius/rdf-mongo/blob/bd877be4e902496c8b5625d9d293d4b8cd1bc8cc/lib/rdf/mongo.rb#L10-L14
train
cryptape/ruby-rlp
lib/rlp/decode_lazy.rb
RLP.DecodeLazy.decode_lazy
def decode_lazy(rlp, sedes: nil, sedes_options: {}) item, next_start = consume_item_lazy(rlp, 0) raise DecodingError.new("RLP length prefix announced wrong length", rlp) if next_start != rlp.size if item.instance_of?(LazyList) item.sedes = sedes item.sedes_options = sedes_options item elsif sedes # FIXME: lazy man's kwargs sedes_options.empty? ? sedes.deserialize(item) : sedes.deserialize(item, **sedes_options) else item end end
ruby
def decode_lazy(rlp, sedes: nil, sedes_options: {}) item, next_start = consume_item_lazy(rlp, 0) raise DecodingError.new("RLP length prefix announced wrong length", rlp) if next_start != rlp.size if item.instance_of?(LazyList) item.sedes = sedes item.sedes_options = sedes_options item elsif sedes # FIXME: lazy man's kwargs sedes_options.empty? ? sedes.deserialize(item) : sedes.deserialize(item, **sedes_options) else item end end
[ "def", "decode_lazy", "(", "rlp", ",", "sedes", ":", "nil", ",", "sedes_options", ":", "{", "}", ")", "item", ",", "next_start", "=", "consume_item_lazy", "(", "rlp", ",", "0", ")", "raise", "DecodingError", ".", "new", "(", "\"RLP length prefix announced wrong length\"", ",", "rlp", ")", "if", "next_start", "!=", "rlp", ".", "size", "if", "item", ".", "instance_of?", "(", "LazyList", ")", "item", ".", "sedes", "=", "sedes", "item", ".", "sedes_options", "=", "sedes_options", "item", "elsif", "sedes", "sedes_options", ".", "empty?", "?", "sedes", ".", "deserialize", "(", "item", ")", ":", "sedes", ".", "deserialize", "(", "item", ",", "**", "sedes_options", ")", "else", "item", "end", "end" ]
Decode an RLP encoded object in a lazy fashion. If the encoded object is a byte string, this function acts similar to {RLP::Decode#decode}. If it is a list however, a {LazyList} is returned instead. This object will decode the string lazily, avoiding both horizontal and vertical traversing as much as possible. The way `sedes` is applied depends on the decoded object: If it is a string `sedes` deserializes it as a whole; if it is a list, each element is deserialized individually. In both cases, `sedes_options` are passed on. Note that, if a deserializer is used, only "horizontal" but not "vertical lazyness" can be preserved. @param rlp [String] the RLP string to decode @param sedes [Object] an object implementing a method `deserialize(code)` which is used as described above, or `nil` if no deserialization should be performed @param sedes_options [Hash] additional keyword arguments that will be passed to the deserializers @return [Object] either the already decoded and deserialized object (if encoded as a string) or an instance of {RLP::LazyList}
[ "Decode", "an", "RLP", "encoded", "object", "in", "a", "lazy", "fashion", "." ]
49c11eaee9f0f58d8028e5f1a291504c22dc947c
https://github.com/cryptape/ruby-rlp/blob/49c11eaee9f0f58d8028e5f1a291504c22dc947c/lib/rlp/decode_lazy.rb#L31-L48
train
cryptape/ruby-rlp
lib/rlp/decode_lazy.rb
RLP.DecodeLazy.consume_item_lazy
def consume_item_lazy(rlp, start) t, l, s = consume_length_prefix(rlp, start) if t == :str consume_payload(rlp, s, :str, l) elsif t == :list [LazyList.new(rlp, s, s+l), s+l] else raise "Invalid item type: #{t}" end end
ruby
def consume_item_lazy(rlp, start) t, l, s = consume_length_prefix(rlp, start) if t == :str consume_payload(rlp, s, :str, l) elsif t == :list [LazyList.new(rlp, s, s+l), s+l] else raise "Invalid item type: #{t}" end end
[ "def", "consume_item_lazy", "(", "rlp", ",", "start", ")", "t", ",", "l", ",", "s", "=", "consume_length_prefix", "(", "rlp", ",", "start", ")", "if", "t", "==", ":str", "consume_payload", "(", "rlp", ",", "s", ",", ":str", ",", "l", ")", "elsif", "t", "==", ":list", "[", "LazyList", ".", "new", "(", "rlp", ",", "s", ",", "s", "+", "l", ")", ",", "s", "+", "l", "]", "else", "raise", "\"Invalid item type: #{t}\"", "end", "end" ]
Read an item from an RLP string lazily. If the length prefix announces a string, the string is read; if it announces a list, a {LazyList} is created. @param rlp [String] the rlp string to read from @param start [Integer] the position at which to start reading @return [Array] A pair `[item, next_start]` where `item` is the read string or a {LazyList} and `next_start` is the position of the first unprocessed byte
[ "Read", "an", "item", "from", "an", "RLP", "string", "lazily", "." ]
49c11eaee9f0f58d8028e5f1a291504c22dc947c
https://github.com/cryptape/ruby-rlp/blob/49c11eaee9f0f58d8028e5f1a291504c22dc947c/lib/rlp/decode_lazy.rb#L63-L72
train
cryptape/ruby-rlp
lib/rlp/decode_lazy.rb
RLP.DecodeLazy.peek
def peek(rlp, index, sedes: nil) ll = decode_lazy(rlp) index = Array(index) index.each do |i| raise IndexError, "Too many indices given" if primitive?(ll) ll = ll.fetch(i) end sedes ? sedes.deserialize(ll) : ll end
ruby
def peek(rlp, index, sedes: nil) ll = decode_lazy(rlp) index = Array(index) index.each do |i| raise IndexError, "Too many indices given" if primitive?(ll) ll = ll.fetch(i) end sedes ? sedes.deserialize(ll) : ll end
[ "def", "peek", "(", "rlp", ",", "index", ",", "sedes", ":", "nil", ")", "ll", "=", "decode_lazy", "(", "rlp", ")", "index", "=", "Array", "(", "index", ")", "index", ".", "each", "do", "|", "i", "|", "raise", "IndexError", ",", "\"Too many indices given\"", "if", "primitive?", "(", "ll", ")", "ll", "=", "ll", ".", "fetch", "(", "i", ")", "end", "sedes", "?", "sedes", ".", "deserialize", "(", "ll", ")", ":", "ll", "end" ]
Get a specific element from an rlp encoded nested list. This method uses {RLP::DecodeLazy#decode_lazy} and, thus, decodes only the necessary parts of the string. @example Usage rlpdata = RLP.encode([1, 2, [3, [4, 5]]]) RLP.peek(rlpdata, 0, sedes: RLP::Sedes.big_endian_int) # => 1 RLP.peek(rlpdata, [2, 0], sedes: RLP::Sedes.big_endian_int) # => 3 @param rlp [String] the rlp string @param index [Integer, Array] the index of the element to peek at (can be a list for nested data) @param sedes [#deserialize] a sedes used to deserialize the peeked at object, or `nil` if no deserialization should be performed @raise [IndexError] if `index` is invalid (out of range or too many levels)
[ "Get", "a", "specific", "element", "from", "an", "rlp", "encoded", "nested", "list", "." ]
49c11eaee9f0f58d8028e5f1a291504c22dc947c
https://github.com/cryptape/ruby-rlp/blob/49c11eaee9f0f58d8028e5f1a291504c22dc947c/lib/rlp/decode_lazy.rb#L93-L103
train
bguthrie/handshake
lib/handshake.rb
Handshake.ClassMethods.contract_reader
def contract_reader(meth_to_clause) attr_reader(*(meth_to_clause.keys)) meth_to_clause.each do |meth, cls| contract meth, nil => cls end end
ruby
def contract_reader(meth_to_clause) attr_reader(*(meth_to_clause.keys)) meth_to_clause.each do |meth, cls| contract meth, nil => cls end end
[ "def", "contract_reader", "(", "meth_to_clause", ")", "attr_reader", "(", "*", "(", "meth_to_clause", ".", "keys", ")", ")", "meth_to_clause", ".", "each", "do", "|", "meth", ",", "cls", "|", "contract", "meth", ",", "nil", "=>", "cls", "end", "end" ]
Defines contract-checked attribute readers with the given hash of method name to clause.
[ "Defines", "contract", "-", "checked", "attribute", "readers", "with", "the", "given", "hash", "of", "method", "name", "to", "clause", "." ]
5fd50a814be5c1df02854fb62d851584273ce813
https://github.com/bguthrie/handshake/blob/5fd50a814be5c1df02854fb62d851584273ce813/lib/handshake.rb#L251-L256
train
bguthrie/handshake
lib/handshake.rb
Handshake.ClassMethods.contract_writer
def contract_writer(meth_to_clause) attr_writer(*(meth_to_clause.keys)) meth_to_clause.each do |meth, cls| contract "#{meth}=".to_sym, cls => anything end end
ruby
def contract_writer(meth_to_clause) attr_writer(*(meth_to_clause.keys)) meth_to_clause.each do |meth, cls| contract "#{meth}=".to_sym, cls => anything end end
[ "def", "contract_writer", "(", "meth_to_clause", ")", "attr_writer", "(", "*", "(", "meth_to_clause", ".", "keys", ")", ")", "meth_to_clause", ".", "each", "do", "|", "meth", ",", "cls", "|", "contract", "\"#{meth}=\"", ".", "to_sym", ",", "cls", "=>", "anything", "end", "end" ]
Defines contract-checked attribute writers with the given hash of method name to clause.
[ "Defines", "contract", "-", "checked", "attribute", "writers", "with", "the", "given", "hash", "of", "method", "name", "to", "clause", "." ]
5fd50a814be5c1df02854fb62d851584273ce813
https://github.com/bguthrie/handshake/blob/5fd50a814be5c1df02854fb62d851584273ce813/lib/handshake.rb#L260-L265
train
bguthrie/handshake
lib/handshake.rb
Handshake.ClassMethods.method_added
def method_added(meth_name) @deferred ||= {} unless @deferred.empty? @deferred.each do |k, v| case k when :before, :after, :around define_condition meth_name, k, v when :contract define_contract meth_name, v end end @deferred.clear end end
ruby
def method_added(meth_name) @deferred ||= {} unless @deferred.empty? @deferred.each do |k, v| case k when :before, :after, :around define_condition meth_name, k, v when :contract define_contract meth_name, v end end @deferred.clear end end
[ "def", "method_added", "(", "meth_name", ")", "@deferred", "||=", "{", "}", "unless", "@deferred", ".", "empty?", "@deferred", ".", "each", "do", "|", "k", ",", "v", "|", "case", "k", "when", ":before", ",", ":after", ",", ":around", "define_condition", "meth_name", ",", "k", ",", "v", "when", ":contract", "define_contract", "meth_name", ",", "v", "end", "end", "@deferred", ".", "clear", "end", "end" ]
Callback from method add event. If a previous method contract declaration was deferred, complete it now with the name of the newly- added method.
[ "Callback", "from", "method", "add", "event", ".", "If", "a", "previous", "method", "contract", "declaration", "was", "deferred", "complete", "it", "now", "with", "the", "name", "of", "the", "newly", "-", "added", "method", "." ]
5fd50a814be5c1df02854fb62d851584273ce813
https://github.com/bguthrie/handshake/blob/5fd50a814be5c1df02854fb62d851584273ce813/lib/handshake.rb#L277-L290
train
bguthrie/handshake
lib/handshake.rb
Handshake.MethodContract.accepts=
def accepts=(args) if args.last == Block # Transform into a ProcContract args.pop @block_contract = ProcContract.new @block_contract.accepts = ClauseMethods::ANYTHING @block_contract.returns = ClauseMethods::ANYTHING elsif args.last.is_a?(ProcContract) @block_contract = args.pop end if args.find_all {|o| o.is_a? Array}.length > 1 raise ContractError, "Cannot define more than one expected variable argument" end super(args) end
ruby
def accepts=(args) if args.last == Block # Transform into a ProcContract args.pop @block_contract = ProcContract.new @block_contract.accepts = ClauseMethods::ANYTHING @block_contract.returns = ClauseMethods::ANYTHING elsif args.last.is_a?(ProcContract) @block_contract = args.pop end if args.find_all {|o| o.is_a? Array}.length > 1 raise ContractError, "Cannot define more than one expected variable argument" end super(args) end
[ "def", "accepts", "=", "(", "args", ")", "if", "args", ".", "last", "==", "Block", "args", ".", "pop", "@block_contract", "=", "ProcContract", ".", "new", "@block_contract", ".", "accepts", "=", "ClauseMethods", "::", "ANYTHING", "@block_contract", ".", "returns", "=", "ClauseMethods", "::", "ANYTHING", "elsif", "args", ".", "last", ".", "is_a?", "(", "ProcContract", ")", "@block_contract", "=", "args", ".", "pop", "end", "if", "args", ".", "find_all", "{", "|", "o", "|", "o", ".", "is_a?", "Array", "}", ".", "length", ">", "1", "raise", "ContractError", ",", "\"Cannot define more than one expected variable argument\"", "end", "super", "(", "args", ")", "end" ]
If the last argument is a Block, handle it as a special case. We do this to ensure that there's no conflict with any real arguments which may accept Procs.
[ "If", "the", "last", "argument", "is", "a", "Block", "handle", "it", "as", "a", "special", "case", ".", "We", "do", "this", "to", "ensure", "that", "there", "s", "no", "conflict", "with", "any", "real", "arguments", "which", "may", "accept", "Procs", "." ]
5fd50a814be5c1df02854fb62d851584273ce813
https://github.com/bguthrie/handshake/blob/5fd50a814be5c1df02854fb62d851584273ce813/lib/handshake.rb#L447-L461
train
github/rack-statsd
lib/rack-statsd.rb
RackStatsD.RequestStatus.call
def call(env) if env[REQUEST_METHOD] == GET if env[PATH_INFO] == @status_path if @callback.respond_to?(:call) return @callback.call else return [200, HEADERS, [@callback.to_s]] end end end @app.call env end
ruby
def call(env) if env[REQUEST_METHOD] == GET if env[PATH_INFO] == @status_path if @callback.respond_to?(:call) return @callback.call else return [200, HEADERS, [@callback.to_s]] end end end @app.call env end
[ "def", "call", "(", "env", ")", "if", "env", "[", "REQUEST_METHOD", "]", "==", "GET", "if", "env", "[", "PATH_INFO", "]", "==", "@status_path", "if", "@callback", ".", "respond_to?", "(", ":call", ")", "return", "@callback", ".", "call", "else", "return", "[", "200", ",", "HEADERS", ",", "[", "@callback", ".", "to_s", "]", "]", "end", "end", "end", "@app", ".", "call", "env", "end" ]
Initializes the middleware. # Responds with "OK" on /status use RequestStatus, "OK" You can change what URL to look for: use RequestStatus, "OK", "/ping" You can also check internal systems and return something more informative. use RequestStatus, lambda { status = MyApp.status # A Hash of some live counters or something [200, {"Content-Type" => "application/json"}, status.to_json] } app - The next Rack app in the pipeline. callback_or_response - Either a Proc or a Rack response. status_path - Optional String path that returns the status. Default: "/status" Returns nothing.
[ "Initializes", "the", "middleware", "." ]
f03b18ef5c27df861384930c206d797be540e956
https://github.com/github/rack-statsd/blob/f03b18ef5c27df861384930c206d797be540e956/lib/rack-statsd.rb#L40-L52
train
github/rack-statsd
lib/rack-statsd.rb
RackStatsD.RequestHostname.call
def call(env) status, headers, body = @app.call(env) headers['X-Node'] = @host if @host headers['X-Revision'] = @sha [status, headers, body] end
ruby
def call(env) status, headers, body = @app.call(env) headers['X-Node'] = @host if @host headers['X-Revision'] = @sha [status, headers, body] end
[ "def", "call", "(", "env", ")", "status", ",", "headers", ",", "body", "=", "@app", ".", "call", "(", "env", ")", "headers", "[", "'X-Node'", "]", "=", "@host", "if", "@host", "headers", "[", "'X-Revision'", "]", "=", "@sha", "[", "status", ",", "headers", ",", "body", "]", "end" ]
Initializes the middlware. app - The next Rack app in the pipeline. options - Hash of options. :host - String hostname. :revision - String SHA that describes the version of code this process is running. Returns nothing.
[ "Initializes", "the", "middlware", "." ]
f03b18ef5c27df861384930c206d797be540e956
https://github.com/github/rack-statsd/blob/f03b18ef5c27df861384930c206d797be540e956/lib/rack-statsd.rb#L74-L79
train
github/rack-statsd
lib/rack-statsd.rb
RackStatsD.ProcessUtilization.procline
def procline "unicorn %s[%s] worker[%02d]: %5d reqs, %4.1f req/s, %4dms avg, %5.1f%% util" % [ domain, revision, worker_number.to_i, total_requests.to_i, requests_per_second.to_f, average_response_time.to_i, percentage_active.to_f ] end
ruby
def procline "unicorn %s[%s] worker[%02d]: %5d reqs, %4.1f req/s, %4dms avg, %5.1f%% util" % [ domain, revision, worker_number.to_i, total_requests.to_i, requests_per_second.to_f, average_response_time.to_i, percentage_active.to_f ] end
[ "def", "procline", "\"unicorn %s[%s] worker[%02d]: %5d reqs, %4.1f req/s, %4dms avg, %5.1f%% util\"", "%", "[", "domain", ",", "revision", ",", "worker_number", ".", "to_i", ",", "total_requests", ".", "to_i", ",", "requests_per_second", ".", "to_f", ",", "average_response_time", ".", "to_i", ",", "percentage_active", ".", "to_f", "]", "end" ]
the generated procline
[ "the", "generated", "procline" ]
f03b18ef5c27df861384930c206d797be540e956
https://github.com/github/rack-statsd/blob/f03b18ef5c27df861384930c206d797be540e956/lib/rack-statsd.rb#L206-L216
train
github/rack-statsd
lib/rack-statsd.rb
RackStatsD.ProcessUtilization.record_request
def record_request(status, env) now = Time.now diff = (now - @start) @active_time += diff @requests += 1 $0 = procline if @stats @stats.timing("#{@stats_prefix}.response_time", diff * 1000) if VALID_METHODS.include?(env[REQUEST_METHOD]) stat = "#{@stats_prefix}.response_time.#{env[REQUEST_METHOD].downcase}" @stats.timing(stat, diff * 1000) end if suffix = status_suffix(status) @stats.increment "#{@stats_prefix}.status_code.#{status_suffix(status)}" end if @track_gc && GC.time > 0 @stats.timing "#{@stats_prefix}.gc.time", GC.time / 1000 @stats.count "#{@stats_prefix}.gc.collections", GC.collections end end reset_horizon if now - horizon > @window rescue => boom warn "ProcessUtilization#record_request failed: #{boom}" end
ruby
def record_request(status, env) now = Time.now diff = (now - @start) @active_time += diff @requests += 1 $0 = procline if @stats @stats.timing("#{@stats_prefix}.response_time", diff * 1000) if VALID_METHODS.include?(env[REQUEST_METHOD]) stat = "#{@stats_prefix}.response_time.#{env[REQUEST_METHOD].downcase}" @stats.timing(stat, diff * 1000) end if suffix = status_suffix(status) @stats.increment "#{@stats_prefix}.status_code.#{status_suffix(status)}" end if @track_gc && GC.time > 0 @stats.timing "#{@stats_prefix}.gc.time", GC.time / 1000 @stats.count "#{@stats_prefix}.gc.collections", GC.collections end end reset_horizon if now - horizon > @window rescue => boom warn "ProcessUtilization#record_request failed: #{boom}" end
[ "def", "record_request", "(", "status", ",", "env", ")", "now", "=", "Time", ".", "now", "diff", "=", "(", "now", "-", "@start", ")", "@active_time", "+=", "diff", "@requests", "+=", "1", "$0", "=", "procline", "if", "@stats", "@stats", ".", "timing", "(", "\"#{@stats_prefix}.response_time\"", ",", "diff", "*", "1000", ")", "if", "VALID_METHODS", ".", "include?", "(", "env", "[", "REQUEST_METHOD", "]", ")", "stat", "=", "\"#{@stats_prefix}.response_time.#{env[REQUEST_METHOD].downcase}\"", "@stats", ".", "timing", "(", "stat", ",", "diff", "*", "1000", ")", "end", "if", "suffix", "=", "status_suffix", "(", "status", ")", "@stats", ".", "increment", "\"#{@stats_prefix}.status_code.#{status_suffix(status)}\"", "end", "if", "@track_gc", "&&", "GC", ".", "time", ">", "0", "@stats", ".", "timing", "\"#{@stats_prefix}.gc.time\"", ",", "GC", ".", "time", "/", "1000", "@stats", ".", "count", "\"#{@stats_prefix}.gc.collections\"", ",", "GC", ".", "collections", "end", "end", "reset_horizon", "if", "now", "-", "horizon", ">", "@window", "rescue", "=>", "boom", "warn", "\"ProcessUtilization#record_request failed: #{boom}\"", "end" ]
called immediately after a request to record statistics, update the procline, and dump information to the logfile
[ "called", "immediately", "after", "a", "request", "to", "record", "statistics", "update", "the", "procline", "and", "dump", "information", "to", "the", "logfile" ]
f03b18ef5c27df861384930c206d797be540e956
https://github.com/github/rack-statsd/blob/f03b18ef5c27df861384930c206d797be540e956/lib/rack-statsd.rb#L220-L247
train
github/rack-statsd
lib/rack-statsd.rb
RackStatsD.ProcessUtilization.call
def call(env) @start = Time.now GC.clear_stats if @track_gc @total_requests += 1 first_request if @total_requests == 1 env['process.request_start'] = @start.to_f env['process.total_requests'] = total_requests # newrelic X-Request-Start env.delete('HTTP_X_REQUEST_START') status, headers, body = @app.call(env) body = Body.new(body) { record_request(status, env) } [status, headers, body] end
ruby
def call(env) @start = Time.now GC.clear_stats if @track_gc @total_requests += 1 first_request if @total_requests == 1 env['process.request_start'] = @start.to_f env['process.total_requests'] = total_requests # newrelic X-Request-Start env.delete('HTTP_X_REQUEST_START') status, headers, body = @app.call(env) body = Body.new(body) { record_request(status, env) } [status, headers, body] end
[ "def", "call", "(", "env", ")", "@start", "=", "Time", ".", "now", "GC", ".", "clear_stats", "if", "@track_gc", "@total_requests", "+=", "1", "first_request", "if", "@total_requests", "==", "1", "env", "[", "'process.request_start'", "]", "=", "@start", ".", "to_f", "env", "[", "'process.total_requests'", "]", "=", "total_requests", "env", ".", "delete", "(", "'HTTP_X_REQUEST_START'", ")", "status", ",", "headers", ",", "body", "=", "@app", ".", "call", "(", "env", ")", "body", "=", "Body", ".", "new", "(", "body", ")", "{", "record_request", "(", "status", ",", "env", ")", "}", "[", "status", ",", "headers", ",", "body", "]", "end" ]
Rack entry point.
[ "Rack", "entry", "point", "." ]
f03b18ef5c27df861384930c206d797be540e956
https://github.com/github/rack-statsd/blob/f03b18ef5c27df861384930c206d797be540e956/lib/rack-statsd.rb#L298-L314
train
theforeman/hammer-cli-foreman-tasks
lib/hammer_cli_foreman_tasks/helper.rb
HammerCLIForemanTasks.Helper.task_progress
def task_progress(task_or_id) task_id = task_or_id.is_a?(Hash) ? task_or_id['id'] : task_or_id if !task_id.empty? options = { verbosity: @context[:verbosity] || HammerCLI::V_VERBOSE } task_progress = TaskProgress.new(task_id, options) { |id| load_task(id) } task_progress.render task_progress.success? else signal_usage_error(_('Please mention appropriate attribute value')) end end
ruby
def task_progress(task_or_id) task_id = task_or_id.is_a?(Hash) ? task_or_id['id'] : task_or_id if !task_id.empty? options = { verbosity: @context[:verbosity] || HammerCLI::V_VERBOSE } task_progress = TaskProgress.new(task_id, options) { |id| load_task(id) } task_progress.render task_progress.success? else signal_usage_error(_('Please mention appropriate attribute value')) end end
[ "def", "task_progress", "(", "task_or_id", ")", "task_id", "=", "task_or_id", ".", "is_a?", "(", "Hash", ")", "?", "task_or_id", "[", "'id'", "]", ":", "task_or_id", "if", "!", "task_id", ".", "empty?", "options", "=", "{", "verbosity", ":", "@context", "[", ":verbosity", "]", "||", "HammerCLI", "::", "V_VERBOSE", "}", "task_progress", "=", "TaskProgress", ".", "new", "(", "task_id", ",", "options", ")", "{", "|", "id", "|", "load_task", "(", "id", ")", "}", "task_progress", ".", "render", "task_progress", ".", "success?", "else", "signal_usage_error", "(", "_", "(", "'Please mention appropriate attribute value'", ")", ")", "end", "end" ]
render the progress of the task using polling to the task API
[ "render", "the", "progress", "of", "the", "task", "using", "polling", "to", "the", "task", "API" ]
1b928158014fc51142aaf434fd32c37d893d0966
https://github.com/theforeman/hammer-cli-foreman-tasks/blob/1b928158014fc51142aaf434fd32c37d893d0966/lib/hammer_cli_foreman_tasks/helper.rb#L4-L14
train
cryptape/ruby-rlp
lib/rlp/decode.rb
RLP.Decode.decode
def decode(rlp, **options) rlp = str_to_bytes(rlp) sedes = options.delete(:sedes) strict = options.has_key?(:strict) ? options.delete(:strict) : true begin item, next_start = consume_item(rlp, 0) rescue Exception => e raise DecodingError.new("Cannot decode rlp string: #{e}", rlp) end raise DecodingError.new("RLP string ends with #{rlp.size - next_start} superfluous bytes", rlp) if next_start != rlp.size && strict if sedes obj = sedes.instance_of?(Class) && sedes.include?(Sedes::Serializable) ? sedes.deserialize(item, **options) : sedes.deserialize(item) if obj.respond_to?(:_cached_rlp) obj._cached_rlp = rlp raise "RLP::Sedes::Serializable object must be immutable after decode" if obj.is_a?(Sedes::Serializable) && obj.mutable? end obj else item end end
ruby
def decode(rlp, **options) rlp = str_to_bytes(rlp) sedes = options.delete(:sedes) strict = options.has_key?(:strict) ? options.delete(:strict) : true begin item, next_start = consume_item(rlp, 0) rescue Exception => e raise DecodingError.new("Cannot decode rlp string: #{e}", rlp) end raise DecodingError.new("RLP string ends with #{rlp.size - next_start} superfluous bytes", rlp) if next_start != rlp.size && strict if sedes obj = sedes.instance_of?(Class) && sedes.include?(Sedes::Serializable) ? sedes.deserialize(item, **options) : sedes.deserialize(item) if obj.respond_to?(:_cached_rlp) obj._cached_rlp = rlp raise "RLP::Sedes::Serializable object must be immutable after decode" if obj.is_a?(Sedes::Serializable) && obj.mutable? end obj else item end end
[ "def", "decode", "(", "rlp", ",", "**", "options", ")", "rlp", "=", "str_to_bytes", "(", "rlp", ")", "sedes", "=", "options", ".", "delete", "(", ":sedes", ")", "strict", "=", "options", ".", "has_key?", "(", ":strict", ")", "?", "options", ".", "delete", "(", ":strict", ")", ":", "true", "begin", "item", ",", "next_start", "=", "consume_item", "(", "rlp", ",", "0", ")", "rescue", "Exception", "=>", "e", "raise", "DecodingError", ".", "new", "(", "\"Cannot decode rlp string: #{e}\"", ",", "rlp", ")", "end", "raise", "DecodingError", ".", "new", "(", "\"RLP string ends with #{rlp.size - next_start} superfluous bytes\"", ",", "rlp", ")", "if", "next_start", "!=", "rlp", ".", "size", "&&", "strict", "if", "sedes", "obj", "=", "sedes", ".", "instance_of?", "(", "Class", ")", "&&", "sedes", ".", "include?", "(", "Sedes", "::", "Serializable", ")", "?", "sedes", ".", "deserialize", "(", "item", ",", "**", "options", ")", ":", "sedes", ".", "deserialize", "(", "item", ")", "if", "obj", ".", "respond_to?", "(", ":_cached_rlp", ")", "obj", ".", "_cached_rlp", "=", "rlp", "raise", "\"RLP::Sedes::Serializable object must be immutable after decode\"", "if", "obj", ".", "is_a?", "(", "Sedes", "::", "Serializable", ")", "&&", "obj", ".", "mutable?", "end", "obj", "else", "item", "end", "end" ]
Decode an RLP encoded object. If the deserialized result `obj` has an attribute `_cached_rlp` (e.g. if `sedes` is a subclass of {RLP::Sedes::Serializable}), it will be set to `rlp`, which will improve performance on subsequent {RLP::Encode#encode} calls. Bear in mind however that `obj` needs to make sure that this value is updated whenever one of its fields changes or prevent such changes entirely ({RLP::Sedes::Serializable} does the latter). @param options (Hash) deserialization options: * sedes (Object) an object implementing a function `deserialize(code)` which will be applied after decoding, or `nil` if no deserialization should be performed * strict (Boolean) if false inputs that are longer than necessary don't cause an exception * (any options left) (Hash) additional keyword arguments passed to the deserializer @return [Object] the decoded and maybe deserialized object @raise [RLP::Error::DecodingError] if the input string does not end after the root item and `strict` is true @raise [RLP::Error::DeserializationError] if the deserialization fails
[ "Decode", "an", "RLP", "encoded", "object", "." ]
49c11eaee9f0f58d8028e5f1a291504c22dc947c
https://github.com/cryptape/ruby-rlp/blob/49c11eaee9f0f58d8028e5f1a291504c22dc947c/lib/rlp/decode.rb#L35-L62
train
cryptape/ruby-rlp
lib/rlp/decode.rb
RLP.Decode.consume_item
def consume_item(rlp, start) t, l, s = consume_length_prefix(rlp, start) consume_payload(rlp, s, t, l) end
ruby
def consume_item(rlp, start) t, l, s = consume_length_prefix(rlp, start) consume_payload(rlp, s, t, l) end
[ "def", "consume_item", "(", "rlp", ",", "start", ")", "t", ",", "l", ",", "s", "=", "consume_length_prefix", "(", "rlp", ",", "start", ")", "consume_payload", "(", "rlp", ",", "s", ",", "t", ",", "l", ")", "end" ]
Read an item from an RLP string. * `rlp` - the string to read from * `start` - the position at which to start reading` Returns a pair `[item, end]` where `item` is the read item and `end` is the position of the first unprocessed byte.
[ "Read", "an", "item", "from", "an", "RLP", "string", "." ]
49c11eaee9f0f58d8028e5f1a291504c22dc947c
https://github.com/cryptape/ruby-rlp/blob/49c11eaee9f0f58d8028e5f1a291504c22dc947c/lib/rlp/decode.rb#L159-L162
train
cryptape/ruby-rlp
lib/rlp/decode.rb
RLP.Decode.consume_payload
def consume_payload(rlp, start, type, length) case type when :str [rlp[start...(start+length)], start+length] when :list items = [] next_item_start = start payload_end = next_item_start + length while next_item_start < payload_end item, next_item_start = consume_item rlp, next_item_start items.push item end raise DecodingError.new('List length prefix announced a too small length', rlp) if next_item_start > payload_end [items, next_item_start] else raise TypeError, 'Type must be either :str or :list' end end
ruby
def consume_payload(rlp, start, type, length) case type when :str [rlp[start...(start+length)], start+length] when :list items = [] next_item_start = start payload_end = next_item_start + length while next_item_start < payload_end item, next_item_start = consume_item rlp, next_item_start items.push item end raise DecodingError.new('List length prefix announced a too small length', rlp) if next_item_start > payload_end [items, next_item_start] else raise TypeError, 'Type must be either :str or :list' end end
[ "def", "consume_payload", "(", "rlp", ",", "start", ",", "type", ",", "length", ")", "case", "type", "when", ":str", "[", "rlp", "[", "start", "...", "(", "start", "+", "length", ")", "]", ",", "start", "+", "length", "]", "when", ":list", "items", "=", "[", "]", "next_item_start", "=", "start", "payload_end", "=", "next_item_start", "+", "length", "while", "next_item_start", "<", "payload_end", "item", ",", "next_item_start", "=", "consume_item", "rlp", ",", "next_item_start", "items", ".", "push", "item", "end", "raise", "DecodingError", ".", "new", "(", "'List length prefix announced a too small length'", ",", "rlp", ")", "if", "next_item_start", ">", "payload_end", "[", "items", ",", "next_item_start", "]", "else", "raise", "TypeError", ",", "'Type must be either :str or :list'", "end", "end" ]
Read the payload of an item from an RLP string. * `rlp` - the rlp string to read from * `type` - the type of the payload (`:str` or `:list`) * `start` - the position at which to start reading * `length` - the length of the payload in bytes Returns a pair `[item, end]`, where `item` is the read item and `end` is the position of the first unprocessed byte.
[ "Read", "the", "payload", "of", "an", "item", "from", "an", "RLP", "string", "." ]
49c11eaee9f0f58d8028e5f1a291504c22dc947c
https://github.com/cryptape/ruby-rlp/blob/49c11eaee9f0f58d8028e5f1a291504c22dc947c/lib/rlp/decode.rb#L216-L236
train
codequest-eu/codequest_pipes
lib/codequest_pipes/context.rb
Pipes.Context.add
def add(values) values.each do |key, val| k_sym = key.to_sym fail Override, "Property :#{key} already present" if respond_to?(k_sym) define_singleton_method(k_sym) { val } end end
ruby
def add(values) values.each do |key, val| k_sym = key.to_sym fail Override, "Property :#{key} already present" if respond_to?(k_sym) define_singleton_method(k_sym) { val } end end
[ "def", "add", "(", "values", ")", "values", ".", "each", "do", "|", "key", ",", "val", "|", "k_sym", "=", "key", ".", "to_sym", "fail", "Override", ",", "\"Property :#{key} already present\"", "if", "respond_to?", "(", "k_sym", ")", "define_singleton_method", "(", "k_sym", ")", "{", "val", "}", "end", "end" ]
Context constructor. @param values [Hash] Method `add` allows adding new properties (as a Hash) to the Context. @param values [Hash]
[ "Context", "constructor", "." ]
3da315a1d789b8ccca16261d5c68506671df2c80
https://github.com/codequest-eu/codequest_pipes/blob/3da315a1d789b8ccca16261d5c68506671df2c80/lib/codequest_pipes/context.rb#L27-L33
train
adhearsion/ruby_fs
lib/ruby_fs/stream.rb
RubyFS.Stream.run
def run logger.debug "Starting up..." @socket = TCPSocket.from_ruby_socket ::TCPSocket.new(@host, @port) post_init loop { receive_data @socket.readpartial(4096) } rescue EOFError, IOError, Errno::ECONNREFUSED => e logger.info "Client socket closed due to (#{e.class}) #{e.message}!" async.terminate end
ruby
def run logger.debug "Starting up..." @socket = TCPSocket.from_ruby_socket ::TCPSocket.new(@host, @port) post_init loop { receive_data @socket.readpartial(4096) } rescue EOFError, IOError, Errno::ECONNREFUSED => e logger.info "Client socket closed due to (#{e.class}) #{e.message}!" async.terminate end
[ "def", "run", "logger", ".", "debug", "\"Starting up...\"", "@socket", "=", "TCPSocket", ".", "from_ruby_socket", "::", "TCPSocket", ".", "new", "(", "@host", ",", "@port", ")", "post_init", "loop", "{", "receive_data", "@socket", ".", "readpartial", "(", "4096", ")", "}", "rescue", "EOFError", ",", "IOError", ",", "Errno", "::", "ECONNREFUSED", "=>", "e", "logger", ".", "info", "\"Client socket closed due to (#{e.class}) #{e.message}!\"", "async", ".", "terminate", "end" ]
Connect to the server and begin handling data
[ "Connect", "to", "the", "server", "and", "begin", "handling", "data" ]
8a282ec6e2c2ada3d472976fcc6c3ec48b98d358
https://github.com/adhearsion/ruby_fs/blob/8a282ec6e2c2ada3d472976fcc6c3ec48b98d358/lib/ruby_fs/stream.rb#L37-L45
train
adhearsion/ruby_fs
lib/ruby_fs/stream.rb
RubyFS.Stream.command
def command(command, options = {}, &callback) uuid = SecureRandom.uuid @command_callbacks << (callback || lambda { |reply| signal uuid, reply }) string = "#{command}\n" body_value = options.delete :command_body_value options.each_pair do |key, value| string << "#{key.to_s.gsub '_', '-'}: #{value}\n" if value end string << "\n" << body_value << "\n" if body_value string << "\n" send_data string wait uuid unless callback end
ruby
def command(command, options = {}, &callback) uuid = SecureRandom.uuid @command_callbacks << (callback || lambda { |reply| signal uuid, reply }) string = "#{command}\n" body_value = options.delete :command_body_value options.each_pair do |key, value| string << "#{key.to_s.gsub '_', '-'}: #{value}\n" if value end string << "\n" << body_value << "\n" if body_value string << "\n" send_data string wait uuid unless callback end
[ "def", "command", "(", "command", ",", "options", "=", "{", "}", ",", "&", "callback", ")", "uuid", "=", "SecureRandom", ".", "uuid", "@command_callbacks", "<<", "(", "callback", "||", "lambda", "{", "|", "reply", "|", "signal", "uuid", ",", "reply", "}", ")", "string", "=", "\"#{command}\\n\"", "body_value", "=", "options", ".", "delete", ":command_body_value", "options", ".", "each_pair", "do", "|", "key", ",", "value", "|", "string", "<<", "\"#{key.to_s.gsub '_', '-'}: #{value}\\n\"", "if", "value", "end", "string", "<<", "\"\\n\"", "<<", "body_value", "<<", "\"\\n\"", "if", "body_value", "string", "<<", "\"\\n\"", "send_data", "string", "wait", "uuid", "unless", "callback", "end" ]
Send a FreeSWITCH command with options and a callback for the response @param [#to_s] command the command to run @param [optional, Hash] options the command's options, where keys have _ substituted for - @return [RubyFS::Response] response the command's response object
[ "Send", "a", "FreeSWITCH", "command", "with", "options", "and", "a", "callback", "for", "the", "response" ]
8a282ec6e2c2ada3d472976fcc6c3ec48b98d358
https://github.com/adhearsion/ruby_fs/blob/8a282ec6e2c2ada3d472976fcc6c3ec48b98d358/lib/ruby_fs/stream.rb#L63-L75
train
adhearsion/ruby_fs
lib/ruby_fs/stream.rb
RubyFS.Stream.application
def application(call, appname, options = nil) opts = {call_command: 'execute', execute_app_name: appname} if options opts[:content_type] = 'text/plain' opts[:content_length] = options.bytesize opts[:command_body_value] = options end sendmsg call, opts end
ruby
def application(call, appname, options = nil) opts = {call_command: 'execute', execute_app_name: appname} if options opts[:content_type] = 'text/plain' opts[:content_length] = options.bytesize opts[:command_body_value] = options end sendmsg call, opts end
[ "def", "application", "(", "call", ",", "appname", ",", "options", "=", "nil", ")", "opts", "=", "{", "call_command", ":", "'execute'", ",", "execute_app_name", ":", "appname", "}", "if", "options", "opts", "[", ":content_type", "]", "=", "'text/plain'", "opts", "[", ":content_length", "]", "=", "options", ".", "bytesize", "opts", "[", ":command_body_value", "]", "=", "options", "end", "sendmsg", "call", ",", "opts", "end" ]
Execute an application on a particular call @param [#to_s] call the call ID on which to execute the application @param [#to_s] appname the app to execute @param [optional, String] options the application options @return [RubyFS::Response] response the application's response object
[ "Execute", "an", "application", "on", "a", "particular", "call" ]
8a282ec6e2c2ada3d472976fcc6c3ec48b98d358
https://github.com/adhearsion/ruby_fs/blob/8a282ec6e2c2ada3d472976fcc6c3ec48b98d358/lib/ruby_fs/stream.rb#L116-L124
train
epfl-exts/rails-gdpr-export
lib/gdpr_exporter.rb
GdprExporter.ClassMethods.gdpr_collect
def gdpr_collect(*args) # Params handling if args.class == Hash # when user provides the hash_params only simple_fields, hash_params = [[], args] else simple_fields, hash_params = [args[0..-2], args.last] end unless hash_params.class == Hash raise ArgumentError.new("Gdpr fields collection error: last argument must be a hash!") end unless hash_params.key?(:user_id) raise ArgumentError.new("Gdpr fields collection error: the field aliasing user_id is not declared for '#{self}'!") end # Adds the eigen class to the set of classes eligible for gdpr data collection. GdprExporter.add_klass(self) # Adds instance fields to the eigenclass. They store # all the fields and info we are interested in. @gdpr_simple_fields = simple_fields @gdpr_hash_params = hash_params # Add readers for the instance vars declared above (for testing reasons) self.class.send :attr_reader, :gdpr_simple_fields self.class.send :attr_reader, :gdpr_hash_params # Build the csv header and prepare the fields used for querying # user_id_field = hash_params[:user_id] # csv_headers = [:user_id].concat @gdpr_simple_fields # Uncomment if user_id needed # query_fields = [user_id_field].concat @gdpr_simple_fields # Uncomment if user_id needed csv_headers = [].concat @gdpr_simple_fields query_fields = [].concat @gdpr_simple_fields if hash_params[:renamed_fields] csv_headers.concat hash_params[:renamed_fields].values query_fields.concat hash_params[:renamed_fields].keys end # Adds the class method 'gdpr_query' to the eigenclass. # It will execute the query. self.define_singleton_method(:gdpr_query) do |_user_id| result = self.where(user_id_field => _user_id) # When there are multiple joins defined, just keep calling 'joins' # for each association. if hash_params[:joins] result = hash_params[:joins].inject(result) do | query, assoc | query.send(:joins, assoc) end end result end # Adds a method to export to csv to the eigenclass. self.define_singleton_method(:gdpr_export) do |rows, csv| return unless !rows.empty? csv << (hash_params[:table_name] ? [hash_params[:table_name]] : [self.to_s]) if hash_params[:desc] csv << ['Description:', hash_params[:desc]] end csv << csv_headers rows.each do |r| csv << query_fields.map do |f| f_splitted = f.to_s.split(' ') if (f_splitted.size == 2) # field f is coming from an assoc, i.e. field has been defined # as "<tablename> <field>" in gdpr_collect then to get its value # do r.<tablename>.<field> f_splitted.inject(r) { |result, method| result.send(method) } elsif (f_splitted.size > 2) raise ArgumentError.new("Field #{f} is made of more than 2 words!?") else # No association involved, simply retrieve the field value. r.send(f) end end end csv << [] end end
ruby
def gdpr_collect(*args) # Params handling if args.class == Hash # when user provides the hash_params only simple_fields, hash_params = [[], args] else simple_fields, hash_params = [args[0..-2], args.last] end unless hash_params.class == Hash raise ArgumentError.new("Gdpr fields collection error: last argument must be a hash!") end unless hash_params.key?(:user_id) raise ArgumentError.new("Gdpr fields collection error: the field aliasing user_id is not declared for '#{self}'!") end # Adds the eigen class to the set of classes eligible for gdpr data collection. GdprExporter.add_klass(self) # Adds instance fields to the eigenclass. They store # all the fields and info we are interested in. @gdpr_simple_fields = simple_fields @gdpr_hash_params = hash_params # Add readers for the instance vars declared above (for testing reasons) self.class.send :attr_reader, :gdpr_simple_fields self.class.send :attr_reader, :gdpr_hash_params # Build the csv header and prepare the fields used for querying # user_id_field = hash_params[:user_id] # csv_headers = [:user_id].concat @gdpr_simple_fields # Uncomment if user_id needed # query_fields = [user_id_field].concat @gdpr_simple_fields # Uncomment if user_id needed csv_headers = [].concat @gdpr_simple_fields query_fields = [].concat @gdpr_simple_fields if hash_params[:renamed_fields] csv_headers.concat hash_params[:renamed_fields].values query_fields.concat hash_params[:renamed_fields].keys end # Adds the class method 'gdpr_query' to the eigenclass. # It will execute the query. self.define_singleton_method(:gdpr_query) do |_user_id| result = self.where(user_id_field => _user_id) # When there are multiple joins defined, just keep calling 'joins' # for each association. if hash_params[:joins] result = hash_params[:joins].inject(result) do | query, assoc | query.send(:joins, assoc) end end result end # Adds a method to export to csv to the eigenclass. self.define_singleton_method(:gdpr_export) do |rows, csv| return unless !rows.empty? csv << (hash_params[:table_name] ? [hash_params[:table_name]] : [self.to_s]) if hash_params[:desc] csv << ['Description:', hash_params[:desc]] end csv << csv_headers rows.each do |r| csv << query_fields.map do |f| f_splitted = f.to_s.split(' ') if (f_splitted.size == 2) # field f is coming from an assoc, i.e. field has been defined # as "<tablename> <field>" in gdpr_collect then to get its value # do r.<tablename>.<field> f_splitted.inject(r) { |result, method| result.send(method) } elsif (f_splitted.size > 2) raise ArgumentError.new("Field #{f} is made of more than 2 words!?") else # No association involved, simply retrieve the field value. r.send(f) end end end csv << [] end end
[ "def", "gdpr_collect", "(", "*", "args", ")", "if", "args", ".", "class", "==", "Hash", "simple_fields", ",", "hash_params", "=", "[", "[", "]", ",", "args", "]", "else", "simple_fields", ",", "hash_params", "=", "[", "args", "[", "0", "..", "-", "2", "]", ",", "args", ".", "last", "]", "end", "unless", "hash_params", ".", "class", "==", "Hash", "raise", "ArgumentError", ".", "new", "(", "\"Gdpr fields collection error: last argument must be a hash!\"", ")", "end", "unless", "hash_params", ".", "key?", "(", ":user_id", ")", "raise", "ArgumentError", ".", "new", "(", "\"Gdpr fields collection error: the field aliasing user_id is not declared for '#{self}'!\"", ")", "end", "GdprExporter", ".", "add_klass", "(", "self", ")", "@gdpr_simple_fields", "=", "simple_fields", "@gdpr_hash_params", "=", "hash_params", "self", ".", "class", ".", "send", ":attr_reader", ",", ":gdpr_simple_fields", "self", ".", "class", ".", "send", ":attr_reader", ",", ":gdpr_hash_params", "user_id_field", "=", "hash_params", "[", ":user_id", "]", "csv_headers", "=", "[", "]", ".", "concat", "@gdpr_simple_fields", "query_fields", "=", "[", "]", ".", "concat", "@gdpr_simple_fields", "if", "hash_params", "[", ":renamed_fields", "]", "csv_headers", ".", "concat", "hash_params", "[", ":renamed_fields", "]", ".", "values", "query_fields", ".", "concat", "hash_params", "[", ":renamed_fields", "]", ".", "keys", "end", "self", ".", "define_singleton_method", "(", ":gdpr_query", ")", "do", "|", "_user_id", "|", "result", "=", "self", ".", "where", "(", "user_id_field", "=>", "_user_id", ")", "if", "hash_params", "[", ":joins", "]", "result", "=", "hash_params", "[", ":joins", "]", ".", "inject", "(", "result", ")", "do", "|", "query", ",", "assoc", "|", "query", ".", "send", "(", ":joins", ",", "assoc", ")", "end", "end", "result", "end", "self", ".", "define_singleton_method", "(", ":gdpr_export", ")", "do", "|", "rows", ",", "csv", "|", "return", "unless", "!", "rows", ".", "empty?", "csv", "<<", "(", "hash_params", "[", ":table_name", "]", "?", "[", "hash_params", "[", ":table_name", "]", "]", ":", "[", "self", ".", "to_s", "]", ")", "if", "hash_params", "[", ":desc", "]", "csv", "<<", "[", "'Description:'", ",", "hash_params", "[", ":desc", "]", "]", "end", "csv", "<<", "csv_headers", "rows", ".", "each", "do", "|", "r", "|", "csv", "<<", "query_fields", ".", "map", "do", "|", "f", "|", "f_splitted", "=", "f", ".", "to_s", ".", "split", "(", "' '", ")", "if", "(", "f_splitted", ".", "size", "==", "2", ")", "f_splitted", ".", "inject", "(", "r", ")", "{", "|", "result", ",", "method", "|", "result", ".", "send", "(", "method", ")", "}", "elsif", "(", "f_splitted", ".", "size", ">", "2", ")", "raise", "ArgumentError", ".", "new", "(", "\"Field #{f} is made of more than 2 words!?\"", ")", "else", "r", ".", "send", "(", "f", ")", "end", "end", "end", "csv", "<<", "[", "]", "end", "end" ]
Declared in each model class with interest in collecting gdpr data. Instruments the singleton of those classes so that gdpr data can be collected and exported to csv. Arguments are: - set of simple fields: i.e. fields that will be output as is - a hash of params: {renamed_fields: {<field_from_db> => <field_name_in_output>} table_name: <the new table name in output> description: <a comment> join: <an association>}
[ "Declared", "in", "each", "model", "class", "with", "interest", "in", "collecting", "gdpr", "data", ".", "Instruments", "the", "singleton", "of", "those", "classes", "so", "that", "gdpr", "data", "can", "be", "collected", "and", "exported", "to", "csv", "." ]
3a7130da5c53ae65fb6aa3d544a8876bbb388c3c
https://github.com/epfl-exts/rails-gdpr-export/blob/3a7130da5c53ae65fb6aa3d544a8876bbb388c3c/lib/gdpr_exporter.rb#L51-L137
train
prydonius/spinning_cursor
lib/spinning_cursor/console_helpers.rb
SpinningCursor.ConsoleHelpers.reset_line
def reset_line(text = "") # Initialise ANSI escape string escape = "" # Get terminal window width cols = console_columns # The number of lines the previous message spanned lines = @@prev / cols # If cols == 80 and @@prev == 80, @@prev / cols == 1 but we don't want to # go up an extra line since it fits exactly lines -= 1 if @@prev % cols == 0 # Clear and go up a line lines.times { escape += "#{ESC_R_AND_CLR}#{ESC_UP_A_LINE}" } # Clear the line that is to be printed on escape += "#{ESC_R_AND_CLR}" # Console is clear, we can print! $console.print "#{escape}#{text}" # Store the current message so we know how many lines it spans @@prev = text.to_s.length end
ruby
def reset_line(text = "") # Initialise ANSI escape string escape = "" # Get terminal window width cols = console_columns # The number of lines the previous message spanned lines = @@prev / cols # If cols == 80 and @@prev == 80, @@prev / cols == 1 but we don't want to # go up an extra line since it fits exactly lines -= 1 if @@prev % cols == 0 # Clear and go up a line lines.times { escape += "#{ESC_R_AND_CLR}#{ESC_UP_A_LINE}" } # Clear the line that is to be printed on escape += "#{ESC_R_AND_CLR}" # Console is clear, we can print! $console.print "#{escape}#{text}" # Store the current message so we know how many lines it spans @@prev = text.to_s.length end
[ "def", "reset_line", "(", "text", "=", "\"\"", ")", "escape", "=", "\"\"", "cols", "=", "console_columns", "lines", "=", "@@prev", "/", "cols", "lines", "-=", "1", "if", "@@prev", "%", "cols", "==", "0", "lines", ".", "times", "{", "escape", "+=", "\"#{ESC_R_AND_CLR}#{ESC_UP_A_LINE}\"", "}", "escape", "+=", "\"#{ESC_R_AND_CLR}\"", "$console", ".", "print", "\"#{escape}#{text}\"", "@@prev", "=", "text", ".", "to_s", ".", "length", "end" ]
Manages line reset in the console
[ "Manages", "line", "reset", "in", "the", "console" ]
e0f2a9a1c5e3461586ac08417cc82c8ccafb4a12
https://github.com/prydonius/spinning_cursor/blob/e0f2a9a1c5e3461586ac08417cc82c8ccafb4a12/lib/spinning_cursor/console_helpers.rb#L32-L57
train
kt3k/bmp
lib/bump/domain/bump_info.rb
Bump.BumpInfo.valid?
def valid? create_update_rules.each do |rule| return false if !rule.file_exists || !rule.pattern_exists end true end
ruby
def valid? create_update_rules.each do |rule| return false if !rule.file_exists || !rule.pattern_exists end true end
[ "def", "valid?", "create_update_rules", ".", "each", "do", "|", "rule", "|", "return", "false", "if", "!", "rule", ".", "file_exists", "||", "!", "rule", ".", "pattern_exists", "end", "true", "end" ]
Checks the all the version patterns are available @return [Boolean]
[ "Checks", "the", "all", "the", "version", "patterns", "are", "available" ]
24c16fa8bcea5da8a72370b537b6dd92002011ee
https://github.com/kt3k/bmp/blob/24c16fa8bcea5da8a72370b537b6dd92002011ee/lib/bump/domain/bump_info.rb#L66-L72
train
ImmaculatePine/hermitage
lib/hermitage/rails_render_core.rb
Hermitage.RailsRenderCore.render
def render # Initialize the resulting tag tag_parts = [] # Slice objects into separate lists lists = slice_objects # Render each list into `tag` variable lists.each do |list| items = list.collect { |item| render_link_for(item) } tag_parts << render_content_tag_for(items) end tag_parts.join.html_safe end
ruby
def render # Initialize the resulting tag tag_parts = [] # Slice objects into separate lists lists = slice_objects # Render each list into `tag` variable lists.each do |list| items = list.collect { |item| render_link_for(item) } tag_parts << render_content_tag_for(items) end tag_parts.join.html_safe end
[ "def", "render", "tag_parts", "=", "[", "]", "lists", "=", "slice_objects", "lists", ".", "each", "do", "|", "list", "|", "items", "=", "list", ".", "collect", "{", "|", "item", "|", "render_link_for", "(", "item", ")", "}", "tag_parts", "<<", "render_content_tag_for", "(", "items", ")", "end", "tag_parts", ".", "join", ".", "html_safe", "end" ]
Renders gallery markup
[ "Renders", "gallery", "markup" ]
262c4d759691e7e11255e31f1eccf7a28d273d42
https://github.com/ImmaculatePine/hermitage/blob/262c4d759691e7e11255e31f1eccf7a28d273d42/lib/hermitage/rails_render_core.rb#L13-L27
train
ImmaculatePine/hermitage
lib/hermitage/rails_render_core.rb
Hermitage.RailsRenderCore.value_for
def value_for(item, option) attribute = @options[option] if attribute.is_a? Proc attribute.call(item) else eval("item.#{attribute}") end end
ruby
def value_for(item, option) attribute = @options[option] if attribute.is_a? Proc attribute.call(item) else eval("item.#{attribute}") end end
[ "def", "value_for", "(", "item", ",", "option", ")", "attribute", "=", "@options", "[", "option", "]", "if", "attribute", ".", "is_a?", "Proc", "attribute", ".", "call", "(", "item", ")", "else", "eval", "(", "\"item.#{attribute}\"", ")", "end", "end" ]
Returns value of item's attribute
[ "Returns", "value", "of", "item", "s", "attribute" ]
262c4d759691e7e11255e31f1eccf7a28d273d42
https://github.com/ImmaculatePine/hermitage/blob/262c4d759691e7e11255e31f1eccf7a28d273d42/lib/hermitage/rails_render_core.rb#L41-L48
train
ImmaculatePine/hermitage
lib/hermitage/rails_render_core.rb
Hermitage.RailsRenderCore.render_link_for
def render_link_for(item) original_path = value_for(item, :original) thumbnail_path = value_for(item, :thumbnail) title = @options[:title] ? value_for(item, :title) : nil image = @template.image_tag(thumbnail_path, class: @options[:image_class]) @template.link_to(image, original_path, rel: 'hermitage', class: @options[:link_class], title: title) end
ruby
def render_link_for(item) original_path = value_for(item, :original) thumbnail_path = value_for(item, :thumbnail) title = @options[:title] ? value_for(item, :title) : nil image = @template.image_tag(thumbnail_path, class: @options[:image_class]) @template.link_to(image, original_path, rel: 'hermitage', class: @options[:link_class], title: title) end
[ "def", "render_link_for", "(", "item", ")", "original_path", "=", "value_for", "(", "item", ",", ":original", ")", "thumbnail_path", "=", "value_for", "(", "item", ",", ":thumbnail", ")", "title", "=", "@options", "[", ":title", "]", "?", "value_for", "(", "item", ",", ":title", ")", ":", "nil", "image", "=", "@template", ".", "image_tag", "(", "thumbnail_path", ",", "class", ":", "@options", "[", ":image_class", "]", ")", "@template", ".", "link_to", "(", "image", ",", "original_path", ",", "rel", ":", "'hermitage'", ",", "class", ":", "@options", "[", ":link_class", "]", ",", "title", ":", "title", ")", "end" ]
Renders link to the specific image in a gallery
[ "Renders", "link", "to", "the", "specific", "image", "in", "a", "gallery" ]
262c4d759691e7e11255e31f1eccf7a28d273d42
https://github.com/ImmaculatePine/hermitage/blob/262c4d759691e7e11255e31f1eccf7a28d273d42/lib/hermitage/rails_render_core.rb#L51-L59
train
cryptape/ruby-rlp
lib/rlp/encode.rb
RLP.Encode.encode
def encode(obj, sedes: nil, infer_serializer: true, cache: false) return obj._cached_rlp if obj.is_a?(Sedes::Serializable) && obj._cached_rlp && sedes.nil? really_cache = obj.is_a?(Sedes::Serializable) && sedes.nil? && cache if sedes item = sedes.serialize(obj) elsif infer_serializer item = Sedes.infer(obj).serialize(obj) else item = obj end result = encode_raw(item) if really_cache obj._cached_rlp = result obj.make_immutable! end result end
ruby
def encode(obj, sedes: nil, infer_serializer: true, cache: false) return obj._cached_rlp if obj.is_a?(Sedes::Serializable) && obj._cached_rlp && sedes.nil? really_cache = obj.is_a?(Sedes::Serializable) && sedes.nil? && cache if sedes item = sedes.serialize(obj) elsif infer_serializer item = Sedes.infer(obj).serialize(obj) else item = obj end result = encode_raw(item) if really_cache obj._cached_rlp = result obj.make_immutable! end result end
[ "def", "encode", "(", "obj", ",", "sedes", ":", "nil", ",", "infer_serializer", ":", "true", ",", "cache", ":", "false", ")", "return", "obj", ".", "_cached_rlp", "if", "obj", ".", "is_a?", "(", "Sedes", "::", "Serializable", ")", "&&", "obj", ".", "_cached_rlp", "&&", "sedes", ".", "nil?", "really_cache", "=", "obj", ".", "is_a?", "(", "Sedes", "::", "Serializable", ")", "&&", "sedes", ".", "nil?", "&&", "cache", "if", "sedes", "item", "=", "sedes", ".", "serialize", "(", "obj", ")", "elsif", "infer_serializer", "item", "=", "Sedes", ".", "infer", "(", "obj", ")", ".", "serialize", "(", "obj", ")", "else", "item", "=", "obj", "end", "result", "=", "encode_raw", "(", "item", ")", "if", "really_cache", "obj", ".", "_cached_rlp", "=", "result", "obj", ".", "make_immutable!", "end", "result", "end" ]
Encode a Ruby object in RLP format. By default, the object is serialized in a suitable way first (using {RLP::Sedes.infer}) and then encoded. Serialization can be explicitly suppressed by setting {RLP::Sedes.infer} to `false` and not passing an alternative as `sedes`. If `obj` has an attribute `_cached_rlp` (as, notably, {RLP::Serializable}) and its value is not `nil`, this value is returned bypassing serialization and encoding, unless `sedes` is given (as the cache is assumed to refer to the standard serialization which can be replaced by specifying `sedes`). If `obj` is a {RLP::Serializable} and `cache` is true, the result of the encoding will be stored in `_cached_rlp` if it is empty and {RLP::Serializable.make_immutable} will be invoked on `obj`. @param obj [Object] object to encode @param sedes [#serialize(obj)] an object implementing a function `serialize(obj)` which will be used to serialize `obj` before encoding, or `nil` to use the infered one (if any) @param infer_serializer [Boolean] if `true` an appropriate serializer will be selected using {RLP::Sedes.infer} to serialize `obj` before encoding @param cache [Boolean] cache the return value in `obj._cached_rlp` if possible and make `obj` immutable (default `false`) @return [String] the RLP encoded item @raise [RLP::EncodingError] in the rather unlikely case that the item is too big to encode (will not happen) @raise [RLP::SerializationError] if the serialization fails
[ "Encode", "a", "Ruby", "object", "in", "RLP", "format", "." ]
49c11eaee9f0f58d8028e5f1a291504c22dc947c
https://github.com/cryptape/ruby-rlp/blob/49c11eaee9f0f58d8028e5f1a291504c22dc947c/lib/rlp/encode.rb#L43-L64
train
kt3k/bmp
lib/bump/application.rb
Bump.Application.create_bump_info
def create_bump_info repo = BumpInfoRepository.new @file begin bump_info = repo.from_file rescue Errno::ENOENT log_red "Error: the file `#{@file}` not found." return nil end bump_info end
ruby
def create_bump_info repo = BumpInfoRepository.new @file begin bump_info = repo.from_file rescue Errno::ENOENT log_red "Error: the file `#{@file}` not found." return nil end bump_info end
[ "def", "create_bump_info", "repo", "=", "BumpInfoRepository", ".", "new", "@file", "begin", "bump_info", "=", "repo", ".", "from_file", "rescue", "Errno", "::", "ENOENT", "log_red", "\"Error: the file `#{@file}` not found.\"", "return", "nil", "end", "bump_info", "end" ]
Gets the bump info @private @return [Bump::BumpInfo]
[ "Gets", "the", "bump", "info" ]
24c16fa8bcea5da8a72370b537b6dd92002011ee
https://github.com/kt3k/bmp/blob/24c16fa8bcea5da8a72370b537b6dd92002011ee/lib/bump/application.rb#L64-L75
train
kt3k/bmp
lib/bump/application.rb
Bump.Application.print_version_patterns
def print_version_patterns(bump_info) log 'Current Version:', false log_green " #{bump_info.before_version}" log 'Version patterns:' bump_info.update_rules.each do |rule| print_rule rule end end
ruby
def print_version_patterns(bump_info) log 'Current Version:', false log_green " #{bump_info.before_version}" log 'Version patterns:' bump_info.update_rules.each do |rule| print_rule rule end end
[ "def", "print_version_patterns", "(", "bump_info", ")", "log", "'Current Version:'", ",", "false", "log_green", "\" #{bump_info.before_version}\"", "log", "'Version patterns:'", "bump_info", ".", "update_rules", ".", "each", "do", "|", "rule", "|", "print_rule", "rule", "end", "end" ]
Shows the version patterns. @param [Bump::BumpInfo] bumpInfo @return [void]
[ "Shows", "the", "version", "patterns", "." ]
24c16fa8bcea5da8a72370b537b6dd92002011ee
https://github.com/kt3k/bmp/blob/24c16fa8bcea5da8a72370b537b6dd92002011ee/lib/bump/application.rb#L89-L98
train
kt3k/bmp
lib/bump/application.rb
Bump.Application.print_rule
def print_rule(rule) unless rule.file_exists log_red " #{rule.file}:", false log_red " '#{rule.before_pattern}' (file not found)" return end log " #{rule.file}:", false unless rule.pattern_exists log_red " '#{rule.before_pattern}' (pattern not found)" return end log_green " '#{rule.before_pattern}'" end
ruby
def print_rule(rule) unless rule.file_exists log_red " #{rule.file}:", false log_red " '#{rule.before_pattern}' (file not found)" return end log " #{rule.file}:", false unless rule.pattern_exists log_red " '#{rule.before_pattern}' (pattern not found)" return end log_green " '#{rule.before_pattern}'" end
[ "def", "print_rule", "(", "rule", ")", "unless", "rule", ".", "file_exists", "log_red", "\" #{rule.file}:\"", ",", "false", "log_red", "\" '#{rule.before_pattern}' (file not found)\"", "return", "end", "log", "\" #{rule.file}:\"", ",", "false", "unless", "rule", ".", "pattern_exists", "log_red", "\" '#{rule.before_pattern}' (pattern not found)\"", "return", "end", "log_green", "\" '#{rule.before_pattern}'\"", "end" ]
Prints the pattern info for the given rule @param [Bump::FileUpdateRule] rule The rule
[ "Prints", "the", "pattern", "info", "for", "the", "given", "rule" ]
24c16fa8bcea5da8a72370b537b6dd92002011ee
https://github.com/kt3k/bmp/blob/24c16fa8bcea5da8a72370b537b6dd92002011ee/lib/bump/application.rb#L102-L119
train
kt3k/bmp
lib/bump/application.rb
Bump.Application.report
def report(bump_info) bump_info.update_rules.each do |rule| log rule.file.to_s log ' Performed pattern replacement:' log_green " '#{rule.before_pattern}' => '#{rule.after_pattern}'" log end end
ruby
def report(bump_info) bump_info.update_rules.each do |rule| log rule.file.to_s log ' Performed pattern replacement:' log_green " '#{rule.before_pattern}' => '#{rule.after_pattern}'" log end end
[ "def", "report", "(", "bump_info", ")", "bump_info", ".", "update_rules", ".", "each", "do", "|", "rule", "|", "log", "rule", ".", "file", ".", "to_s", "log", "' Performed pattern replacement:'", "log_green", "\" '#{rule.before_pattern}' => '#{rule.after_pattern}'\"", "log", "end", "end" ]
Reports the bumping details. @param [Bump::BumpInfo] bumpInfo
[ "Reports", "the", "bumping", "details", "." ]
24c16fa8bcea5da8a72370b537b6dd92002011ee
https://github.com/kt3k/bmp/blob/24c16fa8bcea5da8a72370b537b6dd92002011ee/lib/bump/application.rb#L147-L154
train
kt3k/bmp
lib/bump/application.rb
Bump.Application.action_bump
def action_bump bump_info = create_bump_info return false if bump_info.nil? print_bump_plan bump_info unless bump_info.valid? print_invalid_bump_info bump_info return false end bump_info.perform_update report bump_info save_bump_info bump_info commit_and_tag bump_info if @options[:commit] true end
ruby
def action_bump bump_info = create_bump_info return false if bump_info.nil? print_bump_plan bump_info unless bump_info.valid? print_invalid_bump_info bump_info return false end bump_info.perform_update report bump_info save_bump_info bump_info commit_and_tag bump_info if @options[:commit] true end
[ "def", "action_bump", "bump_info", "=", "create_bump_info", "return", "false", "if", "bump_info", ".", "nil?", "print_bump_plan", "bump_info", "unless", "bump_info", ".", "valid?", "print_invalid_bump_info", "bump_info", "return", "false", "end", "bump_info", ".", "perform_update", "report", "bump_info", "save_bump_info", "bump_info", "commit_and_tag", "bump_info", "if", "@options", "[", ":commit", "]", "true", "end" ]
The bump action @return [Boolean] true iff success
[ "The", "bump", "action" ]
24c16fa8bcea5da8a72370b537b6dd92002011ee
https://github.com/kt3k/bmp/blob/24c16fa8bcea5da8a72370b537b6dd92002011ee/lib/bump/application.rb#L158-L180
train
kt3k/bmp
lib/bump/application.rb
Bump.Application.print_bump_plan
def print_bump_plan(bump_info) level = bump_level print_bump_plan_level level, bump_info unless level.nil? preid = @options[:preid] print_bump_plan_preid preid, bump_info unless preid.nil? print_bump_plan_release bump_info if @options[:release] log end
ruby
def print_bump_plan(bump_info) level = bump_level print_bump_plan_level level, bump_info unless level.nil? preid = @options[:preid] print_bump_plan_preid preid, bump_info unless preid.nil? print_bump_plan_release bump_info if @options[:release] log end
[ "def", "print_bump_plan", "(", "bump_info", ")", "level", "=", "bump_level", "print_bump_plan_level", "level", ",", "bump_info", "unless", "level", ".", "nil?", "preid", "=", "@options", "[", ":preid", "]", "print_bump_plan_preid", "preid", ",", "bump_info", "unless", "preid", ".", "nil?", "print_bump_plan_release", "bump_info", "if", "@options", "[", ":release", "]", "log", "end" ]
Prints the version bump plan. @param [Bump::BumpInfo] bump_info The bump info
[ "Prints", "the", "version", "bump", "plan", "." ]
24c16fa8bcea5da8a72370b537b6dd92002011ee
https://github.com/kt3k/bmp/blob/24c16fa8bcea5da8a72370b537b6dd92002011ee/lib/bump/application.rb#L192-L202
train
kt3k/bmp
lib/bump/application.rb
Bump.Application.print_bump_plan_preid
def print_bump_plan_preid(preid, bump_info) bump_info.preid = preid log 'Set pre-release version id: ', false log_green preid print_version_transition bump_info end
ruby
def print_bump_plan_preid(preid, bump_info) bump_info.preid = preid log 'Set pre-release version id: ', false log_green preid print_version_transition bump_info end
[ "def", "print_bump_plan_preid", "(", "preid", ",", "bump_info", ")", "bump_info", ".", "preid", "=", "preid", "log", "'Set pre-release version id: '", ",", "false", "log_green", "preid", "print_version_transition", "bump_info", "end" ]
Prints the bump plan for the give preid. @param [Bump::BumpInfo] bump_info The bump info
[ "Prints", "the", "bump", "plan", "for", "the", "give", "preid", "." ]
24c16fa8bcea5da8a72370b537b6dd92002011ee
https://github.com/kt3k/bmp/blob/24c16fa8bcea5da8a72370b537b6dd92002011ee/lib/bump/application.rb#L216-L222
train
Digi-Cazter/omniship
lib/omniship/carriers/ups.rb
Omniship.UPS.create_shipment
def create_shipment(origin, destination, packages, options={}) @options = @options.merge(options) origin, destination = upsified_location(origin), upsified_location(destination) options = @options.merge(options) options[:test] = options[:test].nil? ? true : options[:test] packages = Array(packages) access_request = build_access_request ship_confirm_request = build_ship_confirm(origin, destination, packages, options) response = commit(:shipconfirm, save_request(access_request.gsub("\n", "") + ship_confirm_request.gsub("\n", "")), options[:test]) parse_ship_confirm_response(origin, destination, packages, response, options) end
ruby
def create_shipment(origin, destination, packages, options={}) @options = @options.merge(options) origin, destination = upsified_location(origin), upsified_location(destination) options = @options.merge(options) options[:test] = options[:test].nil? ? true : options[:test] packages = Array(packages) access_request = build_access_request ship_confirm_request = build_ship_confirm(origin, destination, packages, options) response = commit(:shipconfirm, save_request(access_request.gsub("\n", "") + ship_confirm_request.gsub("\n", "")), options[:test]) parse_ship_confirm_response(origin, destination, packages, response, options) end
[ "def", "create_shipment", "(", "origin", ",", "destination", ",", "packages", ",", "options", "=", "{", "}", ")", "@options", "=", "@options", ".", "merge", "(", "options", ")", "origin", ",", "destination", "=", "upsified_location", "(", "origin", ")", ",", "upsified_location", "(", "destination", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "options", "[", ":test", "]", "=", "options", "[", ":test", "]", ".", "nil?", "?", "true", ":", "options", "[", ":test", "]", "packages", "=", "Array", "(", "packages", ")", "access_request", "=", "build_access_request", "ship_confirm_request", "=", "build_ship_confirm", "(", "origin", ",", "destination", ",", "packages", ",", "options", ")", "response", "=", "commit", "(", ":shipconfirm", ",", "save_request", "(", "access_request", ".", "gsub", "(", "\"\\n\"", ",", "\"\"", ")", "+", "ship_confirm_request", ".", "gsub", "(", "\"\\n\"", ",", "\"\"", ")", ")", ",", "options", "[", ":test", "]", ")", "parse_ship_confirm_response", "(", "origin", ",", "destination", ",", "packages", ",", "response", ",", "options", ")", "end" ]
Creating shipping functionality for UPS
[ "Creating", "shipping", "functionality", "for", "UPS" ]
a8c3ffca548fc2f00a06e4593d363439512ce6ae
https://github.com/Digi-Cazter/omniship/blob/a8c3ffca548fc2f00a06e4593d363439512ce6ae/lib/omniship/carriers/ups.rb#L123-L133
train
tpickett66/ansible-vault-rb
lib/ansible/vault.rb
Ansible.Vault.write
def write file = FileWriter.new(@path) encryptor = Encryptor.new(password: @password, file: file) encryptor.encrypt(@plaintext) file.write end
ruby
def write file = FileWriter.new(@path) encryptor = Encryptor.new(password: @password, file: file) encryptor.encrypt(@plaintext) file.write end
[ "def", "write", "file", "=", "FileWriter", ".", "new", "(", "@path", ")", "encryptor", "=", "Encryptor", ".", "new", "(", "password", ":", "@password", ",", "file", ":", "file", ")", "encryptor", ".", "encrypt", "(", "@plaintext", ")", "file", ".", "write", "end" ]
Write the plaintext to the file specified @return [File] The closed file handle the vault was written to
[ "Write", "the", "plaintext", "to", "the", "file", "specified" ]
06d7239f10b3fdc074d45523705309ebf5efc2ab
https://github.com/tpickett66/ansible-vault-rb/blob/06d7239f10b3fdc074d45523705309ebf5efc2ab/lib/ansible/vault.rb#L116-L121
train
tpickett66/ansible-vault-rb
lib/ansible/vault.rb
Ansible.Vault.read
def read file = FileReader.new(@path) return File.read(@path) unless file.encrypted? decryptor = Decryptor.new(password: @password, file: file) decryptor.plaintext end
ruby
def read file = FileReader.new(@path) return File.read(@path) unless file.encrypted? decryptor = Decryptor.new(password: @password, file: file) decryptor.plaintext end
[ "def", "read", "file", "=", "FileReader", ".", "new", "(", "@path", ")", "return", "File", ".", "read", "(", "@path", ")", "unless", "file", ".", "encrypted?", "decryptor", "=", "Decryptor", ".", "new", "(", "password", ":", "@password", ",", "file", ":", "file", ")", "decryptor", ".", "plaintext", "end" ]
Extract the plaintext from a previously written vault file If the file does not appear to be encrypted the raw contents will be returned. @return [String] The plaintext contents of the vault, this is marked for zeroing before the GC reaps the object. Any data extracted/parsed from this string should be similarly wiped from memory when no longer used.
[ "Extract", "the", "plaintext", "from", "a", "previously", "written", "vault", "file" ]
06d7239f10b3fdc074d45523705309ebf5efc2ab
https://github.com/tpickett66/ansible-vault-rb/blob/06d7239f10b3fdc074d45523705309ebf5efc2ab/lib/ansible/vault.rb#L131-L136
train
soylent/jschema
lib/jschema/validation_helpers.rb
JSchema.ValidationHelpers.non_empty_array?
def non_empty_array?(value, uniqueness_check = true) result = value.is_a?(Array) && !value.empty? if uniqueness_check result && value.size == value.uniq.size else result end end
ruby
def non_empty_array?(value, uniqueness_check = true) result = value.is_a?(Array) && !value.empty? if uniqueness_check result && value.size == value.uniq.size else result end end
[ "def", "non_empty_array?", "(", "value", ",", "uniqueness_check", "=", "true", ")", "result", "=", "value", ".", "is_a?", "(", "Array", ")", "&&", "!", "value", ".", "empty?", "if", "uniqueness_check", "result", "&&", "value", ".", "size", "==", "value", ".", "uniq", ".", "size", "else", "result", "end", "end" ]
Returns true if a given value is a non-empty array @param value [Object] @return [Boolean]
[ "Returns", "true", "if", "a", "given", "value", "is", "a", "non", "-", "empty", "array" ]
57df9daf333fafb9d0d2bf15df65d4c044a612ea
https://github.com/soylent/jschema/blob/57df9daf333fafb9d0d2bf15df65d4c044a612ea/lib/jschema/validation_helpers.rb#L45-L52
train
soylent/jschema
lib/jschema/validation_helpers.rb
JSchema.ValidationHelpers.schema_array?
def schema_array?(value, id, uniqueness_check = true) non_empty_array?(value, uniqueness_check) && value.to_enum.with_index.all? do |schema, index| full_id = [id, index].join('/') valid_schema? schema, full_id end end
ruby
def schema_array?(value, id, uniqueness_check = true) non_empty_array?(value, uniqueness_check) && value.to_enum.with_index.all? do |schema, index| full_id = [id, index].join('/') valid_schema? schema, full_id end end
[ "def", "schema_array?", "(", "value", ",", "id", ",", "uniqueness_check", "=", "true", ")", "non_empty_array?", "(", "value", ",", "uniqueness_check", ")", "&&", "value", ".", "to_enum", ".", "with_index", ".", "all?", "do", "|", "schema", ",", "index", "|", "full_id", "=", "[", "id", ",", "index", "]", ".", "join", "(", "'/'", ")", "valid_schema?", "schema", ",", "full_id", "end", "end" ]
Returns true if a given value is a list of valid JSON schemas @param value [Object] @param id [String] parent schema id @param uniqueness_check [Boolean] check that all schemas are unique @return [Boolean]
[ "Returns", "true", "if", "a", "given", "value", "is", "a", "list", "of", "valid", "JSON", "schemas" ]
57df9daf333fafb9d0d2bf15df65d4c044a612ea
https://github.com/soylent/jschema/blob/57df9daf333fafb9d0d2bf15df65d4c044a612ea/lib/jschema/validation_helpers.rb#L60-L66
train
soylent/jschema
lib/jschema/validation_helpers.rb
JSchema.ValidationHelpers.valid_schema?
def valid_schema?(schema, id) schema.is_a?(Hash) && Schema.build(schema, parent, id) rescue InvalidSchema false end
ruby
def valid_schema?(schema, id) schema.is_a?(Hash) && Schema.build(schema, parent, id) rescue InvalidSchema false end
[ "def", "valid_schema?", "(", "schema", ",", "id", ")", "schema", ".", "is_a?", "(", "Hash", ")", "&&", "Schema", ".", "build", "(", "schema", ",", "parent", ",", "id", ")", "rescue", "InvalidSchema", "false", "end" ]
Returns true if a given JSON schema is valid @param schema [Object] schema @param id [String] schema id @return [Boolean]
[ "Returns", "true", "if", "a", "given", "JSON", "schema", "is", "valid" ]
57df9daf333fafb9d0d2bf15df65d4c044a612ea
https://github.com/soylent/jschema/blob/57df9daf333fafb9d0d2bf15df65d4c044a612ea/lib/jschema/validation_helpers.rb#L73-L77
train
avdgaag/redmine-api
lib/redmine/accept_json.rb
Redmine.AcceptJson.get
def get(path, headers = {}) response = super(path, { 'Accept' => ACCEPT }.merge(headers.to_h)) case response.content_type when CONTENT_TYPE then [parse_response(response), response] else raise "Unknown content type #{response.content_type.inspect}" end end
ruby
def get(path, headers = {}) response = super(path, { 'Accept' => ACCEPT }.merge(headers.to_h)) case response.content_type when CONTENT_TYPE then [parse_response(response), response] else raise "Unknown content type #{response.content_type.inspect}" end end
[ "def", "get", "(", "path", ",", "headers", "=", "{", "}", ")", "response", "=", "super", "(", "path", ",", "{", "'Accept'", "=>", "ACCEPT", "}", ".", "merge", "(", "headers", ".", "to_h", ")", ")", "case", "response", ".", "content_type", "when", "CONTENT_TYPE", "then", "[", "parse_response", "(", "response", ")", ",", "response", "]", "else", "raise", "\"Unknown content type #{response.content_type.inspect}\"", "end", "end" ]
Wrap requests to add an `Accept` header to ask for JSON, and parse response bodies as JSON data.
[ "Wrap", "requests", "to", "add", "an", "Accept", "header", "to", "ask", "for", "JSON", "and", "parse", "response", "bodies", "as", "JSON", "data", "." ]
4417b801c4ad8ab1442ad557ddaa282239910153
https://github.com/avdgaag/redmine-api/blob/4417b801c4ad8ab1442ad557ddaa282239910153/lib/redmine/accept_json.rb#L22-L28
train
sonots/kondate
lib/kondate/hash_ext.rb
Kondate.HashExt.deep_merge!
def deep_merge!(other_hash, &block) other_hash.each_pair do |current_key, other_value| this_value = self[current_key] self[current_key] = if this_value.is_a?(Hash) && other_value.is_a?(Hash) _this_value = HashExt.new.replace(this_value) _this_value.deep_merge(other_value, &block).to_h else if block_given? && key?(current_key) block.call(current_key, this_value, other_value) else other_value end end end self end
ruby
def deep_merge!(other_hash, &block) other_hash.each_pair do |current_key, other_value| this_value = self[current_key] self[current_key] = if this_value.is_a?(Hash) && other_value.is_a?(Hash) _this_value = HashExt.new.replace(this_value) _this_value.deep_merge(other_value, &block).to_h else if block_given? && key?(current_key) block.call(current_key, this_value, other_value) else other_value end end end self end
[ "def", "deep_merge!", "(", "other_hash", ",", "&", "block", ")", "other_hash", ".", "each_pair", "do", "|", "current_key", ",", "other_value", "|", "this_value", "=", "self", "[", "current_key", "]", "self", "[", "current_key", "]", "=", "if", "this_value", ".", "is_a?", "(", "Hash", ")", "&&", "other_value", ".", "is_a?", "(", "Hash", ")", "_this_value", "=", "HashExt", ".", "new", ".", "replace", "(", "this_value", ")", "_this_value", ".", "deep_merge", "(", "other_value", ",", "&", "block", ")", ".", "to_h", "else", "if", "block_given?", "&&", "key?", "(", "current_key", ")", "block", ".", "call", "(", "current_key", ",", "this_value", ",", "other_value", ")", "else", "other_value", "end", "end", "end", "self", "end" ]
Same as +deep_merge+, but modifies +self+.
[ "Same", "as", "+", "deep_merge", "+", "but", "modifies", "+", "self", "+", "." ]
a56d520b08a1a2bf2d992067ef017175401684ef
https://github.com/sonots/kondate/blob/a56d520b08a1a2bf2d992067ef017175401684ef/lib/kondate/hash_ext.rb#L23-L40
train
carwow/restful_resource
lib/restful_resource/request.rb
RestfulResource.Request.format_headers
def format_headers @headers.stringify_keys.each_with_object({}) do |key_with_value, headers| headers[format_key(key_with_value.first)] = key_with_value.last end end
ruby
def format_headers @headers.stringify_keys.each_with_object({}) do |key_with_value, headers| headers[format_key(key_with_value.first)] = key_with_value.last end end
[ "def", "format_headers", "@headers", ".", "stringify_keys", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "key_with_value", ",", "headers", "|", "headers", "[", "format_key", "(", "key_with_value", ".", "first", ")", "]", "=", "key_with_value", ".", "last", "end", "end" ]
Formats all keys in Word-Word format
[ "Formats", "all", "keys", "in", "Word", "-", "Word", "format" ]
b9224aaad76e24cff231616ffa048859770deb9e
https://github.com/carwow/restful_resource/blob/b9224aaad76e24cff231616ffa048859770deb9e/lib/restful_resource/request.rb#L21-L25
train
cloudfoundry-attic/cfoundry
lib/cfoundry/zip.rb
CFoundry.Zip.unpack
def unpack(file, dest) ::Zip::ZipFile.foreach(file) do |zentry| epath = "#{dest}/#{zentry}" dirname = File.dirname(epath) FileUtils.mkdir_p(dirname) unless File.exists?(dirname) zentry.extract(epath) unless File.exists?(epath) end end
ruby
def unpack(file, dest) ::Zip::ZipFile.foreach(file) do |zentry| epath = "#{dest}/#{zentry}" dirname = File.dirname(epath) FileUtils.mkdir_p(dirname) unless File.exists?(dirname) zentry.extract(epath) unless File.exists?(epath) end end
[ "def", "unpack", "(", "file", ",", "dest", ")", "::", "Zip", "::", "ZipFile", ".", "foreach", "(", "file", ")", "do", "|", "zentry", "|", "epath", "=", "\"#{dest}/#{zentry}\"", "dirname", "=", "File", ".", "dirname", "(", "epath", ")", "FileUtils", ".", "mkdir_p", "(", "dirname", ")", "unless", "File", ".", "exists?", "(", "dirname", ")", "zentry", ".", "extract", "(", "epath", ")", "unless", "File", ".", "exists?", "(", "epath", ")", "end", "end" ]
Unpack a zip +file+ to directory +dest+.
[ "Unpack", "a", "zip", "+", "file", "+", "to", "directory", "+", "dest", "+", "." ]
028576968a054e2524be0b6e00b1400a831db9f4
https://github.com/cloudfoundry-attic/cfoundry/blob/028576968a054e2524be0b6e00b1400a831db9f4/lib/cfoundry/zip.rb#L23-L30
train
cloudfoundry-attic/cfoundry
lib/cfoundry/zip.rb
CFoundry.Zip.files_to_pack
def files_to_pack(dir) Dir.glob("#{dir}/**/*", File::FNM_DOTMATCH).select do |f| File.exists?(f) && PACK_EXCLUSION_GLOBS.none? do |e| File.fnmatch(e, File.basename(f)) end end end
ruby
def files_to_pack(dir) Dir.glob("#{dir}/**/*", File::FNM_DOTMATCH).select do |f| File.exists?(f) && PACK_EXCLUSION_GLOBS.none? do |e| File.fnmatch(e, File.basename(f)) end end end
[ "def", "files_to_pack", "(", "dir", ")", "Dir", ".", "glob", "(", "\"#{dir}/**/*\"", ",", "File", "::", "FNM_DOTMATCH", ")", ".", "select", "do", "|", "f", "|", "File", ".", "exists?", "(", "f", ")", "&&", "PACK_EXCLUSION_GLOBS", ".", "none?", "do", "|", "e", "|", "File", ".", "fnmatch", "(", "e", ",", "File", ".", "basename", "(", "f", ")", ")", "end", "end", "end" ]
Determine what files in +dir+ to pack.
[ "Determine", "what", "files", "in", "+", "dir", "+", "to", "pack", "." ]
028576968a054e2524be0b6e00b1400a831db9f4
https://github.com/cloudfoundry-attic/cfoundry/blob/028576968a054e2524be0b6e00b1400a831db9f4/lib/cfoundry/zip.rb#L33-L40
train
cloudfoundry-attic/cfoundry
lib/cfoundry/zip.rb
CFoundry.Zip.pack
def pack(dir, zipfile) files = files_to_pack(dir) return false if files.empty? ::Zip::ZipFile.open(zipfile, true) do |zf| files.each do |f| zf.add(f.sub("#{dir}/",''), f) end end true end
ruby
def pack(dir, zipfile) files = files_to_pack(dir) return false if files.empty? ::Zip::ZipFile.open(zipfile, true) do |zf| files.each do |f| zf.add(f.sub("#{dir}/",''), f) end end true end
[ "def", "pack", "(", "dir", ",", "zipfile", ")", "files", "=", "files_to_pack", "(", "dir", ")", "return", "false", "if", "files", ".", "empty?", "::", "Zip", "::", "ZipFile", ".", "open", "(", "zipfile", ",", "true", ")", "do", "|", "zf", "|", "files", ".", "each", "do", "|", "f", "|", "zf", ".", "add", "(", "f", ".", "sub", "(", "\"#{dir}/\"", ",", "''", ")", ",", "f", ")", "end", "end", "true", "end" ]
Package directory +dir+ as file +zipfile+.
[ "Package", "directory", "+", "dir", "+", "as", "file", "+", "zipfile", "+", "." ]
028576968a054e2524be0b6e00b1400a831db9f4
https://github.com/cloudfoundry-attic/cfoundry/blob/028576968a054e2524be0b6e00b1400a831db9f4/lib/cfoundry/zip.rb#L43-L54
train
code-and-effect/effective_bootstrap
app/models/effective/form_builder.rb
Effective.FormBuilder.remote_link_to
def remote_link_to(name, url, options = {}, &block) options[:href] ||= url Effective::FormInputs::RemoteLinkTo.new(name, options, builder: self).to_html(&block) end
ruby
def remote_link_to(name, url, options = {}, &block) options[:href] ||= url Effective::FormInputs::RemoteLinkTo.new(name, options, builder: self).to_html(&block) end
[ "def", "remote_link_to", "(", "name", ",", "url", ",", "options", "=", "{", "}", ",", "&", "block", ")", "options", "[", ":href", "]", "||=", "url", "Effective", "::", "FormInputs", "::", "RemoteLinkTo", ".", "new", "(", "name", ",", "options", ",", "builder", ":", "self", ")", ".", "to_html", "(", "&", "block", ")", "end" ]
This is gonna be a post?
[ "This", "is", "gonna", "be", "a", "post?" ]
d2f4641b08a40a4017117cf55331099ef3333b54
https://github.com/code-and-effect/effective_bootstrap/blob/d2f4641b08a40a4017117cf55331099ef3333b54/app/models/effective/form_builder.rb#L84-L87
train
rlister/slackbotsy
lib/slackbotsy/api.rb
Slackbotsy.Api.get_objects
def get_objects(method, key) self.class.get("/#{method}", query: { token: @token }).tap do |response| raise "error retrieving #{key} from #{method}: #{response.fetch('error', 'unknown error')}" unless response['ok'] end.fetch(key) end
ruby
def get_objects(method, key) self.class.get("/#{method}", query: { token: @token }).tap do |response| raise "error retrieving #{key} from #{method}: #{response.fetch('error', 'unknown error')}" unless response['ok'] end.fetch(key) end
[ "def", "get_objects", "(", "method", ",", "key", ")", "self", ".", "class", ".", "get", "(", "\"/#{method}\"", ",", "query", ":", "{", "token", ":", "@token", "}", ")", ".", "tap", "do", "|", "response", "|", "raise", "\"error retrieving #{key} from #{method}: #{response.fetch('error', 'unknown error')}\"", "unless", "response", "[", "'ok'", "]", "end", ".", "fetch", "(", "key", ")", "end" ]
get a channel, group, im or user list
[ "get", "a", "channel", "group", "im", "or", "user", "list" ]
198b9e3316630f4ae76f6c3e7da71ffae89ec4ed
https://github.com/rlister/slackbotsy/blob/198b9e3316630f4ae76f6c3e7da71ffae89ec4ed/lib/slackbotsy/api.rb#L14-L18
train
rlister/slackbotsy
lib/slackbotsy/api.rb
Slackbotsy.Api.join
def join(channel) self.class.post('/channels.join', body: {name: channel, token: @token}).tap do |response| raise "error posting message: #{response.fetch('error', 'unknown error')}" unless response['ok'] end end
ruby
def join(channel) self.class.post('/channels.join', body: {name: channel, token: @token}).tap do |response| raise "error posting message: #{response.fetch('error', 'unknown error')}" unless response['ok'] end end
[ "def", "join", "(", "channel", ")", "self", ".", "class", ".", "post", "(", "'/channels.join'", ",", "body", ":", "{", "name", ":", "channel", ",", "token", ":", "@token", "}", ")", ".", "tap", "do", "|", "response", "|", "raise", "\"error posting message: #{response.fetch('error', 'unknown error')}\"", "unless", "response", "[", "'ok'", "]", "end", "end" ]
join a channel, needed to post to channel
[ "join", "a", "channel", "needed", "to", "post", "to", "channel" ]
198b9e3316630f4ae76f6c3e7da71ffae89ec4ed
https://github.com/rlister/slackbotsy/blob/198b9e3316630f4ae76f6c3e7da71ffae89ec4ed/lib/slackbotsy/api.rb#L37-L41
train
rlister/slackbotsy
lib/slackbotsy/api.rb
Slackbotsy.Api.post_message
def post_message(params) self.class.post('/chat.postMessage', body: params.merge({token: @token})).tap do |response| raise "error posting message: #{response.fetch('error', 'unknown error')}" unless response['ok'] end end
ruby
def post_message(params) self.class.post('/chat.postMessage', body: params.merge({token: @token})).tap do |response| raise "error posting message: #{response.fetch('error', 'unknown error')}" unless response['ok'] end end
[ "def", "post_message", "(", "params", ")", "self", ".", "class", ".", "post", "(", "'/chat.postMessage'", ",", "body", ":", "params", ".", "merge", "(", "{", "token", ":", "@token", "}", ")", ")", ".", "tap", "do", "|", "response", "|", "raise", "\"error posting message: #{response.fetch('error', 'unknown error')}\"", "unless", "response", "[", "'ok'", "]", "end", "end" ]
send message to one channel as a single post with params text, channel, as_user
[ "send", "message", "to", "one", "channel", "as", "a", "single", "post", "with", "params", "text", "channel", "as_user" ]
198b9e3316630f4ae76f6c3e7da71ffae89ec4ed
https://github.com/rlister/slackbotsy/blob/198b9e3316630f4ae76f6c3e7da71ffae89ec4ed/lib/slackbotsy/api.rb#L44-L48
train
cloudfoundry-attic/cfoundry
lib/cfoundry/upload_helpers.rb
CFoundry.UploadHelpers.prune_empty_directories
def prune_empty_directories(path) all_files = all_files(path) directories = all_files.select { |x| File.directory?(x) } directories.sort! { |a, b| b.size <=> a.size } directories.each do |directory| entries = all_files(directory) FileUtils.rmdir(directory) if entries.empty? end end
ruby
def prune_empty_directories(path) all_files = all_files(path) directories = all_files.select { |x| File.directory?(x) } directories.sort! { |a, b| b.size <=> a.size } directories.each do |directory| entries = all_files(directory) FileUtils.rmdir(directory) if entries.empty? end end
[ "def", "prune_empty_directories", "(", "path", ")", "all_files", "=", "all_files", "(", "path", ")", "directories", "=", "all_files", ".", "select", "{", "|", "x", "|", "File", ".", "directory?", "(", "x", ")", "}", "directories", ".", "sort!", "{", "|", "a", ",", "b", "|", "b", ".", "size", "<=>", "a", ".", "size", "}", "directories", ".", "each", "do", "|", "directory", "|", "entries", "=", "all_files", "(", "directory", ")", "FileUtils", ".", "rmdir", "(", "directory", ")", "if", "entries", ".", "empty?", "end", "end" ]
OK, HERES THE PLAN... 1. Get all the directories in the entire file tree. 2. Sort them by the length of their absolute path. 3. Go through the list, longest paths first, and remove the directories that are empty. This ensures that directories containing empty directories are also pruned.
[ "OK", "HERES", "THE", "PLAN", "..." ]
028576968a054e2524be0b6e00b1400a831db9f4
https://github.com/cloudfoundry-attic/cfoundry/blob/028576968a054e2524be0b6e00b1400a831db9f4/lib/cfoundry/upload_helpers.rb#L188-L198
train
rlister/slackbotsy
lib/slackbotsy/bot.rb
Slackbotsy.Bot.setup_incoming_webhook
def setup_incoming_webhook ## incoming_webhook will be used if provided, otherwise fallback to old-style url with team and token url = @options.fetch('incoming_webhook', false) || "https://#{@options['team']}.slack.com/services/hooks/incoming-webhook?token=#{@options['incoming_token']}" @uri = URI.parse(url) @http = Net::HTTP.new(@uri.host, @uri.port) @http.use_ssl = true @http.verify_mode = OpenSSL::SSL::VERIFY_PEER end
ruby
def setup_incoming_webhook ## incoming_webhook will be used if provided, otherwise fallback to old-style url with team and token url = @options.fetch('incoming_webhook', false) || "https://#{@options['team']}.slack.com/services/hooks/incoming-webhook?token=#{@options['incoming_token']}" @uri = URI.parse(url) @http = Net::HTTP.new(@uri.host, @uri.port) @http.use_ssl = true @http.verify_mode = OpenSSL::SSL::VERIFY_PEER end
[ "def", "setup_incoming_webhook", "url", "=", "@options", ".", "fetch", "(", "'incoming_webhook'", ",", "false", ")", "||", "\"https://#{@options['team']}.slack.com/services/hooks/incoming-webhook?token=#{@options['incoming_token']}\"", "@uri", "=", "URI", ".", "parse", "(", "url", ")", "@http", "=", "Net", "::", "HTTP", ".", "new", "(", "@uri", ".", "host", ",", "@uri", ".", "port", ")", "@http", ".", "use_ssl", "=", "true", "@http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_PEER", "end" ]
setup http connection for sending async incoming webhook messages to slack
[ "setup", "http", "connection", "for", "sending", "async", "incoming", "webhook", "messages", "to", "slack" ]
198b9e3316630f4ae76f6c3e7da71ffae89ec4ed
https://github.com/rlister/slackbotsy/blob/198b9e3316630f4ae76f6c3e7da71ffae89ec4ed/lib/slackbotsy/bot.rb#L34-L41
train
rlister/slackbotsy
lib/slackbotsy/bot.rb
Slackbotsy.Bot.post
def post(options) payload = { username: @options['name'], channel: @options['channel'] }.merge(options) payload[:channel] = payload[:channel].gsub(/^#?/, '#') #slack api needs leading # on channel request = Net::HTTP::Post.new(@uri.request_uri) request.set_form_data(payload: payload.to_json) @http.request(request) return nil # so as not to trigger text in outgoing webhook reply end
ruby
def post(options) payload = { username: @options['name'], channel: @options['channel'] }.merge(options) payload[:channel] = payload[:channel].gsub(/^#?/, '#') #slack api needs leading # on channel request = Net::HTTP::Post.new(@uri.request_uri) request.set_form_data(payload: payload.to_json) @http.request(request) return nil # so as not to trigger text in outgoing webhook reply end
[ "def", "post", "(", "options", ")", "payload", "=", "{", "username", ":", "@options", "[", "'name'", "]", ",", "channel", ":", "@options", "[", "'channel'", "]", "}", ".", "merge", "(", "options", ")", "payload", "[", ":channel", "]", "=", "payload", "[", ":channel", "]", ".", "gsub", "(", "/", "/", ",", "'#'", ")", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "@uri", ".", "request_uri", ")", "request", ".", "set_form_data", "(", "payload", ":", "payload", ".", "to_json", ")", "@http", ".", "request", "(", "request", ")", "return", "nil", "end" ]
raw post of hash to slack webhook
[ "raw", "post", "of", "hash", "to", "slack", "webhook" ]
198b9e3316630f4ae76f6c3e7da71ffae89ec4ed
https://github.com/rlister/slackbotsy/blob/198b9e3316630f4ae76f6c3e7da71ffae89ec4ed/lib/slackbotsy/bot.rb#L51-L61
train
rlister/slackbotsy
lib/slackbotsy/bot.rb
Slackbotsy.Bot.hear
def hear(regex, &block) @listeners << OpenStruct.new(regex: regex, desc: @last_desc, proc: block) @last_desc = nil end
ruby
def hear(regex, &block) @listeners << OpenStruct.new(regex: regex, desc: @last_desc, proc: block) @last_desc = nil end
[ "def", "hear", "(", "regex", ",", "&", "block", ")", "@listeners", "<<", "OpenStruct", ".", "new", "(", "regex", ":", "regex", ",", "desc", ":", "@last_desc", ",", "proc", ":", "block", ")", "@last_desc", "=", "nil", "end" ]
add regex to things to hear
[ "add", "regex", "to", "things", "to", "hear" ]
198b9e3316630f4ae76f6c3e7da71ffae89ec4ed
https://github.com/rlister/slackbotsy/blob/198b9e3316630f4ae76f6c3e7da71ffae89ec4ed/lib/slackbotsy/bot.rb#L115-L118
train
rlister/slackbotsy
lib/slackbotsy/bot.rb
Slackbotsy.Bot.eval_scripts
def eval_scripts(*files) files.flatten.each do |file| self.instance_eval(File.open(file).read) end end
ruby
def eval_scripts(*files) files.flatten.each do |file| self.instance_eval(File.open(file).read) end end
[ "def", "eval_scripts", "(", "*", "files", ")", "files", ".", "flatten", ".", "each", "do", "|", "file", "|", "self", ".", "instance_eval", "(", "File", ".", "open", "(", "file", ")", ".", "read", ")", "end", "end" ]
pass list of files containing hear statements, to be opened and evaled
[ "pass", "list", "of", "files", "containing", "hear", "statements", "to", "be", "opened", "and", "evaled" ]
198b9e3316630f4ae76f6c3e7da71ffae89ec4ed
https://github.com/rlister/slackbotsy/blob/198b9e3316630f4ae76f6c3e7da71ffae89ec4ed/lib/slackbotsy/bot.rb#L121-L125
train
rlister/slackbotsy
lib/slackbotsy/bot.rb
Slackbotsy.Bot.handle_outgoing_webhook
def handle_outgoing_webhook(msg) return nil unless @options['outgoing_token'].include?(msg[:token]) # ensure messages are for us from slack return nil if msg[:user_name] == 'slackbot' # do not reply to self return nil unless msg[:text].is_a?(String) # skip empty messages responses = get_responses(msg, msg[:text].strip) if responses { text: responses.compact.join("\n") }.to_json # webhook responses are json end end
ruby
def handle_outgoing_webhook(msg) return nil unless @options['outgoing_token'].include?(msg[:token]) # ensure messages are for us from slack return nil if msg[:user_name] == 'slackbot' # do not reply to self return nil unless msg[:text].is_a?(String) # skip empty messages responses = get_responses(msg, msg[:text].strip) if responses { text: responses.compact.join("\n") }.to_json # webhook responses are json end end
[ "def", "handle_outgoing_webhook", "(", "msg", ")", "return", "nil", "unless", "@options", "[", "'outgoing_token'", "]", ".", "include?", "(", "msg", "[", ":token", "]", ")", "return", "nil", "if", "msg", "[", ":user_name", "]", "==", "'slackbot'", "return", "nil", "unless", "msg", "[", ":text", "]", ".", "is_a?", "(", "String", ")", "responses", "=", "get_responses", "(", "msg", ",", "msg", "[", ":text", "]", ".", "strip", ")", "if", "responses", "{", "text", ":", "responses", ".", "compact", ".", "join", "(", "\"\\n\"", ")", "}", ".", "to_json", "end", "end" ]
check message and run blocks for any matches
[ "check", "message", "and", "run", "blocks", "for", "any", "matches" ]
198b9e3316630f4ae76f6c3e7da71ffae89ec4ed
https://github.com/rlister/slackbotsy/blob/198b9e3316630f4ae76f6c3e7da71ffae89ec4ed/lib/slackbotsy/bot.rb#L128-L138
train
rlister/slackbotsy
lib/slackbotsy/bot.rb
Slackbotsy.Bot.get_responses
def get_responses(msg, text) message = Slackbotsy::Message.new(self, msg) @listeners.map do |listener| text.match(listener.regex) do |mdata| begin message.instance_exec(mdata, *mdata[1..-1], &listener.proc) rescue => err # keep running even with a broken script, but report the error err end end end end
ruby
def get_responses(msg, text) message = Slackbotsy::Message.new(self, msg) @listeners.map do |listener| text.match(listener.regex) do |mdata| begin message.instance_exec(mdata, *mdata[1..-1], &listener.proc) rescue => err # keep running even with a broken script, but report the error err end end end end
[ "def", "get_responses", "(", "msg", ",", "text", ")", "message", "=", "Slackbotsy", "::", "Message", ".", "new", "(", "self", ",", "msg", ")", "@listeners", ".", "map", "do", "|", "listener", "|", "text", ".", "match", "(", "listener", ".", "regex", ")", "do", "|", "mdata", "|", "begin", "message", ".", "instance_exec", "(", "mdata", ",", "*", "mdata", "[", "1", "..", "-", "1", "]", ",", "&", "listener", ".", "proc", ")", "rescue", "=>", "err", "err", "end", "end", "end", "end" ]
run on msg all hear blocks matching text
[ "run", "on", "msg", "all", "hear", "blocks", "matching", "text" ]
198b9e3316630f4ae76f6c3e7da71ffae89ec4ed
https://github.com/rlister/slackbotsy/blob/198b9e3316630f4ae76f6c3e7da71ffae89ec4ed/lib/slackbotsy/bot.rb#L156-L167
train
cloudfoundry-attic/cfoundry
lib/cfoundry/v2/client.rb
CFoundry::V2.Client.current_user
def current_user return unless token token_data = @base.token.token_data if guid = token_data[:user_id] user = user(guid) user.emails = [{ :value => token_data[:email] }] user end end
ruby
def current_user return unless token token_data = @base.token.token_data if guid = token_data[:user_id] user = user(guid) user.emails = [{ :value => token_data[:email] }] user end end
[ "def", "current_user", "return", "unless", "token", "token_data", "=", "@base", ".", "token", ".", "token_data", "if", "guid", "=", "token_data", "[", ":user_id", "]", "user", "=", "user", "(", "guid", ")", "user", ".", "emails", "=", "[", "{", ":value", "=>", "token_data", "[", ":email", "]", "}", "]", "user", "end", "end" ]
The currently authenticated user.
[ "The", "currently", "authenticated", "user", "." ]
028576968a054e2524be0b6e00b1400a831db9f4
https://github.com/cloudfoundry-attic/cfoundry/blob/028576968a054e2524be0b6e00b1400a831db9f4/lib/cfoundry/v2/client.rb#L36-L45
train
nilsding/twittbot
lib/twittbot/bot.rb
Twittbot.Bot.auth
def auth require 'oauth' say "This will reset your current access tokens.", :red if already_authed? # get the request token URL callback = OAuth::OUT_OF_BAND consumer = OAuth::Consumer.new $bot[:config][:consumer_key], $bot[:config][:consumer_secret], site: Twitter::REST::Client::BASE_URL, scheme: :header request_token = consumer.get_request_token(oauth_callback: callback) url = request_token.authorize_url(oauth_callback: callback) puts "Open this URL in a browser: #{url}" pin = '' until pin =~ /^\d+$/ print "Enter PIN =>" pin = $stdin.gets.strip end access_token = request_token.get_access_token(oauth_verifier: pin) $bot[:config][:access_token] = access_token.token $bot[:config][:access_token_secret] = access_token.secret # get the bot's user name (screen_name) and print it to the console $bot[:config][:screen_name] = get_screen_name access_token puts "Hello, #{$bot[:config][:screen_name]}!" end
ruby
def auth require 'oauth' say "This will reset your current access tokens.", :red if already_authed? # get the request token URL callback = OAuth::OUT_OF_BAND consumer = OAuth::Consumer.new $bot[:config][:consumer_key], $bot[:config][:consumer_secret], site: Twitter::REST::Client::BASE_URL, scheme: :header request_token = consumer.get_request_token(oauth_callback: callback) url = request_token.authorize_url(oauth_callback: callback) puts "Open this URL in a browser: #{url}" pin = '' until pin =~ /^\d+$/ print "Enter PIN =>" pin = $stdin.gets.strip end access_token = request_token.get_access_token(oauth_verifier: pin) $bot[:config][:access_token] = access_token.token $bot[:config][:access_token_secret] = access_token.secret # get the bot's user name (screen_name) and print it to the console $bot[:config][:screen_name] = get_screen_name access_token puts "Hello, #{$bot[:config][:screen_name]}!" end
[ "def", "auth", "require", "'oauth'", "say", "\"This will reset your current access tokens.\"", ",", ":red", "if", "already_authed?", "callback", "=", "OAuth", "::", "OUT_OF_BAND", "consumer", "=", "OAuth", "::", "Consumer", ".", "new", "$bot", "[", ":config", "]", "[", ":consumer_key", "]", ",", "$bot", "[", ":config", "]", "[", ":consumer_secret", "]", ",", "site", ":", "Twitter", "::", "REST", "::", "Client", "::", "BASE_URL", ",", "scheme", ":", ":header", "request_token", "=", "consumer", ".", "get_request_token", "(", "oauth_callback", ":", "callback", ")", "url", "=", "request_token", ".", "authorize_url", "(", "oauth_callback", ":", "callback", ")", "puts", "\"Open this URL in a browser: #{url}\"", "pin", "=", "''", "until", "pin", "=~", "/", "\\d", "/", "print", "\"Enter PIN =>\"", "pin", "=", "$stdin", ".", "gets", ".", "strip", "end", "access_token", "=", "request_token", ".", "get_access_token", "(", "oauth_verifier", ":", "pin", ")", "$bot", "[", ":config", "]", "[", ":access_token", "]", "=", "access_token", ".", "token", "$bot", "[", ":config", "]", "[", ":access_token_secret", "]", "=", "access_token", ".", "secret", "$bot", "[", ":config", "]", "[", ":screen_name", "]", "=", "get_screen_name", "access_token", "puts", "\"Hello, #{$bot[:config][:screen_name]}!\"", "end" ]
Authenticates an account with Twitter.
[ "Authenticates", "an", "account", "with", "Twitter", "." ]
acddc9514453b17461255c1201f6309b3fc42b17
https://github.com/nilsding/twittbot/blob/acddc9514453b17461255c1201f6309b3fc42b17/lib/twittbot/bot.rb#L42-L69
train
nilsding/twittbot
lib/twittbot/bot.rb
Twittbot.Bot.start
def start check_config init_clients if $bot[:stream] puts "connecting to streaming APIs" @userstream_thread ||= Thread.new do loop do begin puts "connected to user stream" @streamer.user do |obj| handle_stream_object obj, :user end rescue => e puts "lost user stream connection: " + e.message end puts "reconnecting in #{Twittbot::RECONNECT_WAIT_TIME} seconds..." sleep Twittbot::RECONNECT_WAIT_TIME end end @tweetstream_thread ||= Thread.new do loop do begin puts "connected to tweet stream" @streamer.filter track: $bot[:config][:track].join(",") do |obj| handle_stream_object obj, :filter end rescue puts "lost tweet stream connection: " + e.message end puts "reconnecting in #{Twittbot::RECONNECT_WAIT_TIME} seconds..." sleep Twittbot::RECONNECT_WAIT_TIME end end end @periodic_thread ||= Thread.new do loop do begin Thread.new { do_periodic } rescue => _ end sleep 60 end end do_callbacks :load, nil if $bot[:stream] @userstream_thread.join @tweetstream_thread.join end @periodic_thread.join end
ruby
def start check_config init_clients if $bot[:stream] puts "connecting to streaming APIs" @userstream_thread ||= Thread.new do loop do begin puts "connected to user stream" @streamer.user do |obj| handle_stream_object obj, :user end rescue => e puts "lost user stream connection: " + e.message end puts "reconnecting in #{Twittbot::RECONNECT_WAIT_TIME} seconds..." sleep Twittbot::RECONNECT_WAIT_TIME end end @tweetstream_thread ||= Thread.new do loop do begin puts "connected to tweet stream" @streamer.filter track: $bot[:config][:track].join(",") do |obj| handle_stream_object obj, :filter end rescue puts "lost tweet stream connection: " + e.message end puts "reconnecting in #{Twittbot::RECONNECT_WAIT_TIME} seconds..." sleep Twittbot::RECONNECT_WAIT_TIME end end end @periodic_thread ||= Thread.new do loop do begin Thread.new { do_periodic } rescue => _ end sleep 60 end end do_callbacks :load, nil if $bot[:stream] @userstream_thread.join @tweetstream_thread.join end @periodic_thread.join end
[ "def", "start", "check_config", "init_clients", "if", "$bot", "[", ":stream", "]", "puts", "\"connecting to streaming APIs\"", "@userstream_thread", "||=", "Thread", ".", "new", "do", "loop", "do", "begin", "puts", "\"connected to user stream\"", "@streamer", ".", "user", "do", "|", "obj", "|", "handle_stream_object", "obj", ",", ":user", "end", "rescue", "=>", "e", "puts", "\"lost user stream connection: \"", "+", "e", ".", "message", "end", "puts", "\"reconnecting in #{Twittbot::RECONNECT_WAIT_TIME} seconds...\"", "sleep", "Twittbot", "::", "RECONNECT_WAIT_TIME", "end", "end", "@tweetstream_thread", "||=", "Thread", ".", "new", "do", "loop", "do", "begin", "puts", "\"connected to tweet stream\"", "@streamer", ".", "filter", "track", ":", "$bot", "[", ":config", "]", "[", ":track", "]", ".", "join", "(", "\",\"", ")", "do", "|", "obj", "|", "handle_stream_object", "obj", ",", ":filter", "end", "rescue", "puts", "\"lost tweet stream connection: \"", "+", "e", ".", "message", "end", "puts", "\"reconnecting in #{Twittbot::RECONNECT_WAIT_TIME} seconds...\"", "sleep", "Twittbot", "::", "RECONNECT_WAIT_TIME", "end", "end", "end", "@periodic_thread", "||=", "Thread", ".", "new", "do", "loop", "do", "begin", "Thread", ".", "new", "{", "do_periodic", "}", "rescue", "=>", "_", "end", "sleep", "60", "end", "end", "do_callbacks", ":load", ",", "nil", "if", "$bot", "[", ":stream", "]", "@userstream_thread", ".", "join", "@tweetstream_thread", ".", "join", "end", "@periodic_thread", ".", "join", "end" ]
Starts the bot.
[ "Starts", "the", "bot", "." ]
acddc9514453b17461255c1201f6309b3fc42b17
https://github.com/nilsding/twittbot/blob/acddc9514453b17461255c1201f6309b3fc42b17/lib/twittbot/bot.rb#L72-L127
train
nilsding/twittbot
lib/twittbot/bot.rb
Twittbot.Bot.load_bot_code
def load_bot_code load_special_tasks files = Dir["#{File.expand_path('./lib', @options[:current_dir])}/**/*"] files.each do |file| require_relative file.sub(/\.rb$/, '') if file.end_with? '.rb' end end
ruby
def load_bot_code load_special_tasks files = Dir["#{File.expand_path('./lib', @options[:current_dir])}/**/*"] files.each do |file| require_relative file.sub(/\.rb$/, '') if file.end_with? '.rb' end end
[ "def", "load_bot_code", "load_special_tasks", "files", "=", "Dir", "[", "\"#{File.expand_path('./lib', @options[:current_dir])}/**/*\"", "]", "files", ".", "each", "do", "|", "file", "|", "require_relative", "file", ".", "sub", "(", "/", "\\.", "/", ",", "''", ")", "if", "file", ".", "end_with?", "'.rb'", "end", "end" ]
Loads the bot's actual code which is stored in the bot's +lib+ subdirectory.
[ "Loads", "the", "bot", "s", "actual", "code", "which", "is", "stored", "in", "the", "bot", "s", "+", "lib", "+", "subdirectory", "." ]
acddc9514453b17461255c1201f6309b3fc42b17
https://github.com/nilsding/twittbot/blob/acddc9514453b17461255c1201f6309b3fc42b17/lib/twittbot/bot.rb#L162-L168
train
nilsding/twittbot
lib/twittbot/bot.rb
Twittbot.Bot.do_callbacks
def do_callbacks(callback_type, object, options = {}) return if $bot[:callbacks][callback_type].nil? $bot[:callbacks][callback_type].each do |c| c[:block].call object, options end end
ruby
def do_callbacks(callback_type, object, options = {}) return if $bot[:callbacks][callback_type].nil? $bot[:callbacks][callback_type].each do |c| c[:block].call object, options end end
[ "def", "do_callbacks", "(", "callback_type", ",", "object", ",", "options", "=", "{", "}", ")", "return", "if", "$bot", "[", ":callbacks", "]", "[", "callback_type", "]", ".", "nil?", "$bot", "[", ":callbacks", "]", "[", "callback_type", "]", ".", "each", "do", "|", "c", "|", "c", "[", ":block", "]", ".", "call", "object", ",", "options", "end", "end" ]
Runs callbacks. @param callback_type [:Symbol] The callback type. @param object [Object] The object
[ "Runs", "callbacks", "." ]
acddc9514453b17461255c1201f6309b3fc42b17
https://github.com/nilsding/twittbot/blob/acddc9514453b17461255c1201f6309b3fc42b17/lib/twittbot/bot.rb#L230-L235
train
nilsding/twittbot
lib/twittbot/bot.rb
Twittbot.Bot.do_direct_message
def do_direct_message(dm, opts = {}) return if dm.sender.screen_name == $bot[:config][:screen_name] return do_callbacks(:direct_message, dm, opts) unless dm.text.start_with? $bot[:config][:dm_command_prefix] dm_text = dm.text.sub($bot[:config][:dm_command_prefix], '').strip return if dm_text.empty? return unless /(?<command>[A-Za-z0-9]+)(?:\s*)(?<args>.*)/m =~ dm_text command = Regexp.last_match(:command).to_sym args = Regexp.last_match :args cmd = $bot[:commands][command] return say_status :dm, "#{dm.sender.screen_name} tried to issue non-existent command :#{command}, ignoring", :cyan if cmd.nil? return say_status :dm, "#{dm.sender.screen_name} tried to issue admin command :#{command}, ignoring", :cyan if cmd[:admin] and !dm.sender.admin? say_status :dm, "#{dm.sender.screen_name} issued command :#{command}", :cyan cmd[:block].call(args, dm.sender) end
ruby
def do_direct_message(dm, opts = {}) return if dm.sender.screen_name == $bot[:config][:screen_name] return do_callbacks(:direct_message, dm, opts) unless dm.text.start_with? $bot[:config][:dm_command_prefix] dm_text = dm.text.sub($bot[:config][:dm_command_prefix], '').strip return if dm_text.empty? return unless /(?<command>[A-Za-z0-9]+)(?:\s*)(?<args>.*)/m =~ dm_text command = Regexp.last_match(:command).to_sym args = Regexp.last_match :args cmd = $bot[:commands][command] return say_status :dm, "#{dm.sender.screen_name} tried to issue non-existent command :#{command}, ignoring", :cyan if cmd.nil? return say_status :dm, "#{dm.sender.screen_name} tried to issue admin command :#{command}, ignoring", :cyan if cmd[:admin] and !dm.sender.admin? say_status :dm, "#{dm.sender.screen_name} issued command :#{command}", :cyan cmd[:block].call(args, dm.sender) end
[ "def", "do_direct_message", "(", "dm", ",", "opts", "=", "{", "}", ")", "return", "if", "dm", ".", "sender", ".", "screen_name", "==", "$bot", "[", ":config", "]", "[", ":screen_name", "]", "return", "do_callbacks", "(", ":direct_message", ",", "dm", ",", "opts", ")", "unless", "dm", ".", "text", ".", "start_with?", "$bot", "[", ":config", "]", "[", ":dm_command_prefix", "]", "dm_text", "=", "dm", ".", "text", ".", "sub", "(", "$bot", "[", ":config", "]", "[", ":dm_command_prefix", "]", ",", "''", ")", ".", "strip", "return", "if", "dm_text", ".", "empty?", "return", "unless", "/", "\\s", "/m", "=~", "dm_text", "command", "=", "Regexp", ".", "last_match", "(", ":command", ")", ".", "to_sym", "args", "=", "Regexp", ".", "last_match", ":args", "cmd", "=", "$bot", "[", ":commands", "]", "[", "command", "]", "return", "say_status", ":dm", ",", "\"#{dm.sender.screen_name} tried to issue non-existent command :#{command}, ignoring\"", ",", ":cyan", "if", "cmd", ".", "nil?", "return", "say_status", ":dm", ",", "\"#{dm.sender.screen_name} tried to issue admin command :#{command}, ignoring\"", ",", ":cyan", "if", "cmd", "[", ":admin", "]", "and", "!", "dm", ".", "sender", ".", "admin?", "say_status", ":dm", ",", "\"#{dm.sender.screen_name} issued command :#{command}\"", ",", ":cyan", "cmd", "[", ":block", "]", ".", "call", "(", "args", ",", "dm", ".", "sender", ")", "end" ]
Processes a direct message. @param dm [Twitter::DirectMessage] received direct message
[ "Processes", "a", "direct", "message", "." ]
acddc9514453b17461255c1201f6309b3fc42b17
https://github.com/nilsding/twittbot/blob/acddc9514453b17461255c1201f6309b3fc42b17/lib/twittbot/bot.rb#L251-L267
train
nilsding/twittbot
lib/twittbot/bot.rb
Twittbot.Bot.list_tasks
def list_tasks tasks = $bot[:tasks].map do |name, value| [name, value[:desc]] end.to_h longest_name = tasks.keys.map(&:to_s).max { |a, b| a.length <=> b.length }.length tasks = tasks.map do |name, desc| "twittbot cron %-*s # %s" % [longest_name + 2, name, desc] end.sort puts tasks end
ruby
def list_tasks tasks = $bot[:tasks].map do |name, value| [name, value[:desc]] end.to_h longest_name = tasks.keys.map(&:to_s).max { |a, b| a.length <=> b.length }.length tasks = tasks.map do |name, desc| "twittbot cron %-*s # %s" % [longest_name + 2, name, desc] end.sort puts tasks end
[ "def", "list_tasks", "tasks", "=", "$bot", "[", ":tasks", "]", ".", "map", "do", "|", "name", ",", "value", "|", "[", "name", ",", "value", "[", ":desc", "]", "]", "end", ".", "to_h", "longest_name", "=", "tasks", ".", "keys", ".", "map", "(", "&", ":to_s", ")", ".", "max", "{", "|", "a", ",", "b", "|", "a", ".", "length", "<=>", "b", ".", "length", "}", ".", "length", "tasks", "=", "tasks", ".", "map", "do", "|", "name", ",", "desc", "|", "\"twittbot cron %-*s # %s\"", "%", "[", "longest_name", "+", "2", ",", "name", ",", "desc", "]", "end", ".", "sort", "puts", "tasks", "end" ]
Lists all tasks
[ "Lists", "all", "tasks" ]
acddc9514453b17461255c1201f6309b3fc42b17
https://github.com/nilsding/twittbot/blob/acddc9514453b17461255c1201f6309b3fc42b17/lib/twittbot/bot.rb#L308-L318
train
masa16/phys-units
lib/phys/units/quantity.rb
Phys.Quantity.want
def want(unit=nil) case unit when Unit expr = unit.expr when Quantity expr = unit.expr unit = unit.unit when String,Symbol expr = unit unit = Unit.parse(expr) when Numeric unit = Unit.cast(unit) when NilClass unit = Unit.cast(1) else raise TypeError, "invalid argument: #{unit.inspect}" end val = unit.convert(self) self.class.new( val, expr, unit ) end
ruby
def want(unit=nil) case unit when Unit expr = unit.expr when Quantity expr = unit.expr unit = unit.unit when String,Symbol expr = unit unit = Unit.parse(expr) when Numeric unit = Unit.cast(unit) when NilClass unit = Unit.cast(1) else raise TypeError, "invalid argument: #{unit.inspect}" end val = unit.convert(self) self.class.new( val, expr, unit ) end
[ "def", "want", "(", "unit", "=", "nil", ")", "case", "unit", "when", "Unit", "expr", "=", "unit", ".", "expr", "when", "Quantity", "expr", "=", "unit", ".", "expr", "unit", "=", "unit", ".", "unit", "when", "String", ",", "Symbol", "expr", "=", "unit", "unit", "=", "Unit", ".", "parse", "(", "expr", ")", "when", "Numeric", "unit", "=", "Unit", ".", "cast", "(", "unit", ")", "when", "NilClass", "unit", "=", "Unit", ".", "cast", "(", "1", ")", "else", "raise", "TypeError", ",", "\"invalid argument: #{unit.inspect}\"", "end", "val", "=", "unit", ".", "convert", "(", "self", ")", "self", ".", "class", ".", "new", "(", "val", ",", "expr", ",", "unit", ")", "end" ]
Conversion to a quantity in another unit. @param [String,Symbol,Unit,Quantity] unit unit expression. @return [Phys::Quantity] quantity in the unit of +unit+. @raise [Phys::UnitError] if unit conversion is failed.
[ "Conversion", "to", "a", "quantity", "in", "another", "unit", "." ]
f781f0a031f5476940c4acc175ff5a9cfd197d84
https://github.com/masa16/phys-units/blob/f781f0a031f5476940c4acc175ff5a9cfd197d84/lib/phys/units/quantity.rb#L126-L145
train
masa16/phys-units
lib/phys/units/quantity.rb
Phys.Quantity.close_to
def close_to(other,epsilon=Float::EPSILON) other_value = @unit.convert(other) abs_sum = @value.abs+other_value.abs (@value-other_value).abs <= abs_sum*epsilon end
ruby
def close_to(other,epsilon=Float::EPSILON) other_value = @unit.convert(other) abs_sum = @value.abs+other_value.abs (@value-other_value).abs <= abs_sum*epsilon end
[ "def", "close_to", "(", "other", ",", "epsilon", "=", "Float", "::", "EPSILON", ")", "other_value", "=", "@unit", ".", "convert", "(", "other", ")", "abs_sum", "=", "@value", ".", "abs", "+", "other_value", ".", "abs", "(", "@value", "-", "other_value", ")", ".", "abs", "<=", "abs_sum", "*", "epsilon", "end" ]
Comparison of quantities. Before the comparison, it converts +other+ to the unit of +self+. @param [Phys::Quantity] other @return [Integer] @raise [Phys::UnitError] if unit conversion is failed. Equality. Returns +true+ if +self+ has the same value as +other+. Before the comparison, it converts +other+ to the unit of +self+. @param [Phys::Quantity] other @return [Boolean] Comparison. Returns +true+ if +self+ is greater-than or equal-to +other+. Before the comparison, it converts +other+ to the unit of +self+. @param [Phys::Quantity] other @return [Boolean] @raise [Phys::UnitError] if unit conversion is failed. Comparison. Returns +true+ if +self+ is less-than or equal-to +other+. Before the comparison, it converts +other+ to the unit of +self+. @param [Phys::Quantity] other @return [Boolean] @raise [Phys::UnitError] if unit conversion is failed. Comparison. Returns +true+ if +self+ is less than +other+. Before the comparison, it converts +other+ to the unit of +self+. @param [Phys::Quantity] other @return [Boolean] @raise [Phys::UnitError] if unit conversion is failed. Comparison. Returns +true+ if +self+ is greater than +other+. Before the comparison, it converts +other+ to the unit of +self+. @param [Phys::Quantity] other @return [Boolean] @raise [Phys::UnitError] if unit conversion is failed. Closeness. Returns +true+ if (self-other).abs <= (self.abs+other.abs) * epsilon Before the comparison, it converts +other+ to the unit of +self+. @param [Phys::Quantity] other @param [Numeric] epsilon @return [Boolean] @raise [Phys::UnitError] if unit conversion is failed.
[ "Comparison", "of", "quantities", ".", "Before", "the", "comparison", "it", "converts", "+", "other", "+", "to", "the", "unit", "of", "+", "self", "+", "." ]
f781f0a031f5476940c4acc175ff5a9cfd197d84
https://github.com/masa16/phys-units/blob/f781f0a031f5476940c4acc175ff5a9cfd197d84/lib/phys/units/quantity.rb#L301-L305
train
masa16/phys-units
lib/phys/units/quantity.rb
Phys.Quantity.to_base_unit
def to_base_unit unit = @unit.base_unit val = unit.convert(self) expr = unit.unit_string self.class.new( val, expr, unit ) end
ruby
def to_base_unit unit = @unit.base_unit val = unit.convert(self) expr = unit.unit_string self.class.new( val, expr, unit ) end
[ "def", "to_base_unit", "unit", "=", "@unit", ".", "base_unit", "val", "=", "unit", ".", "convert", "(", "self", ")", "expr", "=", "unit", ".", "unit_string", "self", ".", "class", ".", "new", "(", "val", ",", "expr", ",", "unit", ")", "end" ]
Conversion to base unit. Returns the quantity converted to a base unit. @return [Phys::Quantity] a quantity in the base unit. @raise [Phys::UnitError] if unit conversion is failed.
[ "Conversion", "to", "base", "unit", ".", "Returns", "the", "quantity", "converted", "to", "a", "base", "unit", "." ]
f781f0a031f5476940c4acc175ff5a9cfd197d84
https://github.com/masa16/phys-units/blob/f781f0a031f5476940c4acc175ff5a9cfd197d84/lib/phys/units/quantity.rb#L492-L497
train
masa16/phys-units
lib/phys/units/quantity.rb
Phys.Quantity.inspect
def inspect expr = @expr || @unit.expr expr = (expr) ? ","+expr.inspect : "" sufx = (@@verbose_inspect) ? " "[email protected] : "" self.class.to_s+"["+Unit::Utils.num_inspect(@value)+expr+"]"+sufx end
ruby
def inspect expr = @expr || @unit.expr expr = (expr) ? ","+expr.inspect : "" sufx = (@@verbose_inspect) ? " "[email protected] : "" self.class.to_s+"["+Unit::Utils.num_inspect(@value)+expr+"]"+sufx end
[ "def", "inspect", "expr", "=", "@expr", "||", "@unit", ".", "expr", "expr", "=", "(", "expr", ")", "?", "\",\"", "+", "expr", ".", "inspect", ":", "\"\"", "sufx", "=", "(", "@@verbose_inspect", ")", "?", "\" \"", "+", "@unit", ".", "inspect", ":", "\"\"", "self", ".", "class", ".", "to_s", "+", "\"[\"", "+", "Unit", "::", "Utils", ".", "num_inspect", "(", "@value", ")", "+", "expr", "+", "\"]\"", "+", "sufx", "end" ]
Inspect String. @return [String]
[ "Inspect", "String", "." ]
f781f0a031f5476940c4acc175ff5a9cfd197d84
https://github.com/masa16/phys-units/blob/f781f0a031f5476940c4acc175ff5a9cfd197d84/lib/phys/units/quantity.rb#L547-L552
train
levinalex/lis
lib/lis/messages.rb
LIS::Message.Base.to_message
def to_message @fields ||= {} arr = Array.new(self.class.default_fields) type_id + @fields.inject(arr) { |a,(k,v)| a[k-1] = v; a }.join("|") end
ruby
def to_message @fields ||= {} arr = Array.new(self.class.default_fields) type_id + @fields.inject(arr) { |a,(k,v)| a[k-1] = v; a }.join("|") end
[ "def", "to_message", "@fields", "||=", "{", "}", "arr", "=", "Array", ".", "new", "(", "self", ".", "class", ".", "default_fields", ")", "type_id", "+", "@fields", ".", "inject", "(", "arr", ")", "{", "|", "a", ",", "(", "k", ",", "v", ")", "|", "a", "[", "k", "-", "1", "]", "=", "v", ";", "a", "}", ".", "join", "(", "\"|\"", ")", "end" ]
serialize a Message object into a String message = Message.from_string("5L|1|N") #=> <LIS::Message> message.to_message #=> "5L|1|N"
[ "serialize", "a", "Message", "object", "into", "a", "String" ]
405f97d8ea2e8bbd33ac45fcbdc1bc39a0852d3f
https://github.com/levinalex/lis/blob/405f97d8ea2e8bbd33ac45fcbdc1bc39a0852d3f/lib/lis/messages.rb#L121-L125
train