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
mbj/ducktrap
lib/ducktrap/formatter.rb
Ducktrap.Formatter.nest
def nest(label, nested) indented = indent indented.puts("#{label}:") nested.pretty_dump(indented.indent) self end
ruby
def nest(label, nested) indented = indent indented.puts("#{label}:") nested.pretty_dump(indented.indent) self end
[ "def", "nest", "(", "label", ",", "nested", ")", "indented", "=", "indent", "indented", ".", "puts", "(", "\"#{label}:\"", ")", "nested", ".", "pretty_dump", "(", "indented", ".", "indent", ")", "self", "end" ]
Write nest with label @param [String] label @param [#pretty_dump] nested @return [self] @api private
[ "Write", "nest", "with", "label" ]
482d874d3eb43b2dbb518b8537851d742d785903
https://github.com/mbj/ducktrap/blob/482d874d3eb43b2dbb518b8537851d742d785903/lib/ducktrap/formatter.rb#L58-L63
train
mbj/ducktrap
lib/ducktrap/formatter.rb
Ducktrap.Formatter.puts
def puts(string) util = output util.write(prefix) util.puts(string) self end
ruby
def puts(string) util = output util.write(prefix) util.puts(string) self end
[ "def", "puts", "(", "string", ")", "util", "=", "output", "util", ".", "write", "(", "prefix", ")", "util", ".", "puts", "(", "string", ")", "self", "end" ]
Write string with indentation @param [String] string @return [self] @api private
[ "Write", "string", "with", "indentation" ]
482d874d3eb43b2dbb518b8537851d742d785903
https://github.com/mbj/ducktrap/blob/482d874d3eb43b2dbb518b8537851d742d785903/lib/ducktrap/formatter.rb#L104-L109
train
bmedici/bmc-daemon-lib
lib/bmc-daemon-lib/logger.rb
BmcDaemonLib.Logger.build_context
def build_context context # Skip if no format defined return unless @format[:context].is_a? Hash # Call the instance's method to get hash context return unless context.is_a? Hash # Build each context part return @format[:context].collect do |key, format| sprintf(format, context[key]) end.join rescue KeyError, ArgumentError => ex return "[context: #{ex.message}]" end
ruby
def build_context context # Skip if no format defined return unless @format[:context].is_a? Hash # Call the instance's method to get hash context return unless context.is_a? Hash # Build each context part return @format[:context].collect do |key, format| sprintf(format, context[key]) end.join rescue KeyError, ArgumentError => ex return "[context: #{ex.message}]" end
[ "def", "build_context", "context", "return", "unless", "@format", "[", ":context", "]", ".", "is_a?", "Hash", "return", "unless", "context", ".", "is_a?", "Hash", "return", "@format", "[", ":context", "]", ".", "collect", "do", "|", "key", ",", "format", "|", "sprintf", "(", "format", ",", "context", "[", "key", "]", ")", "end", ".", "join", "rescue", "KeyError", ",", "ArgumentError", "=>", "ex", "return", "\"[context: #{ex.message}]\"", "end" ]
Builds prefix from @format[:context] and context
[ "Builds", "prefix", "from" ]
63682b875adecde960691d8a1dfbade06cf8d1ab
https://github.com/bmedici/bmc-daemon-lib/blob/63682b875adecde960691d8a1dfbade06cf8d1ab/lib/bmc-daemon-lib/logger.rb#L104-L118
train
tatey/simple_mock
lib/simple_mock/mock_delegator.rb
SimpleMock.MockDelegator.expect
def expect name, retval, args = [] method_definition = Module.new do define_method name do |*args, &block| __tracer.assert name, args retval end end extend method_definition __tracer.register name, args self end
ruby
def expect name, retval, args = [] method_definition = Module.new do define_method name do |*args, &block| __tracer.assert name, args retval end end extend method_definition __tracer.register name, args self end
[ "def", "expect", "name", ",", "retval", ",", "args", "=", "[", "]", "method_definition", "=", "Module", ".", "new", "do", "define_method", "name", "do", "|", "*", "args", ",", "&", "block", "|", "__tracer", ".", "assert", "name", ",", "args", "retval", "end", "end", "extend", "method_definition", "__tracer", ".", "register", "name", ",", "args", "self", "end" ]
Expect that method +name+ is called, optionally with +args+, and returns +retval+. mock.expect :meaning_of_life, 42 mock.meaning_of_life # => 42 mock.expect :do_something_with, true, [some_obj, true] mock.do_something_with some_obj, true # => true +args+ is compared to the expected args using case equality (ie, the '===' method), allowing for less specific expectations. mock.expect :uses_any_string, true, [String] mock.uses_any_string 'foo' # => true mock.verify # => true mock.expect :uses_one_string, true, ['foo'] mock.uses_one_string 'bar' # => true mock.verify # => raises MockExpectationError
[ "Expect", "that", "method", "+", "name", "+", "is", "called", "optionally", "with", "+", "args", "+", "and", "returns", "+", "retval", "+", "." ]
3081f714228903745d66f32cc6186946a9f2524e
https://github.com/tatey/simple_mock/blob/3081f714228903745d66f32cc6186946a9f2524e/lib/simple_mock/mock_delegator.rb#L33-L43
train
cknadler/rcomp
lib/rcomp/reporter.rb
RComp.Reporter.report
def report(test) case test.result when :success if @type == :test print_test_success(test) else print_generate_success(test) end @success += 1 when :skipped if @type == :test print_test_skipped(test) else print_generate_skipped(test) end @skipped += 1 # Generate can't fail directly when :failed print_test_failed(test) @failed += 1 when :timedout if @type == :test print_test_timeout(test) else print_generate_timeout(test) end @failed += 1 end end
ruby
def report(test) case test.result when :success if @type == :test print_test_success(test) else print_generate_success(test) end @success += 1 when :skipped if @type == :test print_test_skipped(test) else print_generate_skipped(test) end @skipped += 1 # Generate can't fail directly when :failed print_test_failed(test) @failed += 1 when :timedout if @type == :test print_test_timeout(test) else print_generate_timeout(test) end @failed += 1 end end
[ "def", "report", "(", "test", ")", "case", "test", ".", "result", "when", ":success", "if", "@type", "==", ":test", "print_test_success", "(", "test", ")", "else", "print_generate_success", "(", "test", ")", "end", "@success", "+=", "1", "when", ":skipped", "if", "@type", "==", ":test", "print_test_skipped", "(", "test", ")", "else", "print_generate_skipped", "(", "test", ")", "end", "@skipped", "+=", "1", "when", ":failed", "print_test_failed", "(", "test", ")", "@failed", "+=", "1", "when", ":timedout", "if", "@type", "==", ":test", "print_test_timeout", "(", "test", ")", "else", "print_generate_timeout", "(", "test", ")", "end", "@failed", "+=", "1", "end", "end" ]
Initialize a new Reporter type - The type (Symbol) of the suite Initialize counters for all result types Main interface for reporting Reports the result of a single test or generation test - A test object that has been run Returns nothing
[ "Initialize", "a", "new", "Reporter" ]
76fe71e1ef3b13923738ea6ab9cd502fe2f64f51
https://github.com/cknadler/rcomp/blob/76fe71e1ef3b13923738ea6ab9cd502fe2f64f51/lib/rcomp/reporter.rb#L31-L62
train
ritxi/sermepa_web_tpv
lib/sermepa_web_tpv/request.rb
SermepaWebTpv.Request.url_for
def url_for(option) host = SermepaWebTpv.response_host path = SermepaWebTpv.send(option) return if !host.present? || !path.present? URI.join(host, path).to_s end
ruby
def url_for(option) host = SermepaWebTpv.response_host path = SermepaWebTpv.send(option) return if !host.present? || !path.present? URI.join(host, path).to_s end
[ "def", "url_for", "(", "option", ")", "host", "=", "SermepaWebTpv", ".", "response_host", "path", "=", "SermepaWebTpv", ".", "send", "(", "option", ")", "return", "if", "!", "host", ".", "present?", "||", "!", "path", ".", "present?", "URI", ".", "join", "(", "host", ",", "path", ")", ".", "to_s", "end" ]
Available options redirect_success_path redirect_failure_path callback_response_path
[ "Available", "options", "redirect_success_path", "redirect_failure_path", "callback_response_path" ]
a923d1668ad1ce161896eb8e0fe32082ee969399
https://github.com/ritxi/sermepa_web_tpv/blob/a923d1668ad1ce161896eb8e0fe32082ee969399/lib/sermepa_web_tpv/request.rb#L61-L67
train
premist/motion-locman
lib/locman/manager.rb
Locman.Manager.background=
def background=(background) if !background.is_a?(TrueClass) && !background.is_a?(FalseClass) fail(ArgumentError, "Background should be boolean") end manager.allowsBackgroundLocationUpdates = background @background = background end
ruby
def background=(background) if !background.is_a?(TrueClass) && !background.is_a?(FalseClass) fail(ArgumentError, "Background should be boolean") end manager.allowsBackgroundLocationUpdates = background @background = background end
[ "def", "background", "=", "(", "background", ")", "if", "!", "background", ".", "is_a?", "(", "TrueClass", ")", "&&", "!", "background", ".", "is_a?", "(", "FalseClass", ")", "fail", "(", "ArgumentError", ",", "\"Background should be boolean\"", ")", "end", "manager", ".", "allowsBackgroundLocationUpdates", "=", "background", "@background", "=", "background", "end" ]
Sets whether location should be updated on the background or not.
[ "Sets", "whether", "location", "should", "be", "updated", "on", "the", "background", "or", "not", "." ]
edf8853b16c4bcbddb103b0aa0cec6517256574a
https://github.com/premist/motion-locman/blob/edf8853b16c4bcbddb103b0aa0cec6517256574a/lib/locman/manager.rb#L73-L80
train
wedesoft/multiarray
lib/multiarray/methods.rb
Hornetseye.Methods.define_unary_method
def define_unary_method( mod, op, conversion = :identity ) mod.module_eval do define_method "#{op}_with_hornetseye" do |a| if a.matched? if a.dimension == 0 and a.variables.empty? target = a.typecode.send conversion target.new mod.send( op, a.simplify.get ) else Hornetseye::ElementWise( proc { |x| mod.send op, x }, "#{mod}.#{op}", proc { |x| x.send conversion } ). new(a).force end else send "#{op}_without_hornetseye", a end end alias_method_chain op, :hornetseye module_function "#{op}_without_hornetseye" module_function op end end
ruby
def define_unary_method( mod, op, conversion = :identity ) mod.module_eval do define_method "#{op}_with_hornetseye" do |a| if a.matched? if a.dimension == 0 and a.variables.empty? target = a.typecode.send conversion target.new mod.send( op, a.simplify.get ) else Hornetseye::ElementWise( proc { |x| mod.send op, x }, "#{mod}.#{op}", proc { |x| x.send conversion } ). new(a).force end else send "#{op}_without_hornetseye", a end end alias_method_chain op, :hornetseye module_function "#{op}_without_hornetseye" module_function op end end
[ "def", "define_unary_method", "(", "mod", ",", "op", ",", "conversion", "=", ":identity", ")", "mod", ".", "module_eval", "do", "define_method", "\"#{op}_with_hornetseye\"", "do", "|", "a", "|", "if", "a", ".", "matched?", "if", "a", ".", "dimension", "==", "0", "and", "a", ".", "variables", ".", "empty?", "target", "=", "a", ".", "typecode", ".", "send", "conversion", "target", ".", "new", "mod", ".", "send", "(", "op", ",", "a", ".", "simplify", ".", "get", ")", "else", "Hornetseye", "::", "ElementWise", "(", "proc", "{", "|", "x", "|", "mod", ".", "send", "op", ",", "x", "}", ",", "\"#{mod}.#{op}\"", ",", "proc", "{", "|", "x", "|", "x", ".", "send", "conversion", "}", ")", ".", "new", "(", "a", ")", ".", "force", "end", "else", "send", "\"#{op}_without_hornetseye\"", ",", "a", "end", "end", "alias_method_chain", "op", ",", ":hornetseye", "module_function", "\"#{op}_without_hornetseye\"", "module_function", "op", "end", "end" ]
Extend unary method with capability to handle arrays @param [Module] mod The mathematics module. @param [Symbol,String] op The unary method to extend. @param [Symbol,String] conversion A method for doing the type conversion. @return [Proc] The new method. @private
[ "Extend", "unary", "method", "with", "capability", "to", "handle", "arrays" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/methods.rb#L58-L79
train
wedesoft/multiarray
lib/multiarray/methods.rb
Hornetseye.Methods.define_binary_method
def define_binary_method( mod, op, coercion = :coercion ) mod.module_eval do define_method "#{op}_with_hornetseye" do |a,b| if a.matched? or b.matched? a = Node.match(a, b).new a unless a.matched? b = Node.match(b, a).new b unless b.matched? if a.dimension == 0 and a.variables.empty? and b.dimension == 0 and b.variables.empty? target = a.typecode.send coercion, b.typecode target.new mod.send(op, a.simplify.get, b.simplify.get) else Hornetseye::ElementWise( proc { |x,y| mod.send op, x, y }, "#{mod}.#{op}", proc { |t,u| t.send coercion, u } ). new(a, b).force end else send "#{op}_without_hornetseye", a, b end end alias_method_chain op, :hornetseye module_function "#{op}_without_hornetseye" module_function op end end
ruby
def define_binary_method( mod, op, coercion = :coercion ) mod.module_eval do define_method "#{op}_with_hornetseye" do |a,b| if a.matched? or b.matched? a = Node.match(a, b).new a unless a.matched? b = Node.match(b, a).new b unless b.matched? if a.dimension == 0 and a.variables.empty? and b.dimension == 0 and b.variables.empty? target = a.typecode.send coercion, b.typecode target.new mod.send(op, a.simplify.get, b.simplify.get) else Hornetseye::ElementWise( proc { |x,y| mod.send op, x, y }, "#{mod}.#{op}", proc { |t,u| t.send coercion, u } ). new(a, b).force end else send "#{op}_without_hornetseye", a, b end end alias_method_chain op, :hornetseye module_function "#{op}_without_hornetseye" module_function op end end
[ "def", "define_binary_method", "(", "mod", ",", "op", ",", "coercion", "=", ":coercion", ")", "mod", ".", "module_eval", "do", "define_method", "\"#{op}_with_hornetseye\"", "do", "|", "a", ",", "b", "|", "if", "a", ".", "matched?", "or", "b", ".", "matched?", "a", "=", "Node", ".", "match", "(", "a", ",", "b", ")", ".", "new", "a", "unless", "a", ".", "matched?", "b", "=", "Node", ".", "match", "(", "b", ",", "a", ")", ".", "new", "b", "unless", "b", ".", "matched?", "if", "a", ".", "dimension", "==", "0", "and", "a", ".", "variables", ".", "empty?", "and", "b", ".", "dimension", "==", "0", "and", "b", ".", "variables", ".", "empty?", "target", "=", "a", ".", "typecode", ".", "send", "coercion", ",", "b", ".", "typecode", "target", ".", "new", "mod", ".", "send", "(", "op", ",", "a", ".", "simplify", ".", "get", ",", "b", ".", "simplify", ".", "get", ")", "else", "Hornetseye", "::", "ElementWise", "(", "proc", "{", "|", "x", ",", "y", "|", "mod", ".", "send", "op", ",", "x", ",", "y", "}", ",", "\"#{mod}.#{op}\"", ",", "proc", "{", "|", "t", ",", "u", "|", "t", ".", "send", "coercion", ",", "u", "}", ")", ".", "new", "(", "a", ",", "b", ")", ".", "force", "end", "else", "send", "\"#{op}_without_hornetseye\"", ",", "a", ",", "b", "end", "end", "alias_method_chain", "op", ",", ":hornetseye", "module_function", "\"#{op}_without_hornetseye\"", "module_function", "op", "end", "end" ]
Extend binary method with capability to handle arrays @param [Module] mod The mathematics module. @param [Symbol,String] op The binary method to extend. @param [Symbol,String] conversion A method for doing the type balancing. @return [Proc] The new method. @private
[ "Extend", "binary", "method", "with", "capability", "to", "handle", "arrays" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/methods.rb#L91-L115
train
jinx/core
lib/jinx/import/class_path_modifier.rb
Jinx.ClassPathModifier.expand_to_class_path
def expand_to_class_path(path) # the path separator sep = path[WINDOWS_PATH_SEP] ? WINDOWS_PATH_SEP : UNIX_PATH_SEP # the path directories dirs = path.split(sep).map { |dir| File.expand_path(dir) } expanded = expand_jars(dirs) expanded.each { |dir| add_to_classpath(dir) } end
ruby
def expand_to_class_path(path) # the path separator sep = path[WINDOWS_PATH_SEP] ? WINDOWS_PATH_SEP : UNIX_PATH_SEP # the path directories dirs = path.split(sep).map { |dir| File.expand_path(dir) } expanded = expand_jars(dirs) expanded.each { |dir| add_to_classpath(dir) } end
[ "def", "expand_to_class_path", "(", "path", ")", "sep", "=", "path", "[", "WINDOWS_PATH_SEP", "]", "?", "WINDOWS_PATH_SEP", ":", "UNIX_PATH_SEP", "dirs", "=", "path", ".", "split", "(", "sep", ")", ".", "map", "{", "|", "dir", "|", "File", ".", "expand_path", "(", "dir", ")", "}", "expanded", "=", "expand_jars", "(", "dirs", ")", "expanded", ".", "each", "{", "|", "dir", "|", "add_to_classpath", "(", "dir", ")", "}", "end" ]
Adds the directories in the given path and all Java jar files contained in the directories to the Java classpath. @quirk Java The jar files found by this method are added to the classpath in sort order. Java applications usually add jars in sort order. For examle, the Apache Ant directory-based classpath tasks are in sort order, although this is not stipulated in the documentation. Well-behaved Java libraries are not dependent on the sort order of included jar files. For poorly-behaved Java libraries, ensure that the classpath is in the expected order. If the classpath must be in a non-sorted order, then call {#add_to_classpath} on each jar file instead. @param [String] path the colon or semi-colon separated directories
[ "Adds", "the", "directories", "in", "the", "given", "path", "and", "all", "Java", "jar", "files", "contained", "in", "the", "directories", "to", "the", "Java", "classpath", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/import/class_path_modifier.rb#L17-L24
train
jinx/core
lib/jinx/import/class_path_modifier.rb
Jinx.ClassPathModifier.add_to_classpath
def add_to_classpath(file) unless File.exist?(file) then logger.warn("File to place on Java classpath does not exist: #{file}") return end if File.extname(file) == '.jar' then # require is preferred to classpath append for a jar file. require file else # A directory must end in a slash since JRuby uses an URLClassLoader. if File.directory?(file) then last = file[-1, 1] if last == "\\" then file = file[0...-1] + '/' elsif last != '/' then file = file + '/' end end # Append the file to the classpath. $CLASSPATH << file end end
ruby
def add_to_classpath(file) unless File.exist?(file) then logger.warn("File to place on Java classpath does not exist: #{file}") return end if File.extname(file) == '.jar' then # require is preferred to classpath append for a jar file. require file else # A directory must end in a slash since JRuby uses an URLClassLoader. if File.directory?(file) then last = file[-1, 1] if last == "\\" then file = file[0...-1] + '/' elsif last != '/' then file = file + '/' end end # Append the file to the classpath. $CLASSPATH << file end end
[ "def", "add_to_classpath", "(", "file", ")", "unless", "File", ".", "exist?", "(", "file", ")", "then", "logger", ".", "warn", "(", "\"File to place on Java classpath does not exist: #{file}\"", ")", "return", "end", "if", "File", ".", "extname", "(", "file", ")", "==", "'.jar'", "then", "require", "file", "else", "if", "File", ".", "directory?", "(", "file", ")", "then", "last", "=", "file", "[", "-", "1", ",", "1", "]", "if", "last", "==", "\"\\\\\"", "then", "file", "=", "file", "[", "0", "...", "-", "1", "]", "+", "'/'", "elsif", "last", "!=", "'/'", "then", "file", "=", "file", "+", "'/'", "end", "end", "$CLASSPATH", "<<", "file", "end", "end" ]
Adds the given jar file or directory to the classpath. @param [String] file the jar file or directory to add
[ "Adds", "the", "given", "jar", "file", "or", "directory", "to", "the", "classpath", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/import/class_path_modifier.rb#L29-L50
train
jinx/core
lib/jinx/import/class_path_modifier.rb
Jinx.ClassPathModifier.expand_jars
def expand_jars(directories) # If there are jar files, then the file list is the sorted jar files. # Otherwise, the file list is a singleton directory array. expanded = directories.map do |dir| jars = Dir[File.join(dir , "**", "*.jar")].sort jars.empty? ? [dir] : jars end expanded.flatten end
ruby
def expand_jars(directories) # If there are jar files, then the file list is the sorted jar files. # Otherwise, the file list is a singleton directory array. expanded = directories.map do |dir| jars = Dir[File.join(dir , "**", "*.jar")].sort jars.empty? ? [dir] : jars end expanded.flatten end
[ "def", "expand_jars", "(", "directories", ")", "expanded", "=", "directories", ".", "map", "do", "|", "dir", "|", "jars", "=", "Dir", "[", "File", ".", "join", "(", "dir", ",", "\"**\"", ",", "\"*.jar\"", ")", "]", ".", "sort", "jars", ".", "empty?", "?", "[", "dir", "]", ":", "jars", "end", "expanded", ".", "flatten", "end" ]
Expands the given directories to include the contained jar files. If a directory contains jar files, then the jar files are included in the resulting array. Otherwise, the directory itself is included in the resulting array. @param [<String>] directories the directories containing jars to add @return [<String>] each directory or its jars
[ "Expands", "the", "given", "directories", "to", "include", "the", "contained", "jar", "files", ".", "If", "a", "directory", "contains", "jar", "files", "then", "the", "jar", "files", "are", "included", "in", "the", "resulting", "array", ".", "Otherwise", "the", "directory", "itself", "is", "included", "in", "the", "resulting", "array", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/import/class_path_modifier.rb#L67-L75
train
robfors/ruby-sumac
lib/sumac/messenger.rb
Sumac.Messenger.validate_message_broker
def validate_message_broker message_broker = @connection.message_broker raise TypeError, "'message_broker' must respond to #close" unless message_broker.respond_to?(:close) raise TypeError, "'message_broker' must respond to #kill" unless message_broker.respond_to?(:kill) raise TypeError, "'message_broker' must respond to #object_request_broker=" unless message_broker.respond_to?(:object_request_broker=) raise TypeError, "'message_broker' must respond to #send" unless message_broker.respond_to?(:send) end
ruby
def validate_message_broker message_broker = @connection.message_broker raise TypeError, "'message_broker' must respond to #close" unless message_broker.respond_to?(:close) raise TypeError, "'message_broker' must respond to #kill" unless message_broker.respond_to?(:kill) raise TypeError, "'message_broker' must respond to #object_request_broker=" unless message_broker.respond_to?(:object_request_broker=) raise TypeError, "'message_broker' must respond to #send" unless message_broker.respond_to?(:send) end
[ "def", "validate_message_broker", "message_broker", "=", "@connection", ".", "message_broker", "raise", "TypeError", ",", "\"'message_broker' must respond to #close\"", "unless", "message_broker", ".", "respond_to?", "(", ":close", ")", "raise", "TypeError", ",", "\"'message_broker' must respond to #kill\"", "unless", "message_broker", ".", "respond_to?", "(", ":kill", ")", "raise", "TypeError", ",", "\"'message_broker' must respond to #object_request_broker=\"", "unless", "message_broker", ".", "respond_to?", "(", ":object_request_broker=", ")", "raise", "TypeError", ",", "\"'message_broker' must respond to #send\"", "unless", "message_broker", ".", "respond_to?", "(", ":send", ")", "end" ]
Validates that the message broker will respond to the necessary methods. @raise [TypeError] if any methods are missing @return [void]
[ "Validates", "that", "the", "message", "broker", "will", "respond", "to", "the", "necessary", "methods", "." ]
524fa68b7d1bb10a74baa69cd594ab2b8cae20a3
https://github.com/robfors/ruby-sumac/blob/524fa68b7d1bb10a74baa69cd594ab2b8cae20a3/lib/sumac/messenger.rb#L63-L69
train
bigxiang/bootstrap-component-helper
app/helpers/bootstrap/typography_helper.rb
Bootstrap.TypographyHelper.list
def list(options = {}, &block) builder = List.new(self, options) capture(builder, &block) if block_given? builder.to_s end
ruby
def list(options = {}, &block) builder = List.new(self, options) capture(builder, &block) if block_given? builder.to_s end
[ "def", "list", "(", "options", "=", "{", "}", ",", "&", "block", ")", "builder", "=", "List", ".", "new", "(", "self", ",", "options", ")", "capture", "(", "builder", ",", "&", "block", ")", "if", "block_given?", "builder", ".", "to_s", "end" ]
Typography Headings not implemented Lead not implemented Small not implemented Bold not implemented Italics not implemented muted, text-warning, text-error, text-info, text-success not implemented Abbreviations not implemented Addresses not implemented Blockquotes not implemented Lists Public: Bootstrap Typography List, wraps List class to generate ul or ol tags with html options. options - options can be accepted by ul or ol. :type - unordered, ordered, unstyled. ( default: 'unordered' ) :li_options - common li options in ul ( default: {} ) other options can be accepted by ul or ol. block - yield with List object, used to add li tags into ul or ol. Also can add nested lists. Examples = list(type: 'ordered') do |i| - i.add('line 1') - i.add('line 2') - i.add(link_to('line 3', hello_world_path), class: "li-class") - i.add 'line 4' + list(type: 'unstyled') do |nested_li| - nested_li.add('line 4.1') - nested_li.add('line 4.2') # => <ol> <li>line 1</li> <li>line 2</li> <li class="li-class"> <a href="/hello_world">line 3</a> </li> <li> line 4 <ul class="unstyled"> <li>line 4.1</li> <li>line 4.2</li> </ul> </li> </ol> Returns html content of the list.
[ "Typography", "Headings", "not", "implemented", "Lead", "not", "implemented", "Small", "not", "implemented", "Bold", "not", "implemented", "Italics", "not", "implemented", "muted", "text", "-", "warning", "text", "-", "error", "text", "-", "info", "text", "-", "success", "not", "implemented", "Abbreviations", "not", "implemented", "Addresses", "not", "implemented", "Blockquotes", "not", "implemented", "Lists" ]
e88a243acf6157fdae489af575850862cf08fe0c
https://github.com/bigxiang/bootstrap-component-helper/blob/e88a243acf6157fdae489af575850862cf08fe0c/app/helpers/bootstrap/typography_helper.rb#L100-L104
train
renz45/table_me
lib/table_me/table_me_presenter.rb
TableMe.TableMePresenter.set_defaults_for
def set_defaults_for model options[:page] = 1 options[:per_page] ||= 10 options[:name] ||= model.to_s.downcase options[:order] ||= 'created_at ASC' self.name = options[:name] end
ruby
def set_defaults_for model options[:page] = 1 options[:per_page] ||= 10 options[:name] ||= model.to_s.downcase options[:order] ||= 'created_at ASC' self.name = options[:name] end
[ "def", "set_defaults_for", "model", "options", "[", ":page", "]", "=", "1", "options", "[", ":per_page", "]", "||=", "10", "options", "[", ":name", "]", "||=", "model", ".", "to_s", ".", "downcase", "options", "[", ":order", "]", "||=", "'created_at ASC'", "self", ".", "name", "=", "options", "[", ":name", "]", "end" ]
set defaults for options
[ "set", "defaults", "for", "options" ]
a04bd7c26497828b2f8f0178631253b6749025cf
https://github.com/renz45/table_me/blob/a04bd7c26497828b2f8f0178631253b6749025cf/lib/table_me/table_me_presenter.rb#L50-L56
train
renz45/table_me
lib/table_me/table_me_presenter.rb
TableMe.TableMePresenter.get_data_for
def get_data_for model model = apply_search_to(model) @data = model.limit(options[:per_page]).offset(start_item).order(options[:order]) options[:total_count] = model.count options[:page_total] = (options[:total_count] / options[:per_page].to_f).ceil end
ruby
def get_data_for model model = apply_search_to(model) @data = model.limit(options[:per_page]).offset(start_item).order(options[:order]) options[:total_count] = model.count options[:page_total] = (options[:total_count] / options[:per_page].to_f).ceil end
[ "def", "get_data_for", "model", "model", "=", "apply_search_to", "(", "model", ")", "@data", "=", "model", ".", "limit", "(", "options", "[", ":per_page", "]", ")", ".", "offset", "(", "start_item", ")", ".", "order", "(", "options", "[", ":order", "]", ")", "options", "[", ":total_count", "]", "=", "model", ".", "count", "options", "[", ":page_total", "]", "=", "(", "options", "[", ":total_count", "]", "/", "options", "[", ":per_page", "]", ".", "to_f", ")", ".", "ceil", "end" ]
make the model queries to pull back the data based on pagination and search results if given
[ "make", "the", "model", "queries", "to", "pull", "back", "the", "data", "based", "on", "pagination", "and", "search", "results", "if", "given" ]
a04bd7c26497828b2f8f0178631253b6749025cf
https://github.com/renz45/table_me/blob/a04bd7c26497828b2f8f0178631253b6749025cf/lib/table_me/table_me_presenter.rb#L59-L66
train
raygao/rforce-raygao
wsdl/wsdl.rb
RForce.WSDL.retrieve
def retrieve(fieldList, from, ids) soap.retrieve(Retrieve.new(fieldList, from, ids)).result end
ruby
def retrieve(fieldList, from, ids) soap.retrieve(Retrieve.new(fieldList, from, ids)).result end
[ "def", "retrieve", "(", "fieldList", ",", "from", ",", "ids", ")", "soap", ".", "retrieve", "(", "Retrieve", ".", "new", "(", "fieldList", ",", "from", ",", "ids", ")", ")", ".", "result", "end" ]
Retrieve a list of specific objects
[ "Retrieve", "a", "list", "of", "specific", "objects" ]
21bf35db2844f3e43b1cf8d290bfc0f413384fbf
https://github.com/raygao/rforce-raygao/blob/21bf35db2844f3e43b1cf8d290bfc0f413384fbf/wsdl/wsdl.rb#L86-L88
train
delano/familia
lib/familia/redisobject.rb
Familia.RedisObject.rediskey
def rediskey if parent? # We need to check if the parent has a specific suffix # for the case where we have specified one other than :object. suffix = parent.kind_of?(Familia) && parent.class.suffix != :object ? parent.class.suffix : name k = parent.rediskey(name, nil) else k = [name].flatten.compact.join(Familia.delim) end if @opts[:quantize] args = case @opts[:quantize] when Numeric [@opts[:quantize]] # :quantize => 1.minute when Array @opts[:quantize] # :quantize => [1.day, '%m%D'] else [] # :quantize => true end k = [k, qstamp(*args)].join(Familia.delim) end k end
ruby
def rediskey if parent? # We need to check if the parent has a specific suffix # for the case where we have specified one other than :object. suffix = parent.kind_of?(Familia) && parent.class.suffix != :object ? parent.class.suffix : name k = parent.rediskey(name, nil) else k = [name].flatten.compact.join(Familia.delim) end if @opts[:quantize] args = case @opts[:quantize] when Numeric [@opts[:quantize]] # :quantize => 1.minute when Array @opts[:quantize] # :quantize => [1.day, '%m%D'] else [] # :quantize => true end k = [k, qstamp(*args)].join(Familia.delim) end k end
[ "def", "rediskey", "if", "parent?", "suffix", "=", "parent", ".", "kind_of?", "(", "Familia", ")", "&&", "parent", ".", "class", ".", "suffix", "!=", ":object", "?", "parent", ".", "class", ".", "suffix", ":", "name", "k", "=", "parent", ".", "rediskey", "(", "name", ",", "nil", ")", "else", "k", "=", "[", "name", "]", ".", "flatten", ".", "compact", ".", "join", "(", "Familia", ".", "delim", ")", "end", "if", "@opts", "[", ":quantize", "]", "args", "=", "case", "@opts", "[", ":quantize", "]", "when", "Numeric", "[", "@opts", "[", ":quantize", "]", "]", "when", "Array", "@opts", "[", ":quantize", "]", "else", "[", "]", "end", "k", "=", "[", "k", ",", "qstamp", "(", "*", "args", ")", "]", ".", "join", "(", "Familia", ".", "delim", ")", "end", "k", "end" ]
returns a redis key based on the parent object so it will include the proper index.
[ "returns", "a", "redis", "key", "based", "on", "the", "parent", "object", "so", "it", "will", "include", "the", "proper", "index", "." ]
4ecb29e796c86611c5d37e1924729fb562eeb529
https://github.com/delano/familia/blob/4ecb29e796c86611c5d37e1924729fb562eeb529/lib/familia/redisobject.rb#L160-L181
train
JoshMcKin/hot_tub
lib/hot_tub/pool.rb
HotTub.Pool.clean!
def clean! HotTub.logger.info "[HotTub] Cleaning pool #{@name}!" if HotTub.logger @mutex.synchronize do begin @_pool.each do |clnt| clean_client(clnt) end ensure @cond.signal end end nil end
ruby
def clean! HotTub.logger.info "[HotTub] Cleaning pool #{@name}!" if HotTub.logger @mutex.synchronize do begin @_pool.each do |clnt| clean_client(clnt) end ensure @cond.signal end end nil end
[ "def", "clean!", "HotTub", ".", "logger", ".", "info", "\"[HotTub] Cleaning pool #{@name}!\"", "if", "HotTub", ".", "logger", "@mutex", ".", "synchronize", "do", "begin", "@_pool", ".", "each", "do", "|", "clnt", "|", "clean_client", "(", "clnt", ")", "end", "ensure", "@cond", ".", "signal", "end", "end", "nil", "end" ]
Clean all clients currently checked into the pool. Its possible clients may be returned to the pool after cleaning
[ "Clean", "all", "clients", "currently", "checked", "into", "the", "pool", ".", "Its", "possible", "clients", "may", "be", "returned", "to", "the", "pool", "after", "cleaning" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/pool.rb#L139-L151
train
JoshMcKin/hot_tub
lib/hot_tub/pool.rb
HotTub.Pool.drain!
def drain! HotTub.logger.info "[HotTub] Draining pool #{@name}!" if HotTub.logger @mutex.synchronize do begin while clnt = @_pool.pop close_client(clnt) end ensure @_out.clear @_pool.clear @pid = Process.pid @cond.broadcast end end nil end
ruby
def drain! HotTub.logger.info "[HotTub] Draining pool #{@name}!" if HotTub.logger @mutex.synchronize do begin while clnt = @_pool.pop close_client(clnt) end ensure @_out.clear @_pool.clear @pid = Process.pid @cond.broadcast end end nil end
[ "def", "drain!", "HotTub", ".", "logger", ".", "info", "\"[HotTub] Draining pool #{@name}!\"", "if", "HotTub", ".", "logger", "@mutex", ".", "synchronize", "do", "begin", "while", "clnt", "=", "@_pool", ".", "pop", "close_client", "(", "clnt", ")", "end", "ensure", "@_out", ".", "clear", "@_pool", ".", "clear", "@pid", "=", "Process", ".", "pid", "@cond", ".", "broadcast", "end", "end", "nil", "end" ]
Drain the pool of all clients currently checked into the pool. After draining, wake all sleeping threads to allow repopulating the pool or if shutdown allow threads to quickly finish their work Its possible clients may be returned to the pool after cleaning
[ "Drain", "the", "pool", "of", "all", "clients", "currently", "checked", "into", "the", "pool", ".", "After", "draining", "wake", "all", "sleeping", "threads", "to", "allow", "repopulating", "the", "pool", "or", "if", "shutdown", "allow", "threads", "to", "quickly", "finish", "their", "work", "Its", "possible", "clients", "may", "be", "returned", "to", "the", "pool", "after", "cleaning" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/pool.rb#L157-L172
train
JoshMcKin/hot_tub
lib/hot_tub/pool.rb
HotTub.Pool.shutdown!
def shutdown! HotTub.logger.info "[HotTub] Shutting down pool #{@name}!" if HotTub.logger @shutdown = true kill_reaper if @reaper drain! @shutdown = false nil end
ruby
def shutdown! HotTub.logger.info "[HotTub] Shutting down pool #{@name}!" if HotTub.logger @shutdown = true kill_reaper if @reaper drain! @shutdown = false nil end
[ "def", "shutdown!", "HotTub", ".", "logger", ".", "info", "\"[HotTub] Shutting down pool #{@name}!\"", "if", "HotTub", ".", "logger", "@shutdown", "=", "true", "kill_reaper", "if", "@reaper", "drain!", "@shutdown", "=", "false", "nil", "end" ]
Kills the reaper and drains the pool.
[ "Kills", "the", "reaper", "and", "drains", "the", "pool", "." ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/pool.rb#L177-L184
train
JoshMcKin/hot_tub
lib/hot_tub/pool.rb
HotTub.Pool.reap!
def reap! HotTub.logger.info "[HotTub] Reaping pool #{@name}!" if HotTub.log_trace? while !@shutdown reaped = nil @mutex.synchronize do begin if _reap? if _dead_clients? reaped = @_out.select { |clnt, thrd| !thrd.alive? }.keys @_out.delete_if { |k,v| reaped.include? k } else reaped = [@_pool.shift] end else reaped = nil end ensure @cond.signal end end if reaped reaped.each do |clnt| close_client(clnt) end else break end end nil end
ruby
def reap! HotTub.logger.info "[HotTub] Reaping pool #{@name}!" if HotTub.log_trace? while !@shutdown reaped = nil @mutex.synchronize do begin if _reap? if _dead_clients? reaped = @_out.select { |clnt, thrd| !thrd.alive? }.keys @_out.delete_if { |k,v| reaped.include? k } else reaped = [@_pool.shift] end else reaped = nil end ensure @cond.signal end end if reaped reaped.each do |clnt| close_client(clnt) end else break end end nil end
[ "def", "reap!", "HotTub", ".", "logger", ".", "info", "\"[HotTub] Reaping pool #{@name}!\"", "if", "HotTub", ".", "log_trace?", "while", "!", "@shutdown", "reaped", "=", "nil", "@mutex", ".", "synchronize", "do", "begin", "if", "_reap?", "if", "_dead_clients?", "reaped", "=", "@_out", ".", "select", "{", "|", "clnt", ",", "thrd", "|", "!", "thrd", ".", "alive?", "}", ".", "keys", "@_out", ".", "delete_if", "{", "|", "k", ",", "v", "|", "reaped", ".", "include?", "k", "}", "else", "reaped", "=", "[", "@_pool", ".", "shift", "]", "end", "else", "reaped", "=", "nil", "end", "ensure", "@cond", ".", "signal", "end", "end", "if", "reaped", "reaped", ".", "each", "do", "|", "clnt", "|", "close_client", "(", "clnt", ")", "end", "else", "break", "end", "end", "nil", "end" ]
Remove and close extra clients Releases mutex each iteration because reaping is a low priority action
[ "Remove", "and", "close", "extra", "clients", "Releases", "mutex", "each", "iteration", "because", "reaping", "is", "a", "low", "priority", "action" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/pool.rb#L189-L218
train
JoshMcKin/hot_tub
lib/hot_tub/pool.rb
HotTub.Pool.push
def push(clnt) if clnt orphaned = false @mutex.synchronize do begin if !@shutdown && @_out.delete(clnt) @_pool << clnt else orphaned = true end ensure @cond.signal end end close_orphan(clnt) if orphaned reap! if @blocking_reap end nil end
ruby
def push(clnt) if clnt orphaned = false @mutex.synchronize do begin if !@shutdown && @_out.delete(clnt) @_pool << clnt else orphaned = true end ensure @cond.signal end end close_orphan(clnt) if orphaned reap! if @blocking_reap end nil end
[ "def", "push", "(", "clnt", ")", "if", "clnt", "orphaned", "=", "false", "@mutex", ".", "synchronize", "do", "begin", "if", "!", "@shutdown", "&&", "@_out", ".", "delete", "(", "clnt", ")", "@_pool", "<<", "clnt", "else", "orphaned", "=", "true", "end", "ensure", "@cond", ".", "signal", "end", "end", "close_orphan", "(", "clnt", ")", "if", "orphaned", "reap!", "if", "@blocking_reap", "end", "nil", "end" ]
Safely add client back to pool, only if that client is registered
[ "Safely", "add", "client", "back", "to", "pool", "only", "if", "that", "client", "is", "registered" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/pool.rb#L254-L272
train
JoshMcKin/hot_tub
lib/hot_tub/pool.rb
HotTub.Pool.pop
def pop alarm = (Time.now + @wait_timeout) clnt = nil dirty = false while !@shutdown raise_alarm if (Time.now > alarm) @mutex.synchronize do begin if clnt = @_pool.pop dirty = true else clnt = _fetch_new(&@client_block) end ensure if clnt _checkout(clnt) @cond.signal else @reaper.wakeup if @reaper && _dead_clients? @cond.wait(@mutex,@wait_timeout) end end end break if clnt end clean_client(clnt) if dirty && clnt clnt end
ruby
def pop alarm = (Time.now + @wait_timeout) clnt = nil dirty = false while !@shutdown raise_alarm if (Time.now > alarm) @mutex.synchronize do begin if clnt = @_pool.pop dirty = true else clnt = _fetch_new(&@client_block) end ensure if clnt _checkout(clnt) @cond.signal else @reaper.wakeup if @reaper && _dead_clients? @cond.wait(@mutex,@wait_timeout) end end end break if clnt end clean_client(clnt) if dirty && clnt clnt end
[ "def", "pop", "alarm", "=", "(", "Time", ".", "now", "+", "@wait_timeout", ")", "clnt", "=", "nil", "dirty", "=", "false", "while", "!", "@shutdown", "raise_alarm", "if", "(", "Time", ".", "now", ">", "alarm", ")", "@mutex", ".", "synchronize", "do", "begin", "if", "clnt", "=", "@_pool", ".", "pop", "dirty", "=", "true", "else", "clnt", "=", "_fetch_new", "(", "&", "@client_block", ")", "end", "ensure", "if", "clnt", "_checkout", "(", "clnt", ")", "@cond", ".", "signal", "else", "@reaper", ".", "wakeup", "if", "@reaper", "&&", "_dead_clients?", "@cond", ".", "wait", "(", "@mutex", ",", "@wait_timeout", ")", "end", "end", "end", "break", "if", "clnt", "end", "clean_client", "(", "clnt", ")", "if", "dirty", "&&", "clnt", "clnt", "end" ]
Safely pull client from pool, adding if allowed If a client is not available, check for dead resources and schedule reap if nesseccary
[ "Safely", "pull", "client", "from", "pool", "adding", "if", "allowed", "If", "a", "client", "is", "not", "available", "check", "for", "dead", "resources", "and", "schedule", "reap", "if", "nesseccary" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/pool.rb#L277-L304
train
JoshMcKin/hot_tub
lib/hot_tub/pool.rb
HotTub.Pool._fetch_new
def _fetch_new(&client_block) if (@never_block || (_total_current_size < @max_size)) if client_block.arity == 0 nc = yield else nc = yield @sessions_key end HotTub.logger.info "[HotTub] Adding client: #{nc.class.name} to #{@name}." if HotTub.log_trace? nc end end
ruby
def _fetch_new(&client_block) if (@never_block || (_total_current_size < @max_size)) if client_block.arity == 0 nc = yield else nc = yield @sessions_key end HotTub.logger.info "[HotTub] Adding client: #{nc.class.name} to #{@name}." if HotTub.log_trace? nc end end
[ "def", "_fetch_new", "(", "&", "client_block", ")", "if", "(", "@never_block", "||", "(", "_total_current_size", "<", "@max_size", ")", ")", "if", "client_block", ".", "arity", "==", "0", "nc", "=", "yield", "else", "nc", "=", "yield", "@sessions_key", "end", "HotTub", ".", "logger", ".", "info", "\"[HotTub] Adding client: #{nc.class.name} to #{@name}.\"", "if", "HotTub", ".", "log_trace?", "nc", "end", "end" ]
Returns a new client if its allowed. _add is volatile; and may cause threading issues if called outside @mutex.synchronize {}
[ "Returns", "a", "new", "client", "if", "its", "allowed", ".", "_add", "is", "volatile", ";", "and", "may", "cause", "threading", "issues", "if", "called", "outside" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/pool.rb#L322-L332
train
mrackwitz/CLIntegracon
lib/CLIntegracon/diff.rb
CLIntegracon.Diff.each
def each(options = {}, &block) options = { :source => compares_files? ? 'files' : 'strings', :context => 3 }.merge options Diffy::Diff.new(preprocessed_expected.to_s, preprocessed_produced.to_s, options).each &block end
ruby
def each(options = {}, &block) options = { :source => compares_files? ? 'files' : 'strings', :context => 3 }.merge options Diffy::Diff.new(preprocessed_expected.to_s, preprocessed_produced.to_s, options).each &block end
[ "def", "each", "(", "options", "=", "{", "}", ",", "&", "block", ")", "options", "=", "{", ":source", "=>", "compares_files?", "?", "'files'", ":", "'strings'", ",", ":context", "=>", "3", "}", ".", "merge", "options", "Diffy", "::", "Diff", ".", "new", "(", "preprocessed_expected", ".", "to_s", ",", "preprocessed_produced", ".", "to_s", ",", "options", ")", ".", "each", "&", "block", "end" ]
Enumerate all lines which differ. @param [Hash] options see Diffy#initialize for help. @return [Diffy::Diff]
[ "Enumerate", "all", "lines", "which", "differ", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/diff.rb#L84-L90
train
nepalez/immutability
lib/immutability.rb
Immutability.ClassMethods.new
def new(*args, &block) instance = allocate.tap { |obj| obj.__send__(:initialize, *args, &block) } IceNine.deep_freeze(instance) end
ruby
def new(*args, &block) instance = allocate.tap { |obj| obj.__send__(:initialize, *args, &block) } IceNine.deep_freeze(instance) end
[ "def", "new", "(", "*", "args", ",", "&", "block", ")", "instance", "=", "allocate", ".", "tap", "{", "|", "obj", "|", "obj", ".", "__send__", "(", ":initialize", ",", "*", "args", ",", "&", "block", ")", "}", "IceNine", ".", "deep_freeze", "(", "instance", ")", "end" ]
Reloads instance's constructor to make it immutable @api private @param [Object, Array<Object>] args @param [Proc] block @return [Object]
[ "Reloads", "instance", "s", "constructor", "to", "make", "it", "immutable" ]
6f44a7e3dad9cbc51f40e5ec9b3810d1cc730a10
https://github.com/nepalez/immutability/blob/6f44a7e3dad9cbc51f40e5ec9b3810d1cc730a10/lib/immutability.rb#L86-L89
train
chrisjensen/hash_redactor
lib/hash_redactor/hash_redactor.rb
HashRedactor.HashRedactor.whitelist_redact_hash
def whitelist_redact_hash redact_hash digest_hash = {} redact_hash.each do |key,how| if (how.to_sym == :digest) digest_hash[digest_key(key)] = :keep end end digest_hash.merge redact_hash end
ruby
def whitelist_redact_hash redact_hash digest_hash = {} redact_hash.each do |key,how| if (how.to_sym == :digest) digest_hash[digest_key(key)] = :keep end end digest_hash.merge redact_hash end
[ "def", "whitelist_redact_hash", "redact_hash", "digest_hash", "=", "{", "}", "redact_hash", ".", "each", "do", "|", "key", ",", "how", "|", "if", "(", "how", ".", "to_sym", "==", ":digest", ")", "digest_hash", "[", "digest_key", "(", "key", ")", "]", "=", ":keep", "end", "end", "digest_hash", ".", "merge", "redact_hash", "end" ]
Calculate all keys that should be kept in whitelist mode In multiple iterations of redact -> decrypt - digest keys will remain and then get deleted in the second iteration, so we have to add the digest keys so they're not wiped out on later iteration
[ "Calculate", "all", "keys", "that", "should", "be", "kept", "in", "whitelist", "mode", "In", "multiple", "iterations", "of", "redact", "-", ">", "decrypt", "-", "digest", "keys", "will", "remain", "and", "then", "get", "deleted", "in", "the", "second", "iteration", "so", "we", "have", "to", "add", "the", "digest", "keys", "so", "they", "re", "not", "wiped", "out", "on", "later", "iteration" ]
dd35d5dc9a7fa529ad3a2168975cd8beecce549a
https://github.com/chrisjensen/hash_redactor/blob/dd35d5dc9a7fa529ad3a2168975cd8beecce549a/lib/hash_redactor/hash_redactor.rb#L184-L194
train
sa2taka/nameko
lib/nameko/nameko.rb
Nameko.Mecab.parse
def parse(str) node = MecabNode.new mecab_sparse_tonode(@mecab, str) result = [] while !node.null? do if node.surface.empty? node = node.next next end result << node node = node.next end result end
ruby
def parse(str) node = MecabNode.new mecab_sparse_tonode(@mecab, str) result = [] while !node.null? do if node.surface.empty? node = node.next next end result << node node = node.next end result end
[ "def", "parse", "(", "str", ")", "node", "=", "MecabNode", ".", "new", "mecab_sparse_tonode", "(", "@mecab", ",", "str", ")", "result", "=", "[", "]", "while", "!", "node", ".", "null?", "do", "if", "node", ".", "surface", ".", "empty?", "node", "=", "node", ".", "next", "next", "end", "result", "<<", "node", "node", "=", "node", ".", "next", "end", "result", "end" ]
Initialize the mecab tagger with the given option. How to specify options is as follows: @example mecab = Nameko::Mecab.new("-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd") mecab = Nameko::Mecab.new(["-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd"]) mecab = Nameko::Mecab.new(["-d", "/usr/local/lib/mecab/dic/mecab-ipadic-neologd"]) Parse the given string by MeCab. @param [String] str Parsed text @return [Array<MecabNode>] Result of Mecab parsing @example node = mecab.parse("私以外私じゃないの")[0] node.surface # => "私" node.feature #=> {:pos=>"名詞", :pos1=>"代名詞", :pos2=>"一般", :pos3=>"", :conjugation_form=>"", :conjugation=>"", :base=>"私", :yomi=>"ワタシ", :pronunciation=>"ワタシ"} node.posid #=> 59 node.id #=> 1
[ "Initialize", "the", "mecab", "tagger", "with", "the", "given", "option", "." ]
4d9353a367ebf22bd653f89dea54ccf18aad9aea
https://github.com/sa2taka/nameko/blob/4d9353a367ebf22bd653f89dea54ccf18aad9aea/lib/nameko/nameko.rb#L65-L79
train
DouweM/mongoid-siblings
lib/mongoid/siblings.rb
Mongoid.Siblings.siblings_and_self
def siblings_and_self(options = {}) scopes = options[:scope] || self.default_sibling_scope scope_values = options[:scope_values] || {} scopes = Array.wrap(scopes).compact criteria = base_document_class.all detail_scopes = [] # Find out what scope determines the root criteria. This can be # [klass].all or self.[relation]. # It is assumed that for `scopes: [:rel1, :rel2]`, sibling objects always # have the same `rel1` *and* `rel2`, and that two objects with the same # `rel1` will always have the same `rel2`. scopes.reverse_each do |scope| scope_value = scope_values.fetch(scope) { self.send(scope) } relation_metadata = self.reflect_on_association(scope) if relation_metadata && scope_value proxy = self.siblings_through_relation(scope, scope_value) if proxy criteria = proxy.criteria next end end detail_scopes << scope end # Apply detail criteria, to make sure siblings share every simple # attribute or nil-relation. detail_scopes.each do |scope| scope_value = scope_values.fetch(scope) { self.send(scope) } relation_metadata = self.reflect_on_association(scope) if relation_metadata criteria = criteria.where(relation_metadata.key => scope_value) if scope_value && relation_metadata.polymorphic? type = scope_value.class.name inverse_of = send(relation_metadata.inverse_of_field) criteria = criteria.where(relation_metadata.inverse_type => type) criteria = criteria.any_in(relation_metadata.inverse_of_field => [inverse_of, nil]) end else criteria = criteria.where(scope => scope_value) end end criteria end
ruby
def siblings_and_self(options = {}) scopes = options[:scope] || self.default_sibling_scope scope_values = options[:scope_values] || {} scopes = Array.wrap(scopes).compact criteria = base_document_class.all detail_scopes = [] # Find out what scope determines the root criteria. This can be # [klass].all or self.[relation]. # It is assumed that for `scopes: [:rel1, :rel2]`, sibling objects always # have the same `rel1` *and* `rel2`, and that two objects with the same # `rel1` will always have the same `rel2`. scopes.reverse_each do |scope| scope_value = scope_values.fetch(scope) { self.send(scope) } relation_metadata = self.reflect_on_association(scope) if relation_metadata && scope_value proxy = self.siblings_through_relation(scope, scope_value) if proxy criteria = proxy.criteria next end end detail_scopes << scope end # Apply detail criteria, to make sure siblings share every simple # attribute or nil-relation. detail_scopes.each do |scope| scope_value = scope_values.fetch(scope) { self.send(scope) } relation_metadata = self.reflect_on_association(scope) if relation_metadata criteria = criteria.where(relation_metadata.key => scope_value) if scope_value && relation_metadata.polymorphic? type = scope_value.class.name inverse_of = send(relation_metadata.inverse_of_field) criteria = criteria.where(relation_metadata.inverse_type => type) criteria = criteria.any_in(relation_metadata.inverse_of_field => [inverse_of, nil]) end else criteria = criteria.where(scope => scope_value) end end criteria end
[ "def", "siblings_and_self", "(", "options", "=", "{", "}", ")", "scopes", "=", "options", "[", ":scope", "]", "||", "self", ".", "default_sibling_scope", "scope_values", "=", "options", "[", ":scope_values", "]", "||", "{", "}", "scopes", "=", "Array", ".", "wrap", "(", "scopes", ")", ".", "compact", "criteria", "=", "base_document_class", ".", "all", "detail_scopes", "=", "[", "]", "scopes", ".", "reverse_each", "do", "|", "scope", "|", "scope_value", "=", "scope_values", ".", "fetch", "(", "scope", ")", "{", "self", ".", "send", "(", "scope", ")", "}", "relation_metadata", "=", "self", ".", "reflect_on_association", "(", "scope", ")", "if", "relation_metadata", "&&", "scope_value", "proxy", "=", "self", ".", "siblings_through_relation", "(", "scope", ",", "scope_value", ")", "if", "proxy", "criteria", "=", "proxy", ".", "criteria", "next", "end", "end", "detail_scopes", "<<", "scope", "end", "detail_scopes", ".", "each", "do", "|", "scope", "|", "scope_value", "=", "scope_values", ".", "fetch", "(", "scope", ")", "{", "self", ".", "send", "(", "scope", ")", "}", "relation_metadata", "=", "self", ".", "reflect_on_association", "(", "scope", ")", "if", "relation_metadata", "criteria", "=", "criteria", ".", "where", "(", "relation_metadata", ".", "key", "=>", "scope_value", ")", "if", "scope_value", "&&", "relation_metadata", ".", "polymorphic?", "type", "=", "scope_value", ".", "class", ".", "name", "inverse_of", "=", "send", "(", "relation_metadata", ".", "inverse_of_field", ")", "criteria", "=", "criteria", ".", "where", "(", "relation_metadata", ".", "inverse_type", "=>", "type", ")", "criteria", "=", "criteria", ".", "any_in", "(", "relation_metadata", ".", "inverse_of_field", "=>", "[", "inverse_of", ",", "nil", "]", ")", "end", "else", "criteria", "=", "criteria", ".", "where", "(", "scope", "=>", "scope_value", ")", "end", "end", "criteria", "end" ]
Returns this document's siblings and itself. @example Retrieve document's siblings and itself within a certain scope. book.siblings_and_self(scope: :author) @example Retrieve what would be document's siblings if it had another scope value. book.siblings_and_self( scope: :author, scope_values: { author: other_author } ) @param [ Hash ] options The options. @option options [ Array<Symbol>, Symbol ] scope One or more relations or attributes that siblings of this object need to have in common. @option options [ Hash<Symbol, Object> ] scope_values Optional alternative values to use to determine siblingship. @return [ Mongoid::Criteria ] Criteria to retrieve the document's siblings.
[ "Returns", "this", "document", "s", "siblings", "and", "itself", "." ]
095c973628255eccf4a5341079d0dcac546df3a3
https://github.com/DouweM/mongoid-siblings/blob/095c973628255eccf4a5341079d0dcac546df3a3/lib/mongoid/siblings.rb#L43-L96
train
DouweM/mongoid-siblings
lib/mongoid/siblings.rb
Mongoid.Siblings.sibling_of?
def sibling_of?(other, options = {}) scopes = options[:scope] || self.default_sibling_scope scope_values = options[:scope_values] || {} other_scope_values = options[:other_scope_values] || {} scopes = Array.wrap(scopes).compact return false if base_document_class != base_document_class(other) scopes.each do |scope| scope_value = scope_values.fetch(scope) { self.send(scope) } other_scope_value = other_scope_values.fetch(scope) { other.send(scope) } return false if scope_value != other_scope_value end true end
ruby
def sibling_of?(other, options = {}) scopes = options[:scope] || self.default_sibling_scope scope_values = options[:scope_values] || {} other_scope_values = options[:other_scope_values] || {} scopes = Array.wrap(scopes).compact return false if base_document_class != base_document_class(other) scopes.each do |scope| scope_value = scope_values.fetch(scope) { self.send(scope) } other_scope_value = other_scope_values.fetch(scope) { other.send(scope) } return false if scope_value != other_scope_value end true end
[ "def", "sibling_of?", "(", "other", ",", "options", "=", "{", "}", ")", "scopes", "=", "options", "[", ":scope", "]", "||", "self", ".", "default_sibling_scope", "scope_values", "=", "options", "[", ":scope_values", "]", "||", "{", "}", "other_scope_values", "=", "options", "[", ":other_scope_values", "]", "||", "{", "}", "scopes", "=", "Array", ".", "wrap", "(", "scopes", ")", ".", "compact", "return", "false", "if", "base_document_class", "!=", "base_document_class", "(", "other", ")", "scopes", ".", "each", "do", "|", "scope", "|", "scope_value", "=", "scope_values", ".", "fetch", "(", "scope", ")", "{", "self", ".", "send", "(", "scope", ")", "}", "other_scope_value", "=", "other_scope_values", ".", "fetch", "(", "scope", ")", "{", "other", ".", "send", "(", "scope", ")", "}", "return", "false", "if", "scope_value", "!=", "other_scope_value", "end", "true", "end" ]
Is this document a sibling of the other document? @example Is this document a sibling of the other document? book.sibling_of?(other_book, scope: :author) @param [ Document ] other The document to check against. @param [ Hash ] options The options. @option options [ Array<Symbol>, Symbol ] scope One or more relations and attributes that siblings of this object need to have in common. @option options [ Hash<Symbol, Object> ] scope_values Optional alternative values for this document to use to determine siblings. @option options [ Hash<Symbol, Object> ] other_scope_values Optional alternative values for the other document to use to determine siblingship. @return [ Boolean ] True if the document is a sibling of the other document.
[ "Is", "this", "document", "a", "sibling", "of", "the", "other", "document?" ]
095c973628255eccf4a5341079d0dcac546df3a3
https://github.com/DouweM/mongoid-siblings/blob/095c973628255eccf4a5341079d0dcac546df3a3/lib/mongoid/siblings.rb#L116-L134
train
DouweM/mongoid-siblings
lib/mongoid/siblings.rb
Mongoid.Siblings.become_sibling_of
def become_sibling_of(other, options = {}) return true if self.sibling_of?(other, options) scopes = options[:scope] || self.default_sibling_scope other_scope_values = options[:other_scope_values] || {} scopes = Array.wrap(scopes).compact return false if base_document_class != base_document_class(other) scopes.each do |scope| other_scope_value = other_scope_values.fetch(scope) { other.send(scope) } relation_metadata = self.reflect_on_association(scope) if relation_metadata && other_scope_value inverse_metadata = other.intelligent_inverse_metadata(scope, other_scope_value) if inverse_metadata inverse = inverse_metadata.name if inverse_metadata.many? other_scope_value.send(inverse) << self else other_scope_value.send("#{inverse}=", self) end next end end self.send("#{scope}=", other_scope_value) end end
ruby
def become_sibling_of(other, options = {}) return true if self.sibling_of?(other, options) scopes = options[:scope] || self.default_sibling_scope other_scope_values = options[:other_scope_values] || {} scopes = Array.wrap(scopes).compact return false if base_document_class != base_document_class(other) scopes.each do |scope| other_scope_value = other_scope_values.fetch(scope) { other.send(scope) } relation_metadata = self.reflect_on_association(scope) if relation_metadata && other_scope_value inverse_metadata = other.intelligent_inverse_metadata(scope, other_scope_value) if inverse_metadata inverse = inverse_metadata.name if inverse_metadata.many? other_scope_value.send(inverse) << self else other_scope_value.send("#{inverse}=", self) end next end end self.send("#{scope}=", other_scope_value) end end
[ "def", "become_sibling_of", "(", "other", ",", "options", "=", "{", "}", ")", "return", "true", "if", "self", ".", "sibling_of?", "(", "other", ",", "options", ")", "scopes", "=", "options", "[", ":scope", "]", "||", "self", ".", "default_sibling_scope", "other_scope_values", "=", "options", "[", ":other_scope_values", "]", "||", "{", "}", "scopes", "=", "Array", ".", "wrap", "(", "scopes", ")", ".", "compact", "return", "false", "if", "base_document_class", "!=", "base_document_class", "(", "other", ")", "scopes", ".", "each", "do", "|", "scope", "|", "other_scope_value", "=", "other_scope_values", ".", "fetch", "(", "scope", ")", "{", "other", ".", "send", "(", "scope", ")", "}", "relation_metadata", "=", "self", ".", "reflect_on_association", "(", "scope", ")", "if", "relation_metadata", "&&", "other_scope_value", "inverse_metadata", "=", "other", ".", "intelligent_inverse_metadata", "(", "scope", ",", "other_scope_value", ")", "if", "inverse_metadata", "inverse", "=", "inverse_metadata", ".", "name", "if", "inverse_metadata", ".", "many?", "other_scope_value", ".", "send", "(", "inverse", ")", "<<", "self", "else", "other_scope_value", ".", "send", "(", "\"#{inverse}=\"", ",", "self", ")", "end", "next", "end", "end", "self", ".", "send", "(", "\"#{scope}=\"", ",", "other_scope_value", ")", "end", "end" ]
Makes this document a sibling of the other document. This is done by copying over the values used to determine siblingship from the other document. @example Make document a sibling of the other document. book.become_sibling_of(book_of_other_author, scope: :author) @param [ Document ] other The document to become a sibling of. @param [ Hash ] options The options. @option options [ Array<Symbol>, Symbol ] scope One or more relations and attributes that siblings of this object need to have in common. @option options [ Hash<Symbol, Object> ] other_scope_values Optional alternative values to use to determine siblingship. @return [ Boolean ] True if the document was made a sibling of the other document.
[ "Makes", "this", "document", "a", "sibling", "of", "the", "other", "document", "." ]
095c973628255eccf4a5341079d0dcac546df3a3
https://github.com/DouweM/mongoid-siblings/blob/095c973628255eccf4a5341079d0dcac546df3a3/lib/mongoid/siblings.rb#L154-L184
train
maccman/bowline-bundler
lib/bowline/bundler/finder.rb
Bundler.Finder.search
def search(dependency) @cache[dependency.hash] ||= begin find_by_name(dependency.name).select do |spec| dependency =~ spec end.sort_by {|s| s.version } end end
ruby
def search(dependency) @cache[dependency.hash] ||= begin find_by_name(dependency.name).select do |spec| dependency =~ spec end.sort_by {|s| s.version } end end
[ "def", "search", "(", "dependency", ")", "@cache", "[", "dependency", ".", "hash", "]", "||=", "begin", "find_by_name", "(", "dependency", ".", "name", ")", ".", "select", "do", "|", "spec", "|", "dependency", "=~", "spec", "end", ".", "sort_by", "{", "|", "s", "|", "s", ".", "version", "}", "end", "end" ]
Takes an array of gem sources and fetches the full index of gems from each one. It then combines the indexes together keeping track of the original source so that any resolved gem can be fetched from the correct source. ==== Parameters *sources<String>:: URI pointing to the gem repository Searches for a gem that matches the dependency ==== Parameters dependency<Gem::Dependency>:: The gem dependency to search for ==== Returns [Gem::Specification]:: A collection of gem specifications matching the search
[ "Takes", "an", "array", "of", "gem", "sources", "and", "fetches", "the", "full", "index", "of", "gems", "from", "each", "one", ".", "It", "then", "combines", "the", "indexes", "together", "keeping", "track", "of", "the", "original", "source", "so", "that", "any", "resolved", "gem", "can", "be", "fetched", "from", "the", "correct", "source", "." ]
cb1fb41942d018458f6671e4d5b859636eb0bd64
https://github.com/maccman/bowline-bundler/blob/cb1fb41942d018458f6671e4d5b859636eb0bd64/lib/bowline/bundler/finder.rb#L29-L35
train
hans/jido-rb
lib/jido/conjugator.rb
Jido.Conjugator.search_current_el
def search_current_el xpath # try to find the rule in the current verb desired_el = @current_el.at_xpath xpath return desired_el unless desired_el.nil? # check all the verb's parents, walking up the hierarchy @current_el_parents.each do |parent| desired_el = parent.at_xpath xpath return desired_el unless desired_el.nil? end nil end
ruby
def search_current_el xpath # try to find the rule in the current verb desired_el = @current_el.at_xpath xpath return desired_el unless desired_el.nil? # check all the verb's parents, walking up the hierarchy @current_el_parents.each do |parent| desired_el = parent.at_xpath xpath return desired_el unless desired_el.nil? end nil end
[ "def", "search_current_el", "xpath", "desired_el", "=", "@current_el", ".", "at_xpath", "xpath", "return", "desired_el", "unless", "desired_el", ".", "nil?", "@current_el_parents", ".", "each", "do", "|", "parent", "|", "desired_el", "=", "parent", ".", "at_xpath", "xpath", "return", "desired_el", "unless", "desired_el", ".", "nil?", "end", "nil", "end" ]
Search each parent of some verb for a given element. Used for rule inheritance.
[ "Search", "each", "parent", "of", "some", "verb", "for", "a", "given", "element", ".", "Used", "for", "rule", "inheritance", "." ]
9dd6b776737cb045d08b37e1be7639b4d18ba709
https://github.com/hans/jido-rb/blob/9dd6b776737cb045d08b37e1be7639b4d18ba709/lib/jido/conjugator.rb#L243-L255
train
richard-viney/lightstreamer
lib/lightstreamer/stream_buffer.rb
Lightstreamer.StreamBuffer.process
def process(data) @buffer << data lines = @buffer.split "\n" @buffer = @buffer.end_with?("\n") ? '' : lines.pop lines.each do |line| yield line.strip end end
ruby
def process(data) @buffer << data lines = @buffer.split "\n" @buffer = @buffer.end_with?("\n") ? '' : lines.pop lines.each do |line| yield line.strip end end
[ "def", "process", "(", "data", ")", "@buffer", "<<", "data", "lines", "=", "@buffer", ".", "split", "\"\\n\"", "@buffer", "=", "@buffer", ".", "end_with?", "(", "\"\\n\"", ")", "?", "''", ":", "lines", ".", "pop", "lines", ".", "each", "do", "|", "line", "|", "yield", "line", ".", "strip", "end", "end" ]
Appends a new piece of ASCII data to this buffer and yields back any lines that are now complete. @param [String] data The new piece of ASCII data. @yieldparam [String] line The new line that is now complete.
[ "Appends", "a", "new", "piece", "of", "ASCII", "data", "to", "this", "buffer", "and", "yields", "back", "any", "lines", "that", "are", "now", "complete", "." ]
7be6350bd861495a52ca35a8640a1e6df34cf9d1
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/stream_buffer.rb#L16-L25
train
Latermedia/sidekiq_spread
lib/sidekiq_spread.rb
SidekiqSpread.ClassMethods.perform_spread
def perform_spread(*args) spread_duration = get_sidekiq_options['spread_duration'] || 1.hour spread_in = 0 spread_at = nil spread_method = get_sidekiq_options['spread_method'] || :rand spread_mod_value = nil spread_method = spread_method.to_sym if spread_method.present? # process spread_* options has_options = false opts = if !args.empty? && args.last.is_a?(::Hash) has_options = true args.pop else {} end sd = _extract_spread_opt(opts, :duration) spread_duration = sd if sd.present? si = _extract_spread_opt(opts, :in) spread_in = si if si.present? sa = _extract_spread_opt(opts, :at) spread_at = sa if sa.present? sm = _extract_spread_opt(opts, :method) spread_method = sm.to_sym if sm.present? smv = _extract_spread_opt(opts, :mod_value) spread_mod_value = smv if smv.present? # get left over options / keyword args remaining_opts = opts.reject { |o| PERFORM_SPREAD_OPTS.include?(o.to_sym) } # check args num_args = args.length # figure out the require params for #perform params = new.method(:perform).parameters num_req_args = params.select { |p| p[0] == :req }.length num_opt_args = params.select { |p| p[0] == :opt }.length num_req_key_args = params.select { |p| p[0] == :keyreq }.length num_opt_key_args = params.select { |p| p[0] == :key }.length # Sidekiq doesn't play nicely with named args raise ArgumentError, "#{name}#perform should not use keyword args" if num_req_key_args > 0 || num_opt_key_args > 0 if has_options # if we popped something off to process, push it back on # if it contains arguments we need if num_args < num_req_args args.push(remaining_opts) elsif num_args < (num_req_args + num_opt_args) && !remaining_opts.empty? args.push(remaining_opts) end end # if a spread_mod_value is not provided use the first argument, # assumes it is an Integer spread_mod_value = args.first if spread_mod_value.blank? && spread_method == :mod # validate the spread_* options _check_spread_args!(spread_duration, spread_method, spread_mod_value) # calculate the offset for this job spread = _set_spread(spread_method, spread_duration.to_i, spread_mod_value) # call the correct perform_* method if spread_at.present? t = spread_at.to_i + spread perform_at(t, *args) else t = spread_in.to_i + spread if t.zero? perform_async(*args) else perform_in(t, *args) end end end
ruby
def perform_spread(*args) spread_duration = get_sidekiq_options['spread_duration'] || 1.hour spread_in = 0 spread_at = nil spread_method = get_sidekiq_options['spread_method'] || :rand spread_mod_value = nil spread_method = spread_method.to_sym if spread_method.present? # process spread_* options has_options = false opts = if !args.empty? && args.last.is_a?(::Hash) has_options = true args.pop else {} end sd = _extract_spread_opt(opts, :duration) spread_duration = sd if sd.present? si = _extract_spread_opt(opts, :in) spread_in = si if si.present? sa = _extract_spread_opt(opts, :at) spread_at = sa if sa.present? sm = _extract_spread_opt(opts, :method) spread_method = sm.to_sym if sm.present? smv = _extract_spread_opt(opts, :mod_value) spread_mod_value = smv if smv.present? # get left over options / keyword args remaining_opts = opts.reject { |o| PERFORM_SPREAD_OPTS.include?(o.to_sym) } # check args num_args = args.length # figure out the require params for #perform params = new.method(:perform).parameters num_req_args = params.select { |p| p[0] == :req }.length num_opt_args = params.select { |p| p[0] == :opt }.length num_req_key_args = params.select { |p| p[0] == :keyreq }.length num_opt_key_args = params.select { |p| p[0] == :key }.length # Sidekiq doesn't play nicely with named args raise ArgumentError, "#{name}#perform should not use keyword args" if num_req_key_args > 0 || num_opt_key_args > 0 if has_options # if we popped something off to process, push it back on # if it contains arguments we need if num_args < num_req_args args.push(remaining_opts) elsif num_args < (num_req_args + num_opt_args) && !remaining_opts.empty? args.push(remaining_opts) end end # if a spread_mod_value is not provided use the first argument, # assumes it is an Integer spread_mod_value = args.first if spread_mod_value.blank? && spread_method == :mod # validate the spread_* options _check_spread_args!(spread_duration, spread_method, spread_mod_value) # calculate the offset for this job spread = _set_spread(spread_method, spread_duration.to_i, spread_mod_value) # call the correct perform_* method if spread_at.present? t = spread_at.to_i + spread perform_at(t, *args) else t = spread_in.to_i + spread if t.zero? perform_async(*args) else perform_in(t, *args) end end end
[ "def", "perform_spread", "(", "*", "args", ")", "spread_duration", "=", "get_sidekiq_options", "[", "'spread_duration'", "]", "||", "1", ".", "hour", "spread_in", "=", "0", "spread_at", "=", "nil", "spread_method", "=", "get_sidekiq_options", "[", "'spread_method'", "]", "||", ":rand", "spread_mod_value", "=", "nil", "spread_method", "=", "spread_method", ".", "to_sym", "if", "spread_method", ".", "present?", "has_options", "=", "false", "opts", "=", "if", "!", "args", ".", "empty?", "&&", "args", ".", "last", ".", "is_a?", "(", "::", "Hash", ")", "has_options", "=", "true", "args", ".", "pop", "else", "{", "}", "end", "sd", "=", "_extract_spread_opt", "(", "opts", ",", ":duration", ")", "spread_duration", "=", "sd", "if", "sd", ".", "present?", "si", "=", "_extract_spread_opt", "(", "opts", ",", ":in", ")", "spread_in", "=", "si", "if", "si", ".", "present?", "sa", "=", "_extract_spread_opt", "(", "opts", ",", ":at", ")", "spread_at", "=", "sa", "if", "sa", ".", "present?", "sm", "=", "_extract_spread_opt", "(", "opts", ",", ":method", ")", "spread_method", "=", "sm", ".", "to_sym", "if", "sm", ".", "present?", "smv", "=", "_extract_spread_opt", "(", "opts", ",", ":mod_value", ")", "spread_mod_value", "=", "smv", "if", "smv", ".", "present?", "remaining_opts", "=", "opts", ".", "reject", "{", "|", "o", "|", "PERFORM_SPREAD_OPTS", ".", "include?", "(", "o", ".", "to_sym", ")", "}", "num_args", "=", "args", ".", "length", "params", "=", "new", ".", "method", "(", ":perform", ")", ".", "parameters", "num_req_args", "=", "params", ".", "select", "{", "|", "p", "|", "p", "[", "0", "]", "==", ":req", "}", ".", "length", "num_opt_args", "=", "params", ".", "select", "{", "|", "p", "|", "p", "[", "0", "]", "==", ":opt", "}", ".", "length", "num_req_key_args", "=", "params", ".", "select", "{", "|", "p", "|", "p", "[", "0", "]", "==", ":keyreq", "}", ".", "length", "num_opt_key_args", "=", "params", ".", "select", "{", "|", "p", "|", "p", "[", "0", "]", "==", ":key", "}", ".", "length", "raise", "ArgumentError", ",", "\"#{name}#perform should not use keyword args\"", "if", "num_req_key_args", ">", "0", "||", "num_opt_key_args", ">", "0", "if", "has_options", "if", "num_args", "<", "num_req_args", "args", ".", "push", "(", "remaining_opts", ")", "elsif", "num_args", "<", "(", "num_req_args", "+", "num_opt_args", ")", "&&", "!", "remaining_opts", ".", "empty?", "args", ".", "push", "(", "remaining_opts", ")", "end", "end", "spread_mod_value", "=", "args", ".", "first", "if", "spread_mod_value", ".", "blank?", "&&", "spread_method", "==", ":mod", "_check_spread_args!", "(", "spread_duration", ",", "spread_method", ",", "spread_mod_value", ")", "spread", "=", "_set_spread", "(", "spread_method", ",", "spread_duration", ".", "to_i", ",", "spread_mod_value", ")", "if", "spread_at", ".", "present?", "t", "=", "spread_at", ".", "to_i", "+", "spread", "perform_at", "(", "t", ",", "*", "args", ")", "else", "t", "=", "spread_in", ".", "to_i", "+", "spread", "if", "t", ".", "zero?", "perform_async", "(", "*", "args", ")", "else", "perform_in", "(", "t", ",", "*", "args", ")", "end", "end", "end" ]
Randomly schedule worker over a window of time. Arguments are keys of the final options hash. @param spread_duration [Number] Size of window to spread workers out over @param spread_in [Number] Start of window offset from now @param spread_at [Number] Start of window offset timestamp @param spread_method [rand|mod] perform either a random or modulo spread, default: *:rand* @param spread_mod_value [Integer] value to use for determining mod offset @return [String] Sidekiq job id
[ "Randomly", "schedule", "worker", "over", "a", "window", "of", "time", ".", "Arguments", "are", "keys", "of", "the", "final", "options", "hash", "." ]
e08c71ebdddbcb3cd16d6c9318573e13f3a249c4
https://github.com/Latermedia/sidekiq_spread/blob/e08c71ebdddbcb3cd16d6c9318573e13f3a249c4/lib/sidekiq_spread.rb#L32-L117
train
bemurphy/motivation
lib/motivation.rb
Motivation.ClassMethods.translation_key
def translation_key key = name.gsub(/Motivation\z/, '') key.gsub!(/^.*::/, '') key.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2') key.gsub!(/([a-z\d])([A-Z])/,'\1_\2') key.tr!("-", "_") key.downcase! end
ruby
def translation_key key = name.gsub(/Motivation\z/, '') key.gsub!(/^.*::/, '') key.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2') key.gsub!(/([a-z\d])([A-Z])/,'\1_\2') key.tr!("-", "_") key.downcase! end
[ "def", "translation_key", "key", "=", "name", ".", "gsub", "(", "/", "\\z", "/", ",", "''", ")", "key", ".", "gsub!", "(", "/", "/", ",", "''", ")", "key", ".", "gsub!", "(", "/", "\\d", "/", ",", "'\\1_\\2'", ")", "key", ".", "gsub!", "(", "/", "\\d", "/", ",", "'\\1_\\2'", ")", "key", ".", "tr!", "(", "\"-\"", ",", "\"_\"", ")", "key", ".", "downcase!", "end" ]
Returns the underscored name used in the full i18n translation key Example: UserProjectMotivation.translation_key # => "user_project"
[ "Returns", "the", "underscored", "name", "used", "in", "the", "full", "i18n", "translation", "key" ]
c545b6a3f23400557192f2ef17d08fd44264f2e2
https://github.com/bemurphy/motivation/blob/c545b6a3f23400557192f2ef17d08fd44264f2e2/lib/motivation.rb#L67-L74
train
bemurphy/motivation
lib/motivation.rb
Motivation.ClassMethods.check
def check(name = @current_step_name, &block) raise "No step name" unless name @current_step_name ||= name checks << CheckBlock.new("progression_name", name, &block) define_method("#{name}?") do check = checks.find { |s| s.name == name } !! check.run(self) end end
ruby
def check(name = @current_step_name, &block) raise "No step name" unless name @current_step_name ||= name checks << CheckBlock.new("progression_name", name, &block) define_method("#{name}?") do check = checks.find { |s| s.name == name } !! check.run(self) end end
[ "def", "check", "(", "name", "=", "@current_step_name", ",", "&", "block", ")", "raise", "\"No step name\"", "unless", "name", "@current_step_name", "||=", "name", "checks", "<<", "CheckBlock", ".", "new", "(", "\"progression_name\"", ",", "name", ",", "&", "block", ")", "define_method", "(", "\"#{name}?\"", ")", "do", "check", "=", "checks", ".", "find", "{", "|", "s", "|", "s", ".", "name", "==", "name", "}", "!", "!", "check", ".", "run", "(", "self", ")", "end", "end" ]
Create a predicate method for the current step name to test if it's complete
[ "Create", "a", "predicate", "method", "for", "the", "current", "step", "name", "to", "test", "if", "it", "s", "complete" ]
c545b6a3f23400557192f2ef17d08fd44264f2e2
https://github.com/bemurphy/motivation/blob/c545b6a3f23400557192f2ef17d08fd44264f2e2/lib/motivation.rb#L100-L109
train
bemurphy/motivation
lib/motivation.rb
Motivation.ClassMethods.complete
def complete(&block) name = @current_step_name or raise "No step name" completions << CompletionBlock.new("progression_name", name, &block) define_method("complete_#{name}") do completion = completions.find { |c| c.name == name } completion.run(self) end end
ruby
def complete(&block) name = @current_step_name or raise "No step name" completions << CompletionBlock.new("progression_name", name, &block) define_method("complete_#{name}") do completion = completions.find { |c| c.name == name } completion.run(self) end end
[ "def", "complete", "(", "&", "block", ")", "name", "=", "@current_step_name", "or", "raise", "\"No step name\"", "completions", "<<", "CompletionBlock", ".", "new", "(", "\"progression_name\"", ",", "name", ",", "&", "block", ")", "define_method", "(", "\"complete_#{name}\"", ")", "do", "completion", "=", "completions", ".", "find", "{", "|", "c", "|", "c", ".", "name", "==", "name", "}", "completion", ".", "run", "(", "self", ")", "end", "end" ]
Check a method like `complete_current_step_name` to mark a step complete. This is not always needed but useful if you want to persist a completion for performance purposes.
[ "Check", "a", "method", "like", "complete_current_step_name", "to", "mark", "a", "step", "complete", ".", "This", "is", "not", "always", "needed", "but", "useful", "if", "you", "want", "to", "persist", "a", "completion", "for", "performance", "purposes", "." ]
c545b6a3f23400557192f2ef17d08fd44264f2e2
https://github.com/bemurphy/motivation/blob/c545b6a3f23400557192f2ef17d08fd44264f2e2/lib/motivation.rb#L114-L122
train
fugroup/asset
lib/assets/helpers.rb
Asset.Helpers.tag
def tag(type, *paths, &block) paths.map do |path| # Yield the source back to the tag builder item = ::Asset.manifest.find{|i| i.path == path} # Src is same as path if item not found item ? item.sources.map{|f| yield(asset_url(f))} : yield(path) end.flatten.join("\n") end
ruby
def tag(type, *paths, &block) paths.map do |path| # Yield the source back to the tag builder item = ::Asset.manifest.find{|i| i.path == path} # Src is same as path if item not found item ? item.sources.map{|f| yield(asset_url(f))} : yield(path) end.flatten.join("\n") end
[ "def", "tag", "(", "type", ",", "*", "paths", ",", "&", "block", ")", "paths", ".", "map", "do", "|", "path", "|", "item", "=", "::", "Asset", ".", "manifest", ".", "find", "{", "|", "i", "|", "i", ".", "path", "==", "path", "}", "item", "?", "item", ".", "sources", ".", "map", "{", "|", "f", "|", "yield", "(", "asset_url", "(", "f", ")", ")", "}", ":", "yield", "(", "path", ")", "end", ".", "flatten", ".", "join", "(", "\"\\n\"", ")", "end" ]
Build the tags
[ "Build", "the", "tags" ]
3cc1aad0926d80653f25d5f0a8c9154d00049bc4
https://github.com/fugroup/asset/blob/3cc1aad0926d80653f25d5f0a8c9154d00049bc4/lib/assets/helpers.rb#L40-L48
train
DavidMikeSimon/offroad
lib/cargo_streamer.rb
Offroad.CargoStreamer.each_cargo_section
def each_cargo_section(name) raise CargoStreamerError.new("Mode must be 'r' to read cargo data") unless @mode == "r" locations = @cargo_locations[name] or return locations.each do |seek_location| @ioh.seek(seek_location) digest = "" encoded_data = "" @ioh.each_line do |line| line.chomp! if line == CARGO_END break elsif digest == "" digest = line else encoded_data += line end end yield verify_and_decode_cargo(digest, encoded_data) end end
ruby
def each_cargo_section(name) raise CargoStreamerError.new("Mode must be 'r' to read cargo data") unless @mode == "r" locations = @cargo_locations[name] or return locations.each do |seek_location| @ioh.seek(seek_location) digest = "" encoded_data = "" @ioh.each_line do |line| line.chomp! if line == CARGO_END break elsif digest == "" digest = line else encoded_data += line end end yield verify_and_decode_cargo(digest, encoded_data) end end
[ "def", "each_cargo_section", "(", "name", ")", "raise", "CargoStreamerError", ".", "new", "(", "\"Mode must be 'r' to read cargo data\"", ")", "unless", "@mode", "==", "\"r\"", "locations", "=", "@cargo_locations", "[", "name", "]", "or", "return", "locations", ".", "each", "do", "|", "seek_location", "|", "@ioh", ".", "seek", "(", "seek_location", ")", "digest", "=", "\"\"", "encoded_data", "=", "\"\"", "@ioh", ".", "each_line", "do", "|", "line", "|", "line", ".", "chomp!", "if", "line", "==", "CARGO_END", "break", "elsif", "digest", "==", "\"\"", "digest", "=", "line", "else", "encoded_data", "+=", "line", "end", "end", "yield", "verify_and_decode_cargo", "(", "digest", ",", "encoded_data", ")", "end", "end" ]
Reads, verifies, and decodes each cargo section with a given name, passing each section's decoded data to the block
[ "Reads", "verifies", "and", "decodes", "each", "cargo", "section", "with", "a", "given", "name", "passing", "each", "section", "s", "decoded", "data", "to", "the", "block" ]
0dee8935c6600428204494ba3c24e531277d57b0
https://github.com/DavidMikeSimon/offroad/blob/0dee8935c6600428204494ba3c24e531277d57b0/lib/cargo_streamer.rb#L124-L144
train
litenup/audio_hero
lib/audio_hero.rb
AudioHero.Sox.extract_features
def extract_features(options={}) rate = options[:sample_rate] || "8000" begin parameters = [] parameters << "-r #{rate}" parameters << ":source" parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ") success = Cocaine::CommandLine.new("yaafehero", parameters).run(:source => get_path(@file)) rescue => e raise AudioHeroError, "These was an issue getting stats from #{@basename}" end garbage_collect(@file) if options[:gc] == "true" MessagePack.unpack(success) end
ruby
def extract_features(options={}) rate = options[:sample_rate] || "8000" begin parameters = [] parameters << "-r #{rate}" parameters << ":source" parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ") success = Cocaine::CommandLine.new("yaafehero", parameters).run(:source => get_path(@file)) rescue => e raise AudioHeroError, "These was an issue getting stats from #{@basename}" end garbage_collect(@file) if options[:gc] == "true" MessagePack.unpack(success) end
[ "def", "extract_features", "(", "options", "=", "{", "}", ")", "rate", "=", "options", "[", ":sample_rate", "]", "||", "\"8000\"", "begin", "parameters", "=", "[", "]", "parameters", "<<", "\"-r #{rate}\"", "parameters", "<<", "\":source\"", "parameters", "=", "parameters", ".", "flatten", ".", "compact", ".", "join", "(", "\" \"", ")", ".", "strip", ".", "squeeze", "(", "\" \"", ")", "success", "=", "Cocaine", "::", "CommandLine", ".", "new", "(", "\"yaafehero\"", ",", "parameters", ")", ".", "run", "(", ":source", "=>", "get_path", "(", "@file", ")", ")", "rescue", "=>", "e", "raise", "AudioHeroError", ",", "\"These was an issue getting stats from #{@basename}\"", "end", "garbage_collect", "(", "@file", ")", "if", "options", "[", ":gc", "]", "==", "\"true\"", "MessagePack", ".", "unpack", "(", "success", ")", "end" ]
Requires custom version of yaafe
[ "Requires", "custom", "version", "of", "yaafe" ]
c682a8483c6646782804b9e4ff804a6c39240937
https://github.com/litenup/audio_hero/blob/c682a8483c6646782804b9e4ff804a6c39240937/lib/audio_hero.rb#L178-L191
train
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/revisions_controller.rb
Roroacms.Admin::RevisionsController.restore
def restore post = Post.find(params[:id]) # do the restore restore = Post.restore(post) url = if restore.post_type == 'page' "/admin/pages/#{restore.id}/edit" elsif restore.post_type == 'post' "/admin/articles/#{restore.id}/edit" end # redirect to either the post or page area depending on what post_type the post has redirect_to URI.parse(url).path, notice: I18n.t("controllers.admin.revisions.restore.flash.notice", post_type: restore.post_type.capitalize) end
ruby
def restore post = Post.find(params[:id]) # do the restore restore = Post.restore(post) url = if restore.post_type == 'page' "/admin/pages/#{restore.id}/edit" elsif restore.post_type == 'post' "/admin/articles/#{restore.id}/edit" end # redirect to either the post or page area depending on what post_type the post has redirect_to URI.parse(url).path, notice: I18n.t("controllers.admin.revisions.restore.flash.notice", post_type: restore.post_type.capitalize) end
[ "def", "restore", "post", "=", "Post", ".", "find", "(", "params", "[", ":id", "]", ")", "restore", "=", "Post", ".", "restore", "(", "post", ")", "url", "=", "if", "restore", ".", "post_type", "==", "'page'", "\"/admin/pages/#{restore.id}/edit\"", "elsif", "restore", ".", "post_type", "==", "'post'", "\"/admin/articles/#{restore.id}/edit\"", "end", "redirect_to", "URI", ".", "parse", "(", "url", ")", ".", "path", ",", "notice", ":", "I18n", ".", "t", "(", "\"controllers.admin.revisions.restore.flash.notice\"", ",", "post_type", ":", "restore", ".", "post_type", ".", "capitalize", ")", "end" ]
restore the post to the given post data
[ "restore", "the", "post", "to", "the", "given", "post", "data" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/revisions_controller.rb#L22-L36
train
steveh/fingerjam
lib/fingerjam/helpers.rb
Fingerjam.Helpers.rewrite_asset_path
def rewrite_asset_path(source, path = nil) if Fingerjam::Base.enabled? && Fingerjam::Base.cached?(source) Fingerjam::Base.cached_url(source) else if path && path.respond_to?(:call) return path.call(source) elsif path && path.is_a?(String) return path % [source] end asset_id = rails_asset_id(source) if asset_id.blank? source else source + "?#{asset_id}" end end end
ruby
def rewrite_asset_path(source, path = nil) if Fingerjam::Base.enabled? && Fingerjam::Base.cached?(source) Fingerjam::Base.cached_url(source) else if path && path.respond_to?(:call) return path.call(source) elsif path && path.is_a?(String) return path % [source] end asset_id = rails_asset_id(source) if asset_id.blank? source else source + "?#{asset_id}" end end end
[ "def", "rewrite_asset_path", "(", "source", ",", "path", "=", "nil", ")", "if", "Fingerjam", "::", "Base", ".", "enabled?", "&&", "Fingerjam", "::", "Base", ".", "cached?", "(", "source", ")", "Fingerjam", "::", "Base", ".", "cached_url", "(", "source", ")", "else", "if", "path", "&&", "path", ".", "respond_to?", "(", ":call", ")", "return", "path", ".", "call", "(", "source", ")", "elsif", "path", "&&", "path", ".", "is_a?", "(", "String", ")", "return", "path", "%", "[", "source", "]", "end", "asset_id", "=", "rails_asset_id", "(", "source", ")", "if", "asset_id", ".", "blank?", "source", "else", "source", "+", "\"?#{asset_id}\"", "end", "end", "end" ]
Used by Rails view helpers
[ "Used", "by", "Rails", "view", "helpers" ]
73681d3e3c147a7a294acc734a8c8abcce4dc1fc
https://github.com/steveh/fingerjam/blob/73681d3e3c147a7a294acc734a8c8abcce4dc1fc/lib/fingerjam/helpers.rb#L5-L22
train
nrser/nrser.rb
lib/nrser/props/mutable/stash.rb
NRSER::Props::Mutable::Stash.InstanceMethods.put
def put key, value key = convert_key key if (prop = self.class.metadata[ key ]) prop.set self, value else # We know {#convert_value} is a no-op so can skip it _raw_put key, value end end
ruby
def put key, value key = convert_key key if (prop = self.class.metadata[ key ]) prop.set self, value else # We know {#convert_value} is a no-op so can skip it _raw_put key, value end end
[ "def", "put", "key", ",", "value", "key", "=", "convert_key", "key", "if", "(", "prop", "=", "self", ".", "class", ".", "metadata", "[", "key", "]", ")", "prop", ".", "set", "self", ",", "value", "else", "_raw_put", "key", ",", "value", "end", "end" ]
Store a value at a key. If the key is a prop name, store it through the prop, which will check it's type. @param [Symbol | String] key @param [VALUE] value @return [VALUE] The stored value.
[ "Store", "a", "value", "at", "a", "key", ".", "If", "the", "key", "is", "a", "prop", "name", "store", "it", "through", "the", "prop", "which", "will", "check", "it", "s", "type", "." ]
7db9a729ec65894dfac13fd50851beae8b809738
https://github.com/nrser/nrser.rb/blob/7db9a729ec65894dfac13fd50851beae8b809738/lib/nrser/props/mutable/stash.rb#L172-L181
train
aseldawy/ruby_desk
lib/ruby_desk/connector.rb
RubyDesk.Connector.sign
def sign(params) RubyDesk.logger.debug {"Params to sign: #{params.inspect}"} # sort parameters by its names (keys) sorted_params = params.sort { |a, b| a.to_s <=> b.to_s} RubyDesk.logger.debug {"Sorted params: #{sorted_params.inspect}"} # Unescape escaped params sorted_params.map! do |k, v| [k, URI.unescape(v)] end # concatenate secret with names, values concatenated = @api_secret + sorted_params.join RubyDesk.logger.debug {"concatenated: #{concatenated}"} # Calculate and return md5 of concatenated string md5 = Digest::MD5.hexdigest(concatenated) RubyDesk.logger.debug {"md5: #{md5}"} return md5 end
ruby
def sign(params) RubyDesk.logger.debug {"Params to sign: #{params.inspect}"} # sort parameters by its names (keys) sorted_params = params.sort { |a, b| a.to_s <=> b.to_s} RubyDesk.logger.debug {"Sorted params: #{sorted_params.inspect}"} # Unescape escaped params sorted_params.map! do |k, v| [k, URI.unescape(v)] end # concatenate secret with names, values concatenated = @api_secret + sorted_params.join RubyDesk.logger.debug {"concatenated: #{concatenated}"} # Calculate and return md5 of concatenated string md5 = Digest::MD5.hexdigest(concatenated) RubyDesk.logger.debug {"md5: #{md5}"} return md5 end
[ "def", "sign", "(", "params", ")", "RubyDesk", ".", "logger", ".", "debug", "{", "\"Params to sign: #{params.inspect}\"", "}", "sorted_params", "=", "params", ".", "sort", "{", "|", "a", ",", "b", "|", "a", ".", "to_s", "<=>", "b", ".", "to_s", "}", "RubyDesk", ".", "logger", ".", "debug", "{", "\"Sorted params: #{sorted_params.inspect}\"", "}", "sorted_params", ".", "map!", "do", "|", "k", ",", "v", "|", "[", "k", ",", "URI", ".", "unescape", "(", "v", ")", "]", "end", "concatenated", "=", "@api_secret", "+", "sorted_params", ".", "join", "RubyDesk", ".", "logger", ".", "debug", "{", "\"concatenated: #{concatenated}\"", "}", "md5", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "concatenated", ")", "RubyDesk", ".", "logger", ".", "debug", "{", "\"md5: #{md5}\"", "}", "return", "md5", "end" ]
Sign the given parameters and returns the signature
[ "Sign", "the", "given", "parameters", "and", "returns", "the", "signature" ]
3e62ae5002183b89c9e4c07b640e26c661b7644d
https://github.com/aseldawy/ruby_desk/blob/3e62ae5002183b89c9e4c07b640e26c661b7644d/lib/ruby_desk/connector.rb#L29-L52
train
aseldawy/ruby_desk
lib/ruby_desk/connector.rb
RubyDesk.Connector.invoke_api_call
def invoke_api_call(api_call) url = URI.parse(api_call[:url]) http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE # Concatenate parameters to form data data = api_call[:params].to_a.map{|pair| pair.map{|x| URI.escape(x.to_s)}.join '='}.join('&') headers = { 'Content-Type' => 'application/x-www-form-urlencoded' } RubyDesk.logger.info "URL: #{api_call[:url]}" RubyDesk.logger.info "method: #{api_call[:method]}" RubyDesk.logger.info "Params: #{data}" case api_call[:method] when :get, 'get' then resp, data = http.request(Net::HTTP::Get.new(url.path+"?"+data, headers)) when :post, 'post' then resp, data = http.request(Net::HTTP::Post.new(url.path, headers), data) when :delete, 'delete' then resp, data = http.request(Net::HTTP::Delete.new(url.path, headers), data) end RubyDesk.logger.info "Response code: #{resp.code}" RubyDesk.logger.info "Returned data: #{data}" case resp.code when "200" then return data when "400" then raise RubyDesk::BadRequest, data when "401", "403" then raise RubyDesk::UnauthorizedError, data when "404" then raise RubyDesk::PageNotFound, data when "500" then raise RubyDesk::ServerError, data else raise RubyDesk::Error, data end end
ruby
def invoke_api_call(api_call) url = URI.parse(api_call[:url]) http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE # Concatenate parameters to form data data = api_call[:params].to_a.map{|pair| pair.map{|x| URI.escape(x.to_s)}.join '='}.join('&') headers = { 'Content-Type' => 'application/x-www-form-urlencoded' } RubyDesk.logger.info "URL: #{api_call[:url]}" RubyDesk.logger.info "method: #{api_call[:method]}" RubyDesk.logger.info "Params: #{data}" case api_call[:method] when :get, 'get' then resp, data = http.request(Net::HTTP::Get.new(url.path+"?"+data, headers)) when :post, 'post' then resp, data = http.request(Net::HTTP::Post.new(url.path, headers), data) when :delete, 'delete' then resp, data = http.request(Net::HTTP::Delete.new(url.path, headers), data) end RubyDesk.logger.info "Response code: #{resp.code}" RubyDesk.logger.info "Returned data: #{data}" case resp.code when "200" then return data when "400" then raise RubyDesk::BadRequest, data when "401", "403" then raise RubyDesk::UnauthorizedError, data when "404" then raise RubyDesk::PageNotFound, data when "500" then raise RubyDesk::ServerError, data else raise RubyDesk::Error, data end end
[ "def", "invoke_api_call", "(", "api_call", ")", "url", "=", "URI", ".", "parse", "(", "api_call", "[", ":url", "]", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "url", ".", "host", ",", "url", ".", "port", ")", "http", ".", "use_ssl", "=", "true", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "data", "=", "api_call", "[", ":params", "]", ".", "to_a", ".", "map", "{", "|", "pair", "|", "pair", ".", "map", "{", "|", "x", "|", "URI", ".", "escape", "(", "x", ".", "to_s", ")", "}", ".", "join", "'='", "}", ".", "join", "(", "'&'", ")", "headers", "=", "{", "'Content-Type'", "=>", "'application/x-www-form-urlencoded'", "}", "RubyDesk", ".", "logger", ".", "info", "\"URL: #{api_call[:url]}\"", "RubyDesk", ".", "logger", ".", "info", "\"method: #{api_call[:method]}\"", "RubyDesk", ".", "logger", ".", "info", "\"Params: #{data}\"", "case", "api_call", "[", ":method", "]", "when", ":get", ",", "'get'", "then", "resp", ",", "data", "=", "http", ".", "request", "(", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "url", ".", "path", "+", "\"?\"", "+", "data", ",", "headers", ")", ")", "when", ":post", ",", "'post'", "then", "resp", ",", "data", "=", "http", ".", "request", "(", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "url", ".", "path", ",", "headers", ")", ",", "data", ")", "when", ":delete", ",", "'delete'", "then", "resp", ",", "data", "=", "http", ".", "request", "(", "Net", "::", "HTTP", "::", "Delete", ".", "new", "(", "url", ".", "path", ",", "headers", ")", ",", "data", ")", "end", "RubyDesk", ".", "logger", ".", "info", "\"Response code: #{resp.code}\"", "RubyDesk", ".", "logger", ".", "info", "\"Returned data: #{data}\"", "case", "resp", ".", "code", "when", "\"200\"", "then", "return", "data", "when", "\"400\"", "then", "raise", "RubyDesk", "::", "BadRequest", ",", "data", "when", "\"401\"", ",", "\"403\"", "then", "raise", "RubyDesk", "::", "UnauthorizedError", ",", "data", "when", "\"404\"", "then", "raise", "RubyDesk", "::", "PageNotFound", ",", "data", "when", "\"500\"", "then", "raise", "RubyDesk", "::", "ServerError", ",", "data", "else", "raise", "RubyDesk", "::", "Error", ",", "data", "end", "end" ]
invokes the given API call and returns body of the response as text
[ "invokes", "the", "given", "API", "call", "and", "returns", "body", "of", "the", "response", "as", "text" ]
3e62ae5002183b89c9e4c07b640e26c661b7644d
https://github.com/aseldawy/ruby_desk/blob/3e62ae5002183b89c9e4c07b640e26c661b7644d/lib/ruby_desk/connector.rb#L79-L116
train
aseldawy/ruby_desk
lib/ruby_desk/connector.rb
RubyDesk.Connector.prepare_and_invoke_api_call
def prepare_and_invoke_api_call(path, options = {}) api_call = prepare_api_call(path, options) data = invoke_api_call(api_call) parsed_data = case options[:format] when 'json' then JSON.parse(data) when 'xml' then REXML::Document.new(data) else JSON.parse(data) rescue REXML::Document.new(data) rescue data end RubyDesk.logger.info "Parsed data: #{parsed_data.inspect}" return parsed_data end
ruby
def prepare_and_invoke_api_call(path, options = {}) api_call = prepare_api_call(path, options) data = invoke_api_call(api_call) parsed_data = case options[:format] when 'json' then JSON.parse(data) when 'xml' then REXML::Document.new(data) else JSON.parse(data) rescue REXML::Document.new(data) rescue data end RubyDesk.logger.info "Parsed data: #{parsed_data.inspect}" return parsed_data end
[ "def", "prepare_and_invoke_api_call", "(", "path", ",", "options", "=", "{", "}", ")", "api_call", "=", "prepare_api_call", "(", "path", ",", "options", ")", "data", "=", "invoke_api_call", "(", "api_call", ")", "parsed_data", "=", "case", "options", "[", ":format", "]", "when", "'json'", "then", "JSON", ".", "parse", "(", "data", ")", "when", "'xml'", "then", "REXML", "::", "Document", ".", "new", "(", "data", ")", "else", "JSON", ".", "parse", "(", "data", ")", "rescue", "REXML", "::", "Document", ".", "new", "(", "data", ")", "rescue", "data", "end", "RubyDesk", ".", "logger", ".", "info", "\"Parsed data: #{parsed_data.inspect}\"", "return", "parsed_data", "end" ]
Prepares an API call with the given arguments then invokes it and returns its body
[ "Prepares", "an", "API", "call", "with", "the", "given", "arguments", "then", "invokes", "it", "and", "returns", "its", "body" ]
3e62ae5002183b89c9e4c07b640e26c661b7644d
https://github.com/aseldawy/ruby_desk/blob/3e62ae5002183b89c9e4c07b640e26c661b7644d/lib/ruby_desk/connector.rb#L119-L130
train
aseldawy/ruby_desk
lib/ruby_desk/connector.rb
RubyDesk.Connector.auth_url
def auth_url auth_call = prepare_api_call("", :params=>{:api_key=>@api_key}, :base_url=>ODESK_AUTH_URL, :format=>nil, :method=>:get, :auth=>false) data = auth_call[:params].to_a.map{|pair| pair.join '='}.join('&') return auth_call[:url]+"?"+data end
ruby
def auth_url auth_call = prepare_api_call("", :params=>{:api_key=>@api_key}, :base_url=>ODESK_AUTH_URL, :format=>nil, :method=>:get, :auth=>false) data = auth_call[:params].to_a.map{|pair| pair.join '='}.join('&') return auth_call[:url]+"?"+data end
[ "def", "auth_url", "auth_call", "=", "prepare_api_call", "(", "\"\"", ",", ":params", "=>", "{", ":api_key", "=>", "@api_key", "}", ",", ":base_url", "=>", "ODESK_AUTH_URL", ",", ":format", "=>", "nil", ",", ":method", "=>", ":get", ",", ":auth", "=>", "false", ")", "data", "=", "auth_call", "[", ":params", "]", ".", "to_a", ".", "map", "{", "|", "pair", "|", "pair", ".", "join", "'='", "}", ".", "join", "(", "'&'", ")", "return", "auth_call", "[", ":url", "]", "+", "\"?\"", "+", "data", "end" ]
Returns the URL that authenticates the application for the current user. This is used for web applications only
[ "Returns", "the", "URL", "that", "authenticates", "the", "application", "for", "the", "current", "user", ".", "This", "is", "used", "for", "web", "applications", "only" ]
3e62ae5002183b89c9e4c07b640e26c661b7644d
https://github.com/aseldawy/ruby_desk/blob/3e62ae5002183b89c9e4c07b640e26c661b7644d/lib/ruby_desk/connector.rb#L134-L139
train
aseldawy/ruby_desk
lib/ruby_desk/connector.rb
RubyDesk.Connector.desktop_auth_url
def desktop_auth_url raise "Frob should be requested first. Use RubyDesk::Controller#get_frob()" unless @frob auth_call = prepare_api_call("", :params=>{:api_key=>@api_key, :frob=>@frob}, :base_url=>ODESK_AUTH_URL, :format=>nil, :method=>:get, :auth=>false) data = auth_call[:params].to_a.map{|pair| pair.join '='}.join('&') return auth_call[:url]+"?"+data end
ruby
def desktop_auth_url raise "Frob should be requested first. Use RubyDesk::Controller#get_frob()" unless @frob auth_call = prepare_api_call("", :params=>{:api_key=>@api_key, :frob=>@frob}, :base_url=>ODESK_AUTH_URL, :format=>nil, :method=>:get, :auth=>false) data = auth_call[:params].to_a.map{|pair| pair.join '='}.join('&') return auth_call[:url]+"?"+data end
[ "def", "desktop_auth_url", "raise", "\"Frob should be requested first. Use RubyDesk::Controller#get_frob()\"", "unless", "@frob", "auth_call", "=", "prepare_api_call", "(", "\"\"", ",", ":params", "=>", "{", ":api_key", "=>", "@api_key", ",", ":frob", "=>", "@frob", "}", ",", ":base_url", "=>", "ODESK_AUTH_URL", ",", ":format", "=>", "nil", ",", ":method", "=>", ":get", ",", ":auth", "=>", "false", ")", "data", "=", "auth_call", "[", ":params", "]", ".", "to_a", ".", "map", "{", "|", "pair", "|", "pair", ".", "join", "'='", "}", ".", "join", "(", "'&'", ")", "return", "auth_call", "[", ":url", "]", "+", "\"?\"", "+", "data", "end" ]
Returns a URL that the desktop user should visit to activate current frob. This method should not be called before a frob has been requested
[ "Returns", "a", "URL", "that", "the", "desktop", "user", "should", "visit", "to", "activate", "current", "frob", ".", "This", "method", "should", "not", "be", "called", "before", "a", "frob", "has", "been", "requested" ]
3e62ae5002183b89c9e4c07b640e26c661b7644d
https://github.com/aseldawy/ruby_desk/blob/3e62ae5002183b89c9e4c07b640e26c661b7644d/lib/ruby_desk/connector.rb#L143-L149
train
spllr/rack-secure_only
lib/rack/secure_only.rb
Rack.SecureOnly.handle?
def handle?(req) if @opts.key?(:if) cond = @opts[:if] cond = cond.call(req) if cond.respond_to?(:call) return cond end true end
ruby
def handle?(req) if @opts.key?(:if) cond = @opts[:if] cond = cond.call(req) if cond.respond_to?(:call) return cond end true end
[ "def", "handle?", "(", "req", ")", "if", "@opts", ".", "key?", "(", ":if", ")", "cond", "=", "@opts", "[", ":if", "]", "cond", "=", "cond", ".", "call", "(", "req", ")", "if", "cond", ".", "respond_to?", "(", ":call", ")", "return", "cond", "end", "true", "end" ]
Returns false if the current request should not be handled by the middleware
[ "Returns", "false", "if", "the", "current", "request", "should", "not", "be", "handled", "by", "the", "middleware" ]
1fff5d875ac41a89d7495f1e5b686d5a3032ee0c
https://github.com/spllr/rack-secure_only/blob/1fff5d875ac41a89d7495f1e5b686d5a3032ee0c/lib/rack/secure_only.rb#L55-L62
train
kunklejr/system-metrics
app/models/system_metrics/metric.rb
SystemMetrics.Metric.parent_of?
def parent_of?(metric) if new_record? start = (started_at - metric.started_at) * 1000.0 start <= 0 && (start + duration >= metric.duration) else self.id == metric.parent_id end end
ruby
def parent_of?(metric) if new_record? start = (started_at - metric.started_at) * 1000.0 start <= 0 && (start + duration >= metric.duration) else self.id == metric.parent_id end end
[ "def", "parent_of?", "(", "metric", ")", "if", "new_record?", "start", "=", "(", "started_at", "-", "metric", ".", "started_at", ")", "*", "1000.0", "start", "<=", "0", "&&", "(", "start", "+", "duration", ">=", "metric", ".", "duration", ")", "else", "self", ".", "id", "==", "metric", ".", "parent_id", "end", "end" ]
Returns if the current node is the parent of the given node. If this is a new record, we can use started_at values to detect parenting. However, if it was already saved, we lose microseconds information from timestamps and we must rely solely in id and parent_id information.
[ "Returns", "if", "the", "current", "node", "is", "the", "parent", "of", "the", "given", "node", ".", "If", "this", "is", "a", "new", "record", "we", "can", "use", "started_at", "values", "to", "detect", "parenting", ".", "However", "if", "it", "was", "already", "saved", "we", "lose", "microseconds", "information", "from", "timestamps", "and", "we", "must", "rely", "solely", "in", "id", "and", "parent_id", "information", "." ]
d1b23c88a2c3ce5dd77cb1118d6a539877002516
https://github.com/kunklejr/system-metrics/blob/d1b23c88a2c3ce5dd77cb1118d6a539877002516/app/models/system_metrics/metric.rb#L24-L31
train
qw3/superpay_api
lib/superpay_api/item_pedido.rb
SuperpayApi.ItemPedido.to_request
def to_request item_pedido = { codigo_produto: self.codigo_produto, codigo_categoria: self.codigo_categoria, nome_produto: self.nome_produto, quantidade_produto: self.quantidade_produto, valor_unitario_produto: self.valor_unitario_produto, nome_categoria: self.nome_categoria, } return item_pedido end
ruby
def to_request item_pedido = { codigo_produto: self.codigo_produto, codigo_categoria: self.codigo_categoria, nome_produto: self.nome_produto, quantidade_produto: self.quantidade_produto, valor_unitario_produto: self.valor_unitario_produto, nome_categoria: self.nome_categoria, } return item_pedido end
[ "def", "to_request", "item_pedido", "=", "{", "codigo_produto", ":", "self", ".", "codigo_produto", ",", "codigo_categoria", ":", "self", ".", "codigo_categoria", ",", "nome_produto", ":", "self", ".", "nome_produto", ",", "quantidade_produto", ":", "self", ".", "quantidade_produto", ",", "valor_unitario_produto", ":", "self", ".", "valor_unitario_produto", ",", "nome_categoria", ":", "self", ".", "nome_categoria", ",", "}", "return", "item_pedido", "end" ]
Nova instancia da classe ItemPedido @param [Hash] campos Montar o Hash de dados do ItemPedido no padrão utilizado pelo SuperPay
[ "Nova", "instancia", "da", "classe", "ItemPedido" ]
41bfc78f592956708b576f6d0f7c993fb8a3bc22
https://github.com/qw3/superpay_api/blob/41bfc78f592956708b576f6d0f7c993fb8a3bc22/lib/superpay_api/item_pedido.rb#L51-L61
train
hokstadconsulting/purecdb
lib/purecdb/reader.rb
PureCDB.Reader.values
def values(key) h = hash(key) hoff = @hashes[(h % 256)*2] hlen = @hashes[(h % 256)*2 + 1] return [] if hlen == 0 off = (h / 256) % hlen vals = [] # FIXME: Is this potentially an infinite loop (if full)? # Easy to avoid by exiting if off reaches the same value twice. while (slot = read(hoff + off * hashref_size .. hoff + off * hashref_size + hashref_size - 1)) && (dslot = ary_unpack(slot,2)) && dslot[1] != 0 if dslot[0] == h pos = dslot[1] rkey, value = read_entry(pos) if rkey == key vals << value end end off = (off + 1) % hlen end return vals end
ruby
def values(key) h = hash(key) hoff = @hashes[(h % 256)*2] hlen = @hashes[(h % 256)*2 + 1] return [] if hlen == 0 off = (h / 256) % hlen vals = [] # FIXME: Is this potentially an infinite loop (if full)? # Easy to avoid by exiting if off reaches the same value twice. while (slot = read(hoff + off * hashref_size .. hoff + off * hashref_size + hashref_size - 1)) && (dslot = ary_unpack(slot,2)) && dslot[1] != 0 if dslot[0] == h pos = dslot[1] rkey, value = read_entry(pos) if rkey == key vals << value end end off = (off + 1) % hlen end return vals end
[ "def", "values", "(", "key", ")", "h", "=", "hash", "(", "key", ")", "hoff", "=", "@hashes", "[", "(", "h", "%", "256", ")", "*", "2", "]", "hlen", "=", "@hashes", "[", "(", "h", "%", "256", ")", "*", "2", "+", "1", "]", "return", "[", "]", "if", "hlen", "==", "0", "off", "=", "(", "h", "/", "256", ")", "%", "hlen", "vals", "=", "[", "]", "while", "(", "slot", "=", "read", "(", "hoff", "+", "off", "*", "hashref_size", "..", "hoff", "+", "off", "*", "hashref_size", "+", "hashref_size", "-", "1", ")", ")", "&&", "(", "dslot", "=", "ary_unpack", "(", "slot", ",", "2", ")", ")", "&&", "dslot", "[", "1", "]", "!=", "0", "if", "dslot", "[", "0", "]", "==", "h", "pos", "=", "dslot", "[", "1", "]", "rkey", ",", "value", "=", "read_entry", "(", "pos", ")", "if", "rkey", "==", "key", "vals", "<<", "value", "end", "end", "off", "=", "(", "off", "+", "1", ")", "%", "hlen", "end", "return", "vals", "end" ]
Returns all values for +key+ in an array
[ "Returns", "all", "values", "for", "+", "key", "+", "in", "an", "array" ]
d19102e5dffbb2f0de4fab4f86c603880c3ffea8
https://github.com/hokstadconsulting/purecdb/blob/d19102e5dffbb2f0de4fab4f86c603880c3ffea8/lib/purecdb/reader.rb#L107-L136
train
notioneer/ncore-ruby
lib/ncore/rails/active_model.rb
NCore.ActiveModel.errors_for_actionpack
def errors_for_actionpack e0 = ::ActiveModel::Errors.new(self) @errors.each do |e| e0.add :base, e end e0 end
ruby
def errors_for_actionpack e0 = ::ActiveModel::Errors.new(self) @errors.each do |e| e0.add :base, e end e0 end
[ "def", "errors_for_actionpack", "e0", "=", "::", "ActiveModel", "::", "Errors", ".", "new", "(", "self", ")", "@errors", ".", "each", "do", "|", "e", "|", "e0", ".", "add", ":base", ",", "e", "end", "e0", "end" ]
actionpack 4 requires a more robust Errors object
[ "actionpack", "4", "requires", "a", "more", "robust", "Errors", "object" ]
f2abd124b9012a402e33aa7c25dabacb7eaffcde
https://github.com/notioneer/ncore-ruby/blob/f2abd124b9012a402e33aa7c25dabacb7eaffcde/lib/ncore/rails/active_model.rb#L33-L39
train
davidrichards/gearbox
lib/gearbox/mixins/ad_hoc_properties.rb
Gearbox.AdHocProperties.add_property
def add_property(accessor, predicate, object) new_property = RDF::Statement.new(bnode, predicate, object) attributes_list[accessor] = new_property end
ruby
def add_property(accessor, predicate, object) new_property = RDF::Statement.new(bnode, predicate, object) attributes_list[accessor] = new_property end
[ "def", "add_property", "(", "accessor", ",", "predicate", ",", "object", ")", "new_property", "=", "RDF", "::", "Statement", ".", "new", "(", "bnode", ",", "predicate", ",", "object", ")", "attributes_list", "[", "accessor", "]", "=", "new_property", "end" ]
Add a property without defining it on the class. This will stay, will use the subject, and the regular infrastructure. @param [Symbol] accessor, the new field being created. @param [RDF::Statement] predicate, the predicate for the new field. @param [Any] The value to store
[ "Add", "a", "property", "without", "defining", "it", "on", "the", "class", ".", "This", "will", "stay", "will", "use", "the", "subject", "and", "the", "regular", "infrastructure", "." ]
322e1a44394b6323d849c5e65acad66cdf284aac
https://github.com/davidrichards/gearbox/blob/322e1a44394b6323d849c5e65acad66cdf284aac/lib/gearbox/mixins/ad_hoc_properties.rb#L35-L38
train
openSUSE/dm-bugzilla-adapter
lib/dm-bugzilla-adapter/update.rb
DataMapper::Adapters.BugzillaAdapter.update
def update(attributes, collection) each_resource_with_edit_url(collection) do |resource, edit_url| put_updated_resource(edit_url, resource) end # return count collection.size end
ruby
def update(attributes, collection) each_resource_with_edit_url(collection) do |resource, edit_url| put_updated_resource(edit_url, resource) end # return count collection.size end
[ "def", "update", "(", "attributes", ",", "collection", ")", "each_resource_with_edit_url", "(", "collection", ")", "do", "|", "resource", ",", "edit_url", "|", "put_updated_resource", "(", "edit_url", ",", "resource", ")", "end", "collection", ".", "size", "end" ]
Constructs and executes UPDATE statement for given attributes and a query @param [Hash(Property => Object)] attributes hash of attribute values to set, keyed by Property @param [Collection] collection collection of records to be updated @return [Integer] the number of records updated @api semipublic
[ "Constructs", "and", "executes", "UPDATE", "statement", "for", "given", "attributes", "and", "a", "query" ]
d56a64918f315d5038145b3f0d94852fc38bcca2
https://github.com/openSUSE/dm-bugzilla-adapter/blob/d56a64918f315d5038145b3f0d94852fc38bcca2/lib/dm-bugzilla-adapter/update.rb#L16-L22
train
SquareSquash/ios_symbolicator
lib/squash/symbolicator.rb
Squash.Symbolicator.architectures
def architectures architectures = Hash.new stdin, stdout, stderr = Open3.popen3('dwarfdump', '-u', @dsym) stdout.each_line do |line| if line =~ /^UUID: ([0-9A-F\-]+) \((.+?)\)/ architectures[$2] = $1 end end return architectures end
ruby
def architectures architectures = Hash.new stdin, stdout, stderr = Open3.popen3('dwarfdump', '-u', @dsym) stdout.each_line do |line| if line =~ /^UUID: ([0-9A-F\-]+) \((.+?)\)/ architectures[$2] = $1 end end return architectures end
[ "def", "architectures", "architectures", "=", "Hash", ".", "new", "stdin", ",", "stdout", ",", "stderr", "=", "Open3", ".", "popen3", "(", "'dwarfdump'", ",", "'-u'", ",", "@dsym", ")", "stdout", ".", "each_line", "do", "|", "line", "|", "if", "line", "=~", "/", "\\-", "\\(", "\\)", "/", "architectures", "[", "$2", "]", "=", "$1", "end", "end", "return", "architectures", "end" ]
Creates a new symbolicator for a given dSYM file. @param [String] dsym The path to a dSYM file (or DWARF file within). @param [String] project_dir The path to a project root that will be removed from file paths underneath that root. @return [Hash<String, String>] A hash mapping architectures (such as "i386") to the UUID for the symbolication of that architecture.
[ "Creates", "a", "new", "symbolicator", "for", "a", "given", "dSYM", "file", "." ]
6b7146b7efed0922d22d80fcb49e8d5964a23967
https://github.com/SquareSquash/ios_symbolicator/blob/6b7146b7efed0922d22d80fcb49e8d5964a23967/lib/squash/symbolicator.rb#L38-L49
train
detroit/detroit-email
lib/detroit-email.rb
Detroit.Email.announce
def announce apply_environment unless @approved mailopts = self.mailopts if mailto.empty? report "No recipents given." else if trial? subject = mailopts['subject'] mailto = mailopts['to'].flatten.join(", ") report "email '#{subject}' to #{mailto}" else #emailer = Emailer.new(mailopts) #emailer.email if @approved email(mailopts) else exit -1 end end end end
ruby
def announce apply_environment unless @approved mailopts = self.mailopts if mailto.empty? report "No recipents given." else if trial? subject = mailopts['subject'] mailto = mailopts['to'].flatten.join(", ") report "email '#{subject}' to #{mailto}" else #emailer = Emailer.new(mailopts) #emailer.email if @approved email(mailopts) else exit -1 end end end end
[ "def", "announce", "apply_environment", "unless", "@approved", "mailopts", "=", "self", ".", "mailopts", "if", "mailto", ".", "empty?", "report", "\"No recipents given.\"", "else", "if", "trial?", "subject", "=", "mailopts", "[", "'subject'", "]", "mailto", "=", "mailopts", "[", "'to'", "]", ".", "flatten", ".", "join", "(", "\", \"", ")", "report", "\"email '#{subject}' to #{mailto}\"", "else", "if", "@approved", "email", "(", "mailopts", ")", "else", "exit", "-", "1", "end", "end", "end", "end" ]
Send announcement message.
[ "Send", "announcement", "message", "." ]
682de790705301f2b83cd6afab585f5aaf59d42b
https://github.com/detroit/detroit-email/blob/682de790705301f2b83cd6afab585f5aaf59d42b/lib/detroit-email.rb#L125-L147
train
detroit/detroit-email
lib/detroit-email.rb
Detroit.Email.message
def message @message ||= ( path = Dir[file].first if file if path project.announcement(File.new(file)) else parts.map{ |part| /^file:\/\// =~ part.to_s ? $' : part } project.announcement(*parts) end ) end
ruby
def message @message ||= ( path = Dir[file].first if file if path project.announcement(File.new(file)) else parts.map{ |part| /^file:\/\// =~ part.to_s ? $' : part } project.announcement(*parts) end ) end
[ "def", "message", "@message", "||=", "(", "path", "=", "Dir", "[", "file", "]", ".", "first", "if", "file", "if", "path", "project", ".", "announcement", "(", "File", ".", "new", "(", "file", ")", ")", "else", "parts", ".", "map", "{", "|", "part", "|", "/", "\\/", "\\/", "/", "=~", "part", ".", "to_s", "?", "$'", ":", "part", "}", "project", ".", "announcement", "(", "*", "parts", ")", "end", ")", "end" ]
Message to send. Defaults to a generated release announcement.
[ "Message", "to", "send", ".", "Defaults", "to", "a", "generated", "release", "announcement", "." ]
682de790705301f2b83cd6afab585f5aaf59d42b
https://github.com/detroit/detroit-email/blob/682de790705301f2b83cd6afab585f5aaf59d42b/lib/detroit-email.rb#L155-L165
train
detroit/detroit-email
lib/detroit-email.rb
Detroit.Email.apply_environment
def apply_environment return if noenv @server ||= ENV['EMAIL_SERVER'] @from ||= ENV['EMAIL_FROM'] || ENV['EMAIL_ACCOUNT'] @account ||= ENV['EMAIL_ACCOUNT'] || ENV['EMAIL_FROM'] @password ||= ENV['EMAIL_PASSWORD'] @port ||= ENV['EMAIL_PORT'] @domain ||= ENV['EMAIL_DOMAIN'] @login ||= ENV['EMAIL_LOGIN'] @secure ||= ENV['EMAIL_SECURE'] end
ruby
def apply_environment return if noenv @server ||= ENV['EMAIL_SERVER'] @from ||= ENV['EMAIL_FROM'] || ENV['EMAIL_ACCOUNT'] @account ||= ENV['EMAIL_ACCOUNT'] || ENV['EMAIL_FROM'] @password ||= ENV['EMAIL_PASSWORD'] @port ||= ENV['EMAIL_PORT'] @domain ||= ENV['EMAIL_DOMAIN'] @login ||= ENV['EMAIL_LOGIN'] @secure ||= ENV['EMAIL_SECURE'] end
[ "def", "apply_environment", "return", "if", "noenv", "@server", "||=", "ENV", "[", "'EMAIL_SERVER'", "]", "@from", "||=", "ENV", "[", "'EMAIL_FROM'", "]", "||", "ENV", "[", "'EMAIL_ACCOUNT'", "]", "@account", "||=", "ENV", "[", "'EMAIL_ACCOUNT'", "]", "||", "ENV", "[", "'EMAIL_FROM'", "]", "@password", "||=", "ENV", "[", "'EMAIL_PASSWORD'", "]", "@port", "||=", "ENV", "[", "'EMAIL_PORT'", "]", "@domain", "||=", "ENV", "[", "'EMAIL_DOMAIN'", "]", "@login", "||=", "ENV", "[", "'EMAIL_LOGIN'", "]", "@secure", "||=", "ENV", "[", "'EMAIL_SECURE'", "]", "end" ]
Apply environment settings.
[ "Apply", "environment", "settings", "." ]
682de790705301f2b83cd6afab585f5aaf59d42b
https://github.com/detroit/detroit-email/blob/682de790705301f2b83cd6afab585f5aaf59d42b/lib/detroit-email.rb#L208-L218
train
codescrum/bebox
lib/bebox/provision.rb
Bebox.Provision.apply
def apply started_at = DateTime.now.to_s # Check if a Puppetfile is neccesary for use/not use librarian-puppet check_puppetfile_content # Copy static modules that are not downloaded by librarian-puppet copy_static_modules # Apply step and if the process is succesful create the checkpoint. process_status = apply_step create_step_checkpoint(started_at) if process_status.success? process_status end
ruby
def apply started_at = DateTime.now.to_s # Check if a Puppetfile is neccesary for use/not use librarian-puppet check_puppetfile_content # Copy static modules that are not downloaded by librarian-puppet copy_static_modules # Apply step and if the process is succesful create the checkpoint. process_status = apply_step create_step_checkpoint(started_at) if process_status.success? process_status end
[ "def", "apply", "started_at", "=", "DateTime", ".", "now", ".", "to_s", "check_puppetfile_content", "copy_static_modules", "process_status", "=", "apply_step", "create_step_checkpoint", "(", "started_at", ")", "if", "process_status", ".", "success?", "process_status", "end" ]
Puppet apply Fundamental step
[ "Puppet", "apply", "Fundamental", "step" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/provision.rb#L22-L32
train
codescrum/bebox
lib/bebox/provision.rb
Bebox.Provision.create_step_checkpoint
def create_step_checkpoint(started_at) self.node.started_at = started_at self.node.finished_at = DateTime.now.to_s Bebox::Environment.create_checkpoint_directories(project_root, environment) generate_file_from_template("#{Bebox::FilesHelper::templates_path}/node/provisioned_node.yml.erb", "#{self.project_root}/.checkpoints/environments/#{self.environment}/steps/#{self.step}/#{self.node.hostname}.yml", {node: self.node}) end
ruby
def create_step_checkpoint(started_at) self.node.started_at = started_at self.node.finished_at = DateTime.now.to_s Bebox::Environment.create_checkpoint_directories(project_root, environment) generate_file_from_template("#{Bebox::FilesHelper::templates_path}/node/provisioned_node.yml.erb", "#{self.project_root}/.checkpoints/environments/#{self.environment}/steps/#{self.step}/#{self.node.hostname}.yml", {node: self.node}) end
[ "def", "create_step_checkpoint", "(", "started_at", ")", "self", ".", "node", ".", "started_at", "=", "started_at", "self", ".", "node", ".", "finished_at", "=", "DateTime", ".", "now", ".", "to_s", "Bebox", "::", "Environment", ".", "create_checkpoint_directories", "(", "project_root", ",", "environment", ")", "generate_file_from_template", "(", "\"#{Bebox::FilesHelper::templates_path}/node/provisioned_node.yml.erb\"", ",", "\"#{self.project_root}/.checkpoints/environments/#{self.environment}/steps/#{self.step}/#{self.node.hostname}.yml\"", ",", "{", "node", ":", "self", ".", "node", "}", ")", "end" ]
Create checkpoint for step
[ "Create", "checkpoint", "for", "step" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/provision.rb#L185-L190
train
blambeau/yargi
lib/yargi/vertex_set.rb
Yargi.VertexSet.in_edges
def in_edges(filter=nil, &block) r = self.collect {|v| v.in_edges(filter, &block) } EdgeSet.new(r).flatten.uniq end
ruby
def in_edges(filter=nil, &block) r = self.collect {|v| v.in_edges(filter, &block) } EdgeSet.new(r).flatten.uniq end
[ "def", "in_edges", "(", "filter", "=", "nil", ",", "&", "block", ")", "r", "=", "self", ".", "collect", "{", "|", "v", "|", "v", ".", "in_edges", "(", "filter", ",", "&", "block", ")", "}", "EdgeSet", ".", "new", "(", "r", ")", ".", "flatten", ".", "uniq", "end" ]
Walking section Returns incoming edges of all vertices of this set
[ "Walking", "section", "Returns", "incoming", "edges", "of", "all", "vertices", "of", "this", "set" ]
100141e96d245a0a8211cd4f7590909be149bc3c
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/vertex_set.rb#L17-L20
train
blambeau/yargi
lib/yargi/vertex_set.rb
Yargi.VertexSet.in_adjacent
def in_adjacent(filter=nil, &block) r = self.collect {|v| v.in_adjacent(filter, &block) } VertexSet.new(r).flatten.uniq end
ruby
def in_adjacent(filter=nil, &block) r = self.collect {|v| v.in_adjacent(filter, &block) } VertexSet.new(r).flatten.uniq end
[ "def", "in_adjacent", "(", "filter", "=", "nil", ",", "&", "block", ")", "r", "=", "self", ".", "collect", "{", "|", "v", "|", "v", ".", "in_adjacent", "(", "filter", ",", "&", "block", ")", "}", "VertexSet", ".", "new", "(", "r", ")", ".", "flatten", ".", "uniq", "end" ]
Returns all back-adjacent vertices reachable from this set
[ "Returns", "all", "back", "-", "adjacent", "vertices", "reachable", "from", "this", "set" ]
100141e96d245a0a8211cd4f7590909be149bc3c
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/vertex_set.rb#L23-L26
train
blambeau/yargi
lib/yargi/vertex_set.rb
Yargi.VertexSet.adjacent
def adjacent(filter=nil, &block) (in_adjacent(filter, &block)+out_adjacent(filter, &block)).uniq end
ruby
def adjacent(filter=nil, &block) (in_adjacent(filter, &block)+out_adjacent(filter, &block)).uniq end
[ "def", "adjacent", "(", "filter", "=", "nil", ",", "&", "block", ")", "(", "in_adjacent", "(", "filter", ",", "&", "block", ")", "+", "out_adjacent", "(", "filter", ",", "&", "block", ")", ")", ".", "uniq", "end" ]
Returns all adjacent vertices reachable from this set
[ "Returns", "all", "adjacent", "vertices", "reachable", "from", "this", "set" ]
100141e96d245a0a8211cd4f7590909be149bc3c
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/vertex_set.rb#L41-L43
train
livingsocial/houdah
lib/houdah/job.rb
Houdah.Job.config
def config @parsed_config ||= Nokogiri::XML(config_xml).xpath("//property").inject({}) { |props, xprop| props[xprop.xpath("./name").text] = xprop.xpath("./value").text props } end
ruby
def config @parsed_config ||= Nokogiri::XML(config_xml).xpath("//property").inject({}) { |props, xprop| props[xprop.xpath("./name").text] = xprop.xpath("./value").text props } end
[ "def", "config", "@parsed_config", "||=", "Nokogiri", "::", "XML", "(", "config_xml", ")", ".", "xpath", "(", "\"//property\"", ")", ".", "inject", "(", "{", "}", ")", "{", "|", "props", ",", "xprop", "|", "props", "[", "xprop", ".", "xpath", "(", "\"./name\"", ")", ".", "text", "]", "=", "xprop", ".", "xpath", "(", "\"./value\"", ")", ".", "text", "props", "}", "end" ]
Get the job's config, as a Hash
[ "Get", "the", "job", "s", "config", "as", "a", "Hash" ]
7ab475ccb34fcb6fd894ae865627f7890979b1fa
https://github.com/livingsocial/houdah/blob/7ab475ccb34fcb6fd894ae865627f7890979b1fa/lib/houdah/job.rb#L20-L25
train
Referly/better_sqs
lib/better_sqs/client.rb
BetterSqs.Client.push
def push(queue_name, message_body) sqs.send_message(queue_url: url_for_queue(queue_name), message_body: message_body) end
ruby
def push(queue_name, message_body) sqs.send_message(queue_url: url_for_queue(queue_name), message_body: message_body) end
[ "def", "push", "(", "queue_name", ",", "message_body", ")", "sqs", ".", "send_message", "(", "queue_url", ":", "url_for_queue", "(", "queue_name", ")", ",", "message_body", ":", "message_body", ")", "end" ]
Push a message onto a queue @param queue_name [String, Symbol] the name of the queue that the message should pushed onto @param message_body [String] the message as it will be pushed onto the queue, no serialization occurs as part of this method. You need to encode or serialize your object to a string before sending it to this method @return [Types::SendMessageResult] the sent message object returned from s3
[ "Push", "a", "message", "onto", "a", "queue" ]
c1e20bf5c079df1b65e6ed7702a2449ab2e991ba
https://github.com/Referly/better_sqs/blob/c1e20bf5c079df1b65e6ed7702a2449ab2e991ba/lib/better_sqs/client.rb#L18-L20
train
Referly/better_sqs
lib/better_sqs/client.rb
BetterSqs.Client.reserve
def reserve(queue_name) resp = sqs.receive_message(queue_url: url_for_queue(queue_name), max_number_of_messages: 1) return nil unless resp.messages.any? Message.new queue_client: self, queue: queue_name, sqs_message: resp.messages.first end
ruby
def reserve(queue_name) resp = sqs.receive_message(queue_url: url_for_queue(queue_name), max_number_of_messages: 1) return nil unless resp.messages.any? Message.new queue_client: self, queue: queue_name, sqs_message: resp.messages.first end
[ "def", "reserve", "(", "queue_name", ")", "resp", "=", "sqs", ".", "receive_message", "(", "queue_url", ":", "url_for_queue", "(", "queue_name", ")", ",", "max_number_of_messages", ":", "1", ")", "return", "nil", "unless", "resp", ".", "messages", ".", "any?", "Message", ".", "new", "queue_client", ":", "self", ",", "queue", ":", "queue_name", ",", "sqs_message", ":", "resp", ".", "messages", ".", "first", "end" ]
Reserve a message from the specified queue @param queue_name [String, Symbol] the name of the SQS queue to reserve a message from @return [Messages::Sqs, NilClass] the message retrieved from the queue
[ "Reserve", "a", "message", "from", "the", "specified", "queue" ]
c1e20bf5c079df1b65e6ed7702a2449ab2e991ba
https://github.com/Referly/better_sqs/blob/c1e20bf5c079df1b65e6ed7702a2449ab2e991ba/lib/better_sqs/client.rb#L26-L30
train
Referly/better_sqs
lib/better_sqs/client.rb
BetterSqs.Client.delete
def delete(message) sqs.delete_message queue_url: url_for_queue(message.queue), receipt_handle: message.receipt_handle end
ruby
def delete(message) sqs.delete_message queue_url: url_for_queue(message.queue), receipt_handle: message.receipt_handle end
[ "def", "delete", "(", "message", ")", "sqs", ".", "delete_message", "queue_url", ":", "url_for_queue", "(", "message", ".", "queue", ")", ",", "receipt_handle", ":", "message", ".", "receipt_handle", "end" ]
Delete a message from the queue @param message [Messages::Sqs] the message that should be deleted
[ "Delete", "a", "message", "from", "the", "queue" ]
c1e20bf5c079df1b65e6ed7702a2449ab2e991ba
https://github.com/Referly/better_sqs/blob/c1e20bf5c079df1b65e6ed7702a2449ab2e991ba/lib/better_sqs/client.rb#L35-L37
train
Referly/better_sqs
lib/better_sqs/client.rb
BetterSqs.Client.defer_retry
def defer_retry(message) sqs.change_message_visibility queue_url: url_for_queue(message.queue), receipt_handle: message.receipt_handle, visibility_timeout: BetterSqs.configuration.sqs_message_deferral_seconds end
ruby
def defer_retry(message) sqs.change_message_visibility queue_url: url_for_queue(message.queue), receipt_handle: message.receipt_handle, visibility_timeout: BetterSqs.configuration.sqs_message_deferral_seconds end
[ "def", "defer_retry", "(", "message", ")", "sqs", ".", "change_message_visibility", "queue_url", ":", "url_for_queue", "(", "message", ".", "queue", ")", ",", "receipt_handle", ":", "message", ".", "receipt_handle", ",", "visibility_timeout", ":", "BetterSqs", ".", "configuration", ".", "sqs_message_deferral_seconds", "end" ]
Updates the message visibility timeout to create some delay before an attempt will be made to reprocess the message @param message [Messages::Sqs] the message for which the next retry should be delayed
[ "Updates", "the", "message", "visibility", "timeout", "to", "create", "some", "delay", "before", "an", "attempt", "will", "be", "made", "to", "reprocess", "the", "message" ]
c1e20bf5c079df1b65e6ed7702a2449ab2e991ba
https://github.com/Referly/better_sqs/blob/c1e20bf5c079df1b65e6ed7702a2449ab2e991ba/lib/better_sqs/client.rb#L43-L47
train
fugroup/pushfile
lib/pushfile/resize.rb
Pushfile.Resize.resize!
def resize! begin image = MiniMagick::Image.open(@file.path) image.resize("#{@width}x#{@height}") rescue # Pass on any error else image.write(@file.path) rescue nil end end
ruby
def resize! begin image = MiniMagick::Image.open(@file.path) image.resize("#{@width}x#{@height}") rescue # Pass on any error else image.write(@file.path) rescue nil end end
[ "def", "resize!", "begin", "image", "=", "MiniMagick", "::", "Image", ".", "open", "(", "@file", ".", "path", ")", "image", ".", "resize", "(", "\"#{@width}x#{@height}\"", ")", "rescue", "else", "image", ".", "write", "(", "@file", ".", "path", ")", "rescue", "nil", "end", "end" ]
Resize file. Keeping aspect ratio.
[ "Resize", "file", ".", "Keeping", "aspect", "ratio", "." ]
dd06bd6b023514a1446544986b1ce85b7bae3f78
https://github.com/fugroup/pushfile/blob/dd06bd6b023514a1446544986b1ce85b7bae3f78/lib/pushfile/resize.rb#L7-L16
train
fugroup/pushfile
lib/pushfile/resize.rb
Pushfile.Resize.thumbnail!
def thumbnail! begin image = MiniMagick::Image.open(@file.path) image.resize("#{Pushfile.settings[:images][:thumb][:width]}x") rescue @thumb = nil else t = @name.split('.'); ext = t.pop @thumb = t.join(".").concat("_thumb.#{ext}") image.write("/tmp/#{@thumb}") rescue @thumb = nil end end
ruby
def thumbnail! begin image = MiniMagick::Image.open(@file.path) image.resize("#{Pushfile.settings[:images][:thumb][:width]}x") rescue @thumb = nil else t = @name.split('.'); ext = t.pop @thumb = t.join(".").concat("_thumb.#{ext}") image.write("/tmp/#{@thumb}") rescue @thumb = nil end end
[ "def", "thumbnail!", "begin", "image", "=", "MiniMagick", "::", "Image", ".", "open", "(", "@file", ".", "path", ")", "image", ".", "resize", "(", "\"#{Pushfile.settings[:images][:thumb][:width]}x\"", ")", "rescue", "@thumb", "=", "nil", "else", "t", "=", "@name", ".", "split", "(", "'.'", ")", ";", "ext", "=", "t", ".", "pop", "@thumb", "=", "t", ".", "join", "(", "\".\"", ")", ".", "concat", "(", "\"_thumb.#{ext}\"", ")", "image", ".", "write", "(", "\"/tmp/#{@thumb}\"", ")", "rescue", "@thumb", "=", "nil", "end", "end" ]
Create thumbnail, same name but with _thumb at the end
[ "Create", "thumbnail", "same", "name", "but", "with", "_thumb", "at", "the", "end" ]
dd06bd6b023514a1446544986b1ce85b7bae3f78
https://github.com/fugroup/pushfile/blob/dd06bd6b023514a1446544986b1ce85b7bae3f78/lib/pushfile/resize.rb#L19-L30
train
wedesoft/multiarray
lib/multiarray/lambda.rb
Hornetseye.Lambda.element
def element(i) unless i.matched? unless (0 ... shape.last).member? i raise "Index must be in 0 ... #{shape.last} (was #{i})" end i = INT.new i end i.size = @index.size if i.is_a?(Variable) and @index.size.get @term.subst @index => i end
ruby
def element(i) unless i.matched? unless (0 ... shape.last).member? i raise "Index must be in 0 ... #{shape.last} (was #{i})" end i = INT.new i end i.size = @index.size if i.is_a?(Variable) and @index.size.get @term.subst @index => i end
[ "def", "element", "(", "i", ")", "unless", "i", ".", "matched?", "unless", "(", "0", "...", "shape", ".", "last", ")", ".", "member?", "i", "raise", "\"Index must be in 0 ... #{shape.last} (was #{i})\"", "end", "i", "=", "INT", ".", "new", "i", "end", "i", ".", "size", "=", "@index", ".", "size", "if", "i", ".", "is_a?", "(", "Variable", ")", "and", "@index", ".", "size", ".", "get", "@term", ".", "subst", "@index", "=>", "i", "end" ]
Get element of this term Pass +i+ as argument to this lambda object. @param [Integer,Node] i Index of desired element. @return [Node,Object] Result of inserting +i+ for lambda argument. @private
[ "Get", "element", "of", "this", "term" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/lambda.rb#L163-L172
train
Adaptavist/confluence_reporter
lib/confluence_reporter.rb
ConfluenceReporter.Reporter.report_event
def report_event(name, parrent_page_id=nil, space=nil) page = find_page_by_name(name, parrent_page_id) if page append_to_page(page["id"], parrent_page_id) else create_page(name, space, parrent_page_id) end clear_log end
ruby
def report_event(name, parrent_page_id=nil, space=nil) page = find_page_by_name(name, parrent_page_id) if page append_to_page(page["id"], parrent_page_id) else create_page(name, space, parrent_page_id) end clear_log end
[ "def", "report_event", "(", "name", ",", "parrent_page_id", "=", "nil", ",", "space", "=", "nil", ")", "page", "=", "find_page_by_name", "(", "name", ",", "parrent_page_id", ")", "if", "page", "append_to_page", "(", "page", "[", "\"id\"", "]", ",", "parrent_page_id", ")", "else", "create_page", "(", "name", ",", "space", ",", "parrent_page_id", ")", "end", "clear_log", "end" ]
appends the log to confluence page if found, if not creates new page clears the log
[ "appends", "the", "log", "to", "confluence", "page", "if", "found", "if", "not", "creates", "new", "page", "clears", "the", "log" ]
533d982096b16cec1fa520352c3abdeb26a11f5e
https://github.com/Adaptavist/confluence_reporter/blob/533d982096b16cec1fa520352c3abdeb26a11f5e/lib/confluence_reporter.rb#L126-L134
train
Adaptavist/confluence_reporter
lib/confluence_reporter.rb
ConfluenceReporter.Reporter.create_page
def create_page(title, space, parrent_page_id=nil) params = { 'type' => 'page', 'title' => title, 'space' => {'key' => space}, 'body' => { 'storage' => { 'value' => ("#{ @body_message.to_json.gsub("&&", "&amp;&amp;").gsub(/\\u001b.../, " ") }").force_encoding('UTF-8'), 'representation' => 'storage' } } } if parrent_page_id params['ancestors'] = [{'type' => 'page', 'id' => parrent_page_id}] end uri = URI.parse(@base_url) https = Net::HTTP.new(uri.host,uri.port) https.use_ssl = true # https.set_debug_output $stderr req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'}) req.basic_auth(@user, @password) req['Accept'] = 'application/json' req.body = "#{params.to_json}" response = https.request(req) response = JSON.parse(response.body) if response["statusCode"] == 400 puts response.inspect puts req.body.inspect puts "Create page: Error reporting to confluence: #{response["message"]}" raise "Create page: Error reporting to confluence: #{response["message"]}" else puts "Reported page creation." end end
ruby
def create_page(title, space, parrent_page_id=nil) params = { 'type' => 'page', 'title' => title, 'space' => {'key' => space}, 'body' => { 'storage' => { 'value' => ("#{ @body_message.to_json.gsub("&&", "&amp;&amp;").gsub(/\\u001b.../, " ") }").force_encoding('UTF-8'), 'representation' => 'storage' } } } if parrent_page_id params['ancestors'] = [{'type' => 'page', 'id' => parrent_page_id}] end uri = URI.parse(@base_url) https = Net::HTTP.new(uri.host,uri.port) https.use_ssl = true # https.set_debug_output $stderr req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'}) req.basic_auth(@user, @password) req['Accept'] = 'application/json' req.body = "#{params.to_json}" response = https.request(req) response = JSON.parse(response.body) if response["statusCode"] == 400 puts response.inspect puts req.body.inspect puts "Create page: Error reporting to confluence: #{response["message"]}" raise "Create page: Error reporting to confluence: #{response["message"]}" else puts "Reported page creation." end end
[ "def", "create_page", "(", "title", ",", "space", ",", "parrent_page_id", "=", "nil", ")", "params", "=", "{", "'type'", "=>", "'page'", ",", "'title'", "=>", "title", ",", "'space'", "=>", "{", "'key'", "=>", "space", "}", ",", "'body'", "=>", "{", "'storage'", "=>", "{", "'value'", "=>", "(", "\"#{ @body_message.to_json.gsub(\"&&\", \"&amp;&amp;\").gsub(/\\\\u001b.../, \" \") }\"", ")", ".", "force_encoding", "(", "'UTF-8'", ")", ",", "'representation'", "=>", "'storage'", "}", "}", "}", "if", "parrent_page_id", "params", "[", "'ancestors'", "]", "=", "[", "{", "'type'", "=>", "'page'", ",", "'id'", "=>", "parrent_page_id", "}", "]", "end", "uri", "=", "URI", ".", "parse", "(", "@base_url", ")", "https", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "https", ".", "use_ssl", "=", "true", "req", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ".", "path", ",", "initheader", "=", "{", "'Content-Type'", "=>", "'application/json'", "}", ")", "req", ".", "basic_auth", "(", "@user", ",", "@password", ")", "req", "[", "'Accept'", "]", "=", "'application/json'", "req", ".", "body", "=", "\"#{params.to_json}\"", "response", "=", "https", ".", "request", "(", "req", ")", "response", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", "if", "response", "[", "\"statusCode\"", "]", "==", "400", "puts", "response", ".", "inspect", "puts", "req", ".", "body", ".", "inspect", "puts", "\"Create page: Error reporting to confluence: #{response[\"message\"]}\"", "raise", "\"Create page: Error reporting to confluence: #{response[\"message\"]}\"", "else", "puts", "\"Reported page creation.\"", "end", "end" ]
Creates new page with title set, if parrent_page_id is provided it adjusts ancestor accordingly and the same space short key
[ "Creates", "new", "page", "with", "title", "set", "if", "parrent_page_id", "is", "provided", "it", "adjusts", "ancestor", "accordingly", "and", "the", "same", "space", "short", "key" ]
533d982096b16cec1fa520352c3abdeb26a11f5e
https://github.com/Adaptavist/confluence_reporter/blob/533d982096b16cec1fa520352c3abdeb26a11f5e/lib/confluence_reporter.rb#L139-L172
train
jns/Aims
lib/aims/atom.rb
Aims.Atom.constrained?
def constrained? if self.constrain if self.constrain == true true elsif self.constrain.is_a? String true elsif self.constrain.is_a? Array and not self.constrain.empty? true else false end else false end end
ruby
def constrained? if self.constrain if self.constrain == true true elsif self.constrain.is_a? String true elsif self.constrain.is_a? Array and not self.constrain.empty? true else false end else false end end
[ "def", "constrained?", "if", "self", ".", "constrain", "if", "self", ".", "constrain", "==", "true", "true", "elsif", "self", ".", "constrain", ".", "is_a?", "String", "true", "elsif", "self", ".", "constrain", ".", "is_a?", "Array", "and", "not", "self", ".", "constrain", ".", "empty?", "true", "else", "false", "end", "else", "false", "end", "end" ]
Create an atom of the specified species at the given coordinates @param [Float] x The x coordinate of the atom in angstrom @param [Float] y The y coordinate of the atom in angstrom @param [Float] z The z coordinate of the atom in angstrom @param [String, nil] s The atomic species ex. "C", "Si", "S", etc. (can be nil) @param [Boolean, String, Array<String>] c The relaxation constraints. valid values are TRUE, FALSE, ".true.", ".false.", "x", "y", "z" or %w(x y z) @return [Atom] a new Atom A boolean value, True if the atom has relaxation constraints
[ "Create", "an", "atom", "of", "the", "specified", "species", "at", "the", "given", "coordinates" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/atom.rb#L43-L57
train
jns/Aims
lib/aims/atom.rb
Aims.Atom.distance_to
def distance_to(atom) Math.sqrt((self.x - atom.x)**2 + (self.y - atom.y)**2 + (self.z - atom.z)**2) end
ruby
def distance_to(atom) Math.sqrt((self.x - atom.x)**2 + (self.y - atom.y)**2 + (self.z - atom.z)**2) end
[ "def", "distance_to", "(", "atom", ")", "Math", ".", "sqrt", "(", "(", "self", ".", "x", "-", "atom", ".", "x", ")", "**", "2", "+", "(", "self", ".", "y", "-", "atom", ".", "y", ")", "**", "2", "+", "(", "self", ".", "z", "-", "atom", ".", "z", ")", "**", "2", ")", "end" ]
Return the distance to another atom
[ "Return", "the", "distance", "to", "another", "atom" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/atom.rb#L93-L95
train
jns/Aims
lib/aims/atom.rb
Aims.Atom.displace
def displace(x,y,z) Atom.new(self.x+x, self.y+y, self.z+z, self.species, self.constrain) end
ruby
def displace(x,y,z) Atom.new(self.x+x, self.y+y, self.z+z, self.species, self.constrain) end
[ "def", "displace", "(", "x", ",", "y", ",", "z", ")", "Atom", ".", "new", "(", "self", ".", "x", "+", "x", ",", "self", ".", "y", "+", "y", ",", "self", ".", "z", "+", "z", ",", "self", ".", "species", ",", "self", ".", "constrain", ")", "end" ]
An exact clone of the atom. Same ID and everything Return a new atom with the same species and relaxation constraints but with coordinates displaced by +x+, +y+, +z+
[ "An", "exact", "clone", "of", "the", "atom", ".", "Same", "ID", "and", "everything", "Return", "a", "new", "atom", "with", "the", "same", "species", "and", "relaxation", "constraints", "but", "with", "coordinates", "displaced", "by", "+", "x", "+", "+", "y", "+", "+", "z", "+" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/atom.rb#L112-L114
train
jns/Aims
lib/aims/atom.rb
Aims.Atom.displace!
def displace!(x,y,z) self.x += x self.y += y self.z += z end
ruby
def displace!(x,y,z) self.x += x self.y += y self.z += z end
[ "def", "displace!", "(", "x", ",", "y", ",", "z", ")", "self", ".", "x", "+=", "x", "self", ".", "y", "+=", "y", "self", ".", "z", "+=", "z", "end" ]
Displace this atom in place
[ "Displace", "this", "atom", "in", "place" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/atom.rb#L117-L121
train
jns/Aims
lib/aims/atom.rb
Aims.Atom.format_geometry_in
def format_geometry_in line = "atom %16.6f %16.6f %16.6f %s" % [self.x, self.y, self.z, self.species] if self.constrain if self.constrain == true line << "\nconstrain_relaxation .true." elsif self.constrain.is_a? String line << "\nconstrain_relaxation #{self.constrain}" elsif self.constrain.is_a? Array and not self.constrain.empty? self.constrain.each{|c| line << "\nconstrain_relaxation #{c}" } line << "\n" end end line end
ruby
def format_geometry_in line = "atom %16.6f %16.6f %16.6f %s" % [self.x, self.y, self.z, self.species] if self.constrain if self.constrain == true line << "\nconstrain_relaxation .true." elsif self.constrain.is_a? String line << "\nconstrain_relaxation #{self.constrain}" elsif self.constrain.is_a? Array and not self.constrain.empty? self.constrain.each{|c| line << "\nconstrain_relaxation #{c}" } line << "\n" end end line end
[ "def", "format_geometry_in", "line", "=", "\"atom %16.6f %16.6f %16.6f %s\"", "%", "[", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "z", ",", "self", ".", "species", "]", "if", "self", ".", "constrain", "if", "self", ".", "constrain", "==", "true", "line", "<<", "\"\\nconstrain_relaxation .true.\"", "elsif", "self", ".", "constrain", ".", "is_a?", "String", "line", "<<", "\"\\nconstrain_relaxation #{self.constrain}\"", "elsif", "self", ".", "constrain", ".", "is_a?", "Array", "and", "not", "self", ".", "constrain", ".", "empty?", "self", ".", "constrain", ".", "each", "{", "|", "c", "|", "line", "<<", "\"\\nconstrain_relaxation #{c}\"", "}", "line", "<<", "\"\\n\"", "end", "end", "line", "end" ]
Print a string representation of this atom formatted in the geometry.in format used by Aims
[ "Print", "a", "string", "representation", "of", "this", "atom", "formatted", "in", "the", "geometry", ".", "in", "format", "used", "by", "Aims" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/atom.rb#L189-L204
train
madwire/trooper
lib/trooper/runner.rb
Trooper.Runner.build_commands
def build_commands(strategy_name, type, action_name) action = Arsenal.actions[action_name] if action options = action.options case type when :prerequisite commands = action.prerequisite_call config Trooper.logger.action "Prerequisite: #{action.description}" else commands = action.call config Trooper.logger.action action.description end [commands, options] else raise MissingActionError, "Cant find action: #{action_name}" end end
ruby
def build_commands(strategy_name, type, action_name) action = Arsenal.actions[action_name] if action options = action.options case type when :prerequisite commands = action.prerequisite_call config Trooper.logger.action "Prerequisite: #{action.description}" else commands = action.call config Trooper.logger.action action.description end [commands, options] else raise MissingActionError, "Cant find action: #{action_name}" end end
[ "def", "build_commands", "(", "strategy_name", ",", "type", ",", "action_name", ")", "action", "=", "Arsenal", ".", "actions", "[", "action_name", "]", "if", "action", "options", "=", "action", ".", "options", "case", "type", "when", ":prerequisite", "commands", "=", "action", ".", "prerequisite_call", "config", "Trooper", ".", "logger", ".", "action", "\"Prerequisite: #{action.description}\"", "else", "commands", "=", "action", ".", "call", "config", "Trooper", ".", "logger", ".", "action", "action", ".", "description", "end", "[", "commands", ",", "options", "]", "else", "raise", "MissingActionError", ",", "\"Cant find action: #{action_name}\"", "end", "end" ]
build the commands to be sent to the host object
[ "build", "the", "commands", "to", "be", "sent", "to", "the", "host", "object" ]
ca953f9b78adf1614f7acf82c9076055540ee04c
https://github.com/madwire/trooper/blob/ca953f9b78adf1614f7acf82c9076055540ee04c/lib/trooper/runner.rb#L63-L82
train
madwire/trooper
lib/trooper/runner.rb
Trooper.Runner.hosts
def hosts @hosts ||= begin r, h, u = [], (config[:hosts] rescue nil), (config[:user] rescue nil) h.each {|host| r << Host.new(host, u) } if h && u; r end end
ruby
def hosts @hosts ||= begin r, h, u = [], (config[:hosts] rescue nil), (config[:user] rescue nil) h.each {|host| r << Host.new(host, u) } if h && u; r end end
[ "def", "hosts", "@hosts", "||=", "begin", "r", ",", "h", ",", "u", "=", "[", "]", ",", "(", "config", "[", ":hosts", "]", "rescue", "nil", ")", ",", "(", "config", "[", ":user", "]", "rescue", "nil", ")", "h", ".", "each", "{", "|", "host", "|", "r", "<<", "Host", ".", "new", "(", "host", ",", "u", ")", "}", "if", "h", "&&", "u", ";", "r", "end", "end" ]
returns an array of host objects
[ "returns", "an", "array", "of", "host", "objects" ]
ca953f9b78adf1614f7acf82c9076055540ee04c
https://github.com/madwire/trooper/blob/ca953f9b78adf1614f7acf82c9076055540ee04c/lib/trooper/runner.rb#L85-L90
train
madwire/trooper
lib/trooper/runner.rb
Trooper.Runner.runner_execute!
def runner_execute!(host, commands, options = {}) result = host.execute commands, options if result && result[1] == :stdout Trooper.logger.info "#{result[2]}\n" true else false end end
ruby
def runner_execute!(host, commands, options = {}) result = host.execute commands, options if result && result[1] == :stdout Trooper.logger.info "#{result[2]}\n" true else false end end
[ "def", "runner_execute!", "(", "host", ",", "commands", ",", "options", "=", "{", "}", ")", "result", "=", "host", ".", "execute", "commands", ",", "options", "if", "result", "&&", "result", "[", "1", "]", "==", ":stdout", "Trooper", ".", "logger", ".", "info", "\"#{result[2]}\\n\"", "true", "else", "false", "end", "end" ]
runs the commands on a host and deals with output
[ "runs", "the", "commands", "on", "a", "host", "and", "deals", "with", "output" ]
ca953f9b78adf1614f7acf82c9076055540ee04c
https://github.com/madwire/trooper/blob/ca953f9b78adf1614f7acf82c9076055540ee04c/lib/trooper/runner.rb#L93-L101
train
jeremyolliver/gvis
lib/gvis/data_table.rb
Gvis.DataTable.add_row
def add_row(row) size = row.size raise ArgumentError.new("Given a row of data with #{size} entries, but there are only #{@table_columns.size} columns in the table") unless size == @table_columns.size @data << row end
ruby
def add_row(row) size = row.size raise ArgumentError.new("Given a row of data with #{size} entries, but there are only #{@table_columns.size} columns in the table") unless size == @table_columns.size @data << row end
[ "def", "add_row", "(", "row", ")", "size", "=", "row", ".", "size", "raise", "ArgumentError", ".", "new", "(", "\"Given a row of data with #{size} entries, but there are only #{@table_columns.size} columns in the table\"", ")", "unless", "size", "==", "@table_columns", ".", "size", "@data", "<<", "row", "end" ]
Adds a single row to the table @param [Array] row An array with a single row of data for the table. Should have the same number of entries as there are columns
[ "Adds", "a", "single", "row", "to", "the", "table" ]
2bd3291b43484191f10c0c7eaf333c6105ea2828
https://github.com/jeremyolliver/gvis/blob/2bd3291b43484191f10c0c7eaf333c6105ea2828/lib/gvis/data_table.rb#L44-L48
train
jeremyolliver/gvis
lib/gvis/data_table.rb
Gvis.DataTable.add_rows
def add_rows(rows) sizes = rows.collect {|r| r.size }.uniq expected_size = @table_columns.size errors = sizes.select {|s| s != expected_size } raise ArgumentError.new("Given a row of data with #{errors.to_sentence} entries, but there are only #{expected_size} columns in the table") if errors.any? @data += rows end
ruby
def add_rows(rows) sizes = rows.collect {|r| r.size }.uniq expected_size = @table_columns.size errors = sizes.select {|s| s != expected_size } raise ArgumentError.new("Given a row of data with #{errors.to_sentence} entries, but there are only #{expected_size} columns in the table") if errors.any? @data += rows end
[ "def", "add_rows", "(", "rows", ")", "sizes", "=", "rows", ".", "collect", "{", "|", "r", "|", "r", ".", "size", "}", ".", "uniq", "expected_size", "=", "@table_columns", ".", "size", "errors", "=", "sizes", ".", "select", "{", "|", "s", "|", "s", "!=", "expected_size", "}", "raise", "ArgumentError", ".", "new", "(", "\"Given a row of data with #{errors.to_sentence} entries, but there are only #{expected_size} columns in the table\"", ")", "if", "errors", ".", "any?", "@data", "+=", "rows", "end" ]
Adds multiple rows to the table @param [Array] rows A 2d Array containing multiple rows of data. Each Array should have the same number of entries as the table has columns
[ "Adds", "multiple", "rows", "to", "the", "table" ]
2bd3291b43484191f10c0c7eaf333c6105ea2828
https://github.com/jeremyolliver/gvis/blob/2bd3291b43484191f10c0c7eaf333c6105ea2828/lib/gvis/data_table.rb#L52-L58
train
jeremyolliver/gvis
lib/gvis/data_table.rb
Gvis.DataTable.format_data
def format_data formatted_rows = [] @data.each do |row| values = [] row.each_with_index do |entry,index| values << Gvis::DataCell.new(entry, @column_types.to_a[index][1]).to_js end rowstring = "[#{values.join(", ")}]" formatted_rows << rowstring end "[#{formatted_rows.join(', ')}]" end
ruby
def format_data formatted_rows = [] @data.each do |row| values = [] row.each_with_index do |entry,index| values << Gvis::DataCell.new(entry, @column_types.to_a[index][1]).to_js end rowstring = "[#{values.join(", ")}]" formatted_rows << rowstring end "[#{formatted_rows.join(', ')}]" end
[ "def", "format_data", "formatted_rows", "=", "[", "]", "@data", ".", "each", "do", "|", "row", "|", "values", "=", "[", "]", "row", ".", "each_with_index", "do", "|", "entry", ",", "index", "|", "values", "<<", "Gvis", "::", "DataCell", ".", "new", "(", "entry", ",", "@column_types", ".", "to_a", "[", "index", "]", "[", "1", "]", ")", ".", "to_js", "end", "rowstring", "=", "\"[#{values.join(\", \")}]\"", "formatted_rows", "<<", "rowstring", "end", "\"[#{formatted_rows.join(', ')}]\"", "end" ]
Outputs the data within this table as a javascript array ready for use by google.visualization.DataTable This is where conversions of ruby date objects to javascript Date objects and escaping strings, and formatting options is done @return [String] a javascript array with the first row defining the table, and subsequent rows holding the table's data
[ "Outputs", "the", "data", "within", "this", "table", "as", "a", "javascript", "array", "ready", "for", "use", "by", "google", ".", "visualization", ".", "DataTable", "This", "is", "where", "conversions", "of", "ruby", "date", "objects", "to", "javascript", "Date", "objects", "and", "escaping", "strings", "and", "formatting", "options", "is", "done" ]
2bd3291b43484191f10c0c7eaf333c6105ea2828
https://github.com/jeremyolliver/gvis/blob/2bd3291b43484191f10c0c7eaf333c6105ea2828/lib/gvis/data_table.rb#L72-L83
train
jeremyolliver/gvis
lib/gvis/data_table.rb
Gvis.DataTable.register_column
def register_column(type, name) type = type.to_s.downcase raise ArgumentError.new("invalid column type #{type}, permitted types are #{COLUMN_TYPES.join(', ')}") unless COLUMN_TYPES.include?(type) @table_columns << name.to_s @column_types.merge!(name.to_s => type) end
ruby
def register_column(type, name) type = type.to_s.downcase raise ArgumentError.new("invalid column type #{type}, permitted types are #{COLUMN_TYPES.join(', ')}") unless COLUMN_TYPES.include?(type) @table_columns << name.to_s @column_types.merge!(name.to_s => type) end
[ "def", "register_column", "(", "type", ",", "name", ")", "type", "=", "type", ".", "to_s", ".", "downcase", "raise", "ArgumentError", ".", "new", "(", "\"invalid column type #{type}, permitted types are #{COLUMN_TYPES.join(', ')}\"", ")", "unless", "COLUMN_TYPES", ".", "include?", "(", "type", ")", "@table_columns", "<<", "name", ".", "to_s", "@column_types", ".", "merge!", "(", "name", ".", "to_s", "=>", "type", ")", "end" ]
Registers each column explicitly, with data type, and a name associated @param [String] type the type of data column being registered, valid input here are entries from DataTable::COLUMN_TYPES @param [String] name the column name that will be used as a label on the graph
[ "Registers", "each", "column", "explicitly", "with", "data", "type", "and", "a", "name", "associated" ]
2bd3291b43484191f10c0c7eaf333c6105ea2828
https://github.com/jeremyolliver/gvis/blob/2bd3291b43484191f10c0c7eaf333c6105ea2828/lib/gvis/data_table.rb#L92-L97
train
BUEZE/taaze
lib/taaze/collections.rb
Taaze.TaazeCollections.extract_books
def extract_books booklist = [] if @doc.count != 0 @doc.each do |book_data| book = {} book['title'] = book_data['titleMain'] book['book_url'] = BOOK_URL + book_data['prodId'] book['crt_time'] = book_data['crtTime'].split(' ')[0] booklist << book end end booklist end
ruby
def extract_books booklist = [] if @doc.count != 0 @doc.each do |book_data| book = {} book['title'] = book_data['titleMain'] book['book_url'] = BOOK_URL + book_data['prodId'] book['crt_time'] = book_data['crtTime'].split(' ')[0] booklist << book end end booklist end
[ "def", "extract_books", "booklist", "=", "[", "]", "if", "@doc", ".", "count", "!=", "0", "@doc", ".", "each", "do", "|", "book_data", "|", "book", "=", "{", "}", "book", "[", "'title'", "]", "=", "book_data", "[", "'titleMain'", "]", "book", "[", "'book_url'", "]", "=", "BOOK_URL", "+", "book_data", "[", "'prodId'", "]", "book", "[", "'crt_time'", "]", "=", "book_data", "[", "'crtTime'", "]", ".", "split", "(", "' '", ")", "[", "0", "]", "booklist", "<<", "book", "end", "end", "booklist", "end" ]
Return the books in the format specified in spec.
[ "Return", "the", "books", "in", "the", "format", "specified", "in", "spec", "." ]
ef95e1ad71140a7eaf9e2c65830d900f651bc184
https://github.com/BUEZE/taaze/blob/ef95e1ad71140a7eaf9e2c65830d900f651bc184/lib/taaze/collections.rb#L43-L55
train
buren/site_mapper
lib/site_mapper/crawler.rb
SiteMapper.Crawler.collect_urls
def collect_urls @fetch_queue << @crawl_url.resolved_base_url until @fetch_queue.empty? || @processed.length >= @options[:max_requests] url = @fetch_queue.pop yield(url) page_urls_for(url) end result = @processed + @fetch_queue Logger.log "Crawling finished:" Logger.log "Processed links: #{@processed.length}" Logger.log "Found links: #{result.length}" result.to_a rescue Interrupt, IRB::Abort Logger.err_log 'Crawl interrupted.' @fetch_queue.to_a end
ruby
def collect_urls @fetch_queue << @crawl_url.resolved_base_url until @fetch_queue.empty? || @processed.length >= @options[:max_requests] url = @fetch_queue.pop yield(url) page_urls_for(url) end result = @processed + @fetch_queue Logger.log "Crawling finished:" Logger.log "Processed links: #{@processed.length}" Logger.log "Found links: #{result.length}" result.to_a rescue Interrupt, IRB::Abort Logger.err_log 'Crawl interrupted.' @fetch_queue.to_a end
[ "def", "collect_urls", "@fetch_queue", "<<", "@crawl_url", ".", "resolved_base_url", "until", "@fetch_queue", ".", "empty?", "||", "@processed", ".", "length", ">=", "@options", "[", ":max_requests", "]", "url", "=", "@fetch_queue", ".", "pop", "yield", "(", "url", ")", "page_urls_for", "(", "url", ")", "end", "result", "=", "@processed", "+", "@fetch_queue", "Logger", ".", "log", "\"Crawling finished:\"", "Logger", ".", "log", "\"Processed links: #{@processed.length}\"", "Logger", ".", "log", "\"Found links: #{result.length}\"", "result", ".", "to_a", "rescue", "Interrupt", ",", "IRB", "::", "Abort", "Logger", ".", "err_log", "'Crawl interrupted.'", "@fetch_queue", ".", "to_a", "end" ]
Collects all links on domain for domain. @return [Array] with links. @example URLs for example.com crawler = Crawler.new('example.com') crawler.collect_urls @example URLs for example.com with block (executes in its own thread) crawler = Crawler.new('example.com') crawler.collect_urls do |new_url| puts "New URL found: #{new_url}" end
[ "Collects", "all", "links", "on", "domain", "for", "domain", "." ]
a14233229baacfdb87539c8916ad744ee7832709
https://github.com/buren/site_mapper/blob/a14233229baacfdb87539c8916ad744ee7832709/lib/site_mapper/crawler.rb#L48-L63
train
joshwlewis/liner
lib/liner/hashable.rb
Liner.Hashable.liner
def liner liner_keys.inject({}) { |h,k| h[k] = self[k]; h }.freeze end
ruby
def liner liner_keys.inject({}) { |h,k| h[k] = self[k]; h }.freeze end
[ "def", "liner", "liner_keys", ".", "inject", "(", "{", "}", ")", "{", "|", "h", ",", "k", "|", "h", "[", "k", "]", "=", "self", "[", "k", "]", ";", "h", "}", ".", "freeze", "end" ]
Build a hash of liner attributes @return [Hash] A hash of liner attributes @api public
[ "Build", "a", "hash", "of", "liner", "attributes" ]
d4a3142521fa04a6c9adda5fedde3e57c4c4e00a
https://github.com/joshwlewis/liner/blob/d4a3142521fa04a6c9adda5fedde3e57c4c4e00a/lib/liner/hashable.rb#L28-L30
train
mdub/pith
lib/pith/output.rb
Pith.Output.build
def build return false if @generated logger.info("--> #{path}") @dependencies = Set.new file.parent.mkpath if input.template? evaluate_template else copy_resource end @generated = true end
ruby
def build return false if @generated logger.info("--> #{path}") @dependencies = Set.new file.parent.mkpath if input.template? evaluate_template else copy_resource end @generated = true end
[ "def", "build", "return", "false", "if", "@generated", "logger", ".", "info", "(", "\"", ")", "@dependencies", "=", "Set", ".", "new", "file", ".", "parent", ".", "mkpath", "if", "input", ".", "template?", "evaluate_template", "else", "copy_resource", "end", "@generated", "=", "true", "end" ]
Generate output for this template
[ "Generate", "output", "for", "this", "template" ]
a78047cf65653172817b0527672bf6df960d510f
https://github.com/mdub/pith/blob/a78047cf65653172817b0527672bf6df960d510f/lib/pith/output.rb#L32-L43
train
blambeau/yargi
lib/yargi/digraph.rb
Yargi.Digraph.each_vertex
def each_vertex(filter=nil, &block) if filter.nil? @vertices.each &block else vertices(filter).each &block end end
ruby
def each_vertex(filter=nil, &block) if filter.nil? @vertices.each &block else vertices(filter).each &block end end
[ "def", "each_vertex", "(", "filter", "=", "nil", ",", "&", "block", ")", "if", "filter", ".", "nil?", "@vertices", ".", "each", "&", "block", "else", "vertices", "(", "filter", ")", ".", "each", "&", "block", "end", "end" ]
Calls block on each graph vertex for with the 'filter and block' predicate evaluates to true.
[ "Calls", "block", "on", "each", "graph", "vertex", "for", "with", "the", "filter", "and", "block", "predicate", "evaluates", "to", "true", "." ]
100141e96d245a0a8211cd4f7590909be149bc3c
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/digraph.rb#L53-L59
train
blambeau/yargi
lib/yargi/digraph.rb
Yargi.Digraph.remove_vertices
def remove_vertices(*vertices) vertices = to_vertices(*vertices).sort{|v1,v2| v2<=>v1} vertices.each do |vertex| remove_edges(vertex.in_edges+vertex.out_edges) @vertices.delete_at(vertex.index) vertex.index=-1 end @vertices.each_with_index {|v,i| v.index=i} self end
ruby
def remove_vertices(*vertices) vertices = to_vertices(*vertices).sort{|v1,v2| v2<=>v1} vertices.each do |vertex| remove_edges(vertex.in_edges+vertex.out_edges) @vertices.delete_at(vertex.index) vertex.index=-1 end @vertices.each_with_index {|v,i| v.index=i} self end
[ "def", "remove_vertices", "(", "*", "vertices", ")", "vertices", "=", "to_vertices", "(", "*", "vertices", ")", ".", "sort", "{", "|", "v1", ",", "v2", "|", "v2", "<=>", "v1", "}", "vertices", ".", "each", "do", "|", "vertex", "|", "remove_edges", "(", "vertex", ".", "in_edges", "+", "vertex", ".", "out_edges", ")", "@vertices", ".", "delete_at", "(", "vertex", ".", "index", ")", "vertex", ".", "index", "=", "-", "1", "end", "@vertices", ".", "each_with_index", "{", "|", "v", ",", "i", "|", "v", ".", "index", "=", "i", "}", "self", "end" ]
Removes all vertices returned by evaluating the _vertices_ selection expression.
[ "Removes", "all", "vertices", "returned", "by", "evaluating", "the", "_vertices_", "selection", "expression", "." ]
100141e96d245a0a8211cd4f7590909be149bc3c
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/digraph.rb#L89-L98
train
blambeau/yargi
lib/yargi/digraph.rb
Yargi.Digraph.each_edge
def each_edge(filter=nil, &block) if filter.nil? @edges.each &block else edges(filter).each &block end end
ruby
def each_edge(filter=nil, &block) if filter.nil? @edges.each &block else edges(filter).each &block end end
[ "def", "each_edge", "(", "filter", "=", "nil", ",", "&", "block", ")", "if", "filter", ".", "nil?", "@edges", ".", "each", "&", "block", "else", "edges", "(", "filter", ")", ".", "each", "&", "block", "end", "end" ]
Calls block on each graph edge for with the 'filter and block' predicate evaluates to true.
[ "Calls", "block", "on", "each", "graph", "edge", "for", "with", "the", "filter", "and", "block", "predicate", "evaluates", "to", "true", "." ]
100141e96d245a0a8211cd4f7590909be149bc3c
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/digraph.rb#L121-L127
train
blambeau/yargi
lib/yargi/digraph.rb
Yargi.Digraph.remove_edges
def remove_edges(*edges) edges = to_edges(edges).sort{|e1,e2| e2<=>e1} edges.each do |edge| edge.source.remove_out_edge(edge) edge.target.remove_in_edge(edge) @edges.delete_at(edge.index) edge.index = -1 end @edges.each_with_index {|edge,i| edge.index=i} self end
ruby
def remove_edges(*edges) edges = to_edges(edges).sort{|e1,e2| e2<=>e1} edges.each do |edge| edge.source.remove_out_edge(edge) edge.target.remove_in_edge(edge) @edges.delete_at(edge.index) edge.index = -1 end @edges.each_with_index {|edge,i| edge.index=i} self end
[ "def", "remove_edges", "(", "*", "edges", ")", "edges", "=", "to_edges", "(", "edges", ")", ".", "sort", "{", "|", "e1", ",", "e2", "|", "e2", "<=>", "e1", "}", "edges", ".", "each", "do", "|", "edge", "|", "edge", ".", "source", ".", "remove_out_edge", "(", "edge", ")", "edge", ".", "target", ".", "remove_in_edge", "(", "edge", ")", "@edges", ".", "delete_at", "(", "edge", ".", "index", ")", "edge", ".", "index", "=", "-", "1", "end", "@edges", ".", "each_with_index", "{", "|", "edge", ",", "i", "|", "edge", ".", "index", "=", "i", "}", "self", "end" ]
Removes all edges returned by evaluating the _edges_ selection expression.
[ "Removes", "all", "edges", "returned", "by", "evaluating", "the", "_edges_", "selection", "expression", "." ]
100141e96d245a0a8211cd4f7590909be149bc3c
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/digraph.rb#L164-L174
train
blambeau/yargi
lib/yargi/digraph.rb
Yargi.Digraph.to_dot
def to_dot(buffer='') buffer << "digraph G {\n" buffer << " graph[#{to_dot_attributes(self.to_h(true))}]\n" each_vertex do |v| buffer << " V#{v.index} [#{to_dot_attributes(v.to_h(true))}]\n" end each_edge do |e| buffer << " V#{e.source.index} -> V#{e.target.index} [#{to_dot_attributes(e.to_h(true))}]\n" end buffer << "}\n" end
ruby
def to_dot(buffer='') buffer << "digraph G {\n" buffer << " graph[#{to_dot_attributes(self.to_h(true))}]\n" each_vertex do |v| buffer << " V#{v.index} [#{to_dot_attributes(v.to_h(true))}]\n" end each_edge do |e| buffer << " V#{e.source.index} -> V#{e.target.index} [#{to_dot_attributes(e.to_h(true))}]\n" end buffer << "}\n" end
[ "def", "to_dot", "(", "buffer", "=", "''", ")", "buffer", "<<", "\"digraph G {\\n\"", "buffer", "<<", "\" graph[#{to_dot_attributes(self.to_h(true))}]\\n\"", "each_vertex", "do", "|", "v", "|", "buffer", "<<", "\" V#{v.index} [#{to_dot_attributes(v.to_h(true))}]\\n\"", "end", "each_edge", "do", "|", "e", "|", "buffer", "<<", "\" V#{e.source.index} -> V#{e.target.index} [#{to_dot_attributes(e.to_h(true))}]\\n\"", "end", "buffer", "<<", "\"}\\n\"", "end" ]
Standard exports Encodes this graph for dot graphviz
[ "Standard", "exports", "Encodes", "this", "graph", "for", "dot", "graphviz" ]
100141e96d245a0a8211cd4f7590909be149bc3c
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/digraph.rb#L202-L212
train
blambeau/yargi
lib/yargi/digraph.rb
Yargi.Digraph.to_dot_attributes
def to_dot_attributes(hash) # TODO: fix uncompatible key names # TODO: some values must be encoded (backquoting and the like) buffer = "" hash.each_pair do |k,v| buffer << " " unless buffer.empty? v = case v when Array if v.all?{|elm| Array===elm and elm.length==2 and elm.all?{|subelm| Numeric===subelm}} v.inject('') {|memo, elm| "#{memo} #{elm.join(',')}"}.strip else v.join(', ') end else v.to_s end buffer << "#{k}=\"#{v}\"" end buffer end
ruby
def to_dot_attributes(hash) # TODO: fix uncompatible key names # TODO: some values must be encoded (backquoting and the like) buffer = "" hash.each_pair do |k,v| buffer << " " unless buffer.empty? v = case v when Array if v.all?{|elm| Array===elm and elm.length==2 and elm.all?{|subelm| Numeric===subelm}} v.inject('') {|memo, elm| "#{memo} #{elm.join(',')}"}.strip else v.join(', ') end else v.to_s end buffer << "#{k}=\"#{v}\"" end buffer end
[ "def", "to_dot_attributes", "(", "hash", ")", "buffer", "=", "\"\"", "hash", ".", "each_pair", "do", "|", "k", ",", "v", "|", "buffer", "<<", "\" \"", "unless", "buffer", ".", "empty?", "v", "=", "case", "v", "when", "Array", "if", "v", ".", "all?", "{", "|", "elm", "|", "Array", "===", "elm", "and", "elm", ".", "length", "==", "2", "and", "elm", ".", "all?", "{", "|", "subelm", "|", "Numeric", "===", "subelm", "}", "}", "v", ".", "inject", "(", "''", ")", "{", "|", "memo", ",", "elm", "|", "\"#{memo} #{elm.join(',')}\"", "}", ".", "strip", "else", "v", ".", "join", "(", "', '", ")", "end", "else", "v", ".", "to_s", "end", "buffer", "<<", "\"#{k}=\\\"#{v}\\\"\"", "end", "buffer", "end" ]
Converts a hash to dot attributes
[ "Converts", "a", "hash", "to", "dot", "attributes" ]
100141e96d245a0a8211cd4f7590909be149bc3c
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/digraph.rb#L218-L237
train
blambeau/yargi
lib/yargi/digraph.rb
Yargi.Digraph.check_sanity
def check_sanity @vertices.each_with_index do |v,i| raise "Removed vertex in vertex list" unless v.index==i v.in_edges.each do |ine| raise "Removed edge in vertex incoming edges" if ine.index<0 raise "Vertex and edge don't agree on target" unless ine.target==v end v.out_edges.each do |oute| raise "Removed edge in vertex outgoing edges" if oute.index<0 raise "Vertex and edge don't agree on source" unless oute.source==v end end @edges.each_with_index do |e,i| raise "Removed edge in edge list" unless e.index==i raise "Edge in-connected to a removed vertex" if e.source.index<0 raise "Edge out-connected to a removed vertex" if e.target.index<0 end end
ruby
def check_sanity @vertices.each_with_index do |v,i| raise "Removed vertex in vertex list" unless v.index==i v.in_edges.each do |ine| raise "Removed edge in vertex incoming edges" if ine.index<0 raise "Vertex and edge don't agree on target" unless ine.target==v end v.out_edges.each do |oute| raise "Removed edge in vertex outgoing edges" if oute.index<0 raise "Vertex and edge don't agree on source" unless oute.source==v end end @edges.each_with_index do |e,i| raise "Removed edge in edge list" unless e.index==i raise "Edge in-connected to a removed vertex" if e.source.index<0 raise "Edge out-connected to a removed vertex" if e.target.index<0 end end
[ "def", "check_sanity", "@vertices", ".", "each_with_index", "do", "|", "v", ",", "i", "|", "raise", "\"Removed vertex in vertex list\"", "unless", "v", ".", "index", "==", "i", "v", ".", "in_edges", ".", "each", "do", "|", "ine", "|", "raise", "\"Removed edge in vertex incoming edges\"", "if", "ine", ".", "index", "<", "0", "raise", "\"Vertex and edge don't agree on target\"", "unless", "ine", ".", "target", "==", "v", "end", "v", ".", "out_edges", ".", "each", "do", "|", "oute", "|", "raise", "\"Removed edge in vertex outgoing edges\"", "if", "oute", ".", "index", "<", "0", "raise", "\"Vertex and edge don't agree on source\"", "unless", "oute", ".", "source", "==", "v", "end", "end", "@edges", ".", "each_with_index", "do", "|", "e", ",", "i", "|", "raise", "\"Removed edge in edge list\"", "unless", "e", ".", "index", "==", "i", "raise", "\"Edge in-connected to a removed vertex\"", "if", "e", ".", "source", ".", "index", "<", "0", "raise", "\"Edge out-connected to a removed vertex\"", "if", "e", ".", "target", ".", "index", "<", "0", "end", "end" ]
Checks graph sanity
[ "Checks", "graph", "sanity" ]
100141e96d245a0a8211cd4f7590909be149bc3c
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/digraph.rb#L245-L262
train
blambeau/yargi
lib/yargi/digraph.rb
Yargi.Digraph.to_vertices
def to_vertices(*args) selected = args.collect do |arg| case arg when Integer [@vertices[arg]] when VertexSet arg when Array arg.collect{|v| to_vertices(v)}.flatten.uniq when Digraph::Vertex [arg] else pred = Predicate.to_predicate(arg) vertices(pred) end end.flatten.uniq VertexSet.new(selected) end
ruby
def to_vertices(*args) selected = args.collect do |arg| case arg when Integer [@vertices[arg]] when VertexSet arg when Array arg.collect{|v| to_vertices(v)}.flatten.uniq when Digraph::Vertex [arg] else pred = Predicate.to_predicate(arg) vertices(pred) end end.flatten.uniq VertexSet.new(selected) end
[ "def", "to_vertices", "(", "*", "args", ")", "selected", "=", "args", ".", "collect", "do", "|", "arg", "|", "case", "arg", "when", "Integer", "[", "@vertices", "[", "arg", "]", "]", "when", "VertexSet", "arg", "when", "Array", "arg", ".", "collect", "{", "|", "v", "|", "to_vertices", "(", "v", ")", "}", ".", "flatten", ".", "uniq", "when", "Digraph", "::", "Vertex", "[", "arg", "]", "else", "pred", "=", "Predicate", ".", "to_predicate", "(", "arg", ")", "vertices", "(", "pred", ")", "end", "end", ".", "flatten", ".", "uniq", "VertexSet", ".", "new", "(", "selected", ")", "end" ]
Applies argument conventions about selection of vertices
[ "Applies", "argument", "conventions", "about", "selection", "of", "vertices" ]
100141e96d245a0a8211cd4f7590909be149bc3c
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/digraph.rb#L265-L282
train