repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
codescrum/bebox
lib/bebox/commands/environment_commands.rb
Bebox.EnvironmentCommands.environment_list_command
def environment_list_command(environment_command) environment_command.desc 'List the remote environments in the project' environment_command.command :list do |environment_list_command| environment_list_command.action do |global_options,options,args| environments = Bebox::Environment.list(project_root) title _('cli.environment.list.current_envs') environments.map{|environment| msg(environment)} warn(_('cli.environment.list.no_envs')) if environments.empty? end end end
ruby
def environment_list_command(environment_command) environment_command.desc 'List the remote environments in the project' environment_command.command :list do |environment_list_command| environment_list_command.action do |global_options,options,args| environments = Bebox::Environment.list(project_root) title _('cli.environment.list.current_envs') environments.map{|environment| msg(environment)} warn(_('cli.environment.list.no_envs')) if environments.empty? end end end
[ "def", "environment_list_command", "(", "environment_command", ")", "environment_command", ".", "desc", "'List the remote environments in the project'", "environment_command", ".", "command", ":list", "do", "|", "environment_list_command", "|", "environment_list_command", ".", "action", "do", "|", "global_options", ",", "options", ",", "args", "|", "environments", "=", "Bebox", "::", "Environment", ".", "list", "(", "project_root", ")", "title", "_", "(", "'cli.environment.list.current_envs'", ")", "environments", ".", "map", "{", "|", "environment", "|", "msg", "(", "environment", ")", "}", "warn", "(", "_", "(", "'cli.environment.list.no_envs'", ")", ")", "if", "environments", ".", "empty?", "end", "end", "end" ]
Environment list command
[ "Environment", "list", "command" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/environment_commands.rb#L31-L41
train
Nowaker/ruby-ansi-sys-revived
lib/ansisys.rb
AnsiSys.CSSFormatter.hash_to_styles
def hash_to_styles(hash, separator = '; ') unless hash.empty? return hash.map{|e| "#{e[0]}: #{e[1].join(' ')}"}.join(separator) else return nil end end
ruby
def hash_to_styles(hash, separator = '; ') unless hash.empty? return hash.map{|e| "#{e[0]}: #{e[1].join(' ')}"}.join(separator) else return nil end end
[ "def", "hash_to_styles", "(", "hash", ",", "separator", "=", "'; '", ")", "unless", "hash", ".", "empty?", "return", "hash", ".", "map", "{", "|", "e", "|", "\"#{e[0]}: #{e[1].join(' ')}\"", "}", ".", "join", "(", "separator", ")", "else", "return", "nil", "end", "end" ]
make a CSS style-let from a Hash of CSS settings
[ "make", "a", "CSS", "style", "-", "let", "from", "a", "Hash", "of", "CSS", "settings" ]
6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688
https://github.com/Nowaker/ruby-ansi-sys-revived/blob/6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688/lib/ansisys.rb#L16-L22
train
Nowaker/ruby-ansi-sys-revived
lib/ansisys.rb
AnsiSys.Lexer.lex!
def lex! r = Array.new @buffer.gsub!(/(?:\r\n|\n\r)/, "\n") while @code_start_re =~ @buffer r << [:string, $`] unless $`.empty? if CODE_EQUIVALENT.has_key?($&) CODE_EQUIVALENT[$&].each do |c| r << [:code, c] end @buffer = $' else csi = $& residual = $' if PARAMETER_AND_LETTER =~ residual r << [:code, $&] @buffer = $' else @buffer = csi + residual return r end end end r << [:string, @buffer] unless @buffer.empty? @buffer = '' return r end
ruby
def lex! r = Array.new @buffer.gsub!(/(?:\r\n|\n\r)/, "\n") while @code_start_re =~ @buffer r << [:string, $`] unless $`.empty? if CODE_EQUIVALENT.has_key?($&) CODE_EQUIVALENT[$&].each do |c| r << [:code, c] end @buffer = $' else csi = $& residual = $' if PARAMETER_AND_LETTER =~ residual r << [:code, $&] @buffer = $' else @buffer = csi + residual return r end end end r << [:string, @buffer] unless @buffer.empty? @buffer = '' return r end
[ "def", "lex!", "r", "=", "Array", ".", "new", "@buffer", ".", "gsub!", "(", "/", "\\r", "\\n", "\\n", "\\r", "/", ",", "\"\\n\"", ")", "while", "@code_start_re", "=~", "@buffer", "r", "<<", "[", ":string", ",", "$`", "]", "unless", "$`", ".", "empty?", "if", "CODE_EQUIVALENT", ".", "has_key?", "(", "$&", ")", "CODE_EQUIVALENT", "[", "$&", "]", ".", "each", "do", "|", "c", "|", "r", "<<", "[", ":code", ",", "c", "]", "end", "@buffer", "=", "$'", "else", "csi", "=", "$&", "residual", "=", "$'", "if", "PARAMETER_AND_LETTER", "=~", "residual", "r", "<<", "[", ":code", ",", "$&", "]", "@buffer", "=", "$'", "else", "@buffer", "=", "csi", "+", "residual", "return", "r", "end", "end", "end", "r", "<<", "[", ":string", ",", "@buffer", "]", "unless", "@buffer", ".", "empty?", "@buffer", "=", "''", "return", "r", "end" ]
returns array of tokens while deleting the tokenized part from buffer
[ "returns", "array", "of", "tokens", "while", "deleting", "the", "tokenized", "part", "from", "buffer" ]
6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688
https://github.com/Nowaker/ruby-ansi-sys-revived/blob/6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688/lib/ansisys.rb#L68-L93
train
Nowaker/ruby-ansi-sys-revived
lib/ansisys.rb
AnsiSys.Characters.echo_on
def echo_on(screen, cursor) each_char do |c| w = width(c) cursor.fit!(w) screen.write(c, w, cursor.cur_col, cursor.cur_row, @sgr.dup) cursor.advance!(w) end return self end
ruby
def echo_on(screen, cursor) each_char do |c| w = width(c) cursor.fit!(w) screen.write(c, w, cursor.cur_col, cursor.cur_row, @sgr.dup) cursor.advance!(w) end return self end
[ "def", "echo_on", "(", "screen", ",", "cursor", ")", "each_char", "do", "|", "c", "|", "w", "=", "width", "(", "c", ")", "cursor", ".", "fit!", "(", "w", ")", "screen", ".", "write", "(", "c", ",", "w", ",", "cursor", ".", "cur_col", ",", "cursor", ".", "cur_row", ",", "@sgr", ".", "dup", ")", "cursor", ".", "advance!", "(", "w", ")", "end", "return", "self", "end" ]
Select Graphic Rendition associated with the text echo the string onto the _screen_ with initial cursor as _cursor_ _cursor_ position will be changed as the string is echoed
[ "Select", "Graphic", "Rendition", "associated", "with", "the", "text", "echo", "the", "string", "onto", "the", "_screen_", "with", "initial", "cursor", "as", "_cursor_", "_cursor_", "position", "will", "be", "changed", "as", "the", "string", "is", "echoed" ]
6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688
https://github.com/Nowaker/ruby-ansi-sys-revived/blob/6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688/lib/ansisys.rb#L112-L120
train
Nowaker/ruby-ansi-sys-revived
lib/ansisys.rb
AnsiSys.Cursor.apply_code!
def apply_code!(letter, *pars) case letter when 'A' @cur_row -= pars[0] ? pars[0] : 1 @cur_row = @max_row if @max_row and @cur_row > @max_row when 'B' @cur_row += pars[0] ? pars[0] : 1 @cur_row = @max_row if @max_row and @cur_row > @max_row when 'C' @cur_col += pars[0] ? pars[0] : 1 when 'D' @cur_col -= pars[0] ? pars[0] : 1 when 'E' @cur_row += pars[0] ? pars[0] : 1 @cur_col = 1 @max_row = @cur_row if @max_row and @cur_row > @max_row when 'F' @cur_row -= pars[0] ? pars[0] : 1 @cur_col = 1 @max_row = @cur_row if @max_row and @cur_row > @max_row when 'G' @cur_col = pars[0] ? pars[0] : 1 when 'H' @cur_row = pars[0] ? pars[0] : 1 @cur_col = pars[1] ? pars[1] : 1 @max_row = @cur_row if @max_row and @cur_row > @max_row when 'f' @cur_row = pars[0] ? pars[0] : 1 @cur_col = pars[1] ? pars[1] : 1 @max_row = @cur_row if @max_row and @cur_row > @max_row end if @cur_row < 1 @cur_row = 1 end if @cur_col < 1 @cur_col = 1 elsif @cur_col > @max_col @cur_col = @max_col end return self end
ruby
def apply_code!(letter, *pars) case letter when 'A' @cur_row -= pars[0] ? pars[0] : 1 @cur_row = @max_row if @max_row and @cur_row > @max_row when 'B' @cur_row += pars[0] ? pars[0] : 1 @cur_row = @max_row if @max_row and @cur_row > @max_row when 'C' @cur_col += pars[0] ? pars[0] : 1 when 'D' @cur_col -= pars[0] ? pars[0] : 1 when 'E' @cur_row += pars[0] ? pars[0] : 1 @cur_col = 1 @max_row = @cur_row if @max_row and @cur_row > @max_row when 'F' @cur_row -= pars[0] ? pars[0] : 1 @cur_col = 1 @max_row = @cur_row if @max_row and @cur_row > @max_row when 'G' @cur_col = pars[0] ? pars[0] : 1 when 'H' @cur_row = pars[0] ? pars[0] : 1 @cur_col = pars[1] ? pars[1] : 1 @max_row = @cur_row if @max_row and @cur_row > @max_row when 'f' @cur_row = pars[0] ? pars[0] : 1 @cur_col = pars[1] ? pars[1] : 1 @max_row = @cur_row if @max_row and @cur_row > @max_row end if @cur_row < 1 @cur_row = 1 end if @cur_col < 1 @cur_col = 1 elsif @cur_col > @max_col @cur_col = @max_col end return self end
[ "def", "apply_code!", "(", "letter", ",", "*", "pars", ")", "case", "letter", "when", "'A'", "@cur_row", "-=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "@cur_row", "=", "@max_row", "if", "@max_row", "and", "@cur_row", ">", "@max_row", "when", "'B'", "@cur_row", "+=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "@cur_row", "=", "@max_row", "if", "@max_row", "and", "@cur_row", ">", "@max_row", "when", "'C'", "@cur_col", "+=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "when", "'D'", "@cur_col", "-=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "when", "'E'", "@cur_row", "+=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "@cur_col", "=", "1", "@max_row", "=", "@cur_row", "if", "@max_row", "and", "@cur_row", ">", "@max_row", "when", "'F'", "@cur_row", "-=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "@cur_col", "=", "1", "@max_row", "=", "@cur_row", "if", "@max_row", "and", "@cur_row", ">", "@max_row", "when", "'G'", "@cur_col", "=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "when", "'H'", "@cur_row", "=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "@cur_col", "=", "pars", "[", "1", "]", "?", "pars", "[", "1", "]", ":", "1", "@max_row", "=", "@cur_row", "if", "@max_row", "and", "@cur_row", ">", "@max_row", "when", "'f'", "@cur_row", "=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "@cur_col", "=", "pars", "[", "1", "]", "?", "pars", "[", "1", "]", ":", "1", "@max_row", "=", "@cur_row", "if", "@max_row", "and", "@cur_row", ">", "@max_row", "end", "if", "@cur_row", "<", "1", "@cur_row", "=", "1", "end", "if", "@cur_col", "<", "1", "@cur_col", "=", "1", "elsif", "@cur_col", ">", "@max_col", "@cur_col", "=", "@max_col", "end", "return", "self", "end" ]
maximum row number applies self an escape sequence code that ends with _letter_ as String and with some _pars_ as Integers
[ "maximum", "row", "number", "applies", "self", "an", "escape", "sequence", "code", "that", "ends", "with", "_letter_", "as", "String", "and", "with", "some", "_pars_", "as", "Integers" ]
6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688
https://github.com/Nowaker/ruby-ansi-sys-revived/blob/6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688/lib/ansisys.rb#L167-L207
train
Nowaker/ruby-ansi-sys-revived
lib/ansisys.rb
AnsiSys.SGR.css_styles
def css_styles(colors = Screen.default_css_colors) r = Hash.new{|h, k| h[k] = Array.new} # intensity is not (yet) implemented r['font-style'] << 'italic' if @italic == :on r['text-decoration'] << 'underline' unless @underline == :none r['text-decoration'] << 'blink' unless @blink == :off case @image when :positive fg = @foreground bg = @background when :negative fg = @background bg = @foreground end fg = bg if @conceal == :on r['color'] << colors[@intensity][fg] unless fg == :white r['background-color'] << colors[@intensity][bg] unless bg == :black return r end
ruby
def css_styles(colors = Screen.default_css_colors) r = Hash.new{|h, k| h[k] = Array.new} # intensity is not (yet) implemented r['font-style'] << 'italic' if @italic == :on r['text-decoration'] << 'underline' unless @underline == :none r['text-decoration'] << 'blink' unless @blink == :off case @image when :positive fg = @foreground bg = @background when :negative fg = @background bg = @foreground end fg = bg if @conceal == :on r['color'] << colors[@intensity][fg] unless fg == :white r['background-color'] << colors[@intensity][bg] unless bg == :black return r end
[ "def", "css_styles", "(", "colors", "=", "Screen", ".", "default_css_colors", ")", "r", "=", "Hash", ".", "new", "{", "|", "h", ",", "k", "|", "h", "[", "k", "]", "=", "Array", ".", "new", "}", "r", "[", "'font-style'", "]", "<<", "'italic'", "if", "@italic", "==", ":on", "r", "[", "'text-decoration'", "]", "<<", "'underline'", "unless", "@underline", "==", ":none", "r", "[", "'text-decoration'", "]", "<<", "'blink'", "unless", "@blink", "==", ":off", "case", "@image", "when", ":positive", "fg", "=", "@foreground", "bg", "=", "@background", "when", ":negative", "fg", "=", "@background", "bg", "=", "@foreground", "end", "fg", "=", "bg", "if", "@conceal", "==", ":on", "r", "[", "'color'", "]", "<<", "colors", "[", "@intensity", "]", "[", "fg", "]", "unless", "fg", "==", ":white", "r", "[", "'background-color'", "]", "<<", "colors", "[", "@intensity", "]", "[", "bg", "]", "unless", "bg", "==", ":black", "return", "r", "end" ]
a Hash of CSS stylelet
[ "a", "Hash", "of", "CSS", "stylelet" ]
6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688
https://github.com/Nowaker/ruby-ansi-sys-revived/blob/6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688/lib/ansisys.rb#L364-L382
train
Nowaker/ruby-ansi-sys-revived
lib/ansisys.rb
AnsiSys.Screen.write
def write(char, char_width, col, row, sgr) @lines[Integer(row)][Integer(col)] = [char, char_width, sgr.dup] end
ruby
def write(char, char_width, col, row, sgr) @lines[Integer(row)][Integer(col)] = [char, char_width, sgr.dup] end
[ "def", "write", "(", "char", ",", "char_width", ",", "col", ",", "row", ",", "sgr", ")", "@lines", "[", "Integer", "(", "row", ")", "]", "[", "Integer", "(", "col", ")", "]", "=", "[", "char", ",", "char_width", ",", "sgr", ".", "dup", "]", "end" ]
register the _char_ at a specific location on Screen
[ "register", "the", "_char_", "at", "a", "specific", "location", "on", "Screen" ]
6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688
https://github.com/Nowaker/ruby-ansi-sys-revived/blob/6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688/lib/ansisys.rb#L517-L519
train
nico-hn/PseudoHikiParser
lib/pseudohiki/htmlplugin.rb
PseudoHiki.HtmlPlugin.anchor
def anchor name, anchor_mark = @data.split(/,\s*/o, 2) anchor_mark = "_" if (anchor_mark.nil? or anchor_mark.empty?) HtmlElement.create("a", anchor_mark, "name" => name, "href" => "#" + name) end
ruby
def anchor name, anchor_mark = @data.split(/,\s*/o, 2) anchor_mark = "_" if (anchor_mark.nil? or anchor_mark.empty?) HtmlElement.create("a", anchor_mark, "name" => name, "href" => "#" + name) end
[ "def", "anchor", "name", ",", "anchor_mark", "=", "@data", ".", "split", "(", "/", "\\s", "/o", ",", "2", ")", "anchor_mark", "=", "\"_\"", "if", "(", "anchor_mark", ".", "nil?", "or", "anchor_mark", ".", "empty?", ")", "HtmlElement", ".", "create", "(", "\"a\"", ",", "anchor_mark", ",", "\"name\"", "=>", "name", ",", "\"href\"", "=>", "\"#\"", "+", "name", ")", "end" ]
def inline lines = HtmlElement.decode(@data).split(/\r*\n/o) lines.shift if lines.first == "" HikiBlockParser.new.parse_lines(lines).join end
[ "def", "inline", "lines", "=", "HtmlElement", ".", "decode", "(" ]
d8c3d13be30409f094317ef81bd37c660dbc242d
https://github.com/nico-hn/PseudoHikiParser/blob/d8c3d13be30409f094317ef81bd37c660dbc242d/lib/pseudohiki/htmlplugin.rb#L67-L73
train
wedesoft/multiarray
lib/multiarray/gccfunction.rb
Hornetseye.GCCFunction.params
def params idx = 0 @param_types.collect do |param_type| args = GCCType.new( param_type ).identifiers.collect do arg = GCCValue.new self, "param#{idx}" idx += 1 arg end param_type.construct *args end end
ruby
def params idx = 0 @param_types.collect do |param_type| args = GCCType.new( param_type ).identifiers.collect do arg = GCCValue.new self, "param#{idx}" idx += 1 arg end param_type.construct *args end end
[ "def", "params", "idx", "=", "0", "@param_types", ".", "collect", "do", "|", "param_type", "|", "args", "=", "GCCType", ".", "new", "(", "param_type", ")", ".", "identifiers", ".", "collect", "do", "arg", "=", "GCCValue", ".", "new", "self", ",", "\"param#{idx}\"", "idx", "+=", "1", "arg", "end", "param_type", ".", "construct", "*", "args", "end", "end" ]
Retrieve all parameters @return [Array<Node>] Objects for handling the parameters. @private
[ "Retrieve", "all", "parameters" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccfunction.rb#L146-L156
train
burlesona/nform
lib/nform/html.rb
NForm.HTML.tag
def tag(name, attributes={}, &block) open = sjoin name, attrs(attributes) body = block.call if block_given? if VOID_ELEMENTS.include?(name.to_sym) raise BuilderError, "Void elements cannot have content" if body "<#{open}>" else "<#{open}>#{body}</#{name}>" end end
ruby
def tag(name, attributes={}, &block) open = sjoin name, attrs(attributes) body = block.call if block_given? if VOID_ELEMENTS.include?(name.to_sym) raise BuilderError, "Void elements cannot have content" if body "<#{open}>" else "<#{open}>#{body}</#{name}>" end end
[ "def", "tag", "(", "name", ",", "attributes", "=", "{", "}", ",", "&", "block", ")", "open", "=", "sjoin", "name", ",", "attrs", "(", "attributes", ")", "body", "=", "block", ".", "call", "if", "block_given?", "if", "VOID_ELEMENTS", ".", "include?", "(", "name", ".", "to_sym", ")", "raise", "BuilderError", ",", "\"Void elements cannot have content\"", "if", "body", "\"<#{open}>\"", "else", "\"<#{open}>#{body}</#{name}>\"", "end", "end" ]
Generate an HTML Tag
[ "Generate", "an", "HTML", "Tag" ]
3ba467b55e9fbb480856d069c1792c2ad41da921
https://github.com/burlesona/nform/blob/3ba467b55e9fbb480856d069c1792c2ad41da921/lib/nform/html.rb#L8-L17
train
robfors/ruby-sumac
lib/sumac/objects.rb
Sumac.Objects.process_forget
def process_forget(object, quiet: ) reference = convert_object_to_reference(object, build: false) raise UnexposedObjectError unless reference reference.local_forget_request(quiet: quiet) end
ruby
def process_forget(object, quiet: ) reference = convert_object_to_reference(object, build: false) raise UnexposedObjectError unless reference reference.local_forget_request(quiet: quiet) end
[ "def", "process_forget", "(", "object", ",", "quiet", ":", ")", "reference", "=", "convert_object_to_reference", "(", "object", ",", "build", ":", "false", ")", "raise", "UnexposedObjectError", "unless", "reference", "reference", ".", "local_forget_request", "(", "quiet", ":", "quiet", ")", "end" ]
Process a request from the local application to forget an exposed object. @param object [LocalObject,RemoteObject] @param quiet [Boolean] suppress any message to the remote endpoint @raise [UnexposedObjectError] if object is not exposed or has never been sent on this {Connection} @return [void]
[ "Process", "a", "request", "from", "the", "local", "application", "to", "forget", "an", "exposed", "object", "." ]
524fa68b7d1bb10a74baa69cd594ab2b8cae20a3
https://github.com/robfors/ruby-sumac/blob/524fa68b7d1bb10a74baa69cd594ab2b8cae20a3/lib/sumac/objects.rb#L202-L206
train
robfors/ruby-sumac
lib/sumac/objects.rb
Sumac.Objects.process_forget_message
def process_forget_message(message, quiet: ) reference = convert_properties_to_reference(message.object, build: false) reference.remote_forget_request(quiet: quiet) end
ruby
def process_forget_message(message, quiet: ) reference = convert_properties_to_reference(message.object, build: false) reference.remote_forget_request(quiet: quiet) end
[ "def", "process_forget_message", "(", "message", ",", "quiet", ":", ")", "reference", "=", "convert_properties_to_reference", "(", "message", ".", "object", ",", "build", ":", "false", ")", "reference", ".", "remote_forget_request", "(", "quiet", ":", "quiet", ")", "end" ]
Processes a request from the remote endpoint to forget an exposed object. Called when a forget message has been received by the messenger. @param message [Message::Forget] @param quiet [Boolean] suppress any message to the remote endpoint @raise [ProtocolError] if reference does not exist with id received @return [void]
[ "Processes", "a", "request", "from", "the", "remote", "endpoint", "to", "forget", "an", "exposed", "object", ".", "Called", "when", "a", "forget", "message", "has", "been", "received", "by", "the", "messenger", "." ]
524fa68b7d1bb10a74baa69cd594ab2b8cae20a3
https://github.com/robfors/ruby-sumac/blob/524fa68b7d1bb10a74baa69cd594ab2b8cae20a3/lib/sumac/objects.rb#L214-L217
train
wedesoft/multiarray
lib/multiarray/node.rb
Hornetseye.Node.memorise
def memorise if memory contiguous_strides = (0 ... dimension).collect do |i| shape[0 ... i].inject 1, :* end if strides == contiguous_strides self else dup end else dup end end
ruby
def memorise if memory contiguous_strides = (0 ... dimension).collect do |i| shape[0 ... i].inject 1, :* end if strides == contiguous_strides self else dup end else dup end end
[ "def", "memorise", "if", "memory", "contiguous_strides", "=", "(", "0", "...", "dimension", ")", ".", "collect", "do", "|", "i", "|", "shape", "[", "0", "...", "i", "]", ".", "inject", "1", ",", ":*", "end", "if", "strides", "==", "contiguous_strides", "self", "else", "dup", "end", "else", "dup", "end", "end" ]
Duplicate array expression if it is not in row-major format @return [Node] Duplicate of array or +self+.
[ "Duplicate", "array", "expression", "if", "it", "is", "not", "in", "row", "-", "major", "format" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/node.rb#L329-L342
train
wedesoft/multiarray
lib/multiarray/node.rb
Hornetseye.Node.to_a
def to_a if dimension == 0 force else n = shape.last ( 0 ... n ).collect { |i| element( i ).to_a } end end
ruby
def to_a if dimension == 0 force else n = shape.last ( 0 ... n ).collect { |i| element( i ).to_a } end end
[ "def", "to_a", "if", "dimension", "==", "0", "force", "else", "n", "=", "shape", ".", "last", "(", "0", "...", "n", ")", ".", "collect", "{", "|", "i", "|", "element", "(", "i", ")", ".", "to_a", "}", "end", "end" ]
Convert to Ruby array of objects Perform pending computations and convert native array to Ruby array of objects. @return [Array<Object>] Array of objects.
[ "Convert", "to", "Ruby", "array", "of", "objects" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/node.rb#L412-L419
train
wedesoft/multiarray
lib/multiarray/node.rb
Hornetseye.Node.inspect
def inspect( indent = nil, lines = nil ) if variables.empty? if dimension == 0 and not indent "#{typecode.inspect}(#{force.inspect})" else if indent prepend = '' else prepend = "#{Hornetseye::MultiArray(typecode, dimension).inspect}:\n" indent = 0 lines = 0 end if empty? retval = '[]' else retval = '[ ' for i in 0 ... shape.last x = element i if x.dimension > 0 if i > 0 retval += ",\n " lines += 1 if lines >= 10 retval += '...' if indent == 0 break end retval += ' ' * indent end str = x.inspect indent + 1, lines lines += str.count "\n" retval += str if lines >= 10 retval += '...' if indent == 0 break end else retval += ', ' if i > 0 str = x.force.inspect if retval.size + str.size >= 74 - '...'.size - '[ ]'.size * indent.succ retval += '...' break else retval += str end end end retval += ' ]' unless lines >= 10 end prepend + retval end else to_s end end
ruby
def inspect( indent = nil, lines = nil ) if variables.empty? if dimension == 0 and not indent "#{typecode.inspect}(#{force.inspect})" else if indent prepend = '' else prepend = "#{Hornetseye::MultiArray(typecode, dimension).inspect}:\n" indent = 0 lines = 0 end if empty? retval = '[]' else retval = '[ ' for i in 0 ... shape.last x = element i if x.dimension > 0 if i > 0 retval += ",\n " lines += 1 if lines >= 10 retval += '...' if indent == 0 break end retval += ' ' * indent end str = x.inspect indent + 1, lines lines += str.count "\n" retval += str if lines >= 10 retval += '...' if indent == 0 break end else retval += ', ' if i > 0 str = x.force.inspect if retval.size + str.size >= 74 - '...'.size - '[ ]'.size * indent.succ retval += '...' break else retval += str end end end retval += ' ]' unless lines >= 10 end prepend + retval end else to_s end end
[ "def", "inspect", "(", "indent", "=", "nil", ",", "lines", "=", "nil", ")", "if", "variables", ".", "empty?", "if", "dimension", "==", "0", "and", "not", "indent", "\"#{typecode.inspect}(#{force.inspect})\"", "else", "if", "indent", "prepend", "=", "''", "else", "prepend", "=", "\"#{Hornetseye::MultiArray(typecode, dimension).inspect}:\\n\"", "indent", "=", "0", "lines", "=", "0", "end", "if", "empty?", "retval", "=", "'[]'", "else", "retval", "=", "'[ '", "for", "i", "in", "0", "...", "shape", ".", "last", "x", "=", "element", "i", "if", "x", ".", "dimension", ">", "0", "if", "i", ">", "0", "retval", "+=", "\",\\n \"", "lines", "+=", "1", "if", "lines", ">=", "10", "retval", "+=", "'...'", "if", "indent", "==", "0", "break", "end", "retval", "+=", "' '", "*", "indent", "end", "str", "=", "x", ".", "inspect", "indent", "+", "1", ",", "lines", "lines", "+=", "str", ".", "count", "\"\\n\"", "retval", "+=", "str", "if", "lines", ">=", "10", "retval", "+=", "'...'", "if", "indent", "==", "0", "break", "end", "else", "retval", "+=", "', '", "if", "i", ">", "0", "str", "=", "x", ".", "force", ".", "inspect", "if", "retval", ".", "size", "+", "str", ".", "size", ">=", "74", "-", "'...'", ".", "size", "-", "'[ ]'", ".", "size", "*", "indent", ".", "succ", "retval", "+=", "'...'", "break", "else", "retval", "+=", "str", "end", "end", "end", "retval", "+=", "' ]'", "unless", "lines", ">=", "10", "end", "prepend", "+", "retval", "end", "else", "to_s", "end", "end" ]
Display information about this object @return [String] String with information about this object.
[ "Display", "information", "about", "this", "object" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/node.rb#L424-L478
train
wedesoft/multiarray
lib/multiarray/node.rb
Hornetseye.Node.check_shape
def check_shape(*args) _shape = shape args.each do |arg| _arg_shape = arg.shape if _shape.size < _arg_shape.size raise "#{arg.inspect} has #{arg.dimension} dimension(s) " + "but should not have more than #{dimension}" end if ( _shape + _arg_shape ).all? { |s| s.is_a? Integer } if _shape.last( _arg_shape.size ) != _arg_shape raise "#{arg.inspect} has shape #{arg.shape.inspect} " + "(does not match last value(s) of #{shape.inspect})" end end end end
ruby
def check_shape(*args) _shape = shape args.each do |arg| _arg_shape = arg.shape if _shape.size < _arg_shape.size raise "#{arg.inspect} has #{arg.dimension} dimension(s) " + "but should not have more than #{dimension}" end if ( _shape + _arg_shape ).all? { |s| s.is_a? Integer } if _shape.last( _arg_shape.size ) != _arg_shape raise "#{arg.inspect} has shape #{arg.shape.inspect} " + "(does not match last value(s) of #{shape.inspect})" end end end end
[ "def", "check_shape", "(", "*", "args", ")", "_shape", "=", "shape", "args", ".", "each", "do", "|", "arg", "|", "_arg_shape", "=", "arg", ".", "shape", "if", "_shape", ".", "size", "<", "_arg_shape", ".", "size", "raise", "\"#{arg.inspect} has #{arg.dimension} dimension(s) \"", "+", "\"but should not have more than #{dimension}\"", "end", "if", "(", "_shape", "+", "_arg_shape", ")", ".", "all?", "{", "|", "s", "|", "s", ".", "is_a?", "Integer", "}", "if", "_shape", ".", "last", "(", "_arg_shape", ".", "size", ")", "!=", "_arg_shape", "raise", "\"#{arg.inspect} has shape #{arg.shape.inspect} \"", "+", "\"(does not match last value(s) of #{shape.inspect})\"", "end", "end", "end", "end" ]
Check arguments for compatible shape The method will throw an exception if one of the arguments has an incompatible shape. @param [Array<Class>] args Arguments to check for compatibility. @return [Object] The return value should be ignored.
[ "Check", "arguments", "for", "compatible", "shape" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/node.rb#L570-L585
train
wedesoft/multiarray
lib/multiarray/node.rb
Hornetseye.Node.force
def force if finalised? get elsif (dimension > 0 and Thread.current[:lazy]) or not variables.empty? self elsif compilable? retval = allocate GCCFunction.run Store.new(retval, self) retval.demand.get else retval = allocate Store.new(retval, self).demand retval.demand.get end end
ruby
def force if finalised? get elsif (dimension > 0 and Thread.current[:lazy]) or not variables.empty? self elsif compilable? retval = allocate GCCFunction.run Store.new(retval, self) retval.demand.get else retval = allocate Store.new(retval, self).demand retval.demand.get end end
[ "def", "force", "if", "finalised?", "get", "elsif", "(", "dimension", ">", "0", "and", "Thread", ".", "current", "[", ":lazy", "]", ")", "or", "not", "variables", ".", "empty?", "self", "elsif", "compilable?", "retval", "=", "allocate", "GCCFunction", ".", "run", "Store", ".", "new", "(", "retval", ",", "self", ")", "retval", ".", "demand", ".", "get", "else", "retval", "=", "allocate", "Store", ".", "new", "(", "retval", ",", "self", ")", ".", "demand", "retval", ".", "demand", ".", "get", "end", "end" ]
Force delayed computation unless in lazy mode @return [Node,Object] Result of computation @see #demand @private
[ "Force", "delayed", "computation", "unless", "in", "lazy", "mode" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/node.rb#L656-L670
train
alltom/ruck
lib/ruck/shreduler.rb
Ruck.ShredConvenienceMethods.yield
def yield(dt, clock = nil) clock ||= $shreduler.clock $shreduler.shredule(Shred.current, clock.now + dt, clock) Shred.current.pause end
ruby
def yield(dt, clock = nil) clock ||= $shreduler.clock $shreduler.shredule(Shred.current, clock.now + dt, clock) Shred.current.pause end
[ "def", "yield", "(", "dt", ",", "clock", "=", "nil", ")", "clock", "||=", "$shreduler", ".", "clock", "$shreduler", ".", "shredule", "(", "Shred", ".", "current", ",", "clock", ".", "now", "+", "dt", ",", "clock", ")", "Shred", ".", "current", ".", "pause", "end" ]
yields the given amount of time on the global Shreduler, using the provided Clock if given
[ "yields", "the", "given", "amount", "of", "time", "on", "the", "global", "Shreduler", "using", "the", "provided", "Clock", "if", "given" ]
a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/shreduler.rb#L109-L113
train
alltom/ruck
lib/ruck/shreduler.rb
Ruck.ShredConvenienceMethods.wait_on
def wait_on(event) $shreduler.shredule(Shred.current, event, $shreduler.event_clock) Shred.current.pause end
ruby
def wait_on(event) $shreduler.shredule(Shred.current, event, $shreduler.event_clock) Shred.current.pause end
[ "def", "wait_on", "(", "event", ")", "$shreduler", ".", "shredule", "(", "Shred", ".", "current", ",", "event", ",", "$shreduler", ".", "event_clock", ")", "Shred", ".", "current", ".", "pause", "end" ]
sleeps, waiting on the given event on the default EventClock of the global Shreduler
[ "sleeps", "waiting", "on", "the", "given", "event", "on", "the", "default", "EventClock", "of", "the", "global", "Shreduler" ]
a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/shreduler.rb#L117-L120
train
alltom/ruck
lib/ruck/shreduler.rb
Ruck.Shreduler.run_one
def run_one shred, relative_time = @clock.unschedule_next return nil unless shred fast_forward(relative_time) if relative_time > 0 invoke_shred(shred) end
ruby
def run_one shred, relative_time = @clock.unschedule_next return nil unless shred fast_forward(relative_time) if relative_time > 0 invoke_shred(shred) end
[ "def", "run_one", "shred", ",", "relative_time", "=", "@clock", ".", "unschedule_next", "return", "nil", "unless", "shred", "fast_forward", "(", "relative_time", ")", "if", "relative_time", ">", "0", "invoke_shred", "(", "shred", ")", "end" ]
runs the next scheduled Shred, if one exists, returning that Shred
[ "runs", "the", "next", "scheduled", "Shred", "if", "one", "exists", "returning", "that", "Shred" ]
a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/shreduler.rb#L42-L48
train
alltom/ruck
lib/ruck/shreduler.rb
Ruck.Shreduler.run_until
def run_until(target_time) return if target_time < now loop do shred, relative_time = next_shred break unless shred break unless now + relative_time <= target_time run_one end # I hope rounding errors are okay fast_forward(target_time - now) end
ruby
def run_until(target_time) return if target_time < now loop do shred, relative_time = next_shred break unless shred break unless now + relative_time <= target_time run_one end # I hope rounding errors are okay fast_forward(target_time - now) end
[ "def", "run_until", "(", "target_time", ")", "return", "if", "target_time", "<", "now", "loop", "do", "shred", ",", "relative_time", "=", "next_shred", "break", "unless", "shred", "break", "unless", "now", "+", "relative_time", "<=", "target_time", "run_one", "end", "fast_forward", "(", "target_time", "-", "now", ")", "end" ]
runs shreds until the given target time, then fast-forwards to that time
[ "runs", "shreds", "until", "the", "given", "target", "time", "then", "fast", "-", "forwards", "to", "that", "time" ]
a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/shreduler.rb#L57-L69
train
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.validate_syntax
def validate_syntax update_native validator = Bitcoin::Validation::Tx.new(@native, nil) valid = validator.validate :rules => [:syntax] {:valid => valid, :error => validator.error} end
ruby
def validate_syntax update_native validator = Bitcoin::Validation::Tx.new(@native, nil) valid = validator.validate :rules => [:syntax] {:valid => valid, :error => validator.error} end
[ "def", "validate_syntax", "update_native", "validator", "=", "Bitcoin", "::", "Validation", "::", "Tx", ".", "new", "(", "@native", ",", "nil", ")", "valid", "=", "validator", ".", "validate", ":rules", "=>", "[", ":syntax", "]", "{", ":valid", "=>", "valid", ",", ":error", "=>", "validator", ".", "error", "}", "end" ]
Validate that the transaction is plausibly signable.
[ "Validate", "that", "the", "transaction", "is", "plausibly", "signable", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L131-L136
train
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.validate_script_sigs
def validate_script_sigs bad_inputs = [] valid = true @inputs.each_with_index do |input, index| # TODO: confirm whether we need to mess with the block_timestamp arg unless self.native.verify_input_signature(index, input.output.transaction.native) valid = false bad_inputs << index end end {:valid => valid, :inputs => bad_inputs} end
ruby
def validate_script_sigs bad_inputs = [] valid = true @inputs.each_with_index do |input, index| # TODO: confirm whether we need to mess with the block_timestamp arg unless self.native.verify_input_signature(index, input.output.transaction.native) valid = false bad_inputs << index end end {:valid => valid, :inputs => bad_inputs} end
[ "def", "validate_script_sigs", "bad_inputs", "=", "[", "]", "valid", "=", "true", "@inputs", ".", "each_with_index", "do", "|", "input", ",", "index", "|", "unless", "self", ".", "native", ".", "verify_input_signature", "(", "index", ",", "input", ".", "output", ".", "transaction", ".", "native", ")", "valid", "=", "false", "bad_inputs", "<<", "index", "end", "end", "{", ":valid", "=>", "valid", ",", ":inputs", "=>", "bad_inputs", "}", "end" ]
Verify that the script_sigs for all inputs are valid.
[ "Verify", "that", "the", "script_sigs", "for", "all", "inputs", "are", "valid", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L139-L151
train
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.add_input
def add_input(input, network: @network) # TODO: allow specifying prev_tx and index with a Hash. # Possibly stop using SparseInput. input = Input.new(input.merge(transaction: self, index: @inputs.size, network: network) ) unless input.is_a?(Input) @inputs << input self.update_native do |native| native.add_in input.native end input end
ruby
def add_input(input, network: @network) # TODO: allow specifying prev_tx and index with a Hash. # Possibly stop using SparseInput. input = Input.new(input.merge(transaction: self, index: @inputs.size, network: network) ) unless input.is_a?(Input) @inputs << input self.update_native do |native| native.add_in input.native end input end
[ "def", "add_input", "(", "input", ",", "network", ":", "@network", ")", "input", "=", "Input", ".", "new", "(", "input", ".", "merge", "(", "transaction", ":", "self", ",", "index", ":", "@inputs", ".", "size", ",", "network", ":", "network", ")", ")", "unless", "input", ".", "is_a?", "(", "Input", ")", "@inputs", "<<", "input", "self", ".", "update_native", "do", "|", "native", "|", "native", ".", "add_in", "input", ".", "native", "end", "input", "end" ]
Takes one of * an instance of Input * an instance of Output * a Hash describing an Output
[ "Takes", "one", "of" ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L159-L173
train
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.add_output
def add_output(output, network: @network) if output.is_a?(Output) output.set_transaction(self, @outputs.size) else output = Output.new(output.merge(transaction: self, index: @outputs.size), network: network) end @outputs << output self.update_native do |native| native.add_out(output.native) end end
ruby
def add_output(output, network: @network) if output.is_a?(Output) output.set_transaction(self, @outputs.size) else output = Output.new(output.merge(transaction: self, index: @outputs.size), network: network) end @outputs << output self.update_native do |native| native.add_out(output.native) end end
[ "def", "add_output", "(", "output", ",", "network", ":", "@network", ")", "if", "output", ".", "is_a?", "(", "Output", ")", "output", ".", "set_transaction", "(", "self", ",", "@outputs", ".", "size", ")", "else", "output", "=", "Output", ".", "new", "(", "output", ".", "merge", "(", "transaction", ":", "self", ",", "index", ":", "@outputs", ".", "size", ")", ",", "network", ":", "network", ")", "end", "@outputs", "<<", "output", "self", ".", "update_native", "do", "|", "native", "|", "native", ".", "add_out", "(", "output", ".", "native", ")", "end", "end" ]
Takes either an Output or a Hash describing an output.
[ "Takes", "either", "an", "Output", "or", "a", "Hash", "describing", "an", "output", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L176-L189
train
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.set_script_sigs
def set_script_sigs(*input_args, &block) # No sense trying to authorize when the transaction isn't usable. report = validate_syntax unless report[:valid] == true raise "Invalid syntax: #{report[:errors].to_json}" end # Array#zip here allows us to iterate over the inputs in lockstep with any # number of sets of values. self.inputs.zip(*input_args) do |input, *input_arg| input.script_sig = yield input, *input_arg end end
ruby
def set_script_sigs(*input_args, &block) # No sense trying to authorize when the transaction isn't usable. report = validate_syntax unless report[:valid] == true raise "Invalid syntax: #{report[:errors].to_json}" end # Array#zip here allows us to iterate over the inputs in lockstep with any # number of sets of values. self.inputs.zip(*input_args) do |input, *input_arg| input.script_sig = yield input, *input_arg end end
[ "def", "set_script_sigs", "(", "*", "input_args", ",", "&", "block", ")", "report", "=", "validate_syntax", "unless", "report", "[", ":valid", "]", "==", "true", "raise", "\"Invalid syntax: #{report[:errors].to_json}\"", "end", "self", ".", "inputs", ".", "zip", "(", "*", "input_args", ")", "do", "|", "input", ",", "*", "input_arg", "|", "input", ".", "script_sig", "=", "yield", "input", ",", "*", "input_arg", "end", "end" ]
A convenience method for authorizing inputs in a generic manner. Rather than iterating over the inputs manually, the user can provide this method with an array of values and a block that knows what to do with the values. For example, if you happen to have the script sigs precomputed for some strange reason, you could do this: tx.set_script_sigs sig_array do |input, sig| sig end More realistically, if you have an array of the keypairs corresponding to the inputs: tx.set_script_sigs keys do |input, key| sig_hash = tx.sig_hash(input) key.sign(sig_hash) end Each element of the array may be an array, which allows for easy handling of multisig situations.
[ "A", "convenience", "method", "for", "authorizing", "inputs", "in", "a", "generic", "manner", ".", "Rather", "than", "iterating", "over", "the", "inputs", "manually", "the", "user", "can", "provide", "this", "method", "with", "an", "array", "of", "values", "and", "a", "block", "that", "knows", "what", "to", "do", "with", "the", "values", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L276-L288
train
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.input_value_for
def input_value_for(addresses) own = inputs.select { |input| addresses.include?(input.output.address) } own.inject(0) { |sum, input| input.output.value } end
ruby
def input_value_for(addresses) own = inputs.select { |input| addresses.include?(input.output.address) } own.inject(0) { |sum, input| input.output.value } end
[ "def", "input_value_for", "(", "addresses", ")", "own", "=", "inputs", ".", "select", "{", "|", "input", "|", "addresses", ".", "include?", "(", "input", ".", "output", ".", "address", ")", "}", "own", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "input", "|", "input", ".", "output", ".", "value", "}", "end" ]
Takes a set of Bitcoin addresses and returns the value expressed in the inputs for this transaction.
[ "Takes", "a", "set", "of", "Bitcoin", "addresses", "and", "returns", "the", "value", "expressed", "in", "the", "inputs", "for", "this", "transaction", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L339-L342
train
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.output_value_for
def output_value_for(addresses) own = outputs.select { |output| addresses.include?(output.address) } own.inject(0) { |sum, output| output.value } end
ruby
def output_value_for(addresses) own = outputs.select { |output| addresses.include?(output.address) } own.inject(0) { |sum, output| output.value } end
[ "def", "output_value_for", "(", "addresses", ")", "own", "=", "outputs", ".", "select", "{", "|", "output", "|", "addresses", ".", "include?", "(", "output", ".", "address", ")", "}", "own", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "output", "|", "output", ".", "value", "}", "end" ]
Takes a set of Bitcoin addresses and returns the value expressed in the outputs for this transaction.
[ "Takes", "a", "set", "of", "Bitcoin", "addresses", "and", "returns", "the", "value", "expressed", "in", "the", "outputs", "for", "this", "transaction", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L346-L349
train
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.add_change
def add_change(address, metadata={}) add_output( value: change_value, address: address, metadata: {memo: "change"}.merge(metadata) ) end
ruby
def add_change(address, metadata={}) add_output( value: change_value, address: address, metadata: {memo: "change"}.merge(metadata) ) end
[ "def", "add_change", "(", "address", ",", "metadata", "=", "{", "}", ")", "add_output", "(", "value", ":", "change_value", ",", "address", ":", "address", ",", "metadata", ":", "{", "memo", ":", "\"change\"", "}", ".", "merge", "(", "metadata", ")", ")", "end" ]
Add an output to receive change for this transaction. Takes a bitcoin address and optional metadata Hash.
[ "Add", "an", "output", "to", "receive", "change", "for", "this", "transaction", ".", "Takes", "a", "bitcoin", "address", "and", "optional", "metadata", "Hash", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L358-L364
train
Dev-Crea/swagger-docs-generator
lib/swagger_docs_generator/extractor.rb
SwaggerDocsGenerator.Extractor.path
def path temporary = [] actual_route = nil router do |route| actual_route = extract_and_format_route(route) temporary.push(actual_route) unless temporary.include?(actual_route) actual_route end temporary end
ruby
def path temporary = [] actual_route = nil router do |route| actual_route = extract_and_format_route(route) temporary.push(actual_route) unless temporary.include?(actual_route) actual_route end temporary end
[ "def", "path", "temporary", "=", "[", "]", "actual_route", "=", "nil", "router", "do", "|", "route", "|", "actual_route", "=", "extract_and_format_route", "(", "route", ")", "temporary", ".", "push", "(", "actual_route", ")", "unless", "temporary", ".", "include?", "(", "actual_route", ")", "actual_route", "end", "temporary", "end" ]
Extract path to routes and change format to parameter path
[ "Extract", "path", "to", "routes", "and", "change", "format", "to", "parameter", "path" ]
5d3de176aa1119cb38100b451bee028d66c0809d
https://github.com/Dev-Crea/swagger-docs-generator/blob/5d3de176aa1119cb38100b451bee028d66c0809d/lib/swagger_docs_generator/extractor.rb#L26-L35
train
satchmorun/tst
lib/tst.rb
Tst.Assertions.assert_raises
def assert_raises(expected=StandardError) begin yield rescue => actual return actual if actual.kind_of?(expected) raise Failure.new("Failure: Unexpected Exception", expected, actual) end raise Failure.new("Failure: No Exception", expected, "Nothing raised.") end
ruby
def assert_raises(expected=StandardError) begin yield rescue => actual return actual if actual.kind_of?(expected) raise Failure.new("Failure: Unexpected Exception", expected, actual) end raise Failure.new("Failure: No Exception", expected, "Nothing raised.") end
[ "def", "assert_raises", "(", "expected", "=", "StandardError", ")", "begin", "yield", "rescue", "=>", "actual", "return", "actual", "if", "actual", ".", "kind_of?", "(", "expected", ")", "raise", "Failure", ".", "new", "(", "\"Failure: Unexpected Exception\"", ",", "expected", ",", "actual", ")", "end", "raise", "Failure", ".", "new", "(", "\"Failure: No Exception\"", ",", "expected", ",", "\"Nothing raised.\"", ")", "end" ]
Succeeds if it catches an error AND that error is a `kind_of?` the `expected` error. Fails otherwise.
[ "Succeeds", "if", "it", "catches", "an", "error", "AND", "that", "error", "is", "a", "kind_of?", "the", "expected", "error", ".", "Fails", "otherwise", "." ]
78bb3c034278eefb0db41e62e1e93b67735216a7
https://github.com/satchmorun/tst/blob/78bb3c034278eefb0db41e62e1e93b67735216a7/lib/tst.rb#L35-L43
train
satchmorun/tst
lib/tst.rb
Tst.Runner.tst
def tst(name, &block) start = Time.now block.call status = SUCCEEDED rescue Failure => exception status = FAILED rescue StandardError => exception status = RAISED ensure elapsed = Time.now - start __record(name, status, elapsed, exception) end
ruby
def tst(name, &block) start = Time.now block.call status = SUCCEEDED rescue Failure => exception status = FAILED rescue StandardError => exception status = RAISED ensure elapsed = Time.now - start __record(name, status, elapsed, exception) end
[ "def", "tst", "(", "name", ",", "&", "block", ")", "start", "=", "Time", ".", "now", "block", ".", "call", "status", "=", "SUCCEEDED", "rescue", "Failure", "=>", "exception", "status", "=", "FAILED", "rescue", "StandardError", "=>", "exception", "status", "=", "RAISED", "ensure", "elapsed", "=", "Time", ".", "now", "-", "start", "__record", "(", "name", ",", "status", ",", "elapsed", ",", "exception", ")", "end" ]
The `tst` methods itself. Takes a `name` and a block. Runs the block. Records the result.
[ "The", "tst", "methods", "itself", ".", "Takes", "a", "name", "and", "a", "block", ".", "Runs", "the", "block", ".", "Records", "the", "result", "." ]
78bb3c034278eefb0db41e62e1e93b67735216a7
https://github.com/satchmorun/tst/blob/78bb3c034278eefb0db41e62e1e93b67735216a7/lib/tst.rb#L99-L110
train
jinx/core
lib/jinx/metadata/propertied.rb
Jinx.Propertied.add_attribute
def add_attribute(attribute, type, *flags) prop = create_nonjava_property(attribute, type, *flags) add_property(prop) prop end
ruby
def add_attribute(attribute, type, *flags) prop = create_nonjava_property(attribute, type, *flags) add_property(prop) prop end
[ "def", "add_attribute", "(", "attribute", ",", "type", ",", "*", "flags", ")", "prop", "=", "create_nonjava_property", "(", "attribute", ",", "type", ",", "*", "flags", ")", "add_property", "(", "prop", ")", "prop", "end" ]
Adds the given attribute to this Class. @param [Symbol] attribute the attribute to add @param [Class] type (see Property#initialize) @param flags (see Property#initialize) @return [Property] the attribute meta-data
[ "Adds", "the", "given", "attribute", "to", "this", "Class", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/propertied.rb#L30-L34
train
jinx/core
lib/jinx/metadata/propertied.rb
Jinx.Propertied.init_property_classifiers
def init_property_classifiers @local_std_prop_hash = {} @alias_std_prop_map = append_ancestor_enum(@local_std_prop_hash) { |par| par.alias_standard_attribute_hash } @local_prop_hash = {} @prop_hash = append_ancestor_enum(@local_prop_hash) { |par| par.property_hash } @attributes = Enumerable::Enumerator.new(@prop_hash, :each_key) @local_mndty_attrs = Set.new @local_defaults = {} @defaults = append_ancestor_enum(@local_defaults) { |par| par.defaults } end
ruby
def init_property_classifiers @local_std_prop_hash = {} @alias_std_prop_map = append_ancestor_enum(@local_std_prop_hash) { |par| par.alias_standard_attribute_hash } @local_prop_hash = {} @prop_hash = append_ancestor_enum(@local_prop_hash) { |par| par.property_hash } @attributes = Enumerable::Enumerator.new(@prop_hash, :each_key) @local_mndty_attrs = Set.new @local_defaults = {} @defaults = append_ancestor_enum(@local_defaults) { |par| par.defaults } end
[ "def", "init_property_classifiers", "@local_std_prop_hash", "=", "{", "}", "@alias_std_prop_map", "=", "append_ancestor_enum", "(", "@local_std_prop_hash", ")", "{", "|", "par", "|", "par", ".", "alias_standard_attribute_hash", "}", "@local_prop_hash", "=", "{", "}", "@prop_hash", "=", "append_ancestor_enum", "(", "@local_prop_hash", ")", "{", "|", "par", "|", "par", ".", "property_hash", "}", "@attributes", "=", "Enumerable", "::", "Enumerator", ".", "new", "(", "@prop_hash", ",", ":each_key", ")", "@local_mndty_attrs", "=", "Set", ".", "new", "@local_defaults", "=", "{", "}", "@defaults", "=", "append_ancestor_enum", "(", "@local_defaults", ")", "{", "|", "par", "|", "par", ".", "defaults", "}", "end" ]
Initializes the property meta-data structures.
[ "Initializes", "the", "property", "meta", "-", "data", "structures", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/propertied.rb#L259-L268
train
jinx/core
lib/jinx/metadata/propertied.rb
Jinx.Propertied.compose_property
def compose_property(property, other) if other.inverse.nil? then raise ArgumentError.new("Can't compose #{qp}.#{property} with inverseless #{other.declarer.qp}.#{other}") end # the source -> intermediary access methods sir, siw = property.accessors # the intermediary -> target access methods itr, itw = other.accessors # the target -> intermediary reader method tir = other.inverse # The reader composes the source -> intermediary -> target readers. define_method(itr) do ref = send(sir) ref.send(itr) if ref end # The writer sets the source intermediary to the target intermediary. define_method(itw) do |tgt| if tgt then ref = block_given? ? yield(tgt) : tgt.send(tir) raise ArgumentError.new("#{tgt} does not reference a #{other.inverse}") if ref.nil? end send(siw, ref) end prop = add_attribute(itr, other.type) logger.debug { "Created #{qp}.#{prop} which composes #{qp}.#{property} and #{other.declarer.qp}.#{other}." } prop.qualify(:collection) if other.collection? prop end
ruby
def compose_property(property, other) if other.inverse.nil? then raise ArgumentError.new("Can't compose #{qp}.#{property} with inverseless #{other.declarer.qp}.#{other}") end # the source -> intermediary access methods sir, siw = property.accessors # the intermediary -> target access methods itr, itw = other.accessors # the target -> intermediary reader method tir = other.inverse # The reader composes the source -> intermediary -> target readers. define_method(itr) do ref = send(sir) ref.send(itr) if ref end # The writer sets the source intermediary to the target intermediary. define_method(itw) do |tgt| if tgt then ref = block_given? ? yield(tgt) : tgt.send(tir) raise ArgumentError.new("#{tgt} does not reference a #{other.inverse}") if ref.nil? end send(siw, ref) end prop = add_attribute(itr, other.type) logger.debug { "Created #{qp}.#{prop} which composes #{qp}.#{property} and #{other.declarer.qp}.#{other}." } prop.qualify(:collection) if other.collection? prop end
[ "def", "compose_property", "(", "property", ",", "other", ")", "if", "other", ".", "inverse", ".", "nil?", "then", "raise", "ArgumentError", ".", "new", "(", "\"Can't compose #{qp}.#{property} with inverseless #{other.declarer.qp}.#{other}\"", ")", "end", "sir", ",", "siw", "=", "property", ".", "accessors", "itr", ",", "itw", "=", "other", ".", "accessors", "tir", "=", "other", ".", "inverse", "define_method", "(", "itr", ")", "do", "ref", "=", "send", "(", "sir", ")", "ref", ".", "send", "(", "itr", ")", "if", "ref", "end", "define_method", "(", "itw", ")", "do", "|", "tgt", "|", "if", "tgt", "then", "ref", "=", "block_given?", "?", "yield", "(", "tgt", ")", ":", "tgt", ".", "send", "(", "tir", ")", "raise", "ArgumentError", ".", "new", "(", "\"#{tgt} does not reference a #{other.inverse}\"", ")", "if", "ref", ".", "nil?", "end", "send", "(", "siw", ",", "ref", ")", "end", "prop", "=", "add_attribute", "(", "itr", ",", "other", ".", "type", ")", "logger", ".", "debug", "{", "\"Created #{qp}.#{prop} which composes #{qp}.#{property} and #{other.declarer.qp}.#{other}.\"", "}", "prop", ".", "qualify", "(", ":collection", ")", "if", "other", ".", "collection?", "prop", "end" ]
Creates a new convenience property in this source class which composes the given property and the other property. The new property symbol is the same as the other property symbol. The new property reader and writer methods delegate to the respective composed property reader and writer methods. @param [Property] property the reference from the source to the intermediary @param [Property] other the reference from the intermediary to the target @yield [target] obtain the intermediary object from the target @yieldparam [Resource] target the target object @return [Property] the new property @raise [ArgumentError] if the other property does not have an inverse
[ "Creates", "a", "new", "convenience", "property", "in", "this", "source", "class", "which", "composes", "the", "given", "property", "and", "the", "other", "property", ".", "The", "new", "property", "symbol", "is", "the", "same", "as", "the", "other", "property", "symbol", ".", "The", "new", "property", "reader", "and", "writer", "methods", "delegate", "to", "the", "respective", "composed", "property", "reader", "and", "writer", "methods", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/propertied.rb#L282-L309
train
jinx/core
lib/jinx/metadata/propertied.rb
Jinx.Propertied.most_specific_domain_attribute
def most_specific_domain_attribute(klass, attributes=nil) attributes ||= domain_attributes candidates = attributes.properties best = candidates.inject(nil) do |better, prop| # If the attribute can return the klass then the return type is a candidate. # In that case, the klass replaces the best candidate if it is more specific than # the best candidate so far. klass <= prop.type ? (better && better.type <= prop.type ? better : prop) : better end if best then logger.debug { "Most specific #{qp} -> #{klass.qp} reference from among #{candidates.qp} is #{best.declarer.qp}.#{best}." } best.to_sym end end
ruby
def most_specific_domain_attribute(klass, attributes=nil) attributes ||= domain_attributes candidates = attributes.properties best = candidates.inject(nil) do |better, prop| # If the attribute can return the klass then the return type is a candidate. # In that case, the klass replaces the best candidate if it is more specific than # the best candidate so far. klass <= prop.type ? (better && better.type <= prop.type ? better : prop) : better end if best then logger.debug { "Most specific #{qp} -> #{klass.qp} reference from among #{candidates.qp} is #{best.declarer.qp}.#{best}." } best.to_sym end end
[ "def", "most_specific_domain_attribute", "(", "klass", ",", "attributes", "=", "nil", ")", "attributes", "||=", "domain_attributes", "candidates", "=", "attributes", ".", "properties", "best", "=", "candidates", ".", "inject", "(", "nil", ")", "do", "|", "better", ",", "prop", "|", "klass", "<=", "prop", ".", "type", "?", "(", "better", "&&", "better", ".", "type", "<=", "prop", ".", "type", "?", "better", ":", "prop", ")", ":", "better", "end", "if", "best", "then", "logger", ".", "debug", "{", "\"Most specific #{qp} -> #{klass.qp} reference from among #{candidates.qp} is #{best.declarer.qp}.#{best}.\"", "}", "best", ".", "to_sym", "end", "end" ]
Returns the most specific attribute which references the given target type, or nil if none. If the given class can be returned by more than on of the attributes, then the attribute is chosen whose return type most closely matches the given class. @param [Class] klass the target type @param [AttributeEnumerator, nil] attributes the attributes to check (default all domain attributes) @return [Symbol, nil] the most specific reference attribute, or nil if none
[ "Returns", "the", "most", "specific", "attribute", "which", "references", "the", "given", "target", "type", "or", "nil", "if", "none", ".", "If", "the", "given", "class", "can", "be", "returned", "by", "more", "than", "on", "of", "the", "attributes", "then", "the", "attribute", "is", "chosen", "whose", "return", "type", "most", "closely", "matches", "the", "given", "class", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/propertied.rb#L324-L337
train
jinx/core
lib/jinx/metadata/propertied.rb
Jinx.Propertied.set_attribute_type
def set_attribute_type(attribute, klass) prop = property(attribute) # degenerate no-op case return if klass == prop.type # If this class is the declarer, then simply set the attribute type. # Otherwise, if the attribute type is unspecified or is a superclass of the given class, # then make a new attribute metadata for this class. if prop.declarer == self then prop.type = klass logger.debug { "Set #{qp}.#{attribute} type to #{klass.qp}." } elsif prop.type.nil? or klass < prop.type then prop.restrict(self, :type => klass) logger.debug { "Restricted #{prop.declarer.qp}.#{attribute}(#{prop.type.qp}) to #{qp} with return type #{klass.qp}." } else raise ArgumentError.new("Cannot reset #{qp}.#{attribute} type #{prop.type.qp} to incompatible #{klass.qp}") end end
ruby
def set_attribute_type(attribute, klass) prop = property(attribute) # degenerate no-op case return if klass == prop.type # If this class is the declarer, then simply set the attribute type. # Otherwise, if the attribute type is unspecified or is a superclass of the given class, # then make a new attribute metadata for this class. if prop.declarer == self then prop.type = klass logger.debug { "Set #{qp}.#{attribute} type to #{klass.qp}." } elsif prop.type.nil? or klass < prop.type then prop.restrict(self, :type => klass) logger.debug { "Restricted #{prop.declarer.qp}.#{attribute}(#{prop.type.qp}) to #{qp} with return type #{klass.qp}." } else raise ArgumentError.new("Cannot reset #{qp}.#{attribute} type #{prop.type.qp} to incompatible #{klass.qp}") end end
[ "def", "set_attribute_type", "(", "attribute", ",", "klass", ")", "prop", "=", "property", "(", "attribute", ")", "return", "if", "klass", "==", "prop", ".", "type", "if", "prop", ".", "declarer", "==", "self", "then", "prop", ".", "type", "=", "klass", "logger", ".", "debug", "{", "\"Set #{qp}.#{attribute} type to #{klass.qp}.\"", "}", "elsif", "prop", ".", "type", ".", "nil?", "or", "klass", "<", "prop", ".", "type", "then", "prop", ".", "restrict", "(", "self", ",", ":type", "=>", "klass", ")", "logger", ".", "debug", "{", "\"Restricted #{prop.declarer.qp}.#{attribute}(#{prop.type.qp}) to #{qp} with return type #{klass.qp}.\"", "}", "else", "raise", "ArgumentError", ".", "new", "(", "\"Cannot reset #{qp}.#{attribute} type #{prop.type.qp} to incompatible #{klass.qp}\"", ")", "end", "end" ]
Sets the given attribute type to klass. If attribute is defined in a superclass, then klass must be a subclass of the superclass attribute type. @param [Symbol] attribute the attribute to modify @param [Class] klass the attribute type @raise [ArgumentError] if the new type is incompatible with the current attribute type
[ "Sets", "the", "given", "attribute", "type", "to", "klass", ".", "If", "attribute", "is", "defined", "in", "a", "superclass", "then", "klass", "must", "be", "a", "subclass", "of", "the", "superclass", "attribute", "type", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/propertied.rb#L409-L425
train
jinx/core
lib/jinx/metadata/propertied.rb
Jinx.Propertied.remove_attribute
def remove_attribute(attribute) sa = standard_attribute(attribute) # if the attribute is local, then delete it, otherwise filter out the superclass attribute sp = @local_prop_hash.delete(sa) if sp then # clear the inverse, if any clear_inverse(sp) # remove from the mandatory attributes, if necessary @local_mndty_attrs.delete(sa) # remove from the attribute => metadata hash @local_std_prop_hash.delete_if { |aliaz, pa| pa == sa } else # Filter the superclass hashes. anc_prop_hash = @prop_hash.components[1] @prop_hash.components[1] = anc_prop_hash.filter_on_key { |pa| pa != attribute } anc_alias_hash = @alias_std_prop_map.components[1] @alias_std_prop_map.components[1] = anc_alias_hash.filter_on_key { |pa| pa != attribute } end logger.debug { "Removed the #{qp} #{attribute} property." } end
ruby
def remove_attribute(attribute) sa = standard_attribute(attribute) # if the attribute is local, then delete it, otherwise filter out the superclass attribute sp = @local_prop_hash.delete(sa) if sp then # clear the inverse, if any clear_inverse(sp) # remove from the mandatory attributes, if necessary @local_mndty_attrs.delete(sa) # remove from the attribute => metadata hash @local_std_prop_hash.delete_if { |aliaz, pa| pa == sa } else # Filter the superclass hashes. anc_prop_hash = @prop_hash.components[1] @prop_hash.components[1] = anc_prop_hash.filter_on_key { |pa| pa != attribute } anc_alias_hash = @alias_std_prop_map.components[1] @alias_std_prop_map.components[1] = anc_alias_hash.filter_on_key { |pa| pa != attribute } end logger.debug { "Removed the #{qp} #{attribute} property." } end
[ "def", "remove_attribute", "(", "attribute", ")", "sa", "=", "standard_attribute", "(", "attribute", ")", "sp", "=", "@local_prop_hash", ".", "delete", "(", "sa", ")", "if", "sp", "then", "clear_inverse", "(", "sp", ")", "@local_mndty_attrs", ".", "delete", "(", "sa", ")", "@local_std_prop_hash", ".", "delete_if", "{", "|", "aliaz", ",", "pa", "|", "pa", "==", "sa", "}", "else", "anc_prop_hash", "=", "@prop_hash", ".", "components", "[", "1", "]", "@prop_hash", ".", "components", "[", "1", "]", "=", "anc_prop_hash", ".", "filter_on_key", "{", "|", "pa", "|", "pa", "!=", "attribute", "}", "anc_alias_hash", "=", "@alias_std_prop_map", ".", "components", "[", "1", "]", "@alias_std_prop_map", ".", "components", "[", "1", "]", "=", "anc_alias_hash", ".", "filter_on_key", "{", "|", "pa", "|", "pa", "!=", "attribute", "}", "end", "logger", ".", "debug", "{", "\"Removed the #{qp} #{attribute} property.\"", "}", "end" ]
Removes the given attribute from this Resource. An attribute declared in a superclass Resource is hidden from this Resource but retained in the declaring Resource.
[ "Removes", "the", "given", "attribute", "from", "this", "Resource", ".", "An", "attribute", "declared", "in", "a", "superclass", "Resource", "is", "hidden", "from", "this", "Resource", "but", "retained", "in", "the", "declaring", "Resource", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/propertied.rb#L472-L491
train
jinx/core
lib/jinx/metadata/propertied.rb
Jinx.Propertied.register_property_alias
def register_property_alias(aliaz, attribute) std = standard_attribute(attribute) raise ArgumentError.new("#{self} attribute not found: #{attribute}") if std.nil? @local_std_prop_hash[aliaz.to_sym] = std end
ruby
def register_property_alias(aliaz, attribute) std = standard_attribute(attribute) raise ArgumentError.new("#{self} attribute not found: #{attribute}") if std.nil? @local_std_prop_hash[aliaz.to_sym] = std end
[ "def", "register_property_alias", "(", "aliaz", ",", "attribute", ")", "std", "=", "standard_attribute", "(", "attribute", ")", "raise", "ArgumentError", ".", "new", "(", "\"#{self} attribute not found: #{attribute}\"", ")", "if", "std", ".", "nil?", "@local_std_prop_hash", "[", "aliaz", ".", "to_sym", "]", "=", "std", "end" ]
Registers an alias to an attribute. @param (see #alias_attribute)
[ "Registers", "an", "alias", "to", "an", "attribute", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/propertied.rb#L508-L512
train
hinrik/ircsupport
lib/ircsupport/formatting.rb
IRCSupport.Formatting.strip_color!
def strip_color!(string) [@@mirc_color, @@rgb_color, @@ecma48_color].each do |pattern| string.gsub!(pattern, '') end # strip cancellation codes too if there are no formatting codes string.gsub!(@@normal) if !has_color?(string) return string end
ruby
def strip_color!(string) [@@mirc_color, @@rgb_color, @@ecma48_color].each do |pattern| string.gsub!(pattern, '') end # strip cancellation codes too if there are no formatting codes string.gsub!(@@normal) if !has_color?(string) return string end
[ "def", "strip_color!", "(", "string", ")", "[", "@@mirc_color", ",", "@@rgb_color", ",", "@@ecma48_color", "]", ".", "each", "do", "|", "pattern", "|", "string", ".", "gsub!", "(", "pattern", ",", "''", ")", "end", "string", ".", "gsub!", "(", "@@normal", ")", "if", "!", "has_color?", "(", "string", ")", "return", "string", "end" ]
Strip IRC color codes from a string, modifying it in place. @param [String] string The string you want to strip. @return [String] A string stripped of all IRC color codes.
[ "Strip", "IRC", "color", "codes", "from", "a", "string", "modifying", "it", "in", "place", "." ]
d028b7d5ccc604a6af175ee2264c18d25b1f7dff
https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/formatting.rb#L71-L78
train
michaeljklein/nil-passer
lib/gen/code.rb
Gen.Gen::Code.generate_binding
def generate_binding(a_binding=binding) a_binding.local_variables do |local_var| a_binding.local_variable_set local_var, nil end @bound_procs.each_with_index do |bound_proc, index| a_binding.local_variable_set "proc_#{index}", bound_proc end @bound_constants.each_with_index do |bound_const, index| a_binding.local_variable_set "const_#{index}", bound_const end a_binding end
ruby
def generate_binding(a_binding=binding) a_binding.local_variables do |local_var| a_binding.local_variable_set local_var, nil end @bound_procs.each_with_index do |bound_proc, index| a_binding.local_variable_set "proc_#{index}", bound_proc end @bound_constants.each_with_index do |bound_const, index| a_binding.local_variable_set "const_#{index}", bound_const end a_binding end
[ "def", "generate_binding", "(", "a_binding", "=", "binding", ")", "a_binding", ".", "local_variables", "do", "|", "local_var", "|", "a_binding", ".", "local_variable_set", "local_var", ",", "nil", "end", "@bound_procs", ".", "each_with_index", "do", "|", "bound_proc", ",", "index", "|", "a_binding", ".", "local_variable_set", "\"proc_#{index}\"", ",", "bound_proc", "end", "@bound_constants", ".", "each_with_index", "do", "|", "bound_const", ",", "index", "|", "a_binding", ".", "local_variable_set", "\"const_#{index}\"", ",", "bound_const", "end", "a_binding", "end" ]
Generate a binding containing the locally bound procs and constants
[ "Generate", "a", "binding", "containing", "the", "locally", "bound", "procs", "and", "constants" ]
ec7b9beface13054d9fa82374d860e03dcb17635
https://github.com/michaeljklein/nil-passer/blob/ec7b9beface13054d9fa82374d860e03dcb17635/lib/gen/code.rb#L30-L41
train
KatanaCode/evvnt
lib/evvnt/persistence.rb
Evvnt.Persistence.save_as_new_record
def save_as_new_record new_attributes = attributes.reject { |k, _v| k.to_s =~ /^(id|uuid)$/ } self.class.create(new_attributes) end
ruby
def save_as_new_record new_attributes = attributes.reject { |k, _v| k.to_s =~ /^(id|uuid)$/ } self.class.create(new_attributes) end
[ "def", "save_as_new_record", "new_attributes", "=", "attributes", ".", "reject", "{", "|", "k", ",", "_v", "|", "k", ".", "to_s", "=~", "/", "/", "}", "self", ".", "class", ".", "create", "(", "new_attributes", ")", "end" ]
Save this record to the EVVNT API as a new record using the +create+ action.
[ "Save", "this", "record", "to", "the", "EVVNT", "API", "as", "a", "new", "record", "using", "the", "+", "create", "+", "action", "." ]
e13f6d84af09a71819356620fb25685a6cd159c9
https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/persistence.rb#L29-L32
train
KatanaCode/evvnt
lib/evvnt/persistence.rb
Evvnt.Persistence.save_as_persisted_record
def save_as_persisted_record new_attributes = attributes.reject { |k, _v| k.to_s =~ /^(id|uuid)$/ } self.class.update(id, new_attributes) end
ruby
def save_as_persisted_record new_attributes = attributes.reject { |k, _v| k.to_s =~ /^(id|uuid)$/ } self.class.update(id, new_attributes) end
[ "def", "save_as_persisted_record", "new_attributes", "=", "attributes", ".", "reject", "{", "|", "k", ",", "_v", "|", "k", ".", "to_s", "=~", "/", "/", "}", "self", ".", "class", ".", "update", "(", "id", ",", "new_attributes", ")", "end" ]
Save this record to the EVVNT API as an existing record using the +update+ action.
[ "Save", "this", "record", "to", "the", "EVVNT", "API", "as", "an", "existing", "record", "using", "the", "+", "update", "+", "action", "." ]
e13f6d84af09a71819356620fb25685a6cd159c9
https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/persistence.rb#L36-L39
train
kevinjalbert/godville_kit
lib/godville_kit/api_requester.rb
GodvilleKit.APIRequester.request_raw_hero_data
def request_raw_hero_data return unless authenticated? response = RestClient.get( "https://godvillegame.com/fbh/feed?a=#{@hero_guid}", cookies: @cookies, content_type: :json, accept: :json ) JSON.parse(response) end
ruby
def request_raw_hero_data return unless authenticated? response = RestClient.get( "https://godvillegame.com/fbh/feed?a=#{@hero_guid}", cookies: @cookies, content_type: :json, accept: :json ) JSON.parse(response) end
[ "def", "request_raw_hero_data", "return", "unless", "authenticated?", "response", "=", "RestClient", ".", "get", "(", "\"https://godvillegame.com/fbh/feed?a=#{@hero_guid}\"", ",", "cookies", ":", "@cookies", ",", "content_type", ":", ":json", ",", "accept", ":", ":json", ")", "JSON", ".", "parse", "(", "response", ")", "end" ]
Request the raw hero data from godville
[ "Request", "the", "raw", "hero", "data", "from", "godville" ]
975eb16682f10a278d3c3fff4c7e9c435085b8d1
https://github.com/kevinjalbert/godville_kit/blob/975eb16682f10a278d3c3fff4c7e9c435085b8d1/lib/godville_kit/api_requester.rb#L56-L64
train
riddopic/garcun
lib/garcon/task/obligation.rb
Garcon.Obligation.compare_and_set_state
def compare_and_set_state(next_state, expected_current) # :nodoc: mutex.lock if @state == expected_current @state = next_state true else false end ensure mutex.unlock end
ruby
def compare_and_set_state(next_state, expected_current) # :nodoc: mutex.lock if @state == expected_current @state = next_state true else false end ensure mutex.unlock end
[ "def", "compare_and_set_state", "(", "next_state", ",", "expected_current", ")", "mutex", ".", "lock", "if", "@state", "==", "expected_current", "@state", "=", "next_state", "true", "else", "false", "end", "ensure", "mutex", ".", "unlock", "end" ]
Atomic compare and set operation. State is set to `next_state` only if `current state == expected_current`. @param [Symbol] next_state @param [Symbol] expected_current @return [Boolean] TRrue is state is changed, false otherwise @!visibility private
[ "Atomic", "compare", "and", "set", "operation", ".", "State", "is", "set", "to", "next_state", "only", "if", "current", "state", "==", "expected_current", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/obligation.rb#L225-L235
train
riddopic/garcun
lib/garcon/task/obligation.rb
Garcon.Obligation.if_state
def if_state(*expected_states) mutex.lock raise ArgumentError, 'no block given' unless block_given? if expected_states.include? @state yield else false end ensure mutex.unlock end
ruby
def if_state(*expected_states) mutex.lock raise ArgumentError, 'no block given' unless block_given? if expected_states.include? @state yield else false end ensure mutex.unlock end
[ "def", "if_state", "(", "*", "expected_states", ")", "mutex", ".", "lock", "raise", "ArgumentError", ",", "'no block given'", "unless", "block_given?", "if", "expected_states", ".", "include?", "@state", "yield", "else", "false", "end", "ensure", "mutex", ".", "unlock", "end" ]
executes the block within mutex if current state is included in expected_states @return block value if executed, false otherwise @!visibility private
[ "executes", "the", "block", "within", "mutex", "if", "current", "state", "is", "included", "in", "expected_states" ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/obligation.rb#L243-L254
train
rideliner/poly_delegate
lib/poly_delegate/delegator.rb
PolyDelegate.Delegator.method_missing
def method_missing(name, *args, &block) super unless respond_to_missing?(name) # Send self as the delegator @__delegated_object__.__send__(name, self, *args, &block) end
ruby
def method_missing(name, *args, &block) super unless respond_to_missing?(name) # Send self as the delegator @__delegated_object__.__send__(name, self, *args, &block) end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "super", "unless", "respond_to_missing?", "(", "name", ")", "@__delegated_object__", ".", "__send__", "(", "name", ",", "self", ",", "*", "args", ",", "&", "block", ")", "end" ]
Create a wrapper around a delegated object @api public @param obj [Delegated] delegated object Relay methods to `@__delegated_object__` if they exist @api private @raise [NoMethodError] if the delegated object does not respond to the method being called @param name [Symbol] method name @param args [Array<Object>] arguments to method @yield to method call @return result of method call
[ "Create", "a", "wrapper", "around", "a", "delegated", "object" ]
fc704dd8f0f68b3b7c67cc67249ea2161fdb2761
https://github.com/rideliner/poly_delegate/blob/fc704dd8f0f68b3b7c67cc67249ea2161fdb2761/lib/poly_delegate/delegator.rb#L33-L37
train
avdgaag/observatory
lib/observatory/stack.rb
Observatory.Stack.delete
def delete(observer) old_size = @stack.size @stack.delete_if do |o| o[:observer] == observer end old_size == @stack.size ? nil : observer end
ruby
def delete(observer) old_size = @stack.size @stack.delete_if do |o| o[:observer] == observer end old_size == @stack.size ? nil : observer end
[ "def", "delete", "(", "observer", ")", "old_size", "=", "@stack", ".", "size", "@stack", ".", "delete_if", "do", "|", "o", "|", "o", "[", ":observer", "]", "==", "observer", "end", "old_size", "==", "@stack", ".", "size", "?", "nil", ":", "observer", "end" ]
Remove an observer from the stack. @param [#call] observer the callable object that should be removed. @return [#call, nil] the original object or `nil`
[ "Remove", "an", "observer", "from", "the", "stack", "." ]
af8fdb445c42f425067ac97c39fcdbef5ebac73e
https://github.com/avdgaag/observatory/blob/af8fdb445c42f425067ac97c39fcdbef5ebac73e/lib/observatory/stack.rb#L54-L60
train
avdgaag/observatory
lib/observatory/stack.rb
Observatory.Stack.push
def push(observer, priority = nil) raise ArgumentError, 'Observer is not callable' unless observer.respond_to?(:call) raise ArgumentError, 'Priority must be Fixnum' unless priority.nil? || priority.is_a?(Fixnum) @stack.push({ :observer => observer, :priority => (priority || default_priority) }) sort_by_priority observer end
ruby
def push(observer, priority = nil) raise ArgumentError, 'Observer is not callable' unless observer.respond_to?(:call) raise ArgumentError, 'Priority must be Fixnum' unless priority.nil? || priority.is_a?(Fixnum) @stack.push({ :observer => observer, :priority => (priority || default_priority) }) sort_by_priority observer end
[ "def", "push", "(", "observer", ",", "priority", "=", "nil", ")", "raise", "ArgumentError", ",", "'Observer is not callable'", "unless", "observer", ".", "respond_to?", "(", ":call", ")", "raise", "ArgumentError", ",", "'Priority must be Fixnum'", "unless", "priority", ".", "nil?", "||", "priority", ".", "is_a?", "(", "Fixnum", ")", "@stack", ".", "push", "(", "{", ":observer", "=>", "observer", ",", ":priority", "=>", "(", "priority", "||", "default_priority", ")", "}", ")", "sort_by_priority", "observer", "end" ]
Add an element to the stack with an optional priority. @param [#call] observer is the callable object that acts as observer. @param [Fixnum] priority is a number indicating return order. A higher number means lower priority. @return [#call] the original `observer` passed in. @raise `ArgumentError` when not using a `Fixnum` for `priority` @raise `ArgumentError` when not using callable object for `observer`
[ "Add", "an", "element", "to", "the", "stack", "with", "an", "optional", "priority", "." ]
af8fdb445c42f425067ac97c39fcdbef5ebac73e
https://github.com/avdgaag/observatory/blob/af8fdb445c42f425067ac97c39fcdbef5ebac73e/lib/observatory/stack.rb#L70-L77
train
barkerest/incline
lib/incline/validators/safe_name_validator.rb
Incline.SafeNameValidator.validate_each
def validate_each(record, attribute, value) unless value.blank? unless value =~ VALID_MASK if value =~ /\A[^a-z]/i record.errors[attribute] << (options[:message] || 'must start with a letter') elsif value =~ /_\z/ record.errors[attribute] << (options[:message] || 'must not end with an underscore') else record.errors[attribute] << (options[:message] || 'must contain only letters, numbers, and underscore') end end end end
ruby
def validate_each(record, attribute, value) unless value.blank? unless value =~ VALID_MASK if value =~ /\A[^a-z]/i record.errors[attribute] << (options[:message] || 'must start with a letter') elsif value =~ /_\z/ record.errors[attribute] << (options[:message] || 'must not end with an underscore') else record.errors[attribute] << (options[:message] || 'must contain only letters, numbers, and underscore') end end end end
[ "def", "validate_each", "(", "record", ",", "attribute", ",", "value", ")", "unless", "value", ".", "blank?", "unless", "value", "=~", "VALID_MASK", "if", "value", "=~", "/", "\\A", "/i", "record", ".", "errors", "[", "attribute", "]", "<<", "(", "options", "[", ":message", "]", "||", "'must start with a letter'", ")", "elsif", "value", "=~", "/", "\\z", "/", "record", ".", "errors", "[", "attribute", "]", "<<", "(", "options", "[", ":message", "]", "||", "'must not end with an underscore'", ")", "else", "record", ".", "errors", "[", "attribute", "]", "<<", "(", "options", "[", ":message", "]", "||", "'must contain only letters, numbers, and underscore'", ")", "end", "end", "end", "end" ]
Validates attributes to determine if the values match the requirements of a safe name.
[ "Validates", "attributes", "to", "determine", "if", "the", "values", "match", "the", "requirements", "of", "a", "safe", "name", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/validators/safe_name_validator.rb#L16-L28
train
kenjij/kajiki
lib/kajiki/runner.rb
Kajiki.Runner.validate_command
def validate_command(cmd = ARGV) fail 'Specify one action.' unless cmd.count == 1 cmd = cmd.shift fail 'Invalid action.' unless SUB_COMMANDS.include?(cmd) cmd end
ruby
def validate_command(cmd = ARGV) fail 'Specify one action.' unless cmd.count == 1 cmd = cmd.shift fail 'Invalid action.' unless SUB_COMMANDS.include?(cmd) cmd end
[ "def", "validate_command", "(", "cmd", "=", "ARGV", ")", "fail", "'Specify one action.'", "unless", "cmd", ".", "count", "==", "1", "cmd", "=", "cmd", ".", "shift", "fail", "'Invalid action.'", "unless", "SUB_COMMANDS", ".", "include?", "(", "cmd", ")", "cmd", "end" ]
Validate the given command. @param cmd [Array] only one command should be given. @return [String] extracts out of Array
[ "Validate", "the", "given", "command", "." ]
9b036f2741d515e9bfd158571a813987516d89ed
https://github.com/kenjij/kajiki/blob/9b036f2741d515e9bfd158571a813987516d89ed/lib/kajiki/runner.rb#L33-L38
train
kenjij/kajiki
lib/kajiki/runner.rb
Kajiki.Runner.validate_options
def validate_options if @opts[:daemonize] fail 'Must specify PID file.' unless @opts[:pid_given] end @opts[:pid] = File.expand_path(@opts[:pid]) if @opts[:pid_given] @opts[:log] = File.expand_path(@opts[:log]) if @opts[:log_given] @opts[:error] = File.expand_path(@opts[:error]) if @opts[:error_given] @opts[:config] = File.expand_path(@opts[:config]) if @opts[:config_given] end
ruby
def validate_options if @opts[:daemonize] fail 'Must specify PID file.' unless @opts[:pid_given] end @opts[:pid] = File.expand_path(@opts[:pid]) if @opts[:pid_given] @opts[:log] = File.expand_path(@opts[:log]) if @opts[:log_given] @opts[:error] = File.expand_path(@opts[:error]) if @opts[:error_given] @opts[:config] = File.expand_path(@opts[:config]) if @opts[:config_given] end
[ "def", "validate_options", "if", "@opts", "[", ":daemonize", "]", "fail", "'Must specify PID file.'", "unless", "@opts", "[", ":pid_given", "]", "end", "@opts", "[", ":pid", "]", "=", "File", ".", "expand_path", "(", "@opts", "[", ":pid", "]", ")", "if", "@opts", "[", ":pid_given", "]", "@opts", "[", ":log", "]", "=", "File", ".", "expand_path", "(", "@opts", "[", ":log", "]", ")", "if", "@opts", "[", ":log_given", "]", "@opts", "[", ":error", "]", "=", "File", ".", "expand_path", "(", "@opts", "[", ":error", "]", ")", "if", "@opts", "[", ":error_given", "]", "@opts", "[", ":config", "]", "=", "File", ".", "expand_path", "(", "@opts", "[", ":config", "]", ")", "if", "@opts", "[", ":config_given", "]", "end" ]
Validate the options; otherwise fails.
[ "Validate", "the", "options", ";", "otherwise", "fails", "." ]
9b036f2741d515e9bfd158571a813987516d89ed
https://github.com/kenjij/kajiki/blob/9b036f2741d515e9bfd158571a813987516d89ed/lib/kajiki/runner.rb#L41-L49
train
kenjij/kajiki
lib/kajiki/runner.rb
Kajiki.Runner.start
def start(&block) fail 'No start block given.' if block.nil? check_existing_pid puts "Starting process..." Process.daemon if @opts[:daemonize] change_privileges if @opts[:auto_default_actions] redirect_outputs if @opts[:auto_default_actions] write_pid trap_default_signals if @opts[:auto_default_actions] block.call('start') end
ruby
def start(&block) fail 'No start block given.' if block.nil? check_existing_pid puts "Starting process..." Process.daemon if @opts[:daemonize] change_privileges if @opts[:auto_default_actions] redirect_outputs if @opts[:auto_default_actions] write_pid trap_default_signals if @opts[:auto_default_actions] block.call('start') end
[ "def", "start", "(", "&", "block", ")", "fail", "'No start block given.'", "if", "block", ".", "nil?", "check_existing_pid", "puts", "\"Starting process...\"", "Process", ".", "daemon", "if", "@opts", "[", ":daemonize", "]", "change_privileges", "if", "@opts", "[", ":auto_default_actions", "]", "redirect_outputs", "if", "@opts", "[", ":auto_default_actions", "]", "write_pid", "trap_default_signals", "if", "@opts", "[", ":auto_default_actions", "]", "block", ".", "call", "(", "'start'", ")", "end" ]
Start the process with the given block. @param [Block]
[ "Start", "the", "process", "with", "the", "given", "block", "." ]
9b036f2741d515e9bfd158571a813987516d89ed
https://github.com/kenjij/kajiki/blob/9b036f2741d515e9bfd158571a813987516d89ed/lib/kajiki/runner.rb#L53-L63
train
kenjij/kajiki
lib/kajiki/runner.rb
Kajiki.Runner.stop
def stop(&block) block.call('stop') unless block.nil? pid = read_pid fail 'No valid PID file.' unless pid && pid > 0 Process.kill('TERM', pid) delete_pid puts 'Process terminated.' end
ruby
def stop(&block) block.call('stop') unless block.nil? pid = read_pid fail 'No valid PID file.' unless pid && pid > 0 Process.kill('TERM', pid) delete_pid puts 'Process terminated.' end
[ "def", "stop", "(", "&", "block", ")", "block", ".", "call", "(", "'stop'", ")", "unless", "block", ".", "nil?", "pid", "=", "read_pid", "fail", "'No valid PID file.'", "unless", "pid", "&&", "pid", ">", "0", "Process", ".", "kill", "(", "'TERM'", ",", "pid", ")", "delete_pid", "puts", "'Process terminated.'", "end" ]
Stop the process. @param [Block] will execute prior to shutdown, if given.
[ "Stop", "the", "process", "." ]
9b036f2741d515e9bfd158571a813987516d89ed
https://github.com/kenjij/kajiki/blob/9b036f2741d515e9bfd158571a813987516d89ed/lib/kajiki/runner.rb#L67-L74
train
raygao/rforce-raygao
lib/rforce/soap_pullable.rb
RForce.SoapPullable.local
def local(tag) first, second = tag.split ':' return first if second.nil? @namespaces.include?(first) ? second : tag end
ruby
def local(tag) first, second = tag.split ':' return first if second.nil? @namespaces.include?(first) ? second : tag end
[ "def", "local", "(", "tag", ")", "first", ",", "second", "=", "tag", ".", "split", "':'", "return", "first", "if", "second", ".", "nil?", "@namespaces", ".", "include?", "(", "first", ")", "?", "second", ":", "tag", "end" ]
Split off the local name portion of an XML tag.
[ "Split", "off", "the", "local", "name", "portion", "of", "an", "XML", "tag", "." ]
21bf35db2844f3e43b1cf8d290bfc0f413384fbf
https://github.com/raygao/rforce-raygao/blob/21bf35db2844f3e43b1cf8d290bfc0f413384fbf/lib/rforce/soap_pullable.rb#L8-L12
train
khiemns54/sp2db
lib/sp2db/base_table.rb
Sp2db.BaseTable.to_csv
def to_csv data attributes = data.first&.keys || [] CSV.generate(headers: true) do |csv| csv << attributes data.each do |row| csv << attributes.map do |att| row[att] end end end end
ruby
def to_csv data attributes = data.first&.keys || [] CSV.generate(headers: true) do |csv| csv << attributes data.each do |row| csv << attributes.map do |att| row[att] end end end end
[ "def", "to_csv", "data", "attributes", "=", "data", ".", "first", "&.", "keys", "||", "[", "]", "CSV", ".", "generate", "(", "headers", ":", "true", ")", "do", "|", "csv", "|", "csv", "<<", "attributes", "data", ".", "each", "do", "|", "row", "|", "csv", "<<", "attributes", ".", "map", "do", "|", "att", "|", "row", "[", "att", "]", "end", "end", "end", "end" ]
Array of hash data to csv format
[ "Array", "of", "hash", "data", "to", "csv", "format" ]
76c78df07ea19d6f1b5ff2e883ae206a0e94de27
https://github.com/khiemns54/sp2db/blob/76c78df07ea19d6f1b5ff2e883ae206a0e94de27/lib/sp2db/base_table.rb#L113-L125
train
khiemns54/sp2db
lib/sp2db/base_table.rb
Sp2db.BaseTable.standardize_cell_val
def standardize_cell_val v v = ((float = Float(v)) && (float % 1.0 == 0) ? float.to_i : float) rescue v v = v.force_encoding("UTF-8") if v.is_a?(String) v end
ruby
def standardize_cell_val v v = ((float = Float(v)) && (float % 1.0 == 0) ? float.to_i : float) rescue v v = v.force_encoding("UTF-8") if v.is_a?(String) v end
[ "def", "standardize_cell_val", "v", "v", "=", "(", "(", "float", "=", "Float", "(", "v", ")", ")", "&&", "(", "float", "%", "1.0", "==", "0", ")", "?", "float", ".", "to_i", ":", "float", ")", "rescue", "v", "v", "=", "v", ".", "force_encoding", "(", "\"UTF-8\"", ")", "if", "v", ".", "is_a?", "(", "String", ")", "v", "end" ]
Convert number string to number
[ "Convert", "number", "string", "to", "number" ]
76c78df07ea19d6f1b5ff2e883ae206a0e94de27
https://github.com/khiemns54/sp2db/blob/76c78df07ea19d6f1b5ff2e883ae206a0e94de27/lib/sp2db/base_table.rb#L161-L165
train
khiemns54/sp2db
lib/sp2db/base_table.rb
Sp2db.BaseTable.raw_filter
def raw_filter raw_data, opts={} raw_header = raw_data[header_row].map.with_index do |h, idx| is_valid = valid_header?(h) { idx: idx, is_remove: !is_valid, is_required: require_header?(h), name: is_valid && h.gsub(/\s*/, '').gsub(/!/, '').downcase } end rows = raw_data[(header_row + 1)..-1].map.with_index do |raw, rdx| row = {}.with_indifferent_access raw_header.each do |h| val = raw[h[:idx]] next if h[:is_remove] if h[:is_required] && val.blank? row = {} break end row[h[:name]] = standardize_cell_val val end next if row.values.all?(&:blank?) row[:id] = rdx + 1 if find_columns.include?(:id) && row[:id].blank? row end.compact .reject(&:blank?) rows = rows.select do |row| if required_columns.present? required_columns.all? {|col| row[col].present? } else true end end rows end
ruby
def raw_filter raw_data, opts={} raw_header = raw_data[header_row].map.with_index do |h, idx| is_valid = valid_header?(h) { idx: idx, is_remove: !is_valid, is_required: require_header?(h), name: is_valid && h.gsub(/\s*/, '').gsub(/!/, '').downcase } end rows = raw_data[(header_row + 1)..-1].map.with_index do |raw, rdx| row = {}.with_indifferent_access raw_header.each do |h| val = raw[h[:idx]] next if h[:is_remove] if h[:is_required] && val.blank? row = {} break end row[h[:name]] = standardize_cell_val val end next if row.values.all?(&:blank?) row[:id] = rdx + 1 if find_columns.include?(:id) && row[:id].blank? row end.compact .reject(&:blank?) rows = rows.select do |row| if required_columns.present? required_columns.all? {|col| row[col].present? } else true end end rows end
[ "def", "raw_filter", "raw_data", ",", "opts", "=", "{", "}", "raw_header", "=", "raw_data", "[", "header_row", "]", ".", "map", ".", "with_index", "do", "|", "h", ",", "idx", "|", "is_valid", "=", "valid_header?", "(", "h", ")", "{", "idx", ":", "idx", ",", "is_remove", ":", "!", "is_valid", ",", "is_required", ":", "require_header?", "(", "h", ")", ",", "name", ":", "is_valid", "&&", "h", ".", "gsub", "(", "/", "\\s", "/", ",", "''", ")", ".", "gsub", "(", "/", "/", ",", "''", ")", ".", "downcase", "}", "end", "rows", "=", "raw_data", "[", "(", "header_row", "+", "1", ")", "..", "-", "1", "]", ".", "map", ".", "with_index", "do", "|", "raw", ",", "rdx", "|", "row", "=", "{", "}", ".", "with_indifferent_access", "raw_header", ".", "each", "do", "|", "h", "|", "val", "=", "raw", "[", "h", "[", ":idx", "]", "]", "next", "if", "h", "[", ":is_remove", "]", "if", "h", "[", ":is_required", "]", "&&", "val", ".", "blank?", "row", "=", "{", "}", "break", "end", "row", "[", "h", "[", ":name", "]", "]", "=", "standardize_cell_val", "val", "end", "next", "if", "row", ".", "values", ".", "all?", "(", "&", ":blank?", ")", "row", "[", ":id", "]", "=", "rdx", "+", "1", "if", "find_columns", ".", "include?", "(", ":id", ")", "&&", "row", "[", ":id", "]", ".", "blank?", "row", "end", ".", "compact", ".", "reject", "(", "&", ":blank?", ")", "rows", "=", "rows", ".", "select", "do", "|", "row", "|", "if", "required_columns", ".", "present?", "required_columns", ".", "all?", "{", "|", "col", "|", "row", "[", "col", "]", ".", "present?", "}", "else", "true", "end", "end", "rows", "end" ]
Remove uncessary columns and invalid rows from csv format data
[ "Remove", "uncessary", "columns", "and", "invalid", "rows", "from", "csv", "format", "data" ]
76c78df07ea19d6f1b5ff2e883ae206a0e94de27
https://github.com/khiemns54/sp2db/blob/76c78df07ea19d6f1b5ff2e883ae206a0e94de27/lib/sp2db/base_table.rb#L176-L215
train
ihoka/friendly-attributes
lib/friendly_attributes/class_methods.rb
FriendlyAttributes.ClassMethods.friendly_details
def friendly_details(*args, &block) klass = args.shift options = args.extract_options! attributes = args.extract_options! if attributes.empty? attributes = options options = {} end DetailsDelegator.new(klass, self, attributes, options, &block).tap do |dd| dd.setup_delegated_attributes dd.instance_eval(&block) if block_given? end end
ruby
def friendly_details(*args, &block) klass = args.shift options = args.extract_options! attributes = args.extract_options! if attributes.empty? attributes = options options = {} end DetailsDelegator.new(klass, self, attributes, options, &block).tap do |dd| dd.setup_delegated_attributes dd.instance_eval(&block) if block_given? end end
[ "def", "friendly_details", "(", "*", "args", ",", "&", "block", ")", "klass", "=", "args", ".", "shift", "options", "=", "args", ".", "extract_options!", "attributes", "=", "args", ".", "extract_options!", "if", "attributes", ".", "empty?", "attributes", "=", "options", "options", "=", "{", "}", "end", "DetailsDelegator", ".", "new", "(", "klass", ",", "self", ",", "attributes", ",", "options", ",", "&", "block", ")", ".", "tap", "do", "|", "dd", "|", "dd", ".", "setup_delegated_attributes", "dd", ".", "instance_eval", "(", "&", "block", ")", "if", "block_given?", "end", "end" ]
Configure a Friendly Base model associated with an ActiveRecord model. @overload friendly_details(klass, attributes) @param [Class] klass FriendlyAttributes::Base instance used to extend the ActiveRecord model @param [Hash] attributes hash of types and attributes names with which to extend the ActiveRecord, through FriendlyAttributes::Base @overload friendly_details(klass, attributes, options) @param [Hash] options configuration options for extending the FriendlyAttributes extension (see {DetailsDelegator#initialize}) @return [DetailsDelegator]
[ "Configure", "a", "Friendly", "Base", "model", "associated", "with", "an", "ActiveRecord", "model", "." ]
52c70a4028aa915f791d121bcf905a01989cad84
https://github.com/ihoka/friendly-attributes/blob/52c70a4028aa915f791d121bcf905a01989cad84/lib/friendly_attributes/class_methods.rb#L13-L26
train
codescrum/bebox
lib/bebox/cli.rb
Bebox.Cli.inside_project?
def inside_project? project_found = false cwd = Pathname(Dir.pwd) home_directory = File.expand_path('~') cwd.ascend do |current_path| project_found = File.file?("#{current_path.to_s}/.bebox") self.project_root = current_path.to_s if project_found break if project_found || (current_path.to_s == home_directory) end project_found end
ruby
def inside_project? project_found = false cwd = Pathname(Dir.pwd) home_directory = File.expand_path('~') cwd.ascend do |current_path| project_found = File.file?("#{current_path.to_s}/.bebox") self.project_root = current_path.to_s if project_found break if project_found || (current_path.to_s == home_directory) end project_found end
[ "def", "inside_project?", "project_found", "=", "false", "cwd", "=", "Pathname", "(", "Dir", ".", "pwd", ")", "home_directory", "=", "File", ".", "expand_path", "(", "'~'", ")", "cwd", ".", "ascend", "do", "|", "current_path", "|", "project_found", "=", "File", ".", "file?", "(", "\"#{current_path.to_s}/.bebox\"", ")", "self", ".", "project_root", "=", "current_path", ".", "to_s", "if", "project_found", "break", "if", "project_found", "||", "(", "current_path", ".", "to_s", "==", "home_directory", ")", "end", "project_found", "end" ]
Search recursively for .bebox file to see if current directory is a bebox project or not
[ "Search", "recursively", "for", ".", "bebox", "file", "to", "see", "if", "current", "directory", "is", "a", "bebox", "project", "or", "not" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/cli.rb#L31-L41
train
rjoberon/bibsonomy-ruby
lib/bibsonomy/api.rb
BibSonomy.API.get_post
def get_post(user_name, intra_hash) response = @conn.get @url_post.expand({ :user_name => user_name, :intra_hash => intra_hash, :format => @format }) if @parse attributes = JSON.parse(response.body) return Post.new(attributes["post"]) end return response.body end
ruby
def get_post(user_name, intra_hash) response = @conn.get @url_post.expand({ :user_name => user_name, :intra_hash => intra_hash, :format => @format }) if @parse attributes = JSON.parse(response.body) return Post.new(attributes["post"]) end return response.body end
[ "def", "get_post", "(", "user_name", ",", "intra_hash", ")", "response", "=", "@conn", ".", "get", "@url_post", ".", "expand", "(", "{", ":user_name", "=>", "user_name", ",", ":intra_hash", "=>", "intra_hash", ",", ":format", "=>", "@format", "}", ")", "if", "@parse", "attributes", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", "return", "Post", ".", "new", "(", "attributes", "[", "\"post\"", "]", ")", "end", "return", "response", ".", "body", "end" ]
Initializes the client with the given credentials. @param user_name [String] the name of the user account used for accessing the API @param api_key [String] the API key corresponding to the user account - can be obtained from http://www.bibsonomy.org/settings?selTab=1 @param format [String] The requested return format. One of: 'xml', 'json', 'ruby', 'csl', 'bibtex'. The default is 'ruby' which returns Ruby objects defined by this library. Currently, 'csl' and 'bibtex' are only available for publications. Get a single post @param user_name [String] the name of the post's owner @param intra_hash [String] the intrag hash of the post @return [BibSonomy::Post, String] the requested post
[ "Initializes", "the", "client", "with", "the", "given", "credentials", "." ]
15afed3f32e434d28576ac62ecf3cfd8a392e055
https://github.com/rjoberon/bibsonomy-ruby/blob/15afed3f32e434d28576ac62ecf3cfd8a392e055/lib/bibsonomy/api.rb#L78-L90
train
rjoberon/bibsonomy-ruby
lib/bibsonomy/api.rb
BibSonomy.API.get_posts_for_user
def get_posts_for_user(user_name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST) return get_posts("user", user_name, resource_type, tags, start, endc) end
ruby
def get_posts_for_user(user_name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST) return get_posts("user", user_name, resource_type, tags, start, endc) end
[ "def", "get_posts_for_user", "(", "user_name", ",", "resource_type", ",", "tags", "=", "nil", ",", "start", "=", "0", ",", "endc", "=", "$MAX_POSTS_PER_REQUEST", ")", "return", "get_posts", "(", "\"user\"", ",", "user_name", ",", "resource_type", ",", "tags", ",", "start", ",", "endc", ")", "end" ]
Get posts owned by a user, optionally filtered by tags. @param user_name [String] the name of the posts' owner @param resource_type [String] the type of the post. Currently supported are 'bookmark' and 'publication'. @param tags [Array<String>] the tags that all posts must contain (can be empty) @param start [Integer] number of first post to download @param endc [Integer] number of last post to download @return [Array<BibSonomy::Post>, String] the requested posts
[ "Get", "posts", "owned", "by", "a", "user", "optionally", "filtered", "by", "tags", "." ]
15afed3f32e434d28576ac62ecf3cfd8a392e055
https://github.com/rjoberon/bibsonomy-ruby/blob/15afed3f32e434d28576ac62ecf3cfd8a392e055/lib/bibsonomy/api.rb#L101-L103
train
rjoberon/bibsonomy-ruby
lib/bibsonomy/api.rb
BibSonomy.API.get_posts_for_group
def get_posts_for_group(group_name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST) return get_posts("group", group_name, resource_type, tags, start, endc) end
ruby
def get_posts_for_group(group_name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST) return get_posts("group", group_name, resource_type, tags, start, endc) end
[ "def", "get_posts_for_group", "(", "group_name", ",", "resource_type", ",", "tags", "=", "nil", ",", "start", "=", "0", ",", "endc", "=", "$MAX_POSTS_PER_REQUEST", ")", "return", "get_posts", "(", "\"group\"", ",", "group_name", ",", "resource_type", ",", "tags", ",", "start", ",", "endc", ")", "end" ]
Get the posts of the users of a group, optionally filtered by tags. @param group_name [String] the name of the group @param resource_type [String] the type of the post. Currently supported are 'bookmark' and 'publication'. @param tags [Array<String>] the tags that all posts must contain (can be empty) @param start [Integer] number of first post to download @param endc [Integer] number of last post to download @return [Array<BibSonomy::Post>, String] the requested posts
[ "Get", "the", "posts", "of", "the", "users", "of", "a", "group", "optionally", "filtered", "by", "tags", "." ]
15afed3f32e434d28576ac62ecf3cfd8a392e055
https://github.com/rjoberon/bibsonomy-ruby/blob/15afed3f32e434d28576ac62ecf3cfd8a392e055/lib/bibsonomy/api.rb#L114-L116
train
rjoberon/bibsonomy-ruby
lib/bibsonomy/api.rb
BibSonomy.API.get_posts
def get_posts(grouping, name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST) url = @url_posts.partial_expand({ :format => @format, :resourcetype => get_resource_type(resource_type), :start => start, :end => endc }) # decide what to get if grouping == "user" url = url.partial_expand({:user => name}) elsif grouping == "group" url = url.partial_expand({:group => name}) end # add tags, if requested if tags != nil url = url.partial_expand({:tags => tags.join(" ")}) end response = @conn.get url.expand({}) if @parse posts = JSON.parse(response.body)["posts"]["post"] return posts.map { |attributes| Post.new(attributes) } end return response.body end
ruby
def get_posts(grouping, name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST) url = @url_posts.partial_expand({ :format => @format, :resourcetype => get_resource_type(resource_type), :start => start, :end => endc }) # decide what to get if grouping == "user" url = url.partial_expand({:user => name}) elsif grouping == "group" url = url.partial_expand({:group => name}) end # add tags, if requested if tags != nil url = url.partial_expand({:tags => tags.join(" ")}) end response = @conn.get url.expand({}) if @parse posts = JSON.parse(response.body)["posts"]["post"] return posts.map { |attributes| Post.new(attributes) } end return response.body end
[ "def", "get_posts", "(", "grouping", ",", "name", ",", "resource_type", ",", "tags", "=", "nil", ",", "start", "=", "0", ",", "endc", "=", "$MAX_POSTS_PER_REQUEST", ")", "url", "=", "@url_posts", ".", "partial_expand", "(", "{", ":format", "=>", "@format", ",", ":resourcetype", "=>", "get_resource_type", "(", "resource_type", ")", ",", ":start", "=>", "start", ",", ":end", "=>", "endc", "}", ")", "if", "grouping", "==", "\"user\"", "url", "=", "url", ".", "partial_expand", "(", "{", ":user", "=>", "name", "}", ")", "elsif", "grouping", "==", "\"group\"", "url", "=", "url", ".", "partial_expand", "(", "{", ":group", "=>", "name", "}", ")", "end", "if", "tags", "!=", "nil", "url", "=", "url", ".", "partial_expand", "(", "{", ":tags", "=>", "tags", ".", "join", "(", "\" \"", ")", "}", ")", "end", "response", "=", "@conn", ".", "get", "url", ".", "expand", "(", "{", "}", ")", "if", "@parse", "posts", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", "[", "\"posts\"", "]", "[", "\"post\"", "]", "return", "posts", ".", "map", "{", "|", "attributes", "|", "Post", ".", "new", "(", "attributes", ")", "}", "end", "return", "response", ".", "body", "end" ]
Get posts for a user or group, optionally filtered by tags. @param grouping [String] the type of the name (either "user" or "group") @param name [String] the name of the group or user @param resource_type [String] the type of the post. Currently supported are 'bookmark' and 'publication'. @param tags [Array<String>] the tags that all posts must contain (can be empty) @param start [Integer] number of first post to download @param endc [Integer] number of last post to download @return [Array<BibSonomy::Post>, String] the requested posts
[ "Get", "posts", "for", "a", "user", "or", "group", "optionally", "filtered", "by", "tags", "." ]
15afed3f32e434d28576ac62ecf3cfd8a392e055
https://github.com/rjoberon/bibsonomy-ruby/blob/15afed3f32e434d28576ac62ecf3cfd8a392e055/lib/bibsonomy/api.rb#L128-L153
train
rjoberon/bibsonomy-ruby
lib/bibsonomy/api.rb
BibSonomy.API.get_document
def get_document(user_name, intra_hash, file_name) response = @conn.get get_document_href(user_name, intra_hash, file_name) if response.status == 200 return [response.body, response.headers['content-type']] end return nil, nil end
ruby
def get_document(user_name, intra_hash, file_name) response = @conn.get get_document_href(user_name, intra_hash, file_name) if response.status == 200 return [response.body, response.headers['content-type']] end return nil, nil end
[ "def", "get_document", "(", "user_name", ",", "intra_hash", ",", "file_name", ")", "response", "=", "@conn", ".", "get", "get_document_href", "(", "user_name", ",", "intra_hash", ",", "file_name", ")", "if", "response", ".", "status", "==", "200", "return", "[", "response", ".", "body", ",", "response", ".", "headers", "[", "'content-type'", "]", "]", "end", "return", "nil", ",", "nil", "end" ]
Get a document belonging to a post. @param user_name @param intra_hash @param file_name @return the document and the content type
[ "Get", "a", "document", "belonging", "to", "a", "post", "." ]
15afed3f32e434d28576ac62ecf3cfd8a392e055
https://github.com/rjoberon/bibsonomy-ruby/blob/15afed3f32e434d28576ac62ecf3cfd8a392e055/lib/bibsonomy/api.rb#L171-L177
train
rjoberon/bibsonomy-ruby
lib/bibsonomy/api.rb
BibSonomy.API.get_document_preview
def get_document_preview(user_name, intra_hash, file_name, size) response = @conn.get get_document_href(user_name, intra_hash, file_name), { :preview => size } if response.status == 200 return [response.body, 'image/jpeg'] end return nil, nil end
ruby
def get_document_preview(user_name, intra_hash, file_name, size) response = @conn.get get_document_href(user_name, intra_hash, file_name), { :preview => size } if response.status == 200 return [response.body, 'image/jpeg'] end return nil, nil end
[ "def", "get_document_preview", "(", "user_name", ",", "intra_hash", ",", "file_name", ",", "size", ")", "response", "=", "@conn", ".", "get", "get_document_href", "(", "user_name", ",", "intra_hash", ",", "file_name", ")", ",", "{", ":preview", "=>", "size", "}", "if", "response", ".", "status", "==", "200", "return", "[", "response", ".", "body", ",", "'image/jpeg'", "]", "end", "return", "nil", ",", "nil", "end" ]
Get the preview for a document belonging to a post. @param user_name @param intra_hash @param file_name @param size [String] requested preview size (allowed values: SMALL, MEDIUM, LARGE) @return the preview image and the content type `image/jpeg`
[ "Get", "the", "preview", "for", "a", "document", "belonging", "to", "a", "post", "." ]
15afed3f32e434d28576ac62ecf3cfd8a392e055
https://github.com/rjoberon/bibsonomy-ruby/blob/15afed3f32e434d28576ac62ecf3cfd8a392e055/lib/bibsonomy/api.rb#L187-L193
train
rjoberon/bibsonomy-ruby
lib/bibsonomy/api.rb
BibSonomy.API.get_resource_type
def get_resource_type(resource_type) if $resource_types_bookmark.include? resource_type.downcase() return "bookmark" end if $resource_types_bibtex.include? resource_type.downcase() return "bibtex" end raise ArgumentError.new("Unknown resource type: #{resource_type}. Supported resource types are ") end
ruby
def get_resource_type(resource_type) if $resource_types_bookmark.include? resource_type.downcase() return "bookmark" end if $resource_types_bibtex.include? resource_type.downcase() return "bibtex" end raise ArgumentError.new("Unknown resource type: #{resource_type}. Supported resource types are ") end
[ "def", "get_resource_type", "(", "resource_type", ")", "if", "$resource_types_bookmark", ".", "include?", "resource_type", ".", "downcase", "(", ")", "return", "\"bookmark\"", "end", "if", "$resource_types_bibtex", ".", "include?", "resource_type", ".", "downcase", "(", ")", "return", "\"bibtex\"", "end", "raise", "ArgumentError", ".", "new", "(", "\"Unknown resource type: #{resource_type}. Supported resource types are \"", ")", "end" ]
Convenience method to allow sloppy specification of the resource type.
[ "Convenience", "method", "to", "allow", "sloppy", "specification", "of", "the", "resource", "type", "." ]
15afed3f32e434d28576ac62ecf3cfd8a392e055
https://github.com/rjoberon/bibsonomy-ruby/blob/15afed3f32e434d28576ac62ecf3cfd8a392e055/lib/bibsonomy/api.rb#L203-L213
train
LifebookerInc/table_renamable
lib/table_renamable/deprecated_table.rb
TableRenamable.DeprecatedTable.get_current_table_name
def get_current_table_name [self.old_name, self.new_name].each do |name| return name.to_s if self.table_exists?(name) end # raise exception if we don't have a valid table self.raise_no_table_error end
ruby
def get_current_table_name [self.old_name, self.new_name].each do |name| return name.to_s if self.table_exists?(name) end # raise exception if we don't have a valid table self.raise_no_table_error end
[ "def", "get_current_table_name", "[", "self", ".", "old_name", ",", "self", ".", "new_name", "]", ".", "each", "do", "|", "name", "|", "return", "name", ".", "to_s", "if", "self", ".", "table_exists?", "(", "name", ")", "end", "self", ".", "raise_no_table_error", "end" ]
Constructor - sets up the record and tries to connect to the correct database @param klass [Class] Class whose table we are renaming @param old_name [String, Symbol] The old table name @param new_name [String, Symbol] The new table name Returns the name of the table that currently exists of our two options (old or new) @return [String] The name of the existing table
[ "Constructor", "-", "sets", "up", "the", "record", "and", "tries", "to", "connect", "to", "the", "correct", "database" ]
337eaa4e71173c242df1d830776d3f72f0f4554f
https://github.com/LifebookerInc/table_renamable/blob/337eaa4e71173c242df1d830776d3f72f0f4554f/lib/table_renamable/deprecated_table.rb#L45-L51
train
LifebookerInc/table_renamable
lib/table_renamable/deprecated_table.rb
TableRenamable.DeprecatedTable.set_table_name
def set_table_name [self.old_name, self.new_name].each do |name| # make sure this table exists if self.table_exists?(name) # return true if we are already using this table return true if self.klass.table_name == name.to_s # otherwise we can change the table name self.klass.table_name = name return true end end self.raise_no_table_error end
ruby
def set_table_name [self.old_name, self.new_name].each do |name| # make sure this table exists if self.table_exists?(name) # return true if we are already using this table return true if self.klass.table_name == name.to_s # otherwise we can change the table name self.klass.table_name = name return true end end self.raise_no_table_error end
[ "def", "set_table_name", "[", "self", ".", "old_name", ",", "self", ".", "new_name", "]", ".", "each", "do", "|", "name", "|", "if", "self", ".", "table_exists?", "(", "name", ")", "return", "true", "if", "self", ".", "klass", ".", "table_name", "==", "name", ".", "to_s", "self", ".", "klass", ".", "table_name", "=", "name", "return", "true", "end", "end", "self", ".", "raise_no_table_error", "end" ]
Set the correct table name for the Class we are controlling @raise [TableRenamable::NoTableError] Error if neither name works @return [Boolean] True if we set the table name
[ "Set", "the", "correct", "table", "name", "for", "the", "Class", "we", "are", "controlling" ]
337eaa4e71173c242df1d830776d3f72f0f4554f
https://github.com/LifebookerInc/table_renamable/blob/337eaa4e71173c242df1d830776d3f72f0f4554f/lib/table_renamable/deprecated_table.rb#L68-L80
train
dmerrick/lights_app
lib/philips_hue/light.rb
PhilipsHue.Light.set
def set(options) json_body = options.to_json request_uri = "#{base_request_uri}/state" HTTParty.put(request_uri, :body => json_body) end
ruby
def set(options) json_body = options.to_json request_uri = "#{base_request_uri}/state" HTTParty.put(request_uri, :body => json_body) end
[ "def", "set", "(", "options", ")", "json_body", "=", "options", ".", "to_json", "request_uri", "=", "\"#{base_request_uri}/state\"", "HTTParty", ".", "put", "(", "request_uri", ",", ":body", "=>", "json_body", ")", "end" ]
change the state of a light note that colormode will automagically update
[ "change", "the", "state", "of", "a", "light", "note", "that", "colormode", "will", "automagically", "update" ]
0bcbc566fa3964c74f7cfe73708d5ad1a7ce696d
https://github.com/dmerrick/lights_app/blob/0bcbc566fa3964c74f7cfe73708d5ad1a7ce696d/lib/philips_hue/light.rb#L23-L27
train
dmerrick/lights_app
lib/philips_hue/light.rb
PhilipsHue.Light.rename
def rename(new_name) json_body = { :name => new_name }.to_json HTTParty.put(base_request_uri, :body => json_body) @name = new_name end
ruby
def rename(new_name) json_body = { :name => new_name }.to_json HTTParty.put(base_request_uri, :body => json_body) @name = new_name end
[ "def", "rename", "(", "new_name", ")", "json_body", "=", "{", ":name", "=>", "new_name", "}", ".", "to_json", "HTTParty", ".", "put", "(", "base_request_uri", ",", ":body", "=>", "json_body", ")", "@name", "=", "new_name", "end" ]
change the name of the light
[ "change", "the", "name", "of", "the", "light" ]
0bcbc566fa3964c74f7cfe73708d5ad1a7ce696d
https://github.com/dmerrick/lights_app/blob/0bcbc566fa3964c74f7cfe73708d5ad1a7ce696d/lib/philips_hue/light.rb#L30-L34
train
dmerrick/lights_app
lib/philips_hue/light.rb
PhilipsHue.Light.to_s
def to_s pretty_name = @name.to_s.split(/_/).map(&:capitalize).join(" ") on_or_off = on? ? "on" : "off" reachable = reachable? ? "reachable" : "unreachable" "#{pretty_name} is #{on_or_off} and #{reachable}" end
ruby
def to_s pretty_name = @name.to_s.split(/_/).map(&:capitalize).join(" ") on_or_off = on? ? "on" : "off" reachable = reachable? ? "reachable" : "unreachable" "#{pretty_name} is #{on_or_off} and #{reachable}" end
[ "def", "to_s", "pretty_name", "=", "@name", ".", "to_s", ".", "split", "(", "/", "/", ")", ".", "map", "(", "&", ":capitalize", ")", ".", "join", "(", "\" \"", ")", "on_or_off", "=", "on?", "?", "\"on\"", ":", "\"off\"", "reachable", "=", "reachable?", "?", "\"reachable\"", ":", "\"unreachable\"", "\"#{pretty_name} is #{on_or_off} and #{reachable}\"", "end" ]
pretty-print the light's status
[ "pretty", "-", "print", "the", "light", "s", "status" ]
0bcbc566fa3964c74f7cfe73708d5ad1a7ce696d
https://github.com/dmerrick/lights_app/blob/0bcbc566fa3964c74f7cfe73708d5ad1a7ce696d/lib/philips_hue/light.rb#L154-L159
train
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/pages_controller.rb
Roroacms.Admin::PagesController.edit
def edit @edit = true @record = Post.find(params[:id]) # add breadcrumb and set title add_breadcrumb I18n.t("controllers.admin.pages.edit.breadcrumb") set_title(I18n.t("controllers.admin.pages.edit.title", post_title: @record.post_title)) @action = 'update' end
ruby
def edit @edit = true @record = Post.find(params[:id]) # add breadcrumb and set title add_breadcrumb I18n.t("controllers.admin.pages.edit.breadcrumb") set_title(I18n.t("controllers.admin.pages.edit.title", post_title: @record.post_title)) @action = 'update' end
[ "def", "edit", "@edit", "=", "true", "@record", "=", "Post", ".", "find", "(", "params", "[", ":id", "]", ")", "add_breadcrumb", "I18n", ".", "t", "(", "\"controllers.admin.pages.edit.breadcrumb\"", ")", "set_title", "(", "I18n", ".", "t", "(", "\"controllers.admin.pages.edit.title\"", ",", "post_title", ":", "@record", ".", "post_title", ")", ")", "@action", "=", "'update'", "end" ]
gets and displays the post object with the necessary dependencies
[ "gets", "and", "displays", "the", "post", "object", "with", "the", "necessary", "dependencies" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/pages_controller.rb#L57-L65
train
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/pages_controller.rb
Roroacms.Admin::PagesController.destroy
def destroy Post.disable_post(params[:id]) respond_to do |format| format.html { redirect_to admin_pages_path, notice: I18n.t("controllers.admin.pages.destroy.flash.success") } end end
ruby
def destroy Post.disable_post(params[:id]) respond_to do |format| format.html { redirect_to admin_pages_path, notice: I18n.t("controllers.admin.pages.destroy.flash.success") } end end
[ "def", "destroy", "Post", ".", "disable_post", "(", "params", "[", ":id", "]", ")", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "redirect_to", "admin_pages_path", ",", "notice", ":", "I18n", ".", "t", "(", "\"controllers.admin.pages.destroy.flash.success\"", ")", "}", "end", "end" ]
deletes the post
[ "deletes", "the", "post" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/pages_controller.rb#L98-L103
train
tilsammans/nilly_vanilly
lib/nilly_vanilly/inspect.rb
NillyVanilly.Inspect.results
def results ActiveRecord::Base.connection.tables.each do |table| model = table.classify.constantize rescue next model.columns.each do |column| present = model.respond_to?(:nillify_attributes) && model.nillify_attributes.include?(column.name.to_sym) @results << [present, model.name, column.name] if include_column(column) end end @results end
ruby
def results ActiveRecord::Base.connection.tables.each do |table| model = table.classify.constantize rescue next model.columns.each do |column| present = model.respond_to?(:nillify_attributes) && model.nillify_attributes.include?(column.name.to_sym) @results << [present, model.name, column.name] if include_column(column) end end @results end
[ "def", "results", "ActiveRecord", "::", "Base", ".", "connection", ".", "tables", ".", "each", "do", "|", "table", "|", "model", "=", "table", ".", "classify", ".", "constantize", "rescue", "next", "model", ".", "columns", ".", "each", "do", "|", "column", "|", "present", "=", "model", ".", "respond_to?", "(", ":nillify_attributes", ")", "&&", "model", ".", "nillify_attributes", ".", "include?", "(", "column", ".", "name", ".", "to_sym", ")", "@results", "<<", "[", "present", ",", "model", ".", "name", ",", "column", ".", "name", "]", "if", "include_column", "(", "column", ")", "end", "end", "@results", "end" ]
A nested array with one row for each column suitable for nillification.
[ "A", "nested", "array", "with", "one", "row", "for", "each", "column", "suitable", "for", "nillification", "." ]
5b95d8ae8a849272ec8bcf9036bb6bd99a86204c
https://github.com/tilsammans/nilly_vanilly/blob/5b95d8ae8a849272ec8bcf9036bb6bd99a86204c/lib/nilly_vanilly/inspect.rb#L9-L21
train
tongueroo/chap
lib/chap/config.rb
Chap.Config.load_json
def load_json(key) path = if yaml[key] =~ %r{^/} # root path given yaml[key] else # relative path dirname = File.dirname(options[:config]) "#{dirname}/#{yaml[key]}" end if File.exist?(path) Mash.from_hash(JSON.parse(IO.read(path))) else puts "ERROR: #{key}.json config does not exist at: #{path}" exit 1 end end
ruby
def load_json(key) path = if yaml[key] =~ %r{^/} # root path given yaml[key] else # relative path dirname = File.dirname(options[:config]) "#{dirname}/#{yaml[key]}" end if File.exist?(path) Mash.from_hash(JSON.parse(IO.read(path))) else puts "ERROR: #{key}.json config does not exist at: #{path}" exit 1 end end
[ "def", "load_json", "(", "key", ")", "path", "=", "if", "yaml", "[", "key", "]", "=~", "%r{", "}", "yaml", "[", "key", "]", "else", "dirname", "=", "File", ".", "dirname", "(", "options", "[", ":config", "]", ")", "\"#{dirname}/#{yaml[key]}\"", "end", "if", "File", ".", "exist?", "(", "path", ")", "Mash", ".", "from_hash", "(", "JSON", ".", "parse", "(", "IO", ".", "read", "(", "path", ")", ")", ")", "else", "puts", "\"ERROR: #{key}.json config does not exist at: #{path}\"", "exit", "1", "end", "end" ]
the chap.json and node.json is assumed to be in th same folder as chap.yml if a relative path is given
[ "the", "chap", ".", "json", "and", "node", ".", "json", "is", "assumed", "to", "be", "in", "th", "same", "folder", "as", "chap", ".", "yml", "if", "a", "relative", "path", "is", "given" ]
317cebeace6cbae793ecd0e4a3d357c671ac1106
https://github.com/tongueroo/chap/blob/317cebeace6cbae793ecd0e4a3d357c671ac1106/lib/chap/config.rb#L35-L48
train
kukushkin/mimi-config
lib/mimi/config.rb
Mimi.Config.load
def load(manifest_filename, opts = {}) opts = self.class.module_options.deep_merge(opts) manifest_filename = Pathname.new(manifest_filename).expand_path load_manifest(manifest_filename, opts) load_params(opts) if opts[:raise_on_missing_params] && !missing_params.empty? raise "Missing required configurable parameters: #{missing_params.join(', ')}" end self end
ruby
def load(manifest_filename, opts = {}) opts = self.class.module_options.deep_merge(opts) manifest_filename = Pathname.new(manifest_filename).expand_path load_manifest(manifest_filename, opts) load_params(opts) if opts[:raise_on_missing_params] && !missing_params.empty? raise "Missing required configurable parameters: #{missing_params.join(', ')}" end self end
[ "def", "load", "(", "manifest_filename", ",", "opts", "=", "{", "}", ")", "opts", "=", "self", ".", "class", ".", "module_options", ".", "deep_merge", "(", "opts", ")", "manifest_filename", "=", "Pathname", ".", "new", "(", "manifest_filename", ")", ".", "expand_path", "load_manifest", "(", "manifest_filename", ",", "opts", ")", "load_params", "(", "opts", ")", "if", "opts", "[", ":raise_on_missing_params", "]", "&&", "!", "missing_params", ".", "empty?", "raise", "\"Missing required configurable parameters: #{missing_params.join(', ')}\"", "end", "self", "end" ]
Creates a Config object. Loads and parses manifest.yml, reads and sets configurable parameters from ENV. Raises an error if any of the required configurable parameters are missing. @param manifest_filename [String,nil] path to the manifest.yml or nil to skip loading manifest Loads and parses manifest.yml, reads and sets configurable parameters from ENV.
[ "Creates", "a", "Config", "object", "." ]
0dc0a733b8442abe2684e0b9e9bd1ccb872f9b20
https://github.com/kukushkin/mimi-config/blob/0dc0a733b8442abe2684e0b9e9bd1ccb872f9b20/lib/mimi/config.rb#L48-L57
train
kukushkin/mimi-config
lib/mimi/config.rb
Mimi.Config.missing_params
def missing_params required_params = manifest.select { |p| p[:required] }.map { |p| p[:name] } required_params - @params.keys end
ruby
def missing_params required_params = manifest.select { |p| p[:required] }.map { |p| p[:name] } required_params - @params.keys end
[ "def", "missing_params", "required_params", "=", "manifest", ".", "select", "{", "|", "p", "|", "p", "[", ":required", "]", "}", ".", "map", "{", "|", "p", "|", "p", "[", ":name", "]", "}", "required_params", "-", "@params", ".", "keys", "end" ]
Returns list of missing required params
[ "Returns", "list", "of", "missing", "required", "params" ]
0dc0a733b8442abe2684e0b9e9bd1ccb872f9b20
https://github.com/kukushkin/mimi-config/blob/0dc0a733b8442abe2684e0b9e9bd1ccb872f9b20/lib/mimi/config.rb#L61-L64
train
kukushkin/mimi-config
lib/mimi/config.rb
Mimi.Config.manifest
def manifest @manifest.map do |k, v| { name: k, desc: v[:desc], required: !v.key?(:default), const: v[:const], default: v[:default] } end end
ruby
def manifest @manifest.map do |k, v| { name: k, desc: v[:desc], required: !v.key?(:default), const: v[:const], default: v[:default] } end end
[ "def", "manifest", "@manifest", ".", "map", "do", "|", "k", ",", "v", "|", "{", "name", ":", "k", ",", "desc", ":", "v", "[", ":desc", "]", ",", "required", ":", "!", "v", ".", "key?", "(", ":default", ")", ",", "const", ":", "v", "[", ":const", "]", ",", "default", ":", "v", "[", ":default", "]", "}", "end", "end" ]
Returns annotated manifest
[ "Returns", "annotated", "manifest" ]
0dc0a733b8442abe2684e0b9e9bd1ccb872f9b20
https://github.com/kukushkin/mimi-config/blob/0dc0a733b8442abe2684e0b9e9bd1ccb872f9b20/lib/mimi/config.rb#L68-L78
train
kukushkin/mimi-config
lib/mimi/config.rb
Mimi.Config.load_params
def load_params(opts = {}) Dotenv.load if opts[:use_dotenv] manifest.each do |p| env_name = p[:name].to_s if p[:const] # const @params[p[:name]] = p[:default] elsif p[:required] # required configurable @params[p[:name]] = ENV[env_name] if ENV.key?(env_name) else # optional configurable @params[p[:name]] = ENV.key?(env_name) ? ENV[env_name] : p[:default] end end @params end
ruby
def load_params(opts = {}) Dotenv.load if opts[:use_dotenv] manifest.each do |p| env_name = p[:name].to_s if p[:const] # const @params[p[:name]] = p[:default] elsif p[:required] # required configurable @params[p[:name]] = ENV[env_name] if ENV.key?(env_name) else # optional configurable @params[p[:name]] = ENV.key?(env_name) ? ENV[env_name] : p[:default] end end @params end
[ "def", "load_params", "(", "opts", "=", "{", "}", ")", "Dotenv", ".", "load", "if", "opts", "[", ":use_dotenv", "]", "manifest", ".", "each", "do", "|", "p", "|", "env_name", "=", "p", "[", ":name", "]", ".", "to_s", "if", "p", "[", ":const", "]", "@params", "[", "p", "[", ":name", "]", "]", "=", "p", "[", ":default", "]", "elsif", "p", "[", ":required", "]", "@params", "[", "p", "[", ":name", "]", "]", "=", "ENV", "[", "env_name", "]", "if", "ENV", ".", "key?", "(", "env_name", ")", "else", "@params", "[", "p", "[", ":name", "]", "]", "=", "ENV", ".", "key?", "(", "env_name", ")", "?", "ENV", "[", "env_name", "]", ":", "p", "[", ":default", "]", "end", "end", "@params", "end" ]
Reads parameters from the ENV according to the current manifest
[ "Reads", "parameters", "from", "the", "ENV", "according", "to", "the", "current", "manifest" ]
0dc0a733b8442abe2684e0b9e9bd1ccb872f9b20
https://github.com/kukushkin/mimi-config/blob/0dc0a733b8442abe2684e0b9e9bd1ccb872f9b20/lib/mimi/config.rb#L150-L166
train
Raybeam/myreplicator
lib/transporter/parallelizer.rb
Myreplicator.Parallelizer.run
def run @done = false @manager_running = false reaper = nil while @queue.size > 0 if @threads.size <= @max_threads @threads << Thread.new(@queue.pop) do |proc| Thread.current[:thread_state] = "running" @klass.new.instance_exec(proc[:params], &proc[:block]) Thread.current[:thread_state] = "done" end else unless @manager_running reaper = manage_threads @manager_running = true end sleep 1 end end # Run manager if thread size never reached max reaper = manage_threads unless @manager_running # Waits until all threads are completed # Before exiting reaper.join end
ruby
def run @done = false @manager_running = false reaper = nil while @queue.size > 0 if @threads.size <= @max_threads @threads << Thread.new(@queue.pop) do |proc| Thread.current[:thread_state] = "running" @klass.new.instance_exec(proc[:params], &proc[:block]) Thread.current[:thread_state] = "done" end else unless @manager_running reaper = manage_threads @manager_running = true end sleep 1 end end # Run manager if thread size never reached max reaper = manage_threads unless @manager_running # Waits until all threads are completed # Before exiting reaper.join end
[ "def", "run", "@done", "=", "false", "@manager_running", "=", "false", "reaper", "=", "nil", "while", "@queue", ".", "size", ">", "0", "if", "@threads", ".", "size", "<=", "@max_threads", "@threads", "<<", "Thread", ".", "new", "(", "@queue", ".", "pop", ")", "do", "|", "proc", "|", "Thread", ".", "current", "[", ":thread_state", "]", "=", "\"running\"", "@klass", ".", "new", ".", "instance_exec", "(", "proc", "[", ":params", "]", ",", "&", "proc", "[", ":block", "]", ")", "Thread", ".", "current", "[", ":thread_state", "]", "=", "\"done\"", "end", "else", "unless", "@manager_running", "reaper", "=", "manage_threads", "@manager_running", "=", "true", "end", "sleep", "1", "end", "end", "reaper", "=", "manage_threads", "unless", "@manager_running", "reaper", ".", "join", "end" ]
Runs while there are jobs in the queue Waits for a second and checks for available threads Exits when all jobs are allocated in threads
[ "Runs", "while", "there", "are", "jobs", "in", "the", "queue", "Waits", "for", "a", "second", "and", "checks", "for", "available", "threads", "Exits", "when", "all", "jobs", "are", "allocated", "in", "threads" ]
470938e70f46886b525c65a4a464b4cf8383d00d
https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/lib/transporter/parallelizer.rb#L29-L56
train
Raybeam/myreplicator
lib/transporter/parallelizer.rb
Myreplicator.Parallelizer.manage_threads
def manage_threads Thread.new do while(@threads.size > 0) done = [] @threads.each do |t| done << t if t[:thread_state] == "done" || !t.status # puts t.object_id.to_s + "--" + t.status.to_s + "--" + t.to_s # raise "Nil Thread State" if t[:thread_state].nil? end done.each{|d| @threads.delete(d)} # Clear dead threads # If no more jobs are left, mark done if done? @done = true else puts "Sleeping for 2" sleep 2 # Wait for more threads to spawn end end end end
ruby
def manage_threads Thread.new do while(@threads.size > 0) done = [] @threads.each do |t| done << t if t[:thread_state] == "done" || !t.status # puts t.object_id.to_s + "--" + t.status.to_s + "--" + t.to_s # raise "Nil Thread State" if t[:thread_state].nil? end done.each{|d| @threads.delete(d)} # Clear dead threads # If no more jobs are left, mark done if done? @done = true else puts "Sleeping for 2" sleep 2 # Wait for more threads to spawn end end end end
[ "def", "manage_threads", "Thread", ".", "new", "do", "while", "(", "@threads", ".", "size", ">", "0", ")", "done", "=", "[", "]", "@threads", ".", "each", "do", "|", "t", "|", "done", "<<", "t", "if", "t", "[", ":thread_state", "]", "==", "\"done\"", "||", "!", "t", ".", "status", "end", "done", ".", "each", "{", "|", "d", "|", "@threads", ".", "delete", "(", "d", ")", "}", "if", "done?", "@done", "=", "true", "else", "puts", "\"Sleeping for 2\"", "sleep", "2", "end", "end", "end", "end" ]
Clears dead threads, frees thread pool for more jobs Exits when no more threads are left
[ "Clears", "dead", "threads", "frees", "thread", "pool", "for", "more", "jobs", "Exits", "when", "no", "more", "threads", "are", "left" ]
470938e70f46886b525c65a4a464b4cf8383d00d
https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/lib/transporter/parallelizer.rb#L63-L85
train
syborg/mme_tools
lib/mme_tools/debug.rb
MMETools.Debug.print_debug
def print_debug(stck_lvls, *vars) @mutex ||= Mutex.new # instance mutex created the first time it is called referers = caller[0...stck_lvls] if stck_lvls > 0 @mutex.synchronize do referers.each { |r| puts "#{r}:"} vars.each { |v| pp v } if vars end end
ruby
def print_debug(stck_lvls, *vars) @mutex ||= Mutex.new # instance mutex created the first time it is called referers = caller[0...stck_lvls] if stck_lvls > 0 @mutex.synchronize do referers.each { |r| puts "#{r}:"} vars.each { |v| pp v } if vars end end
[ "def", "print_debug", "(", "stck_lvls", ",", "*", "vars", ")", "@mutex", "||=", "Mutex", ".", "new", "referers", "=", "caller", "[", "0", "...", "stck_lvls", "]", "if", "stck_lvls", ">", "0", "@mutex", ".", "synchronize", "do", "referers", ".", "each", "{", "|", "r", "|", "puts", "\"#{r}:\"", "}", "vars", ".", "each", "{", "|", "v", "|", "pp", "v", "}", "if", "vars", "end", "end" ]
outputs a debug message and details of each one of the +vars+ if included. +stck_lvls+ is the number of stack levels to be showed +vars+ is a list of vars to be pretty printed. It is convenient to make the first to be a String with an informative message.
[ "outputs", "a", "debug", "message", "and", "details", "of", "each", "one", "of", "the", "+", "vars", "+", "if", "included", ".", "+", "stck_lvls", "+", "is", "the", "number", "of", "stack", "levels", "to", "be", "showed", "+", "vars", "+", "is", "a", "list", "of", "vars", "to", "be", "pretty", "printed", ".", "It", "is", "convenient", "to", "make", "the", "first", "to", "be", "a", "String", "with", "an", "informative", "message", "." ]
e93919f7fcfb408b941d6144290991a7feabaa7d
https://github.com/syborg/mme_tools/blob/e93919f7fcfb408b941d6144290991a7feabaa7d/lib/mme_tools/debug.rb#L18-L25
train
ihoka/friendly-attributes
lib/friendly_attributes/instance_methods.rb
FriendlyAttributes.InstanceMethods.friendly_instance_for_attribute
def friendly_instance_for_attribute(attr) klass = friendly_attributes_configuration.model_for_attribute(attr) send DetailsDelegator.friendly_model_reader(klass) end
ruby
def friendly_instance_for_attribute(attr) klass = friendly_attributes_configuration.model_for_attribute(attr) send DetailsDelegator.friendly_model_reader(klass) end
[ "def", "friendly_instance_for_attribute", "(", "attr", ")", "klass", "=", "friendly_attributes_configuration", ".", "model_for_attribute", "(", "attr", ")", "send", "DetailsDelegator", ".", "friendly_model_reader", "(", "klass", ")", "end" ]
Returns the Friendly instance corresponding to the specified attribute @param [Symbol, String] attr name of the attribute @return [Class] FriendyAttributes::Base instance
[ "Returns", "the", "Friendly", "instance", "corresponding", "to", "the", "specified", "attribute" ]
52c70a4028aa915f791d121bcf905a01989cad84
https://github.com/ihoka/friendly-attributes/blob/52c70a4028aa915f791d121bcf905a01989cad84/lib/friendly_attributes/instance_methods.rb#L23-L26
train
ihoka/friendly-attributes
lib/friendly_attributes/instance_methods.rb
FriendlyAttributes.InstanceMethods.friendly_instance_present?
def friendly_instance_present?(friendly_model) friendly_model_ivar = DetailsDelegator.friendly_model_ivar(friendly_model) val = instance_variable_get(friendly_model_ivar) val.present? end
ruby
def friendly_instance_present?(friendly_model) friendly_model_ivar = DetailsDelegator.friendly_model_ivar(friendly_model) val = instance_variable_get(friendly_model_ivar) val.present? end
[ "def", "friendly_instance_present?", "(", "friendly_model", ")", "friendly_model_ivar", "=", "DetailsDelegator", ".", "friendly_model_ivar", "(", "friendly_model", ")", "val", "=", "instance_variable_get", "(", "friendly_model_ivar", ")", "val", ".", "present?", "end" ]
Returns true if the FriendlyAttributes specified instance is loaded. @param [Class, Symbol, String] friendly_model Class or name of the FriendlyAttributes model @return [true, false] is the FriendlyAttributes instance loaded
[ "Returns", "true", "if", "the", "FriendlyAttributes", "specified", "instance", "is", "loaded", "." ]
52c70a4028aa915f791d121bcf905a01989cad84
https://github.com/ihoka/friendly-attributes/blob/52c70a4028aa915f791d121bcf905a01989cad84/lib/friendly_attributes/instance_methods.rb#L90-L94
train
dabassett/shibbolite
app/controllers/shibbolite/shibboleth_controller.rb
Shibbolite.ShibbolethController.load_session
def load_session unless logged_in? session[Shibbolite.pid] = request.env[Shibbolite.pid.to_s] current_user.update(get_attributes) if registered_user? end end
ruby
def load_session unless logged_in? session[Shibbolite.pid] = request.env[Shibbolite.pid.to_s] current_user.update(get_attributes) if registered_user? end end
[ "def", "load_session", "unless", "logged_in?", "session", "[", "Shibbolite", ".", "pid", "]", "=", "request", ".", "env", "[", "Shibbolite", ".", "pid", ".", "to_s", "]", "current_user", ".", "update", "(", "get_attributes", ")", "if", "registered_user?", "end", "end" ]
loads the session data created by shibboleth ensures that the user's id is set in session and updates the user's shibboleth attributes
[ "loads", "the", "session", "data", "created", "by", "shibboleth", "ensures", "that", "the", "user", "s", "id", "is", "set", "in", "session", "and", "updates", "the", "user", "s", "shibboleth", "attributes" ]
cbd679c88de4ab238c40029447715f6ff22f3f50
https://github.com/dabassett/shibbolite/blob/cbd679c88de4ab238c40029447715f6ff22f3f50/app/controllers/shibbolite/shibboleth_controller.rb#L39-L44
train
techiferous/rack-plastic
lib/rack-plastic.rb
Rack.Plastic.create_node
def create_node(doc, node_name, content=nil) #:doc: node = Nokogiri::XML::Node.new(node_name, doc) node.content = content if content node end
ruby
def create_node(doc, node_name, content=nil) #:doc: node = Nokogiri::XML::Node.new(node_name, doc) node.content = content if content node end
[ "def", "create_node", "(", "doc", ",", "node_name", ",", "content", "=", "nil", ")", "node", "=", "Nokogiri", "::", "XML", "::", "Node", ".", "new", "(", "node_name", ",", "doc", ")", "node", ".", "content", "=", "content", "if", "content", "node", "end" ]
a convenience method for quickly creating a new HTML element
[ "a", "convenience", "method", "for", "quickly", "creating", "a", "new", "HTML", "element" ]
581c299d85ef1c8b5fea32713e353a125f7619d4
https://github.com/techiferous/rack-plastic/blob/581c299d85ef1c8b5fea32713e353a125f7619d4/lib/rack-plastic.rb#L71-L75
train
cknadler/rcomp
lib/rcomp/process.rb
RComp.Process.run
def run begin @process.start rescue ChildProcess::LaunchError => e raise StandardError.new(e.message) end begin @process.poll_for_exit(@timeout) rescue ChildProcess::TimeoutError @timedout = true @process.stop(@timeout) end end
ruby
def run begin @process.start rescue ChildProcess::LaunchError => e raise StandardError.new(e.message) end begin @process.poll_for_exit(@timeout) rescue ChildProcess::TimeoutError @timedout = true @process.stop(@timeout) end end
[ "def", "run", "begin", "@process", ".", "start", "rescue", "ChildProcess", "::", "LaunchError", "=>", "e", "raise", "StandardError", ".", "new", "(", "e", ".", "message", ")", "end", "begin", "@process", ".", "poll_for_exit", "(", "@timeout", ")", "rescue", "ChildProcess", "::", "TimeoutError", "@timedout", "=", "true", "@process", ".", "stop", "(", "@timeout", ")", "end", "end" ]
Initialize a new process cmd - An array of shellwords of a command timeout - Time until the process is automatically killed out - Path to send stdout of process err - Path to send stderr of process Runs a process and with a specified command and timeout Returns nothing
[ "Initialize", "a", "new", "process" ]
76fe71e1ef3b13923738ea6ab9cd502fe2f64f51
https://github.com/cknadler/rcomp/blob/76fe71e1ef3b13923738ea6ab9cd502fe2f64f51/lib/rcomp/process.rb#L24-L37
train
mrsimonfletcher/roroacms
app/helpers/roroacms/general_helper.rb
Roroacms.GeneralHelper.rewrite_theme_helper
def rewrite_theme_helper if File.exists?("#{Rails.root}/app/views/themes/#{current_theme}/theme_helper.rb") # get the theme helper from the theme folder file = File.open("#{Rails.root}/app/views/themes/#{current_theme}/theme_helper.rb", "rb") contents = file.read # check if the first line starts with the module name or not parts = contents.split(/[\r\n]+/) if parts[0] != 'module ThemeHelper' contents = "module ThemeHelper\n\n" + contents + "\n\nend" end # write the contents to the actual file file File.open("#{Rails.root}/app/helpers/theme_helper.rb", 'w') { |file| file.write(contents) } else contents = "module ThemeHelper\n\nend" File.open("#{Rails.root}/app/helpers/theme_helper.rb", 'w') { |file| file.write(contents) } end load("#{Rails.root}/app/helpers/theme_helper.rb") end
ruby
def rewrite_theme_helper if File.exists?("#{Rails.root}/app/views/themes/#{current_theme}/theme_helper.rb") # get the theme helper from the theme folder file = File.open("#{Rails.root}/app/views/themes/#{current_theme}/theme_helper.rb", "rb") contents = file.read # check if the first line starts with the module name or not parts = contents.split(/[\r\n]+/) if parts[0] != 'module ThemeHelper' contents = "module ThemeHelper\n\n" + contents + "\n\nend" end # write the contents to the actual file file File.open("#{Rails.root}/app/helpers/theme_helper.rb", 'w') { |file| file.write(contents) } else contents = "module ThemeHelper\n\nend" File.open("#{Rails.root}/app/helpers/theme_helper.rb", 'w') { |file| file.write(contents) } end load("#{Rails.root}/app/helpers/theme_helper.rb") end
[ "def", "rewrite_theme_helper", "if", "File", ".", "exists?", "(", "\"#{Rails.root}/app/views/themes/#{current_theme}/theme_helper.rb\"", ")", "file", "=", "File", ".", "open", "(", "\"#{Rails.root}/app/views/themes/#{current_theme}/theme_helper.rb\"", ",", "\"rb\"", ")", "contents", "=", "file", ".", "read", "parts", "=", "contents", ".", "split", "(", "/", "\\r", "\\n", "/", ")", "if", "parts", "[", "0", "]", "!=", "'module ThemeHelper'", "contents", "=", "\"module ThemeHelper\\n\\n\"", "+", "contents", "+", "\"\\n\\nend\"", "end", "File", ".", "open", "(", "\"#{Rails.root}/app/helpers/theme_helper.rb\"", ",", "'w'", ")", "{", "|", "file", "|", "file", ".", "write", "(", "contents", ")", "}", "else", "contents", "=", "\"module ThemeHelper\\n\\nend\"", "File", ".", "open", "(", "\"#{Rails.root}/app/helpers/theme_helper.rb\"", ",", "'w'", ")", "{", "|", "file", "|", "file", ".", "write", "(", "contents", ")", "}", "end", "load", "(", "\"#{Rails.root}/app/helpers/theme_helper.rb\"", ")", "end" ]
rewrite the theme helper to use the themes function file
[ "rewrite", "the", "theme", "helper", "to", "use", "the", "themes", "function", "file" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/general_helper.rb#L19-L44
train
janx/factom-ruby
lib/factom-ruby/client.rb
Factom.Client.address_to_pubkey
def address_to_pubkey(addr) return unless addr.size == 52 prefix = ADDRESS_PREFIX[addr[0,2]] return unless prefix v = Bitcoin.decode_base58(addr) return if v[0,4] != prefix bytes = [v[0, 68]].pack('H*') return if v[68, 8] != sha256d(bytes)[0, 8] v[4, 64] end
ruby
def address_to_pubkey(addr) return unless addr.size == 52 prefix = ADDRESS_PREFIX[addr[0,2]] return unless prefix v = Bitcoin.decode_base58(addr) return if v[0,4] != prefix bytes = [v[0, 68]].pack('H*') return if v[68, 8] != sha256d(bytes)[0, 8] v[4, 64] end
[ "def", "address_to_pubkey", "(", "addr", ")", "return", "unless", "addr", ".", "size", "==", "52", "prefix", "=", "ADDRESS_PREFIX", "[", "addr", "[", "0", ",", "2", "]", "]", "return", "unless", "prefix", "v", "=", "Bitcoin", ".", "decode_base58", "(", "addr", ")", "return", "if", "v", "[", "0", ",", "4", "]", "!=", "prefix", "bytes", "=", "[", "v", "[", "0", ",", "68", "]", "]", ".", "pack", "(", "'H*'", ")", "return", "if", "v", "[", "68", ",", "8", "]", "!=", "sha256d", "(", "bytes", ")", "[", "0", ",", "8", "]", "v", "[", "4", ",", "64", "]", "end" ]
to pubkey in hex, 32 bytes
[ "to", "pubkey", "in", "hex", "32", "bytes" ]
54d9fafeeed106b37e73671f276ce622f6fd77a3
https://github.com/janx/factom-ruby/blob/54d9fafeeed106b37e73671f276ce622f6fd77a3/lib/factom-ruby/client.rb#L236-L249
train
codescrum/bebox
lib/bebox/vagrant_helper.rb
Bebox.VagrantHelper.prepare_vagrant
def prepare_vagrant(node) project_name = Bebox::Project.name_from_file(node.project_root) vagrant_box_base = Bebox::Project.vagrant_box_base_from_file(node.project_root) configure_local_hosts(project_name, node) add_vagrant_node(project_name, vagrant_box_base, node) end
ruby
def prepare_vagrant(node) project_name = Bebox::Project.name_from_file(node.project_root) vagrant_box_base = Bebox::Project.vagrant_box_base_from_file(node.project_root) configure_local_hosts(project_name, node) add_vagrant_node(project_name, vagrant_box_base, node) end
[ "def", "prepare_vagrant", "(", "node", ")", "project_name", "=", "Bebox", "::", "Project", ".", "name_from_file", "(", "node", ".", "project_root", ")", "vagrant_box_base", "=", "Bebox", "::", "Project", ".", "vagrant_box_base_from_file", "(", "node", ".", "project_root", ")", "configure_local_hosts", "(", "project_name", ",", "node", ")", "add_vagrant_node", "(", "project_name", ",", "vagrant_box_base", ",", "node", ")", "end" ]
Prepare the vagrant nodes
[ "Prepare", "the", "vagrant", "nodes" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/vagrant_helper.rb#L56-L61
train
kui/active_window_x
lib/active_window_x/window.rb
ActiveWindowX.Window.prop
def prop atom val, format, nitems = prop_raw atom case format when 32; val.unpack("l!#{nitems}") when 16; val.unpack("s#{nitems}") when 8; val[0, nitems] when 0; nil end end
ruby
def prop atom val, format, nitems = prop_raw atom case format when 32; val.unpack("l!#{nitems}") when 16; val.unpack("s#{nitems}") when 8; val[0, nitems] when 0; nil end end
[ "def", "prop", "atom", "val", ",", "format", ",", "nitems", "=", "prop_raw", "atom", "case", "format", "when", "32", ";", "val", ".", "unpack", "(", "\"l!#{nitems}\"", ")", "when", "16", ";", "val", ".", "unpack", "(", "\"s#{nitems}\"", ")", "when", "8", ";", "val", "[", "0", ",", "nitems", "]", "when", "0", ";", "nil", "end", "end" ]
window property getter with easy way for XGetWindowProperty which return nil, if the specified property name does not exist, a String or a Array of Number
[ "window", "property", "getter", "with", "easy", "way", "for", "XGetWindowProperty", "which", "return", "nil", "if", "the", "specified", "property", "name", "does", "not", "exist", "a", "String", "or", "a", "Array", "of", "Number" ]
9c571aeaace5e739d6c577917234e708541f5216
https://github.com/kui/active_window_x/blob/9c571aeaace5e739d6c577917234e708541f5216/lib/active_window_x/window.rb#L75-L83
train
chrisjones-tripletri/action_command
lib/action_command/input_output.rb
ActionCommand.InputOutput.validate_input
def validate_input(dest, args) return true unless should_validate(dest) @input.each do |p| val = args[p[:symbol]] # if the argument has a value, no need to test whether it is optional. next unless !val || val == '*' || val == '' opts = p[:opts] unless opts[:optional] raise ArgumentError, "You must specify the required input #{p[:symbol]}" end end return true end
ruby
def validate_input(dest, args) return true unless should_validate(dest) @input.each do |p| val = args[p[:symbol]] # if the argument has a value, no need to test whether it is optional. next unless !val || val == '*' || val == '' opts = p[:opts] unless opts[:optional] raise ArgumentError, "You must specify the required input #{p[:symbol]}" end end return true end
[ "def", "validate_input", "(", "dest", ",", "args", ")", "return", "true", "unless", "should_validate", "(", "dest", ")", "@input", ".", "each", "do", "|", "p", "|", "val", "=", "args", "[", "p", "[", ":symbol", "]", "]", "next", "unless", "!", "val", "||", "val", "==", "'*'", "||", "val", "==", "''", "opts", "=", "p", "[", ":opts", "]", "unless", "opts", "[", ":optional", "]", "raise", "ArgumentError", ",", "\"You must specify the required input #{p[:symbol]}\"", "end", "end", "return", "true", "end" ]
Validates that the specified parameters are valid for this input description. @param args [Hash] the arguments to validate
[ "Validates", "that", "the", "specified", "parameters", "are", "valid", "for", "this", "input", "description", "." ]
9b9a8ba30e407ca6d88a62a164d1dc22ba149874
https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/input_output.rb#L37-L51
train
chrisjones-tripletri/action_command
lib/action_command/input_output.rb
ActionCommand.InputOutput.process_input
def process_input(dest, args) # pass down predefined attributes. dest.parent = args[:parent] dest.test = args[:test] return unless validate_input(dest, args) @input.each do |param| sym = param[:symbol] if args.key? sym sym_assign = "#{sym}=".to_sym dest.send(sym_assign, args[sym]) end end end
ruby
def process_input(dest, args) # pass down predefined attributes. dest.parent = args[:parent] dest.test = args[:test] return unless validate_input(dest, args) @input.each do |param| sym = param[:symbol] if args.key? sym sym_assign = "#{sym}=".to_sym dest.send(sym_assign, args[sym]) end end end
[ "def", "process_input", "(", "dest", ",", "args", ")", "dest", ".", "parent", "=", "args", "[", ":parent", "]", "dest", ".", "test", "=", "args", "[", ":test", "]", "return", "unless", "validate_input", "(", "dest", ",", "args", ")", "@input", ".", "each", "do", "|", "param", "|", "sym", "=", "param", "[", ":symbol", "]", "if", "args", ".", "key?", "sym", "sym_assign", "=", "\"#{sym}=\"", ".", "to_sym", "dest", ".", "send", "(", "sym_assign", ",", "args", "[", "sym", "]", ")", "end", "end", "end" ]
Goes through, and assigns the value for each declared parameter to an accessor with the same name, validating that required parameters are not missing
[ "Goes", "through", "and", "assigns", "the", "value", "for", "each", "declared", "parameter", "to", "an", "accessor", "with", "the", "same", "name", "validating", "that", "required", "parameters", "are", "not", "missing" ]
9b9a8ba30e407ca6d88a62a164d1dc22ba149874
https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/input_output.rb#L55-L69
train
chrisjones-tripletri/action_command
lib/action_command/input_output.rb
ActionCommand.InputOutput.process_output
def process_output(dest, result) return unless result.ok? && should_validate(dest) @output.each do |param| sym = param[:symbol] unless result.key?(sym) opts = param[:opts] raise ArgumentError, "Missing required value #{sym} in output" unless opts[:optional] end end end
ruby
def process_output(dest, result) return unless result.ok? && should_validate(dest) @output.each do |param| sym = param[:symbol] unless result.key?(sym) opts = param[:opts] raise ArgumentError, "Missing required value #{sym} in output" unless opts[:optional] end end end
[ "def", "process_output", "(", "dest", ",", "result", ")", "return", "unless", "result", ".", "ok?", "&&", "should_validate", "(", "dest", ")", "@output", ".", "each", "do", "|", "param", "|", "sym", "=", "param", "[", ":symbol", "]", "unless", "result", ".", "key?", "(", "sym", ")", "opts", "=", "param", "[", ":opts", "]", "raise", "ArgumentError", ",", "\"Missing required value #{sym} in output\"", "unless", "opts", "[", ":optional", "]", "end", "end", "end" ]
Goes through, and makes sure that required output parameters exist
[ "Goes", "through", "and", "makes", "sure", "that", "required", "output", "parameters", "exist" ]
9b9a8ba30e407ca6d88a62a164d1dc22ba149874
https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/input_output.rb#L72-L82
train
chrisjones-tripletri/action_command
lib/action_command/input_output.rb
ActionCommand.InputOutput.rake_input
def rake_input(rake_arg) params = {} rake_arg.each do |key, val| params[key] = val end # by default, use human logging if a logger is enabled. params[:logger] = Logger.new(STDOUT) unless params.key?(:logger) params[:log_format] = :human unless params.key?(:log_format) return params end
ruby
def rake_input(rake_arg) params = {} rake_arg.each do |key, val| params[key] = val end # by default, use human logging if a logger is enabled. params[:logger] = Logger.new(STDOUT) unless params.key?(:logger) params[:log_format] = :human unless params.key?(:log_format) return params end
[ "def", "rake_input", "(", "rake_arg", ")", "params", "=", "{", "}", "rake_arg", ".", "each", "do", "|", "key", ",", "val", "|", "params", "[", "key", "]", "=", "val", "end", "params", "[", ":logger", "]", "=", "Logger", ".", "new", "(", "STDOUT", ")", "unless", "params", ".", "key?", "(", ":logger", ")", "params", "[", ":log_format", "]", "=", ":human", "unless", "params", ".", "key?", "(", ":log_format", ")", "return", "params", "end" ]
convert rake task arguments to a standard hash.
[ "convert", "rake", "task", "arguments", "to", "a", "standard", "hash", "." ]
9b9a8ba30e407ca6d88a62a164d1dc22ba149874
https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/input_output.rb#L85-L95
train
jkotests/watir-wait_with_refresh
lib/watir/wait_with_refresh/element.rb
Watir.Element.refresh_until_present
def refresh_until_present(timeout = 30) message = "waiting for #{@selector.inspect} to become present" Watir::WaitWithRefresh.refresh_until(browser, timeout, message) { present? } end
ruby
def refresh_until_present(timeout = 30) message = "waiting for #{@selector.inspect} to become present" Watir::WaitWithRefresh.refresh_until(browser, timeout, message) { present? } end
[ "def", "refresh_until_present", "(", "timeout", "=", "30", ")", "message", "=", "\"waiting for #{@selector.inspect} to become present\"", "Watir", "::", "WaitWithRefresh", ".", "refresh_until", "(", "browser", ",", "timeout", ",", "message", ")", "{", "present?", "}", "end" ]
Refresh the page until the element is present. @example browser.button(:id => 'foo').refresh_until_present @param [Fixnum] timeout seconds to wait before timing out @see Watir::WaitWithRefresh @see Watir::Element#present?
[ "Refresh", "the", "page", "until", "the", "element", "is", "present", "." ]
f8f6e202cc5d9843dd6ecb657f65b904b46fe048
https://github.com/jkotests/watir-wait_with_refresh/blob/f8f6e202cc5d9843dd6ecb657f65b904b46fe048/lib/watir/wait_with_refresh/element.rb#L17-L20
train
jkotests/watir-wait_with_refresh
lib/watir/wait_with_refresh/element.rb
Watir.Element.refresh_while_present
def refresh_while_present(timeout = 30) message = "waiting for #{@selector.inspect} to disappear" Watir::WaitWithRefresh.refresh_while(browser, timeout, message) { present? } end
ruby
def refresh_while_present(timeout = 30) message = "waiting for #{@selector.inspect} to disappear" Watir::WaitWithRefresh.refresh_while(browser, timeout, message) { present? } end
[ "def", "refresh_while_present", "(", "timeout", "=", "30", ")", "message", "=", "\"waiting for #{@selector.inspect} to disappear\"", "Watir", "::", "WaitWithRefresh", ".", "refresh_while", "(", "browser", ",", "timeout", ",", "message", ")", "{", "present?", "}", "end" ]
Refresh the page while the element is present. @example browser.button(:id => 'foo').refresh_while_present @param [Integer] timeout seconds to wait before timing out @see Watir::WaitWithRefresh @see Watir::Element#present?
[ "Refresh", "the", "page", "while", "the", "element", "is", "present", "." ]
f8f6e202cc5d9843dd6ecb657f65b904b46fe048
https://github.com/jkotests/watir-wait_with_refresh/blob/f8f6e202cc5d9843dd6ecb657f65b904b46fe048/lib/watir/wait_with_refresh/element.rb#L34-L37
train
jkotests/watir-wait_with_refresh
lib/watir/wait_with_refresh/element.rb
Watir.Element.when_present_after_refresh
def when_present_after_refresh(timeout = 30) message = "waiting for #{@selector.inspect} to become present" if block_given? Watir::WaitWithRefresh.refresh_until(browser, timeout, message) { present? } yield self else WhenPresentAfterRefreshDecorator.new(self, timeout, message) end end
ruby
def when_present_after_refresh(timeout = 30) message = "waiting for #{@selector.inspect} to become present" if block_given? Watir::WaitWithRefresh.refresh_until(browser, timeout, message) { present? } yield self else WhenPresentAfterRefreshDecorator.new(self, timeout, message) end end
[ "def", "when_present_after_refresh", "(", "timeout", "=", "30", ")", "message", "=", "\"waiting for #{@selector.inspect} to become present\"", "if", "block_given?", "Watir", "::", "WaitWithRefresh", ".", "refresh_until", "(", "browser", ",", "timeout", ",", "message", ")", "{", "present?", "}", "yield", "self", "else", "WhenPresentAfterRefreshDecorator", ".", "new", "(", "self", ",", "timeout", ",", "message", ")", "end", "end" ]
Refreshes the page until the element is present. @example browser.button(:id => 'foo').when_present_after_refresh.click browser.div(:id => 'bar').when_present_after_refresh { |div| ... } browser.p(:id => 'baz').when_present_after_refresh(60).text @param [Fixnum] timeout seconds to wait before timing out @see Watir::WaitWithRefresh @see Watir::Element#present?
[ "Refreshes", "the", "page", "until", "the", "element", "is", "present", "." ]
f8f6e202cc5d9843dd6ecb657f65b904b46fe048
https://github.com/jkotests/watir-wait_with_refresh/blob/f8f6e202cc5d9843dd6ecb657f65b904b46fe048/lib/watir/wait_with_refresh/element.rb#L53-L62
train
robertwahler/mutagem
lib/mutagem/lockfile.rb
Mutagem.Lockfile.locked?
def locked? return false unless File.exists?(lockfile) result = false open(lockfile, 'w') do |f| # exclusive non-blocking lock result = !lock(f, File::LOCK_EX | File::LOCK_NB) end result end
ruby
def locked? return false unless File.exists?(lockfile) result = false open(lockfile, 'w') do |f| # exclusive non-blocking lock result = !lock(f, File::LOCK_EX | File::LOCK_NB) end result end
[ "def", "locked?", "return", "false", "unless", "File", ".", "exists?", "(", "lockfile", ")", "result", "=", "false", "open", "(", "lockfile", ",", "'w'", ")", "do", "|", "f", "|", "result", "=", "!", "lock", "(", "f", ",", "File", "::", "LOCK_EX", "|", "File", "::", "LOCK_NB", ")", "end", "result", "end" ]
Create a new LockFile @param [String] lockfile filename Does another process have a lock? True if we can't get an exclusive lock
[ "Create", "a", "new", "LockFile" ]
75ac2f7fd307f575d81114b32e1a3b09c526e01d
https://github.com/robertwahler/mutagem/blob/75ac2f7fd307f575d81114b32e1a3b09c526e01d/lib/mutagem/lockfile.rb#L18-L26
train