repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
Clever/clever-ruby
lib/clever-ruby/api/data_api.rb
Clever.DataApi.get_term_for_section
def get_term_for_section(id, opts = {}) data, _status_code, _headers = get_term_for_section_with_http_info(id, opts) return data end
ruby
def get_term_for_section(id, opts = {}) data, _status_code, _headers = get_term_for_section_with_http_info(id, opts) return data end
[ "def", "get_term_for_section", "(", "id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_term_for_section_with_http_info", "(", "id", ",", "opts", ")", "return", "data", "end" ]
Returns the term for a section @param id @param [Hash] opts the optional parameters @return [TermResponse]
[ "Returns", "the", "term", "for", "a", "section" ]
f9f19496c33699c4adfdebfbc7f118e75007b9e2
https://github.com/Clever/clever-ruby/blob/f9f19496c33699c4adfdebfbc7f118e75007b9e2/lib/clever-ruby/api/data_api.rb#L2787-L2790
train
Clever/clever-ruby
lib/clever-ruby/api/events_api.rb
Clever.EventsApi.get_event
def get_event(id, opts = {}) data, _status_code, _headers = get_event_with_http_info(id, opts) return data end
ruby
def get_event(id, opts = {}) data, _status_code, _headers = get_event_with_http_info(id, opts) return data end
[ "def", "get_event", "(", "id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_event_with_http_info", "(", "id", ",", "opts", ")", "return", "data", "end" ]
Returns the specific event @param id @param [Hash] opts the optional parameters @return [EventResponse]
[ "Returns", "the", "specific", "event" ]
f9f19496c33699c4adfdebfbc7f118e75007b9e2
https://github.com/Clever/clever-ruby/blob/f9f19496c33699c4adfdebfbc7f118e75007b9e2/lib/clever-ruby/api/events_api.rb#L28-L31
train
arthurnn/apn_sender
lib/apn/client.rb
APN.Client.setup_socket
def setup_socket ctx = setup_certificate APN.log(:debug, "Connecting to #{@host}:#{@port}...") socket_tcp = TCPSocket.new(@host, @port) OpenSSL::SSL::SSLSocket.new(socket_tcp, ctx).tap do |s| s.sync = true s.connect end end
ruby
def setup_socket ctx = setup_certificate APN.log(:debug, "Connecting to #{@host}:#{@port}...") socket_tcp = TCPSocket.new(@host, @port) OpenSSL::SSL::SSLSocket.new(socket_tcp, ctx).tap do |s| s.sync = true s.connect end end
[ "def", "setup_socket", "ctx", "=", "setup_certificate", "APN", ".", "log", "(", ":debug", ",", "\"Connecting to #{@host}:#{@port}...\"", ")", "socket_tcp", "=", "TCPSocket", ".", "new", "(", "@host", ",", "@port", ")", "OpenSSL", "::", "SSL", "::", "SSLSocket", ".", "new", "(", "socket_tcp", ",", "ctx", ")", ".", "tap", "do", "|", "s", "|", "s", ".", "sync", "=", "true", "s", ".", "connect", "end", "end" ]
Open socket to Apple's servers
[ "Open", "socket", "to", "Apple", "s", "servers" ]
ecb1539b61fc4022dadb91fc09c1786f476d1c36
https://github.com/arthurnn/apn_sender/blob/ecb1539b61fc4022dadb91fc09c1786f476d1c36/lib/apn/client.rb#L46-L56
train
ruby-numo/numo-linalg
lib/numo/linalg/function.rb
Numo.Linalg.dot
def dot(a, b) a = NArray.asarray(a) b = NArray.asarray(b) case a.ndim when 1 case b.ndim when 1 func = blas_char(a, b) =~ /c|z/ ? :dotu : :dot Blas.call(func, a, b) else if b.contiguous? trans = 't' else if b.fortran_contiguous? trans = 'n' b = b.transpose else trans = 't' b = b.dup end end Blas.call(:gemv, b, a, trans:trans) end else case b.ndim when 1 if a.contiguous? trans = 'n' else if a.fortran_contiguous? trans = 't' a = a.transpose else trans = 'n' a = a.dup end end Blas.call(:gemv, a, b, trans:trans) else if a.contiguous? transa = 'n' else if a.fortran_contiguous? transa = 't' a = a.transpose else transa = 'n' a = a.dup end end if b.contiguous? transb = 'n' else if b.fortran_contiguous? transb='t' b = b.transpose else transb='n' b = b.dup end end Blas.call(:gemm, a, b, transa:transa, transb:transb) end end end
ruby
def dot(a, b) a = NArray.asarray(a) b = NArray.asarray(b) case a.ndim when 1 case b.ndim when 1 func = blas_char(a, b) =~ /c|z/ ? :dotu : :dot Blas.call(func, a, b) else if b.contiguous? trans = 't' else if b.fortran_contiguous? trans = 'n' b = b.transpose else trans = 't' b = b.dup end end Blas.call(:gemv, b, a, trans:trans) end else case b.ndim when 1 if a.contiguous? trans = 'n' else if a.fortran_contiguous? trans = 't' a = a.transpose else trans = 'n' a = a.dup end end Blas.call(:gemv, a, b, trans:trans) else if a.contiguous? transa = 'n' else if a.fortran_contiguous? transa = 't' a = a.transpose else transa = 'n' a = a.dup end end if b.contiguous? transb = 'n' else if b.fortran_contiguous? transb='t' b = b.transpose else transb='n' b = b.dup end end Blas.call(:gemm, a, b, transa:transa, transb:transb) end end end
[ "def", "dot", "(", "a", ",", "b", ")", "a", "=", "NArray", ".", "asarray", "(", "a", ")", "b", "=", "NArray", ".", "asarray", "(", "b", ")", "case", "a", ".", "ndim", "when", "1", "case", "b", ".", "ndim", "when", "1", "func", "=", "blas_char", "(", "a", ",", "b", ")", "=~", "/", "/", "?", ":dotu", ":", ":dot", "Blas", ".", "call", "(", "func", ",", "a", ",", "b", ")", "else", "if", "b", ".", "contiguous?", "trans", "=", "'t'", "else", "if", "b", ".", "fortran_contiguous?", "trans", "=", "'n'", "b", "=", "b", ".", "transpose", "else", "trans", "=", "'t'", "b", "=", "b", ".", "dup", "end", "end", "Blas", ".", "call", "(", ":gemv", ",", "b", ",", "a", ",", "trans", ":", "trans", ")", "end", "else", "case", "b", ".", "ndim", "when", "1", "if", "a", ".", "contiguous?", "trans", "=", "'n'", "else", "if", "a", ".", "fortran_contiguous?", "trans", "=", "'t'", "a", "=", "a", ".", "transpose", "else", "trans", "=", "'n'", "a", "=", "a", ".", "dup", "end", "end", "Blas", ".", "call", "(", ":gemv", ",", "a", ",", "b", ",", "trans", ":", "trans", ")", "else", "if", "a", ".", "contiguous?", "transa", "=", "'n'", "else", "if", "a", ".", "fortran_contiguous?", "transa", "=", "'t'", "a", "=", "a", ".", "transpose", "else", "transa", "=", "'n'", "a", "=", "a", ".", "dup", "end", "end", "if", "b", ".", "contiguous?", "transb", "=", "'n'", "else", "if", "b", ".", "fortran_contiguous?", "transb", "=", "'t'", "b", "=", "b", ".", "transpose", "else", "transb", "=", "'n'", "b", "=", "b", ".", "dup", "end", "end", "Blas", ".", "call", "(", ":gemm", ",", "a", ",", "b", ",", "transa", ":", "transa", ",", "transb", ":", "transb", ")", "end", "end", "end" ]
module methods Matrix and vector products Dot product. @param a [Numo::NArray] matrix or vector (>= 1-dimensinal NArray) @param b [Numo::NArray] matrix or vector (>= 1-dimensinal NArray) @return [Numo::NArray] result of dot product
[ "module", "methods", "Matrix", "and", "vector", "products", "Dot", "product", "." ]
bb0929aae0f3285a41d404040eda651833ffccef
https://github.com/ruby-numo/numo-linalg/blob/bb0929aae0f3285a41d404040eda651833ffccef/lib/numo/linalg/function.rb#L82-L146
train
ruby-numo/numo-linalg
lib/numo/linalg/function.rb
Numo.Linalg.matrix_power
def matrix_power(a, n) a = NArray.asarray(a) m,k = a.shape[-2..-1] unless m==k raise NArray::ShapeError, "input must be a square array" end unless Integer===n raise ArgumentError, "exponent must be an integer" end if n == 0 return a.class.eye(m) elsif n < 0 a = inv(a) n = n.abs end if n <= 3 r = a (n-1).times do r = matmul(r,a) end else while (n & 1) == 0 a = matmul(a,a) n >>= 1 end r = a while n != 0 a = matmul(a,a) n >>= 1 if (n & 1) != 0 r = matmul(r,a) end end end r end
ruby
def matrix_power(a, n) a = NArray.asarray(a) m,k = a.shape[-2..-1] unless m==k raise NArray::ShapeError, "input must be a square array" end unless Integer===n raise ArgumentError, "exponent must be an integer" end if n == 0 return a.class.eye(m) elsif n < 0 a = inv(a) n = n.abs end if n <= 3 r = a (n-1).times do r = matmul(r,a) end else while (n & 1) == 0 a = matmul(a,a) n >>= 1 end r = a while n != 0 a = matmul(a,a) n >>= 1 if (n & 1) != 0 r = matmul(r,a) end end end r end
[ "def", "matrix_power", "(", "a", ",", "n", ")", "a", "=", "NArray", ".", "asarray", "(", "a", ")", "m", ",", "k", "=", "a", ".", "shape", "[", "-", "2", "..", "-", "1", "]", "unless", "m", "==", "k", "raise", "NArray", "::", "ShapeError", ",", "\"input must be a square array\"", "end", "unless", "Integer", "===", "n", "raise", "ArgumentError", ",", "\"exponent must be an integer\"", "end", "if", "n", "==", "0", "return", "a", ".", "class", ".", "eye", "(", "m", ")", "elsif", "n", "<", "0", "a", "=", "inv", "(", "a", ")", "n", "=", "n", ".", "abs", "end", "if", "n", "<=", "3", "r", "=", "a", "(", "n", "-", "1", ")", ".", "times", "do", "r", "=", "matmul", "(", "r", ",", "a", ")", "end", "else", "while", "(", "n", "&", "1", ")", "==", "0", "a", "=", "matmul", "(", "a", ",", "a", ")", "n", ">>=", "1", "end", "r", "=", "a", "while", "n", "!=", "0", "a", "=", "matmul", "(", "a", ",", "a", ")", "n", ">>=", "1", "if", "(", "n", "&", "1", ")", "!=", "0", "r", "=", "matmul", "(", "r", ",", "a", ")", "end", "end", "end", "r", "end" ]
Compute a square matrix `a` to the power `n`. * If n > 0: return `a**n`. * If n == 0: return identity matrix. * If n < 0: return `(a*\*-1)*\*n.abs`. @param a [Numo::NArray] square matrix (>= 2-dimensinal NArray). @param n [Integer] the exponent. @example i = Numo::DFloat[[0, 1], [-1, 0]] => Numo::DFloat#shape=[2,2] [[0, 1], [-1, 0]] Numo::Linalg.matrix_power(i,3) => Numo::DFloat#shape=[2,2] [[0, -1], [1, 0]] Numo::Linalg.matrix_power(i,0) => Numo::DFloat#shape=[2,2] [[1, 0], [0, 1]] Numo::Linalg.matrix_power(i,-3) => Numo::DFloat#shape=[2,2] [[0, 1], [-1, 0]] q = Numo::DFloat.zeros(4,4) q[0..1,0..1] = -i q[2..3,2..3] = i q => Numo::DFloat#shape=[4,4] [[-0, -1, 0, 0], [1, -0, 0, 0], [0, 0, 0, 1], [0, 0, -1, 0]] Numo::Linalg.matrix_power(q,2) => Numo::DFloat#shape=[4,4] [[-1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]]
[ "Compute", "a", "square", "matrix", "a", "to", "the", "power", "n", "." ]
bb0929aae0f3285a41d404040eda651833ffccef
https://github.com/ruby-numo/numo-linalg/blob/bb0929aae0f3285a41d404040eda651833ffccef/lib/numo/linalg/function.rb#L198-L233
train
ruby-numo/numo-linalg
lib/numo/linalg/function.rb
Numo.Linalg.svdvals
def svdvals(a, driver:'svd') case driver.to_s when /^(ge)?sdd$/i, "turbo" Lapack.call(:gesdd, a, jobz:'N')[0] when /^(ge)?svd$/i Lapack.call(:gesvd, a, jobu:'N', jobvt:'N')[0] else raise ArgumentError, "invalid driver: #{driver}" end end
ruby
def svdvals(a, driver:'svd') case driver.to_s when /^(ge)?sdd$/i, "turbo" Lapack.call(:gesdd, a, jobz:'N')[0] when /^(ge)?svd$/i Lapack.call(:gesvd, a, jobu:'N', jobvt:'N')[0] else raise ArgumentError, "invalid driver: #{driver}" end end
[ "def", "svdvals", "(", "a", ",", "driver", ":", "'svd'", ")", "case", "driver", ".", "to_s", "when", "/", "/i", ",", "\"turbo\"", "Lapack", ".", "call", "(", ":gesdd", ",", "a", ",", "jobz", ":", "'N'", ")", "[", "0", "]", "when", "/", "/i", "Lapack", ".", "call", "(", ":gesvd", ",", "a", ",", "jobu", ":", "'N'", ",", "jobvt", ":", "'N'", ")", "[", "0", "]", "else", "raise", "ArgumentError", ",", "\"invalid driver: #{driver}\"", "end", "end" ]
Computes the Singular Values of a M-by-N matrix A. The SVD is written A = U * SIGMA * transpose(V) where SIGMA is an M-by-N matrix which is zero except for its min(m,n) diagonal elements. The diagonal elements of SIGMA are the singular values of A; they are real and non-negative, and are returned in descending order. @param a [Numo::NArray] m-by-n matrix A (>= 2-dimensinal NArray) @param driver [String or Symbol] choose LAPACK solver from 'svd', 'sdd'. (optional, default='svd') @return [Numo::NArray] returns SIGMA (singular values).
[ "Computes", "the", "Singular", "Values", "of", "a", "M", "-", "by", "-", "N", "matrix", "A", ".", "The", "SVD", "is", "written" ]
bb0929aae0f3285a41d404040eda651833ffccef
https://github.com/ruby-numo/numo-linalg/blob/bb0929aae0f3285a41d404040eda651833ffccef/lib/numo/linalg/function.rb#L332-L341
train
ruby-numo/numo-linalg
lib/numo/linalg/function.rb
Numo.Linalg.orth
def orth(a, rcond: -1) raise NArray::ShapeError, '2-d array is required' if a.ndim < 2 s, u, = svd(a) tol = s.max * (rcond.nil? || rcond < 0 ? a.class::EPSILON * a.shape.max : rcond) k = (s > tol).count u[true, 0...k] end
ruby
def orth(a, rcond: -1) raise NArray::ShapeError, '2-d array is required' if a.ndim < 2 s, u, = svd(a) tol = s.max * (rcond.nil? || rcond < 0 ? a.class::EPSILON * a.shape.max : rcond) k = (s > tol).count u[true, 0...k] end
[ "def", "orth", "(", "a", ",", "rcond", ":", "-", "1", ")", "raise", "NArray", "::", "ShapeError", ",", "'2-d array is required'", "if", "a", ".", "ndim", "<", "2", "s", ",", "u", ",", "=", "svd", "(", "a", ")", "tol", "=", "s", ".", "max", "*", "(", "rcond", ".", "nil?", "||", "rcond", "<", "0", "?", "a", ".", "class", "::", "EPSILON", "*", "a", ".", "shape", ".", "max", ":", "rcond", ")", "k", "=", "(", "s", ">", "tol", ")", ".", "count", "u", "[", "true", ",", "0", "...", "k", "]", "end" ]
Computes an orthonormal basis for the range of matrix A. @param a [Numo::NArray] m-by-n matrix A (>= 2-dimensional NArray). @param rcond [Float] (optional) rcond is used to determine the effective rank of A. Singular values `s[i] <= rcond * s.max` are treated as zero. If rcond < 0, machine precision is used instead. @return [Numo::NArray] The orthonormal basis for the range of matrix A.
[ "Computes", "an", "orthonormal", "basis", "for", "the", "range", "of", "matrix", "A", "." ]
bb0929aae0f3285a41d404040eda651833ffccef
https://github.com/ruby-numo/numo-linalg/blob/bb0929aae0f3285a41d404040eda651833ffccef/lib/numo/linalg/function.rb#L352-L358
train
ruby-numo/numo-linalg
lib/numo/linalg/function.rb
Numo.Linalg.null_space
def null_space(a, rcond: -1) raise NArray::ShapeError, '2-d array is required' if a.ndim < 2 s, _u, vh = svd(a) tol = s.max * (rcond.nil? || rcond < 0 ? a.class::EPSILON * a.shape.max : rcond) k = (s > tol).count return a.class.new if k == vh.shape[0] r = vh[k..-1, true].transpose.dup blas_char(vh) =~ /c|z/ ? r.conj : r end
ruby
def null_space(a, rcond: -1) raise NArray::ShapeError, '2-d array is required' if a.ndim < 2 s, _u, vh = svd(a) tol = s.max * (rcond.nil? || rcond < 0 ? a.class::EPSILON * a.shape.max : rcond) k = (s > tol).count return a.class.new if k == vh.shape[0] r = vh[k..-1, true].transpose.dup blas_char(vh) =~ /c|z/ ? r.conj : r end
[ "def", "null_space", "(", "a", ",", "rcond", ":", "-", "1", ")", "raise", "NArray", "::", "ShapeError", ",", "'2-d array is required'", "if", "a", ".", "ndim", "<", "2", "s", ",", "_u", ",", "vh", "=", "svd", "(", "a", ")", "tol", "=", "s", ".", "max", "*", "(", "rcond", ".", "nil?", "||", "rcond", "<", "0", "?", "a", ".", "class", "::", "EPSILON", "*", "a", ".", "shape", ".", "max", ":", "rcond", ")", "k", "=", "(", "s", ">", "tol", ")", ".", "count", "return", "a", ".", "class", ".", "new", "if", "k", "==", "vh", ".", "shape", "[", "0", "]", "r", "=", "vh", "[", "k", "..", "-", "1", ",", "true", "]", ".", "transpose", ".", "dup", "blas_char", "(", "vh", ")", "=~", "/", "/", "?", "r", ".", "conj", ":", "r", "end" ]
Computes an orthonormal basis for the null space of matrix A. @param a [Numo::NArray] m-by-n matrix A (>= 2-dimensional NArray). @param rcond [Float] (optional) rcond is used to determine the effective rank of A. Singular values `s[i] <= rcond * s.max` are treated as zero. If rcond < 0, machine precision is used instead. @return [Numo::NArray] The orthonormal basis for the null space of matrix A.
[ "Computes", "an", "orthonormal", "basis", "for", "the", "null", "space", "of", "matrix", "A", "." ]
bb0929aae0f3285a41d404040eda651833ffccef
https://github.com/ruby-numo/numo-linalg/blob/bb0929aae0f3285a41d404040eda651833ffccef/lib/numo/linalg/function.rb#L369-L377
train
ruby-numo/numo-linalg
lib/numo/linalg/function.rb
Numo.Linalg.lu
def lu(a, permute_l: false) raise NArray::ShapeError, '2-d array is required' if a.ndim < 2 m, n = a.shape k = [m, n].min lu, ip = lu_fact(a) l = lu.tril.tap { |mat| mat[mat.diag_indices(0)] = 1.0 }[true, 0...k] u = lu.triu[0...k, 0...n] p = Numo::DFloat.eye(m).tap do |mat| ip.to_a.each_with_index { |i, j| mat[true, [i - 1, j]] = mat[true, [j, i - 1]].dup } end permute_l ? [p.dot(l), u] : [p, l, u] end
ruby
def lu(a, permute_l: false) raise NArray::ShapeError, '2-d array is required' if a.ndim < 2 m, n = a.shape k = [m, n].min lu, ip = lu_fact(a) l = lu.tril.tap { |mat| mat[mat.diag_indices(0)] = 1.0 }[true, 0...k] u = lu.triu[0...k, 0...n] p = Numo::DFloat.eye(m).tap do |mat| ip.to_a.each_with_index { |i, j| mat[true, [i - 1, j]] = mat[true, [j, i - 1]].dup } end permute_l ? [p.dot(l), u] : [p, l, u] end
[ "def", "lu", "(", "a", ",", "permute_l", ":", "false", ")", "raise", "NArray", "::", "ShapeError", ",", "'2-d array is required'", "if", "a", ".", "ndim", "<", "2", "m", ",", "n", "=", "a", ".", "shape", "k", "=", "[", "m", ",", "n", "]", ".", "min", "lu", ",", "ip", "=", "lu_fact", "(", "a", ")", "l", "=", "lu", ".", "tril", ".", "tap", "{", "|", "mat", "|", "mat", "[", "mat", ".", "diag_indices", "(", "0", ")", "]", "=", "1.0", "}", "[", "true", ",", "0", "...", "k", "]", "u", "=", "lu", ".", "triu", "[", "0", "...", "k", ",", "0", "...", "n", "]", "p", "=", "Numo", "::", "DFloat", ".", "eye", "(", "m", ")", ".", "tap", "do", "|", "mat", "|", "ip", ".", "to_a", ".", "each_with_index", "{", "|", "i", ",", "j", "|", "mat", "[", "true", ",", "[", "i", "-", "1", ",", "j", "]", "]", "=", "mat", "[", "true", ",", "[", "j", ",", "i", "-", "1", "]", "]", ".", "dup", "}", "end", "permute_l", "?", "[", "p", ".", "dot", "(", "l", ")", ",", "u", "]", ":", "[", "p", ",", "l", ",", "u", "]", "end" ]
Computes an LU factorization of a M-by-N matrix A using partial pivoting with row interchanges. The factorization has the form A = P * L * U where P is a permutation matrix, L is lower triangular with unit diagonal elements (lower trapezoidal if m > n), and U is upper triangular (upper trapezoidal if m < n). @param a [Numo::NArray] m-by-n matrix A (>= 2-dimensinal NArray) @param permute_l [Bool] (optional) If true, perform the matrix product of P and L. @return [[p,l,u]] if permute_l == false @return [[pl,u]] if permute_l == true - **p** [Numo::NArray] -- The permutation matrix P. - **l** [Numo::NArray] -- The factor L. - **u** [Numo::NArray] -- The factor U.
[ "Computes", "an", "LU", "factorization", "of", "a", "M", "-", "by", "-", "N", "matrix", "A", "using", "partial", "pivoting", "with", "row", "interchanges", "." ]
bb0929aae0f3285a41d404040eda651833ffccef
https://github.com/ruby-numo/numo-linalg/blob/bb0929aae0f3285a41d404040eda651833ffccef/lib/numo/linalg/function.rb#L399-L410
train
ruby-numo/numo-linalg
lib/numo/linalg/function.rb
Numo.Linalg.lu_solve
def lu_solve(lu, ipiv, b, trans:"N") Lapack.call(:getrs, lu, ipiv, b, trans:trans)[0] end
ruby
def lu_solve(lu, ipiv, b, trans:"N") Lapack.call(:getrs, lu, ipiv, b, trans:trans)[0] end
[ "def", "lu_solve", "(", "lu", ",", "ipiv", ",", "b", ",", "trans", ":", "\"N\"", ")", "Lapack", ".", "call", "(", ":getrs", ",", "lu", ",", "ipiv", ",", "b", ",", "trans", ":", "trans", ")", "[", "0", "]", "end" ]
Solves a system of linear equations A * X = B or A**T * X = B with a N-by-N matrix A using the LU factorization computed by Numo::Linalg.lu_fact @param lu [Numo::NArray] matrix containing the factors L and U from the factorization `A = P*L*U` as computed by Numo::Linalg.lu_fact. @param ipiv [Numo::NArray] The pivot indices from Numo::Linalg.lu_fact; for 1<=i<=N, row i of the matrix was interchanged with row IPIV(i). @param b [Numo::NArray] the right hand side matrix B. @param trans [String or Symbol] Specifies the form of the system of equations: - If 'N': `A * X = B` (No transpose). - If 'T': `A*\*T* X = B` (Transpose). - If 'C': `A*\*T* X = B` (Conjugate transpose = Transpose). @return [Numo::NArray] the solution matrix X.
[ "Solves", "a", "system", "of", "linear", "equations" ]
bb0929aae0f3285a41d404040eda651833ffccef
https://github.com/ruby-numo/numo-linalg/blob/bb0929aae0f3285a41d404040eda651833ffccef/lib/numo/linalg/function.rb#L476-L478
train
ruby-numo/numo-linalg
lib/numo/linalg/function.rb
Numo.Linalg.eigvals
def eigvals(a) jobvl, jobvr = 'N','N' case blas_char(a) when /c|z/ w, = Lapack.call(:geev, a, jobvl:jobvl, jobvr:jobvr) else wr, wi, = Lapack.call(:geev, a, jobvl:jobvl, jobvr:jobvr) w = wr + wi * Complex::I end w end
ruby
def eigvals(a) jobvl, jobvr = 'N','N' case blas_char(a) when /c|z/ w, = Lapack.call(:geev, a, jobvl:jobvl, jobvr:jobvr) else wr, wi, = Lapack.call(:geev, a, jobvl:jobvl, jobvr:jobvr) w = wr + wi * Complex::I end w end
[ "def", "eigvals", "(", "a", ")", "jobvl", ",", "jobvr", "=", "'N'", ",", "'N'", "case", "blas_char", "(", "a", ")", "when", "/", "/", "w", ",", "=", "Lapack", ".", "call", "(", ":geev", ",", "a", ",", "jobvl", ":", "jobvl", ",", "jobvr", ":", "jobvr", ")", "else", "wr", ",", "wi", ",", "=", "Lapack", ".", "call", "(", ":geev", ",", "a", ",", "jobvl", ":", "jobvl", ",", "jobvr", ":", "jobvr", ")", "w", "=", "wr", "+", "wi", "*", "Complex", "::", "I", "end", "w", "end" ]
Computes the eigenvalues only for a square nonsymmetric matrix A. @param a [Numo::NArray] square nonsymmetric matrix (>= 2-dimensinal NArray) @return [Numo::NArray] eigenvalues
[ "Computes", "the", "eigenvalues", "only", "for", "a", "square", "nonsymmetric", "matrix", "A", "." ]
bb0929aae0f3285a41d404040eda651833ffccef
https://github.com/ruby-numo/numo-linalg/blob/bb0929aae0f3285a41d404040eda651833ffccef/lib/numo/linalg/function.rb#L682-L692
train
ruby-numo/numo-linalg
lib/numo/linalg/function.rb
Numo.Linalg.cond
def cond(a,ord=nil) if ord.nil? s = svdvals(a) s[false, 0]/s[false, -1] else norm(a, ord, axis:[-2,-1]) * norm(inv(a), ord, axis:[-2,-1]) end end
ruby
def cond(a,ord=nil) if ord.nil? s = svdvals(a) s[false, 0]/s[false, -1] else norm(a, ord, axis:[-2,-1]) * norm(inv(a), ord, axis:[-2,-1]) end end
[ "def", "cond", "(", "a", ",", "ord", "=", "nil", ")", "if", "ord", ".", "nil?", "s", "=", "svdvals", "(", "a", ")", "s", "[", "false", ",", "0", "]", "/", "s", "[", "false", ",", "-", "1", "]", "else", "norm", "(", "a", ",", "ord", ",", "axis", ":", "[", "-", "2", ",", "-", "1", "]", ")", "*", "norm", "(", "inv", "(", "a", ")", ",", "ord", ",", "axis", ":", "[", "-", "2", ",", "-", "1", "]", ")", "end", "end" ]
Compute the condition number of a matrix using the norm with one of the following order. | ord | matrix norm | | ----- | ---------------------- | | nil | 2-norm using SVD | | 'fro' | Frobenius norm | | 'inf' | x.abs.sum(axis:-1).max | | 1 | x.abs.sum(axis:-2).max | | 2 | 2-norm (max sing_vals) | @param a [Numo::NArray] matrix or vector (>= 1-dimensinal NArray) @param ord [String or Symbol] Order of the norm. @return [Numo::NArray] cond result @example a = Numo::DFloat[[1, 0, -1], [0, 1, 0], [1, 0, 1]] => Numo::DFloat#shape=[3,3] [[1, 0, -1], [0, 1, 0], [1, 0, 1]] LA = Numo::Linalg LA.cond(a) => 1.4142135623730951 LA.cond(a, 'fro') => 3.1622776601683795 LA.cond(a, 'inf') => 2.0 LA.cond(a, '-inf') => 1.0 LA.cond(a, 1) => 2.0 LA.cond(a, -1) => 1.0 LA.cond(a, 2) => 1.4142135623730951 LA.cond(a, -2) => 0.7071067811865475 (LA.svdvals(a)).min*(LA.svdvals(LA.inv(a))).min => 0.7071067811865475
[ "Compute", "the", "condition", "number", "of", "a", "matrix", "using", "the", "norm", "with", "one", "of", "the", "following", "order", "." ]
bb0929aae0f3285a41d404040eda651833ffccef
https://github.com/ruby-numo/numo-linalg/blob/bb0929aae0f3285a41d404040eda651833ffccef/lib/numo/linalg/function.rb#L882-L889
train
ruby-numo/numo-linalg
lib/numo/linalg/function.rb
Numo.Linalg.det
def det(a) lu, piv, = Lapack.call(:getrf, a) idx = piv.new_narray.store(piv.class.new(piv.shape[-1]).seq(1)) m = piv.eq(idx).count_false(axis:-1) % 2 sign = m * -2 + 1 lu.diagonal.prod(axis:-1) * sign end
ruby
def det(a) lu, piv, = Lapack.call(:getrf, a) idx = piv.new_narray.store(piv.class.new(piv.shape[-1]).seq(1)) m = piv.eq(idx).count_false(axis:-1) % 2 sign = m * -2 + 1 lu.diagonal.prod(axis:-1) * sign end
[ "def", "det", "(", "a", ")", "lu", ",", "piv", ",", "=", "Lapack", ".", "call", "(", ":getrf", ",", "a", ")", "idx", "=", "piv", ".", "new_narray", ".", "store", "(", "piv", ".", "class", ".", "new", "(", "piv", ".", "shape", "[", "-", "1", "]", ")", ".", "seq", "(", "1", ")", ")", "m", "=", "piv", ".", "eq", "(", "idx", ")", ".", "count_false", "(", "axis", ":", "-", "1", ")", "%", "2", "sign", "=", "m", "*", "-", "2", "+", "1", "lu", ".", "diagonal", ".", "prod", "(", "axis", ":", "-", "1", ")", "*", "sign", "end" ]
Determinant of a matrix @param a [Numo::NArray] matrix (>= 2-dimensional NArray) @return [Float or Complex or Numo::NArray]
[ "Determinant", "of", "a", "matrix" ]
bb0929aae0f3285a41d404040eda651833ffccef
https://github.com/ruby-numo/numo-linalg/blob/bb0929aae0f3285a41d404040eda651833ffccef/lib/numo/linalg/function.rb#L896-L902
train
ruby-numo/numo-linalg
lib/numo/linalg/function.rb
Numo.Linalg.slogdet
def slogdet(a) lu, piv, = Lapack.call(:getrf, a) idx = piv.new_narray.store(piv.class.new(piv.shape[-1]).seq(1)) m = piv.eq(idx).count_false(axis:-1) % 2 sign = m * -2 + 1 lud = lu.diagonal if (lud.eq 0).any? return 0, (-Float::INFINITY) end lud_abs = lud.abs sign *= (lud/lud_abs).prod [sign, NMath.log(lud_abs).sum(axis:-1)] end
ruby
def slogdet(a) lu, piv, = Lapack.call(:getrf, a) idx = piv.new_narray.store(piv.class.new(piv.shape[-1]).seq(1)) m = piv.eq(idx).count_false(axis:-1) % 2 sign = m * -2 + 1 lud = lu.diagonal if (lud.eq 0).any? return 0, (-Float::INFINITY) end lud_abs = lud.abs sign *= (lud/lud_abs).prod [sign, NMath.log(lud_abs).sum(axis:-1)] end
[ "def", "slogdet", "(", "a", ")", "lu", ",", "piv", ",", "=", "Lapack", ".", "call", "(", ":getrf", ",", "a", ")", "idx", "=", "piv", ".", "new_narray", ".", "store", "(", "piv", ".", "class", ".", "new", "(", "piv", ".", "shape", "[", "-", "1", "]", ")", ".", "seq", "(", "1", ")", ")", "m", "=", "piv", ".", "eq", "(", "idx", ")", ".", "count_false", "(", "axis", ":", "-", "1", ")", "%", "2", "sign", "=", "m", "*", "-", "2", "+", "1", "lud", "=", "lu", ".", "diagonal", "if", "(", "lud", ".", "eq", "0", ")", ".", "any?", "return", "0", ",", "(", "-", "Float", "::", "INFINITY", ")", "end", "lud_abs", "=", "lud", ".", "abs", "sign", "*=", "(", "lud", "/", "lud_abs", ")", ".", "prod", "[", "sign", ",", "NMath", ".", "log", "(", "lud_abs", ")", ".", "sum", "(", "axis", ":", "-", "1", ")", "]", "end" ]
Natural logarithm of the determinant of a matrix @param a [Numo::NArray] matrix (>= 2-dimensional NArray) @return [[sign,logdet]] - **sign** -- A number representing the sign of the determinant. - **logdet** -- The natural log of the absolute value of the determinant.
[ "Natural", "logarithm", "of", "the", "determinant", "of", "a", "matrix" ]
bb0929aae0f3285a41d404040eda651833ffccef
https://github.com/ruby-numo/numo-linalg/blob/bb0929aae0f3285a41d404040eda651833ffccef/lib/numo/linalg/function.rb#L911-L924
train
ruby-numo/numo-linalg
lib/numo/linalg/function.rb
Numo.Linalg.inv
def inv(a, driver:"getrf", uplo:'U') case driver when /(ge|sy|he|po)sv$/ d = $1 b = a.new_zeros.eye solve(a, b, driver:d, uplo:uplo) when /(ge|sy|he)tr[fi]$/ d = $1 lu, piv = lu_fact(a) lu_inv(lu, piv) when /potr[fi]$/ lu = cho_fact(a, uplo:uplo) cho_inv(lu, uplo:uplo) else raise ArgumentError, "invalid driver: #{driver}" end end
ruby
def inv(a, driver:"getrf", uplo:'U') case driver when /(ge|sy|he|po)sv$/ d = $1 b = a.new_zeros.eye solve(a, b, driver:d, uplo:uplo) when /(ge|sy|he)tr[fi]$/ d = $1 lu, piv = lu_fact(a) lu_inv(lu, piv) when /potr[fi]$/ lu = cho_fact(a, uplo:uplo) cho_inv(lu, uplo:uplo) else raise ArgumentError, "invalid driver: #{driver}" end end
[ "def", "inv", "(", "a", ",", "driver", ":", "\"getrf\"", ",", "uplo", ":", "'U'", ")", "case", "driver", "when", "/", "/", "d", "=", "$1", "b", "=", "a", ".", "new_zeros", ".", "eye", "solve", "(", "a", ",", "b", ",", "driver", ":", "d", ",", "uplo", ":", "uplo", ")", "when", "/", "/", "d", "=", "$1", "lu", ",", "piv", "=", "lu_fact", "(", "a", ")", "lu_inv", "(", "lu", ",", "piv", ")", "when", "/", "/", "lu", "=", "cho_fact", "(", "a", ",", "uplo", ":", "uplo", ")", "cho_inv", "(", "lu", ",", "uplo", ":", "uplo", ")", "else", "raise", "ArgumentError", ",", "\"invalid driver: #{driver}\"", "end", "end" ]
Inverse matrix from square matrix `a` @param a [Numo::NArray] n-by-n square matrix (>= 2-dimensinal NArray) @param driver [String or Symbol] choose LAPACK diriver ('ge'|'sy'|'he'|'po') + ("sv"|"trf") (optional, default='getrf') @param uplo [String or Symbol] optional, default='U'. Access upper or ('U') lower ('L') triangle. (omitted when driver:"ge") @return [Numo::NArray] The inverse matrix. @example Numo::Linalg.inv(a,driver:'getrf') => Numo::DFloat#shape=[2,2] [[-2, 1], [1.5, -0.5]] a.dot(Numo::Linalg.inv(a,driver:'getrf')) => Numo::DFloat#shape=[2,2] [[1, 0], [8.88178e-16, 1]]
[ "Inverse", "matrix", "from", "square", "matrix", "a" ]
bb0929aae0f3285a41d404040eda651833ffccef
https://github.com/ruby-numo/numo-linalg/blob/bb0929aae0f3285a41d404040eda651833ffccef/lib/numo/linalg/function.rb#L1000-L1016
train
google/autoparse
lib/autoparse/instance.rb
AutoParse.Instance.valid?
def valid? unvalidated_fields = @data.keys.dup for property_key, schema_class in self.class.properties property_value = @data[property_key] if !self.class.validate_property_value( property_value, schema_class.data) return false end if property_value == nil && schema_class.data['required'] != true # Value was omitted, but not required. Still valid. Skip dependency # checks. next end # Verify property dependencies property_dependencies = self.class.property_dependencies[property_key] case property_dependencies when String, Array property_dependencies = [property_dependencies].flatten for dependency_key in property_dependencies dependency_value = @data[dependency_key] return false if dependency_value == nil end when Class if property_dependencies.ancestors.include?(Instance) dependency_instance = property_dependencies.new(property_value) return false unless dependency_instance.valid? else raise TypeError, "Expected schema Class, got #{property_dependencies.class}." end end end if self.class.additional_properties_schema == nil # No additional properties allowed return false unless unvalidated_fields.empty? elsif self.class.additional_properties_schema != EMPTY_SCHEMA # Validate all remaining fields against this schema for property_key in unvalidated_fields property_value = @data[property_key] if !self.class.additional_properties_schema.validate_property_value( property_value, self.class.additional_properties_schema.data) return false end end end if self.class.superclass && self.class.superclass != Instance && self.class.ancestors.first != Instance # The spec actually only defined the 'extends' semantics as children # must also validate aainst the parent. return false unless self.class.superclass.new(@data).valid? end return true end
ruby
def valid? unvalidated_fields = @data.keys.dup for property_key, schema_class in self.class.properties property_value = @data[property_key] if !self.class.validate_property_value( property_value, schema_class.data) return false end if property_value == nil && schema_class.data['required'] != true # Value was omitted, but not required. Still valid. Skip dependency # checks. next end # Verify property dependencies property_dependencies = self.class.property_dependencies[property_key] case property_dependencies when String, Array property_dependencies = [property_dependencies].flatten for dependency_key in property_dependencies dependency_value = @data[dependency_key] return false if dependency_value == nil end when Class if property_dependencies.ancestors.include?(Instance) dependency_instance = property_dependencies.new(property_value) return false unless dependency_instance.valid? else raise TypeError, "Expected schema Class, got #{property_dependencies.class}." end end end if self.class.additional_properties_schema == nil # No additional properties allowed return false unless unvalidated_fields.empty? elsif self.class.additional_properties_schema != EMPTY_SCHEMA # Validate all remaining fields against this schema for property_key in unvalidated_fields property_value = @data[property_key] if !self.class.additional_properties_schema.validate_property_value( property_value, self.class.additional_properties_schema.data) return false end end end if self.class.superclass && self.class.superclass != Instance && self.class.ancestors.first != Instance # The spec actually only defined the 'extends' semantics as children # must also validate aainst the parent. return false unless self.class.superclass.new(@data).valid? end return true end
[ "def", "valid?", "unvalidated_fields", "=", "@data", ".", "keys", ".", "dup", "for", "property_key", ",", "schema_class", "in", "self", ".", "class", ".", "properties", "property_value", "=", "@data", "[", "property_key", "]", "if", "!", "self", ".", "class", ".", "validate_property_value", "(", "property_value", ",", "schema_class", ".", "data", ")", "return", "false", "end", "if", "property_value", "==", "nil", "&&", "schema_class", ".", "data", "[", "'required'", "]", "!=", "true", "next", "end", "property_dependencies", "=", "self", ".", "class", ".", "property_dependencies", "[", "property_key", "]", "case", "property_dependencies", "when", "String", ",", "Array", "property_dependencies", "=", "[", "property_dependencies", "]", ".", "flatten", "for", "dependency_key", "in", "property_dependencies", "dependency_value", "=", "@data", "[", "dependency_key", "]", "return", "false", "if", "dependency_value", "==", "nil", "end", "when", "Class", "if", "property_dependencies", ".", "ancestors", ".", "include?", "(", "Instance", ")", "dependency_instance", "=", "property_dependencies", ".", "new", "(", "property_value", ")", "return", "false", "unless", "dependency_instance", ".", "valid?", "else", "raise", "TypeError", ",", "\"Expected schema Class, got #{property_dependencies.class}.\"", "end", "end", "end", "if", "self", ".", "class", ".", "additional_properties_schema", "==", "nil", "return", "false", "unless", "unvalidated_fields", ".", "empty?", "elsif", "self", ".", "class", ".", "additional_properties_schema", "!=", "EMPTY_SCHEMA", "for", "property_key", "in", "unvalidated_fields", "property_value", "=", "@data", "[", "property_key", "]", "if", "!", "self", ".", "class", ".", "additional_properties_schema", ".", "validate_property_value", "(", "property_value", ",", "self", ".", "class", ".", "additional_properties_schema", ".", "data", ")", "return", "false", "end", "end", "end", "if", "self", ".", "class", ".", "superclass", "&&", "self", ".", "class", ".", "superclass", "!=", "Instance", "&&", "self", ".", "class", ".", "ancestors", ".", "first", "!=", "Instance", "return", "false", "unless", "self", ".", "class", ".", "superclass", ".", "new", "(", "@data", ")", ".", "valid?", "end", "return", "true", "end" ]
Validates the parsed data against the schema.
[ "Validates", "the", "parsed", "data", "against", "the", "schema", "." ]
c710936d68b30840c9feea01f9d89038944b4ec9
https://github.com/google/autoparse/blob/c710936d68b30840c9feea01f9d89038944b4ec9/lib/autoparse/instance.rb#L394-L447
train
zachinglis/crummy
lib/crummy/action_view.rb
Crummy.ViewMethods.render_crumbs
def render_crumbs(options = {}) raise ArgumentError, "Renderer and block given" if options.has_key?(:renderer) && block_given? return yield(crumbs, options) if block_given? @_renderer ||= if options.has_key?(:renderer) options.delete(:renderer) else require 'crummy/standard_renderer' Crummy::StandardRenderer.new end @_renderer.render_crumbs(crumbs, options) end
ruby
def render_crumbs(options = {}) raise ArgumentError, "Renderer and block given" if options.has_key?(:renderer) && block_given? return yield(crumbs, options) if block_given? @_renderer ||= if options.has_key?(:renderer) options.delete(:renderer) else require 'crummy/standard_renderer' Crummy::StandardRenderer.new end @_renderer.render_crumbs(crumbs, options) end
[ "def", "render_crumbs", "(", "options", "=", "{", "}", ")", "raise", "ArgumentError", ",", "\"Renderer and block given\"", "if", "options", ".", "has_key?", "(", ":renderer", ")", "&&", "block_given?", "return", "yield", "(", "crumbs", ",", "options", ")", "if", "block_given?", "@_renderer", "||=", "if", "options", ".", "has_key?", "(", ":renderer", ")", "options", ".", "delete", "(", ":renderer", ")", "else", "require", "'crummy/standard_renderer'", "Crummy", "::", "StandardRenderer", ".", "new", "end", "@_renderer", ".", "render_crumbs", "(", "crumbs", ",", "options", ")", "end" ]
Render the list of crumbs using renderer
[ "Render", "the", "list", "of", "crumbs", "using", "renderer" ]
915b93a3e98f9162170ccbcaa9fba714f60ca870
https://github.com/zachinglis/crummy/blob/915b93a3e98f9162170ccbcaa9fba714f60ca870/lib/crummy/action_view.rb#L15-L27
train
erector/erector
lib/erector/convenience.rb
Erector.Convenience.javascript
def javascript(value = nil, attributes = {}) if value.is_a?(Hash) attributes = value value = nil elsif block_given? && value raise ArgumentError, "You can't pass both a block and a value to javascript -- please choose one." end script(attributes.merge(:type => "text/javascript")) do # Shouldn't this be a "cdata" HtmlPart? # (maybe, but the syntax is specific to javascript; it isn't # really a generic XML CDATA section. Specifically, # ]]> within value is not treated as ending the # CDATA section by Firefox2 when parsing text/html, # although I guess we could refuse to generate ]]> # there, for the benefit of XML/XHTML parsers). output << raw("\n// <![CDATA[\n") if block_given? yield else output << raw(value) end output << raw("\n// ]]>") output.append_newline # this forces a newline even if we're not in pretty mode end output << raw("\n") end
ruby
def javascript(value = nil, attributes = {}) if value.is_a?(Hash) attributes = value value = nil elsif block_given? && value raise ArgumentError, "You can't pass both a block and a value to javascript -- please choose one." end script(attributes.merge(:type => "text/javascript")) do # Shouldn't this be a "cdata" HtmlPart? # (maybe, but the syntax is specific to javascript; it isn't # really a generic XML CDATA section. Specifically, # ]]> within value is not treated as ending the # CDATA section by Firefox2 when parsing text/html, # although I guess we could refuse to generate ]]> # there, for the benefit of XML/XHTML parsers). output << raw("\n// <![CDATA[\n") if block_given? yield else output << raw(value) end output << raw("\n// ]]>") output.append_newline # this forces a newline even if we're not in pretty mode end output << raw("\n") end
[ "def", "javascript", "(", "value", "=", "nil", ",", "attributes", "=", "{", "}", ")", "if", "value", ".", "is_a?", "(", "Hash", ")", "attributes", "=", "value", "value", "=", "nil", "elsif", "block_given?", "&&", "value", "raise", "ArgumentError", ",", "\"You can't pass both a block and a value to javascript -- please choose one.\"", "end", "script", "(", "attributes", ".", "merge", "(", ":type", "=>", "\"text/javascript\"", ")", ")", "do", "output", "<<", "raw", "(", "\"\\n// <![CDATA[\\n\"", ")", "if", "block_given?", "yield", "else", "output", "<<", "raw", "(", "value", ")", "end", "output", "<<", "raw", "(", "\"\\n// ]]>\"", ")", "output", ".", "append_newline", "end", "output", "<<", "raw", "(", "\"\\n\"", ")", "end" ]
Emits a javascript block inside a +script+ tag, wrapped in CDATA doohickeys like all the cool JS kids do.
[ "Emits", "a", "javascript", "block", "inside", "a", "+", "script", "+", "tag", "wrapped", "in", "CDATA", "doohickeys", "like", "all", "the", "cool", "JS", "kids", "do", "." ]
59754211101b2c50a4c9daa8e64a64e6edc9e976
https://github.com/erector/erector/blob/59754211101b2c50a4c9daa8e64a64e6edc9e976/lib/erector/convenience.rb#L62-L89
train
kolosek/finance_math
lib/finance_math/loan.rb
FinanceMath.Loan.pmt
def pmt(options = {}) future_value = options.fetch(:future_value, 0) type = options.fetch(:type, 0) ((@amount * interest(@monthly_rate, @duration) - future_value ) / ((1.0 + @monthly_rate * type) * fvifa(@monthly_rate, duration))) end
ruby
def pmt(options = {}) future_value = options.fetch(:future_value, 0) type = options.fetch(:type, 0) ((@amount * interest(@monthly_rate, @duration) - future_value ) / ((1.0 + @monthly_rate * type) * fvifa(@monthly_rate, duration))) end
[ "def", "pmt", "(", "options", "=", "{", "}", ")", "future_value", "=", "options", ".", "fetch", "(", ":future_value", ",", "0", ")", "type", "=", "options", ".", "fetch", "(", ":type", ",", "0", ")", "(", "(", "@amount", "*", "interest", "(", "@monthly_rate", ",", "@duration", ")", "-", "future_value", ")", "/", "(", "(", "1.0", "+", "@monthly_rate", "*", "type", ")", "*", "fvifa", "(", "@monthly_rate", ",", "duration", ")", ")", ")", "end" ]
create a new Loan instance @return [Loan] @param [Numeric] decimal value of the interest rate @param [Integer] Duration of the loan period @param [Float] Loan amount @param [Float] structure fee - fee for the market in percentages @param [Float] currency protection - Protection for currency changes - usually 3%, default to 0% @example create a 10.5% Nominal rate @see http://en.wikipedia.org/wiki/Nominal_interest_rate @api public
[ "create", "a", "new", "Loan", "instance" ]
850f774bb7ac80ceb0d6a17c2f2fb8066ef02dfd
https://github.com/kolosek/finance_math/blob/850f774bb7ac80ceb0d6a17c2f2fb8066ef02dfd/lib/finance_math/loan.rb#L54-L58
train
erector/erector
lib/erector/jquery.rb
Erector.JQuery.jquery
def jquery(*args) event = if args.first.is_a? Symbol args.shift else :ready end txt = args.shift attributes = args.shift || {} javascript attributes do rawtext "\n" rawtext "jQuery(document).#{event}(function($){\n" rawtext txt rawtext "\n});" end end
ruby
def jquery(*args) event = if args.first.is_a? Symbol args.shift else :ready end txt = args.shift attributes = args.shift || {} javascript attributes do rawtext "\n" rawtext "jQuery(document).#{event}(function($){\n" rawtext txt rawtext "\n});" end end
[ "def", "jquery", "(", "*", "args", ")", "event", "=", "if", "args", ".", "first", ".", "is_a?", "Symbol", "args", ".", "shift", "else", ":ready", "end", "txt", "=", "args", ".", "shift", "attributes", "=", "args", ".", "shift", "||", "{", "}", "javascript", "attributes", "do", "rawtext", "\"\\n\"", "rawtext", "\"jQuery(document).#{event}(function($){\\n\"", "rawtext", "txt", "rawtext", "\"\\n});\"", "end", "end" ]
Emits a jQuery script, inside its own script tag, that is to be run on document ready or load. Usage (from inside a widget method): jquery "alert('hi')" :: a jquery ready handler jquery "alert('hi')", :id => 'foo' :: a jquery ready handler, with attributes in the script tag jquery :load, "alert('hi')" :: a jquery load handler
[ "Emits", "a", "jQuery", "script", "inside", "its", "own", "script", "tag", "that", "is", "to", "be", "run", "on", "document", "ready", "or", "load", "." ]
59754211101b2c50a4c9daa8e64a64e6edc9e976
https://github.com/erector/erector/blob/59754211101b2c50a4c9daa8e64a64e6edc9e976/lib/erector/jquery.rb#L10-L25
train
erector/erector
lib/erector/abstract_widget.rb
Erector.AbstractWidget.capture_content
def capture_content original, @_output = output, Output.new yield original.widgets.concat(output.widgets) # todo: test!!! output.to_s ensure @_output = original end
ruby
def capture_content original, @_output = output, Output.new yield original.widgets.concat(output.widgets) # todo: test!!! output.to_s ensure @_output = original end
[ "def", "capture_content", "original", ",", "@_output", "=", "output", ",", "Output", ".", "new", "yield", "original", ".", "widgets", ".", "concat", "(", "output", ".", "widgets", ")", "output", ".", "to_s", "ensure", "@_output", "=", "original", "end" ]
Creates a whole new output string, executes the block, then converts the output string to a string and returns it as raw text. If at all possible you should avoid this method since it hurts performance, and use +widget+ instead.
[ "Creates", "a", "whole", "new", "output", "string", "executes", "the", "block", "then", "converts", "the", "output", "string", "to", "a", "string", "and", "returns", "it", "as", "raw", "text", ".", "If", "at", "all", "possible", "you", "should", "avoid", "this", "method", "since", "it", "hurts", "performance", "and", "use", "+", "widget", "+", "instead", "." ]
59754211101b2c50a4c9daa8e64a64e6edc9e976
https://github.com/erector/erector/blob/59754211101b2c50a4c9daa8e64a64e6edc9e976/lib/erector/abstract_widget.rb#L176-L183
train
erector/erector
lib/erector/abstract_widget.rb
Erector.AbstractWidget._emit_via
def _emit_via(parent, options = {}, &block) _emit(options.merge(:parent => parent, :output => parent.output, :helpers => parent.helpers), &block) end
ruby
def _emit_via(parent, options = {}, &block) _emit(options.merge(:parent => parent, :output => parent.output, :helpers => parent.helpers), &block) end
[ "def", "_emit_via", "(", "parent", ",", "options", "=", "{", "}", ",", "&", "block", ")", "_emit", "(", "options", ".", "merge", "(", ":parent", "=>", "parent", ",", ":output", "=>", "parent", ".", "output", ",", ":helpers", "=>", "parent", ".", "helpers", ")", ",", "&", "block", ")", "end" ]
same as _emit, but using a parent widget's output stream and helpers
[ "same", "as", "_emit", "but", "using", "a", "parent", "widget", "s", "output", "stream", "and", "helpers" ]
59754211101b2c50a4c9daa8e64a64e6edc9e976
https://github.com/erector/erector/blob/59754211101b2c50a4c9daa8e64a64e6edc9e976/lib/erector/abstract_widget.rb#L210-L214
train
erector/erector
lib/erector/rails3.rb
Erector.Rails.render
def render(*args, &block) captured = helpers.capture do helpers.concat(helpers.render(*args, &block)) helpers.output_buffer.to_s end rawtext(captured) end
ruby
def render(*args, &block) captured = helpers.capture do helpers.concat(helpers.render(*args, &block)) helpers.output_buffer.to_s end rawtext(captured) end
[ "def", "render", "(", "*", "args", ",", "&", "block", ")", "captured", "=", "helpers", ".", "capture", "do", "helpers", ".", "concat", "(", "helpers", ".", "render", "(", "*", "args", ",", "&", "block", ")", ")", "helpers", ".", "output_buffer", ".", "to_s", "end", "rawtext", "(", "captured", ")", "end" ]
Wrap Rails' render method, to capture output from partials etc.
[ "Wrap", "Rails", "render", "method", "to", "capture", "output", "from", "partials", "etc", "." ]
59754211101b2c50a4c9daa8e64a64e6edc9e976
https://github.com/erector/erector/blob/59754211101b2c50a4c9daa8e64a64e6edc9e976/lib/erector/rails3.rb#L115-L121
train
erector/erector
lib/erector/rails3.rb
Erector.Rails.content_for
def content_for(*args,&block) if block helpers.content_for(*args,&block) else rawtext(helpers.content_for(*args)) '' end end
ruby
def content_for(*args,&block) if block helpers.content_for(*args,&block) else rawtext(helpers.content_for(*args)) '' end end
[ "def", "content_for", "(", "*", "args", ",", "&", "block", ")", "if", "block", "helpers", ".", "content_for", "(", "*", "args", ",", "&", "block", ")", "else", "rawtext", "(", "helpers", ".", "content_for", "(", "*", "args", ")", ")", "''", "end", "end" ]
Rails content_for is output if and only if no block given
[ "Rails", "content_for", "is", "output", "if", "and", "only", "if", "no", "block", "given" ]
59754211101b2c50a4c9daa8e64a64e6edc9e976
https://github.com/erector/erector/blob/59754211101b2c50a4c9daa8e64a64e6edc9e976/lib/erector/rails3.rb#L124-L131
train
erector/erector
lib/erector/text.rb
Erector.Text.character
def character(code_point_or_name) if code_point_or_name.is_a?(Symbol) require "erector/unicode" found = Erector::CHARACTERS[code_point_or_name] if found.nil? raise "Unrecognized character #{code_point_or_name}" end raw("&#x#{sprintf '%x', found};") elsif code_point_or_name.is_a?(Integer) raw("&#x#{sprintf '%x', code_point_or_name};") else raise "Unrecognized argument to character: #{code_point_or_name}" end end
ruby
def character(code_point_or_name) if code_point_or_name.is_a?(Symbol) require "erector/unicode" found = Erector::CHARACTERS[code_point_or_name] if found.nil? raise "Unrecognized character #{code_point_or_name}" end raw("&#x#{sprintf '%x', found};") elsif code_point_or_name.is_a?(Integer) raw("&#x#{sprintf '%x', code_point_or_name};") else raise "Unrecognized argument to character: #{code_point_or_name}" end end
[ "def", "character", "(", "code_point_or_name", ")", "if", "code_point_or_name", ".", "is_a?", "(", "Symbol", ")", "require", "\"erector/unicode\"", "found", "=", "Erector", "::", "CHARACTERS", "[", "code_point_or_name", "]", "if", "found", ".", "nil?", "raise", "\"Unrecognized character #{code_point_or_name}\"", "end", "raw", "(", "\"&#x#{sprintf '%x', found};\"", ")", "elsif", "code_point_or_name", ".", "is_a?", "(", "Integer", ")", "raw", "(", "\"&#x#{sprintf '%x', code_point_or_name};\"", ")", "else", "raise", "\"Unrecognized argument to character: #{code_point_or_name}\"", "end", "end" ]
Return a character given its unicode code point or unicode name.
[ "Return", "a", "character", "given", "its", "unicode", "code", "point", "or", "unicode", "name", "." ]
59754211101b2c50a4c9daa8e64a64e6edc9e976
https://github.com/erector/erector/blob/59754211101b2c50a4c9daa8e64a64e6edc9e976/lib/erector/text.rb#L107-L120
train
hcatlin/make_resourceful
lib/resourceful/response.rb
Resourceful.Response.method_missing
def method_missing(name, &block) @formats.push([name, block || proc {}]) unless @formats.any? {|n,b| n == name} end
ruby
def method_missing(name, &block) @formats.push([name, block || proc {}]) unless @formats.any? {|n,b| n == name} end
[ "def", "method_missing", "(", "name", ",", "&", "block", ")", "@formats", ".", "push", "(", "[", "name", ",", "block", "||", "proc", "{", "}", "]", ")", "unless", "@formats", ".", "any?", "{", "|", "n", ",", "b", "|", "n", "==", "name", "}", "end" ]
Returns a new Response with no format data. Used to dispatch the individual format methods.
[ "Returns", "a", "new", "Response", "with", "no", "format", "data", ".", "Used", "to", "dispatch", "the", "individual", "format", "methods", "." ]
138455b3650917ffdf31dfee4ef9d4aff3f47b06
https://github.com/hcatlin/make_resourceful/blob/138455b3650917ffdf31dfee4ef9d4aff3f47b06/lib/resourceful/response.rb#L29-L31
train
raw1z/amistad
lib/amistad/active_record_friendship_model.rb
Amistad.ActiveRecordFriendshipModel.can_block?
def can_block?(friendable) active? && (approved? || (pending? && self.friend_id == friendable.id && friendable.class.to_s == Amistad.friend_model)) end
ruby
def can_block?(friendable) active? && (approved? || (pending? && self.friend_id == friendable.id && friendable.class.to_s == Amistad.friend_model)) end
[ "def", "can_block?", "(", "friendable", ")", "active?", "&&", "(", "approved?", "||", "(", "pending?", "&&", "self", ".", "friend_id", "==", "friendable", ".", "id", "&&", "friendable", ".", "class", ".", "to_s", "==", "Amistad", ".", "friend_model", ")", ")", "end" ]
returns true if a friendship can be blocked by given friendable
[ "returns", "true", "if", "a", "friendship", "can", "be", "blocked", "by", "given", "friendable" ]
3da822509611450e4777f6571ea0967fd5bf6602
https://github.com/raw1z/amistad/blob/3da822509611450e4777f6571ea0967fd5bf6602/lib/amistad/active_record_friendship_model.rb#L43-L45
train
raw1z/amistad
lib/amistad/active_record_friendship_model.rb
Amistad.ActiveRecordFriendshipModel.can_unblock?
def can_unblock?(friendable) blocked? && self.blocker_id == friendable.id && friendable.class.to_s == Amistad.friend_model end
ruby
def can_unblock?(friendable) blocked? && self.blocker_id == friendable.id && friendable.class.to_s == Amistad.friend_model end
[ "def", "can_unblock?", "(", "friendable", ")", "blocked?", "&&", "self", ".", "blocker_id", "==", "friendable", ".", "id", "&&", "friendable", ".", "class", ".", "to_s", "==", "Amistad", ".", "friend_model", "end" ]
returns true if a friendship can be unblocked by given friendable
[ "returns", "true", "if", "a", "friendship", "can", "be", "unblocked", "by", "given", "friendable" ]
3da822509611450e4777f6571ea0967fd5bf6602
https://github.com/raw1z/amistad/blob/3da822509611450e4777f6571ea0967fd5bf6602/lib/amistad/active_record_friendship_model.rb#L48-L50
train
rktjmp/tileup
lib/tileup/logger.rb
TileUp.TileUpLogger.add
def add(severity, message) severity = TileUpLogger.sym_to_severity(severity) logger.add(severity, message) end
ruby
def add(severity, message) severity = TileUpLogger.sym_to_severity(severity) logger.add(severity, message) end
[ "def", "add", "(", "severity", ",", "message", ")", "severity", "=", "TileUpLogger", ".", "sym_to_severity", "(", "severity", ")", "logger", ".", "add", "(", "severity", ",", "message", ")", "end" ]
add message to log
[ "add", "message", "to", "log" ]
5002151f8603ea5d4af76892081af85d9deff9fb
https://github.com/rktjmp/tileup/blob/5002151f8603ea5d4af76892081af85d9deff9fb/lib/tileup/logger.rb#L62-L65
train
cloudfoundry-community/bosh-gen
lib/bosh/gen/bosh-config.rb
Bosh::Cli.Config.deployment
def deployment return nil if target.nil? if @config_file.has_key?("deployment") if is_old_deployment_config? set_deployment(@config_file["deployment"]) save end if @config_file["deployment"].is_a?(Hash) return @config_file["deployment"][target] end end end
ruby
def deployment return nil if target.nil? if @config_file.has_key?("deployment") if is_old_deployment_config? set_deployment(@config_file["deployment"]) save end if @config_file["deployment"].is_a?(Hash) return @config_file["deployment"][target] end end end
[ "def", "deployment", "return", "nil", "if", "target", ".", "nil?", "if", "@config_file", ".", "has_key?", "(", "\"deployment\"", ")", "if", "is_old_deployment_config?", "set_deployment", "(", "@config_file", "[", "\"deployment\"", "]", ")", "save", "end", "if", "@config_file", "[", "\"deployment\"", "]", ".", "is_a?", "(", "Hash", ")", "return", "@config_file", "[", "\"deployment\"", "]", "[", "target", "]", "end", "end", "end" ]
Read the deployment configuration. Return the deployment for the current target. @return [String?] The deployment path for the current target.
[ "Read", "the", "deployment", "configuration", ".", "Return", "the", "deployment", "for", "the", "current", "target", "." ]
73022585f762fa75f021bfd35b2e3f9096c99c74
https://github.com/cloudfoundry-community/bosh-gen/blob/73022585f762fa75f021bfd35b2e3f9096c99c74/lib/bosh/gen/bosh-config.rb#L151-L162
train
hcatlin/make_resourceful
lib/resourceful/builder.rb
Resourceful.Builder.apply
def apply apply_publish kontroller = @controller Resourceful::ACTIONS.each do |action_named| # See if this is a method listed by #actions unless @ok_actions.include? action_named # If its not listed, then remove the method # No one can hit it... if its DEAD! @action_module.send :remove_method, action_named end end kontroller.hidden_actions.reject! &@ok_actions.method(:include?) kontroller.send :include, @action_module merged_callbacks = kontroller.resourceful_callbacks.merge @callbacks merged_responses = kontroller.resourceful_responses.merge @responses kontroller.resourceful_callbacks = merged_callbacks kontroller.resourceful_responses = merged_responses kontroller.made_resourceful = true kontroller.parents = @parents kontroller.shallow_parent = @shallow_parent kontroller.model_namespace = @model_namespace kontroller.before_filter :load_object, :only => (@ok_actions & SINGULAR_PRELOADED_ACTIONS) + @custom_member_actions kontroller.before_filter :load_objects, :only => (@ok_actions & PLURAL_ACTIONS) + @custom_collection_actions kontroller.before_filter :load_parent_object, :only => @ok_actions + @custom_member_actions + @custom_collection_actions end
ruby
def apply apply_publish kontroller = @controller Resourceful::ACTIONS.each do |action_named| # See if this is a method listed by #actions unless @ok_actions.include? action_named # If its not listed, then remove the method # No one can hit it... if its DEAD! @action_module.send :remove_method, action_named end end kontroller.hidden_actions.reject! &@ok_actions.method(:include?) kontroller.send :include, @action_module merged_callbacks = kontroller.resourceful_callbacks.merge @callbacks merged_responses = kontroller.resourceful_responses.merge @responses kontroller.resourceful_callbacks = merged_callbacks kontroller.resourceful_responses = merged_responses kontroller.made_resourceful = true kontroller.parents = @parents kontroller.shallow_parent = @shallow_parent kontroller.model_namespace = @model_namespace kontroller.before_filter :load_object, :only => (@ok_actions & SINGULAR_PRELOADED_ACTIONS) + @custom_member_actions kontroller.before_filter :load_objects, :only => (@ok_actions & PLURAL_ACTIONS) + @custom_collection_actions kontroller.before_filter :load_parent_object, :only => @ok_actions + @custom_member_actions + @custom_collection_actions end
[ "def", "apply", "apply_publish", "kontroller", "=", "@controller", "Resourceful", "::", "ACTIONS", ".", "each", "do", "|", "action_named", "|", "unless", "@ok_actions", ".", "include?", "action_named", "@action_module", ".", "send", ":remove_method", ",", "action_named", "end", "end", "kontroller", ".", "hidden_actions", ".", "reject!", "&", "@ok_actions", ".", "method", "(", ":include?", ")", "kontroller", ".", "send", ":include", ",", "@action_module", "merged_callbacks", "=", "kontroller", ".", "resourceful_callbacks", ".", "merge", "@callbacks", "merged_responses", "=", "kontroller", ".", "resourceful_responses", ".", "merge", "@responses", "kontroller", ".", "resourceful_callbacks", "=", "merged_callbacks", "kontroller", ".", "resourceful_responses", "=", "merged_responses", "kontroller", ".", "made_resourceful", "=", "true", "kontroller", ".", "parents", "=", "@parents", "kontroller", ".", "shallow_parent", "=", "@shallow_parent", "kontroller", ".", "model_namespace", "=", "@model_namespace", "kontroller", ".", "before_filter", ":load_object", ",", ":only", "=>", "(", "@ok_actions", "&", "SINGULAR_PRELOADED_ACTIONS", ")", "+", "@custom_member_actions", "kontroller", ".", "before_filter", ":load_objects", ",", ":only", "=>", "(", "@ok_actions", "&", "PLURAL_ACTIONS", ")", "+", "@custom_collection_actions", "kontroller", ".", "before_filter", ":load_parent_object", ",", ":only", "=>", "@ok_actions", "+", "@custom_member_actions", "+", "@custom_collection_actions", "end" ]
The constructor is only meant to be called internally. This takes the klass (class object) of a controller and constructs a Builder ready to apply the make_resourceful additions to the controller. This method is only meant to be called internally. Applies all the changes that have been declared via the instance methods of this Builder to the kontroller passed in to the constructor.
[ "The", "constructor", "is", "only", "meant", "to", "be", "called", "internally", "." ]
138455b3650917ffdf31dfee4ef9d4aff3f47b06
https://github.com/hcatlin/make_resourceful/blob/138455b3650917ffdf31dfee4ef9d4aff3f47b06/lib/resourceful/builder.rb#L40-L70
train
hcatlin/make_resourceful
lib/resourceful/builder.rb
Resourceful.Builder.belongs_to
def belongs_to(*parents) options = parents.extract_options! @parents = parents.map(&:to_s) if options[:shallow] options[:shallow] = options[:shallow].to_s raise ArgumentError, ":shallow needs the name of a parent resource" unless @parents.include? options[:shallow] @shallow_parent = options[:shallow] end end
ruby
def belongs_to(*parents) options = parents.extract_options! @parents = parents.map(&:to_s) if options[:shallow] options[:shallow] = options[:shallow].to_s raise ArgumentError, ":shallow needs the name of a parent resource" unless @parents.include? options[:shallow] @shallow_parent = options[:shallow] end end
[ "def", "belongs_to", "(", "*", "parents", ")", "options", "=", "parents", ".", "extract_options!", "@parents", "=", "parents", ".", "map", "(", "&", ":to_s", ")", "if", "options", "[", ":shallow", "]", "options", "[", ":shallow", "]", "=", "options", "[", ":shallow", "]", ".", "to_s", "raise", "ArgumentError", ",", "\":shallow needs the name of a parent resource\"", "unless", "@parents", ".", "include?", "options", "[", ":shallow", "]", "@shallow_parent", "=", "options", "[", ":shallow", "]", "end", "end" ]
Specifies parent resources for the current resource. Each of these parents will be loaded automatically if the proper id parameter is given. For example, # cake_controller.rb belongs_to :baker, :customer Then on GET /bakers/12/cakes, params[:baker_id] #=> 12 parent? #=> true parent_name #=> "baker" parent_model #=> Baker parent_object #=> Baker.find(12) current_objects #=> Baker.find(12).cakes
[ "Specifies", "parent", "resources", "for", "the", "current", "resource", ".", "Each", "of", "these", "parents", "will", "be", "loaded", "automatically", "if", "the", "proper", "id", "parameter", "is", "given", ".", "For", "example" ]
138455b3650917ffdf31dfee4ef9d4aff3f47b06
https://github.com/hcatlin/make_resourceful/blob/138455b3650917ffdf31dfee4ef9d4aff3f47b06/lib/resourceful/builder.rb#L364-L372
train
raw1z/amistad
lib/amistad/mongo_friend_model.rb
Amistad.MongoFriendModel.blocked?
def blocked?(user) (blocked_friend_ids + blocked_inverse_friend_ids + blocked_pending_inverse_friend_ids).include?(user.id) or user.blocked_pending_inverse_friend_ids.include?(self.id) end
ruby
def blocked?(user) (blocked_friend_ids + blocked_inverse_friend_ids + blocked_pending_inverse_friend_ids).include?(user.id) or user.blocked_pending_inverse_friend_ids.include?(self.id) end
[ "def", "blocked?", "(", "user", ")", "(", "blocked_friend_ids", "+", "blocked_inverse_friend_ids", "+", "blocked_pending_inverse_friend_ids", ")", ".", "include?", "(", "user", ".", "id", ")", "or", "user", ".", "blocked_pending_inverse_friend_ids", ".", "include?", "(", "self", ".", "id", ")", "end" ]
checks if a user is blocked
[ "checks", "if", "a", "user", "is", "blocked" ]
3da822509611450e4777f6571ea0967fd5bf6602
https://github.com/raw1z/amistad/blob/3da822509611450e4777f6571ea0967fd5bf6602/lib/amistad/mongo_friend_model.rb#L146-L148
train
raw1z/amistad
lib/amistad/mongo_friend_model.rb
Amistad.MongoFriendModel.friendshiped_with?
def friendshiped_with?(user) (friend_ids + inverse_friend_ids + pending_friend_ids + pending_inverse_friend_ids + blocked_friend_ids).include?(user.id) end
ruby
def friendshiped_with?(user) (friend_ids + inverse_friend_ids + pending_friend_ids + pending_inverse_friend_ids + blocked_friend_ids).include?(user.id) end
[ "def", "friendshiped_with?", "(", "user", ")", "(", "friend_ids", "+", "inverse_friend_ids", "+", "pending_friend_ids", "+", "pending_inverse_friend_ids", "+", "blocked_friend_ids", ")", ".", "include?", "(", "user", ".", "id", ")", "end" ]
check if any friendship exists with another user
[ "check", "if", "any", "friendship", "exists", "with", "another", "user" ]
3da822509611450e4777f6571ea0967fd5bf6602
https://github.com/raw1z/amistad/blob/3da822509611450e4777f6571ea0967fd5bf6602/lib/amistad/mongo_friend_model.rb#L151-L153
train
raw1z/amistad
lib/amistad/mongo_friend_model.rb
Amistad.MongoFriendModel.delete_all_friendships
def delete_all_friendships friend_ids.clear inverse_friend_ids.clear pending_friend_ids.clear pending_inverse_friend_ids.clear blocked_friend_ids.clear blocked_inverse_friend_ids.clear blocked_pending_friend_ids.clear blocked_pending_inverse_friend_ids.clear self.save end
ruby
def delete_all_friendships friend_ids.clear inverse_friend_ids.clear pending_friend_ids.clear pending_inverse_friend_ids.clear blocked_friend_ids.clear blocked_inverse_friend_ids.clear blocked_pending_friend_ids.clear blocked_pending_inverse_friend_ids.clear self.save end
[ "def", "delete_all_friendships", "friend_ids", ".", "clear", "inverse_friend_ids", ".", "clear", "pending_friend_ids", ".", "clear", "pending_inverse_friend_ids", ".", "clear", "blocked_friend_ids", ".", "clear", "blocked_inverse_friend_ids", ".", "clear", "blocked_pending_friend_ids", ".", "clear", "blocked_pending_inverse_friend_ids", ".", "clear", "self", ".", "save", "end" ]
deletes all the friendships
[ "deletes", "all", "the", "friendships" ]
3da822509611450e4777f6571ea0967fd5bf6602
https://github.com/raw1z/amistad/blob/3da822509611450e4777f6571ea0967fd5bf6602/lib/amistad/mongo_friend_model.rb#L156-L166
train
hcatlin/make_resourceful
spec/spec_helper.rb
RailsMocks.ControllerMethods.render
def render(options=nil, deprecated_status_or_extra_options=nil, &block) if ::Rails::VERSION::STRING >= '2.0.0' && deprecated_status_or_extra_options.nil? deprecated_status_or_extra_options = {} end unless block_given? if @template.respond_to?(:finder) (class << @template.finder; self; end).class_eval do define_method :file_exists? do; true; end end else (class << @template; self; end).class_eval do define_method :file_exists? do; true; end end end (class << @template; self; end).class_eval do define_method :render_file do |*args| @first_render ||= args[0] unless args[0] =~ /^layouts/ @_first_render ||= args[0] unless args[0] =~ /^layouts/ end define_method :_pick_template do |*args| @_first_render ||= args[0] unless args[0] =~ /^layouts/ PickedTemplate.new end end end super(options, deprecated_status_or_extra_options, &block) end
ruby
def render(options=nil, deprecated_status_or_extra_options=nil, &block) if ::Rails::VERSION::STRING >= '2.0.0' && deprecated_status_or_extra_options.nil? deprecated_status_or_extra_options = {} end unless block_given? if @template.respond_to?(:finder) (class << @template.finder; self; end).class_eval do define_method :file_exists? do; true; end end else (class << @template; self; end).class_eval do define_method :file_exists? do; true; end end end (class << @template; self; end).class_eval do define_method :render_file do |*args| @first_render ||= args[0] unless args[0] =~ /^layouts/ @_first_render ||= args[0] unless args[0] =~ /^layouts/ end define_method :_pick_template do |*args| @_first_render ||= args[0] unless args[0] =~ /^layouts/ PickedTemplate.new end end end super(options, deprecated_status_or_extra_options, &block) end
[ "def", "render", "(", "options", "=", "nil", ",", "deprecated_status_or_extra_options", "=", "nil", ",", "&", "block", ")", "if", "::", "Rails", "::", "VERSION", "::", "STRING", ">=", "'2.0.0'", "&&", "deprecated_status_or_extra_options", ".", "nil?", "deprecated_status_or_extra_options", "=", "{", "}", "end", "unless", "block_given?", "if", "@template", ".", "respond_to?", "(", ":finder", ")", "(", "class", "<<", "@template", ".", "finder", ";", "self", ";", "end", ")", ".", "class_eval", "do", "define_method", ":file_exists?", "do", ";", "true", ";", "end", "end", "else", "(", "class", "<<", "@template", ";", "self", ";", "end", ")", ".", "class_eval", "do", "define_method", ":file_exists?", "do", ";", "true", ";", "end", "end", "end", "(", "class", "<<", "@template", ";", "self", ";", "end", ")", ".", "class_eval", "do", "define_method", ":render_file", "do", "|", "*", "args", "|", "@first_render", "||=", "args", "[", "0", "]", "unless", "args", "[", "0", "]", "=~", "/", "/", "@_first_render", "||=", "args", "[", "0", "]", "unless", "args", "[", "0", "]", "=~", "/", "/", "end", "define_method", ":_pick_template", "do", "|", "*", "args", "|", "@_first_render", "||=", "args", "[", "0", "]", "unless", "args", "[", "0", "]", "=~", "/", "/", "PickedTemplate", ".", "new", "end", "end", "end", "super", "(", "options", ",", "deprecated_status_or_extra_options", ",", "&", "block", ")", "end" ]
From rspec-rails ControllerExampleGroup
[ "From", "rspec", "-", "rails", "ControllerExampleGroup" ]
138455b3650917ffdf31dfee4ef9d4aff3f47b06
https://github.com/hcatlin/make_resourceful/blob/138455b3650917ffdf31dfee4ef9d4aff3f47b06/spec/spec_helper.rb#L227-L256
train
raw1z/amistad
lib/amistad/active_record_friend_model.rb
Amistad.ActiveRecordFriendModel.unblock
def unblock(user) friendship = find_any_friendship_with(user) return false if friendship.nil? || !friendship.can_unblock?(self) friendship.update_attribute(:blocker, nil) end
ruby
def unblock(user) friendship = find_any_friendship_with(user) return false if friendship.nil? || !friendship.can_unblock?(self) friendship.update_attribute(:blocker, nil) end
[ "def", "unblock", "(", "user", ")", "friendship", "=", "find_any_friendship_with", "(", "user", ")", "return", "false", "if", "friendship", ".", "nil?", "||", "!", "friendship", ".", "can_unblock?", "(", "self", ")", "friendship", ".", "update_attribute", "(", ":blocker", ",", "nil", ")", "end" ]
unblocks a friendship
[ "unblocks", "a", "friendship" ]
3da822509611450e4777f6571ea0967fd5bf6602
https://github.com/raw1z/amistad/blob/3da822509611450e4777f6571ea0967fd5bf6602/lib/amistad/active_record_friend_model.rb#L84-L88
train
raw1z/amistad
lib/amistad/active_record_friend_model.rb
Amistad.ActiveRecordFriendModel.find_any_friendship_with
def find_any_friendship_with(user) friendship = Amistad.friendship_class.where(:friendable_id => self.id, :friend_id => user.id).first if friendship.nil? friendship = Amistad.friendship_class.where(:friendable_id => user.id, :friend_id => self.id).first end friendship end
ruby
def find_any_friendship_with(user) friendship = Amistad.friendship_class.where(:friendable_id => self.id, :friend_id => user.id).first if friendship.nil? friendship = Amistad.friendship_class.where(:friendable_id => user.id, :friend_id => self.id).first end friendship end
[ "def", "find_any_friendship_with", "(", "user", ")", "friendship", "=", "Amistad", ".", "friendship_class", ".", "where", "(", ":friendable_id", "=>", "self", ".", "id", ",", ":friend_id", "=>", "user", ".", "id", ")", ".", "first", "if", "friendship", ".", "nil?", "friendship", "=", "Amistad", ".", "friendship_class", ".", "where", "(", ":friendable_id", "=>", "user", ".", "id", ",", ":friend_id", "=>", "self", ".", "id", ")", ".", "first", "end", "friendship", "end" ]
returns friendship with given user or nil
[ "returns", "friendship", "with", "given", "user", "or", "nil" ]
3da822509611450e4777f6571ea0967fd5bf6602
https://github.com/raw1z/amistad/blob/3da822509611450e4777f6571ea0967fd5bf6602/lib/amistad/active_record_friend_model.rb#L136-L142
train
Swirrl/tripod
lib/tripod/extensions/module.rb
Tripod::Extensions.Module.re_define_method
def re_define_method(name, &block) undef_method(name) if method_defined?(name) define_method(name, &block) end
ruby
def re_define_method(name, &block) undef_method(name) if method_defined?(name) define_method(name, &block) end
[ "def", "re_define_method", "(", "name", ",", "&", "block", ")", "undef_method", "(", "name", ")", "if", "method_defined?", "(", "name", ")", "define_method", "(", "name", ",", "&", "block", ")", "end" ]
Redefine the method. Will undef the method if it exists or simply just define it. @example Redefine the method. Object.re_define_method("exists?") do self end @param [ String, Symbol ] name The name of the method. @param [ Proc ] block The method body. @return [ Method ] The new method.
[ "Redefine", "the", "method", ".", "Will", "undef", "the", "method", "if", "it", "exists", "or", "simply", "just", "define", "it", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/extensions/module.rb#L17-L20
train
Swirrl/tripod
lib/tripod/rdf_type.rb
Tripod::RdfType.ClassMethods.rdf_type
def rdf_type(new_rdf_type) self._RDF_TYPE = RDF::URI.new(new_rdf_type.to_s) field :rdf_type, RDF.type, :multivalued => true, :is_uri => true # things can have more than 1 type and often do end
ruby
def rdf_type(new_rdf_type) self._RDF_TYPE = RDF::URI.new(new_rdf_type.to_s) field :rdf_type, RDF.type, :multivalued => true, :is_uri => true # things can have more than 1 type and often do end
[ "def", "rdf_type", "(", "new_rdf_type", ")", "self", ".", "_RDF_TYPE", "=", "RDF", "::", "URI", ".", "new", "(", "new_rdf_type", ".", "to_s", ")", "field", ":rdf_type", ",", "RDF", ".", "type", ",", ":multivalued", "=>", "true", ",", ":is_uri", "=>", "true", "end" ]
makes a "field" on this model called rdf_type and sets a class level _RDF_TYPE variable with the rdf_type passed in.
[ "makes", "a", "field", "on", "this", "model", "called", "rdf_type", "and", "sets", "a", "class", "level", "_RDF_TYPE", "variable", "with", "the", "rdf_type", "passed", "in", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/rdf_type.rb#L16-L19
train
xi-livecode/xi
lib/xi/pattern.rb
Xi.Pattern.p
def p(*delta, **metadata) delta = delta.compact.empty? ? @delta : delta Pattern.new(@source, delta: delta, size: @size, **@metadata.merge(metadata)) end
ruby
def p(*delta, **metadata) delta = delta.compact.empty? ? @delta : delta Pattern.new(@source, delta: delta, size: @size, **@metadata.merge(metadata)) end
[ "def", "p", "(", "*", "delta", ",", "**", "metadata", ")", "delta", "=", "delta", ".", "compact", ".", "empty?", "?", "@delta", ":", "delta", "Pattern", ".", "new", "(", "@source", ",", "delta", ":", "delta", ",", "size", ":", "@size", ",", "**", "@metadata", ".", "merge", "(", "metadata", ")", ")", "end" ]
Returns a new Pattern with the same +source+, but with +delta+ overriden and +metadata+ merged. @param delta [Array<Numeric>, Pattern<Numeric>, Numeric] @param metadata [Hash] @return [Pattern]
[ "Returns", "a", "new", "Pattern", "with", "the", "same", "+", "source", "+", "but", "with", "+", "delta", "+", "overriden", "and", "+", "metadata", "+", "merged", "." ]
215dfb84899b3dd00f11089ae3eab0febf498e95
https://github.com/xi-livecode/xi/blob/215dfb84899b3dd00f11089ae3eab0febf498e95/lib/xi/pattern.rb#L131-L134
train
xi-livecode/xi
lib/xi/pattern.rb
Xi.Pattern.each_event
def each_event(cycle=0) return enum_for(__method__, cycle) unless block_given? EventEnumerator.new(self, cycle).each { |v, s, d, i| yield v, s, d, i } end
ruby
def each_event(cycle=0) return enum_for(__method__, cycle) unless block_given? EventEnumerator.new(self, cycle).each { |v, s, d, i| yield v, s, d, i } end
[ "def", "each_event", "(", "cycle", "=", "0", ")", "return", "enum_for", "(", "__method__", ",", "cycle", ")", "unless", "block_given?", "EventEnumerator", ".", "new", "(", "self", ",", "cycle", ")", ".", "each", "{", "|", "v", ",", "s", ",", "d", ",", "i", "|", "yield", "v", ",", "s", ",", "d", ",", "i", "}", "end" ]
Calls the given block once for each event, passing its value, start position, duration and iteration as parameters. +cycle+ can be any number, even if there is no event that starts exactly at that moment. It will start from the next event. If no block is given, an enumerator is returned instead. Enumeration loops forever, and starts yielding events based on pattern's delta and from the +cycle+ position, which is by default 0. @example block yields value, start, duration and iteration Pattern.new([1, 2], delta: 0.25).each_event.take(4) # => [[1, 0.0, 0.25, 0], # [2, 0.25, 0.25, 0], # [1, 0.5, 0.25, 1], # [2, 0.75, 0.25, 1]] @example +cycle+ is used to start iterating from that moment in time Pattern.new([:a, :b, :c], delta: 1/2).each_event(42).take(4) # => [[:a, (42/1), (1/2), 28], # [:b, (85/2), (1/2), 28], # [:c, (43/1), (1/2), 28], # [:a, (87/2), (1/2), 29]] @example +cycle+ can also be a fractional number Pattern.new([:a, :b, :c]).each_event(0.97).take(3) # => [[:b, 1, 1, 0], # [:c, 2, 1, 0], # [:a, 3, 1, 1]] @param cycle [Numeric] @yield [v, s, d, i] value, start, duration and iteration @return [Enumerator]
[ "Calls", "the", "given", "block", "once", "for", "each", "event", "passing", "its", "value", "start", "position", "duration", "and", "iteration", "as", "parameters", "." ]
215dfb84899b3dd00f11089ae3eab0febf498e95
https://github.com/xi-livecode/xi/blob/215dfb84899b3dd00f11089ae3eab0febf498e95/lib/xi/pattern.rb#L194-L197
train
xi-livecode/xi
lib/xi/pattern.rb
Xi.Pattern.each_delta
def each_delta(index=0) return enum_for(__method__, index) unless block_given? delta = @delta if delta.is_a?(Array) size = delta.size return if size == 0 start = index.floor i = start % size loop do yield delta[i] i = (i + 1) % size start += 1 end elsif delta.is_a?(Pattern) delta.each_event(index) { |v, _| yield v } else loop { yield delta } end end
ruby
def each_delta(index=0) return enum_for(__method__, index) unless block_given? delta = @delta if delta.is_a?(Array) size = delta.size return if size == 0 start = index.floor i = start % size loop do yield delta[i] i = (i + 1) % size start += 1 end elsif delta.is_a?(Pattern) delta.each_event(index) { |v, _| yield v } else loop { yield delta } end end
[ "def", "each_delta", "(", "index", "=", "0", ")", "return", "enum_for", "(", "__method__", ",", "index", ")", "unless", "block_given?", "delta", "=", "@delta", "if", "delta", ".", "is_a?", "(", "Array", ")", "size", "=", "delta", ".", "size", "return", "if", "size", "==", "0", "start", "=", "index", ".", "floor", "i", "=", "start", "%", "size", "loop", "do", "yield", "delta", "[", "i", "]", "i", "=", "(", "i", "+", "1", ")", "%", "size", "start", "+=", "1", "end", "elsif", "delta", ".", "is_a?", "(", "Pattern", ")", "delta", ".", "each_event", "(", "index", ")", "{", "|", "v", ",", "_", "|", "yield", "v", "}", "else", "loop", "{", "yield", "delta", "}", "end", "end" ]
Calls the given block passing the delta of each value in pattern This method is used internally by {#each_event} to calculate when each event in pattern occurs in time. If no block is given, an Enumerator is returned instead. @param index [Numeric] @yield [d] duration @return [Enumerator]
[ "Calls", "the", "given", "block", "passing", "the", "delta", "of", "each", "value", "in", "pattern" ]
215dfb84899b3dd00f11089ae3eab0febf498e95
https://github.com/xi-livecode/xi/blob/215dfb84899b3dd00f11089ae3eab0febf498e95/lib/xi/pattern.rb#L209-L230
train
xi-livecode/xi
lib/xi/pattern.rb
Xi.Pattern.each
def each return enum_for(__method__) unless block_given? each_event { |v, _, _, i| break if i > 0 yield v } end
ruby
def each return enum_for(__method__) unless block_given? each_event { |v, _, _, i| break if i > 0 yield v } end
[ "def", "each", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "each_event", "{", "|", "v", ",", "_", ",", "_", ",", "i", "|", "break", "if", "i", ">", "0", "yield", "v", "}", "end" ]
Calls the given block once for each value in source @example Pattern.new([1, 2, 3]).each.to_a # => [1, 2, 3] @return [Enumerator] @yield [Object] value
[ "Calls", "the", "given", "block", "once", "for", "each", "value", "in", "source" ]
215dfb84899b3dd00f11089ae3eab0febf498e95
https://github.com/xi-livecode/xi/blob/215dfb84899b3dd00f11089ae3eab0febf498e95/lib/xi/pattern.rb#L241-L248
train
xi-livecode/xi
lib/xi/pattern.rb
Xi.Pattern.select
def select return enum_for(__method__) unless block_given? Pattern.new(self) do |y, d| each_event do |v, s, ed, i| y << v if yield(v, s, ed, i) end end end
ruby
def select return enum_for(__method__) unless block_given? Pattern.new(self) do |y, d| each_event do |v, s, ed, i| y << v if yield(v, s, ed, i) end end end
[ "def", "select", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "Pattern", ".", "new", "(", "self", ")", "do", "|", "y", ",", "d", "|", "each_event", "do", "|", "v", ",", "s", ",", "ed", ",", "i", "|", "y", "<<", "v", "if", "yield", "(", "v", ",", "s", ",", "ed", ",", "i", ")", "end", "end", "end" ]
Returns a Pattern containing all events of +self+ for which +block+ is true. If no block is given, an Enumerator is returned. @see Pattern#reject @yield [v, s, d, i] value, start, duration and iteration @yieldreturn [Boolean] whether value is selected @return [Pattern]
[ "Returns", "a", "Pattern", "containing", "all", "events", "of", "+", "self", "+", "for", "which", "+", "block", "+", "is", "true", "." ]
215dfb84899b3dd00f11089ae3eab0febf498e95
https://github.com/xi-livecode/xi/blob/215dfb84899b3dd00f11089ae3eab0febf498e95/lib/xi/pattern.rb#L318-L326
train
xi-livecode/xi
lib/xi/pattern.rb
Xi.Pattern.reject
def reject return enum_for(__method__) unless block_given? select { |v, s, d, i| !yield(v, s, d, i) } end
ruby
def reject return enum_for(__method__) unless block_given? select { |v, s, d, i| !yield(v, s, d, i) } end
[ "def", "reject", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "select", "{", "|", "v", ",", "s", ",", "d", ",", "i", "|", "!", "yield", "(", "v", ",", "s", ",", "d", ",", "i", ")", "}", "end" ]
Returns a Pattern containing all events of +self+ for which +block+ is false. If no block is given, an Enumerator is returned. @see Pattern#select @yield [v, s, d, i] value, start, duration and iteration @yieldreturn [Boolean] whether event is rejected @return [Pattern]
[ "Returns", "a", "Pattern", "containing", "all", "events", "of", "+", "self", "+", "for", "which", "+", "block", "+", "is", "false", "." ]
215dfb84899b3dd00f11089ae3eab0febf498e95
https://github.com/xi-livecode/xi/blob/215dfb84899b3dd00f11089ae3eab0febf498e95/lib/xi/pattern.rb#L340-L344
train
xi-livecode/xi
lib/xi/pattern.rb
Xi.Pattern.first
def first(n=nil, *args) res = take(n || 1, *args) n.nil? ? res.first : res end
ruby
def first(n=nil, *args) res = take(n || 1, *args) n.nil? ? res.first : res end
[ "def", "first", "(", "n", "=", "nil", ",", "*", "args", ")", "res", "=", "take", "(", "n", "||", "1", ",", "*", "args", ")", "n", ".", "nil?", "?", "res", ".", "first", ":", "res", "end" ]
Returns the first element, or the first +n+ elements, of the pattern. If the pattern is empty, the first form returns nil, and the second form returns an empty array. @see #take @param n [Integer] @param args same arguments as {#take} @return [Object, Array]
[ "Returns", "the", "first", "element", "or", "the", "first", "+", "n", "+", "elements", "of", "the", "pattern", "." ]
215dfb84899b3dd00f11089ae3eab0febf498e95
https://github.com/xi-livecode/xi/blob/215dfb84899b3dd00f11089ae3eab0febf498e95/lib/xi/pattern.rb#L387-L390
train
xi-livecode/xi
lib/xi/pattern.rb
Xi.Pattern.inspect
def inspect ss = if @source.respond_to?(:join) @source.map(&:inspect).join(', ') elsif @source.is_a?(Proc) "?proc" else @source.inspect end ms = @metadata.reject { |_, v| v.nil? } ms.merge!(delta: delta) if delta != 1 ms = ms.map { |k, v| "#{k}: #{v.inspect}" }.join(', ') "P[#{ss}#{", #{ms}" unless ms.empty?}]" end
ruby
def inspect ss = if @source.respond_to?(:join) @source.map(&:inspect).join(', ') elsif @source.is_a?(Proc) "?proc" else @source.inspect end ms = @metadata.reject { |_, v| v.nil? } ms.merge!(delta: delta) if delta != 1 ms = ms.map { |k, v| "#{k}: #{v.inspect}" }.join(', ') "P[#{ss}#{", #{ms}" unless ms.empty?}]" end
[ "def", "inspect", "ss", "=", "if", "@source", ".", "respond_to?", "(", ":join", ")", "@source", ".", "map", "(", "&", ":inspect", ")", ".", "join", "(", "', '", ")", "elsif", "@source", ".", "is_a?", "(", "Proc", ")", "\"?proc\"", "else", "@source", ".", "inspect", "end", "ms", "=", "@metadata", ".", "reject", "{", "|", "_", ",", "v", "|", "v", ".", "nil?", "}", "ms", ".", "merge!", "(", "delta", ":", "delta", ")", "if", "delta", "!=", "1", "ms", "=", "ms", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{k}: #{v.inspect}\"", "}", ".", "join", "(", "', '", ")", "\"P[#{ss}#{\", #{ms}\" unless ms.empty?}]\"", "end" ]
Returns a string containing a human-readable representation When source is not a Proc, this string can be evaluated to construct the same instance. @return [String]
[ "Returns", "a", "string", "containing", "a", "human", "-", "readable", "representation" ]
215dfb84899b3dd00f11089ae3eab0febf498e95
https://github.com/xi-livecode/xi/blob/215dfb84899b3dd00f11089ae3eab0febf498e95/lib/xi/pattern.rb#L399-L413
train
Swirrl/tripod
lib/tripod/fields.rb
Tripod::Fields.ClassMethods.get_field
def get_field(name) @fields ||= {} field = fields[name] raise Tripod::Errors::FieldNotPresent.new unless field field end
ruby
def get_field(name) @fields ||= {} field = fields[name] raise Tripod::Errors::FieldNotPresent.new unless field field end
[ "def", "get_field", "(", "name", ")", "@fields", "||=", "{", "}", "field", "=", "fields", "[", "name", "]", "raise", "Tripod", "::", "Errors", "::", "FieldNotPresent", ".", "new", "unless", "field", "field", "end" ]
Return the field object on a +Resource+ associated with the given name. @example Get the field. Person.get_field(:name) @param [ Symbol ] name The name of the field.
[ "Return", "the", "field", "object", "on", "a", "+", "Resource", "+", "associated", "with", "the", "given", "name", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/fields.rb#L56-L61
train
Swirrl/tripod
lib/tripod/fields.rb
Tripod::Fields.ClassMethods.fields
def fields tripod_superclasses.map { |c| c.instance_variable_get(:@fields) }.reduce do |acc,class_fields| class_fields.merge(acc) end end
ruby
def fields tripod_superclasses.map { |c| c.instance_variable_get(:@fields) }.reduce do |acc,class_fields| class_fields.merge(acc) end end
[ "def", "fields", "tripod_superclasses", ".", "map", "{", "|", "c", "|", "c", ".", "instance_variable_get", "(", ":@fields", ")", "}", ".", "reduce", "do", "|", "acc", ",", "class_fields", "|", "class_fields", ".", "merge", "(", "acc", ")", "end", "end" ]
Return all of the fields on a +Resource+ in a manner that respects Ruby's inheritance rules. i.e. subclass fields should override superclass fields with the same
[ "Return", "all", "of", "the", "fields", "on", "a", "+", "Resource", "+", "in", "a", "manner", "that", "respects", "Ruby", "s", "inheritance", "rules", ".", "i", ".", "e", ".", "subclass", "fields", "should", "override", "superclass", "fields", "with", "the", "same" ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/fields.rb#L66-L70
train
Swirrl/tripod
lib/tripod/fields.rb
Tripod::Fields.ClassMethods.add_field
def add_field(name, predicate, options = {}) # create a field object and store it in our hash field = field_for(name, predicate, options) @fields ||= {} @fields[name] = field # set up the accessors for the fields create_accessors(name, name, options) # create a URL validation if appropriate # (format nabbed from https://gist.github.com/joshuap/948880) validates(name, is_url: true) if field.is_uri? field end
ruby
def add_field(name, predicate, options = {}) # create a field object and store it in our hash field = field_for(name, predicate, options) @fields ||= {} @fields[name] = field # set up the accessors for the fields create_accessors(name, name, options) # create a URL validation if appropriate # (format nabbed from https://gist.github.com/joshuap/948880) validates(name, is_url: true) if field.is_uri? field end
[ "def", "add_field", "(", "name", ",", "predicate", ",", "options", "=", "{", "}", ")", "field", "=", "field_for", "(", "name", ",", "predicate", ",", "options", ")", "@fields", "||=", "{", "}", "@fields", "[", "name", "]", "=", "field", "create_accessors", "(", "name", ",", "name", ",", "options", ")", "validates", "(", "name", ",", "is_url", ":", "true", ")", "if", "field", ".", "is_uri?", "field", "end" ]
Define a field attribute for the +Resource+. @example Set the field. Person.add_field(:name, 'http://myfield') @param [ Symbol ] name The name of the field. @param [ String, RDF::URI ] predicate The predicate for the field. @param [ Hash ] options The hash of options.
[ "Define", "a", "field", "attribute", "for", "the", "+", "Resource", "+", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/fields.rb#L86-L100
train
Swirrl/tripod
lib/tripod/fields.rb
Tripod::Fields.ClassMethods.create_accessors
def create_accessors(name, meth, options = {}) field = @fields[name] create_field_getter(name, meth, field) create_field_setter(name, meth, field) create_field_check(name, meth, field) # from dirty.rb create_dirty_methods(name, meth) end
ruby
def create_accessors(name, meth, options = {}) field = @fields[name] create_field_getter(name, meth, field) create_field_setter(name, meth, field) create_field_check(name, meth, field) # from dirty.rb create_dirty_methods(name, meth) end
[ "def", "create_accessors", "(", "name", ",", "meth", ",", "options", "=", "{", "}", ")", "field", "=", "@fields", "[", "name", "]", "create_field_getter", "(", "name", ",", "meth", ",", "field", ")", "create_field_setter", "(", "name", ",", "meth", ",", "field", ")", "create_field_check", "(", "name", ",", "meth", ",", "field", ")", "create_dirty_methods", "(", "name", ",", "meth", ")", "end" ]
Create the field accessors. @example Generate the accessors. Person.create_accessors(:name, "name") person.name #=> returns the field person.name = "" #=> sets the field person.name? #=> Is the field present? @param [ Symbol ] name The name of the field. @param [ Symbol ] meth The name of the accessor. @param [ Hash ] options The options.
[ "Create", "the", "field", "accessors", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/fields.rb#L113-L122
train
Swirrl/tripod
lib/tripod/fields.rb
Tripod::Fields.ClassMethods.create_field_getter
def create_field_getter(name, meth, field) generated_methods.module_eval do re_define_method(meth) do read_attribute(name, field) end end end
ruby
def create_field_getter(name, meth, field) generated_methods.module_eval do re_define_method(meth) do read_attribute(name, field) end end end
[ "def", "create_field_getter", "(", "name", ",", "meth", ",", "field", ")", "generated_methods", ".", "module_eval", "do", "re_define_method", "(", "meth", ")", "do", "read_attribute", "(", "name", ",", "field", ")", "end", "end", "end" ]
Create the getter method for the provided field. @example Create the getter. Model.create_field_getter("name", "name", field) @param [ String ] name The name of the attribute. @param [ String ] meth The name of the method. @param [ Field ] field The field.
[ "Create", "the", "getter", "method", "for", "the", "provided", "field", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/fields.rb#L132-L138
train
Swirrl/tripod
lib/tripod/fields.rb
Tripod::Fields.ClassMethods.create_field_setter
def create_field_setter(name, meth, field) generated_methods.module_eval do re_define_method("#{meth}=") do |value| write_attribute(name, value, field) end end end
ruby
def create_field_setter(name, meth, field) generated_methods.module_eval do re_define_method("#{meth}=") do |value| write_attribute(name, value, field) end end end
[ "def", "create_field_setter", "(", "name", ",", "meth", ",", "field", ")", "generated_methods", ".", "module_eval", "do", "re_define_method", "(", "\"#{meth}=\"", ")", "do", "|", "value", "|", "write_attribute", "(", "name", ",", "value", ",", "field", ")", "end", "end", "end" ]
Create the setter method for the provided field. @example Create the setter. Model.create_field_setter("name", "name") @param [ String ] name The name of the attribute. @param [ String ] meth The name of the method. @param [ Field ] field The field.
[ "Create", "the", "setter", "method", "for", "the", "provided", "field", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/fields.rb#L148-L154
train
Swirrl/tripod
lib/tripod/fields.rb
Tripod::Fields.ClassMethods.create_field_check
def create_field_check(name, meth, field) generated_methods.module_eval do re_define_method("#{meth}?") do attr = read_attribute(name, field) attr == true || attr.present? end end end
ruby
def create_field_check(name, meth, field) generated_methods.module_eval do re_define_method("#{meth}?") do attr = read_attribute(name, field) attr == true || attr.present? end end end
[ "def", "create_field_check", "(", "name", ",", "meth", ",", "field", ")", "generated_methods", ".", "module_eval", "do", "re_define_method", "(", "\"#{meth}?\"", ")", "do", "attr", "=", "read_attribute", "(", "name", ",", "field", ")", "attr", "==", "true", "||", "attr", ".", "present?", "end", "end", "end" ]
Create the check method for the provided field. @example Create the check. Model.create_field_check("name", "name") @param [ String ] name The name of the attribute. @param [ String ] meth The name of the method.
[ "Create", "the", "check", "method", "for", "the", "provided", "field", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/fields.rb#L163-L170
train
Swirrl/tripod
lib/tripod/fields.rb
Tripod::Fields.ClassMethods.field_for
def field_for(name, predicate, options) Tripod::Fields::Standard.new(name, predicate, options) end
ruby
def field_for(name, predicate, options) Tripod::Fields::Standard.new(name, predicate, options) end
[ "def", "field_for", "(", "name", ",", "predicate", ",", "options", ")", "Tripod", "::", "Fields", "::", "Standard", ".", "new", "(", "name", ",", "predicate", ",", "options", ")", "end" ]
instantiates and returns a new standard field
[ "instantiates", "and", "returns", "a", "new", "standard", "field" ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/fields.rb#L188-L190
train
Swirrl/tripod
lib/tripod/finders.rb
Tripod::Finders.ClassMethods.describe_uris
def describe_uris(uris) graph = RDF::Graph.new if uris.length > 0 uris_sparql_str = uris.map{ |u| "<#{u.to_s}>" }.join(" ") # Do a big describe statement, and read the results into an in-memory repo ntriples_string = Tripod::SparqlClient::Query.query("CONSTRUCT { ?s ?p ?o } WHERE { VALUES ?s { #{uris_sparql_str} }. ?s ?p ?o . }", Tripod.ntriples_header_str) graph = _rdf_graph_from_ntriples_string(ntriples_string, graph) end graph end
ruby
def describe_uris(uris) graph = RDF::Graph.new if uris.length > 0 uris_sparql_str = uris.map{ |u| "<#{u.to_s}>" }.join(" ") # Do a big describe statement, and read the results into an in-memory repo ntriples_string = Tripod::SparqlClient::Query.query("CONSTRUCT { ?s ?p ?o } WHERE { VALUES ?s { #{uris_sparql_str} }. ?s ?p ?o . }", Tripod.ntriples_header_str) graph = _rdf_graph_from_ntriples_string(ntriples_string, graph) end graph end
[ "def", "describe_uris", "(", "uris", ")", "graph", "=", "RDF", "::", "Graph", ".", "new", "if", "uris", ".", "length", ">", "0", "uris_sparql_str", "=", "uris", ".", "map", "{", "|", "u", "|", "\"<#{u.to_s}>\"", "}", ".", "join", "(", "\" \"", ")", "ntriples_string", "=", "Tripod", "::", "SparqlClient", "::", "Query", ".", "query", "(", "\"CONSTRUCT { ?s ?p ?o } WHERE { VALUES ?s { #{uris_sparql_str} }. ?s ?p ?o . }\"", ",", "Tripod", ".", "ntriples_header_str", ")", "graph", "=", "_rdf_graph_from_ntriples_string", "(", "ntriples_string", ",", "graph", ")", "end", "graph", "end" ]
returns a graph of triples which describe the uris passed in.
[ "returns", "a", "graph", "of", "triples", "which", "describe", "the", "uris", "passed", "in", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/finders.rb#L105-L117
train
Swirrl/tripod
lib/tripod/finders.rb
Tripod::Finders.ClassMethods._rdf_graph_from_ntriples_string
def _rdf_graph_from_ntriples_string(ntriples_string, graph=nil) graph ||= RDF::Graph.new RDF::Reader.for(:ntriples).new(ntriples_string) do |reader| reader.each_statement do |statement| graph << statement end end graph end
ruby
def _rdf_graph_from_ntriples_string(ntriples_string, graph=nil) graph ||= RDF::Graph.new RDF::Reader.for(:ntriples).new(ntriples_string) do |reader| reader.each_statement do |statement| graph << statement end end graph end
[ "def", "_rdf_graph_from_ntriples_string", "(", "ntriples_string", ",", "graph", "=", "nil", ")", "graph", "||=", "RDF", "::", "Graph", ".", "new", "RDF", "::", "Reader", ".", "for", "(", ":ntriples", ")", ".", "new", "(", "ntriples_string", ")", "do", "|", "reader", "|", "reader", ".", "each_statement", "do", "|", "statement", "|", "graph", "<<", "statement", "end", "end", "graph", "end" ]
given a string of ntriples data, populate an RDF graph. If you pass a graph in, it will add to that one.
[ "given", "a", "string", "of", "ntriples", "data", "populate", "an", "RDF", "graph", ".", "If", "you", "pass", "a", "graph", "in", "it", "will", "add", "to", "that", "one", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/finders.rb#L140-L148
train
Swirrl/tripod
lib/tripod/finders.rb
Tripod::Finders.ClassMethods._graph_of_triples_from_construct_or_describe
def _graph_of_triples_from_construct_or_describe(construct_query) ntriples_str = Tripod::SparqlClient::Query.query(construct_query, Tripod.ntriples_header_str) _rdf_graph_from_ntriples_string(ntriples_str, graph=nil) end
ruby
def _graph_of_triples_from_construct_or_describe(construct_query) ntriples_str = Tripod::SparqlClient::Query.query(construct_query, Tripod.ntriples_header_str) _rdf_graph_from_ntriples_string(ntriples_str, graph=nil) end
[ "def", "_graph_of_triples_from_construct_or_describe", "(", "construct_query", ")", "ntriples_str", "=", "Tripod", "::", "SparqlClient", "::", "Query", ".", "query", "(", "construct_query", ",", "Tripod", ".", "ntriples_header_str", ")", "_rdf_graph_from_ntriples_string", "(", "ntriples_str", ",", "graph", "=", "nil", ")", "end" ]
given a construct or describe query, return a graph of triples.
[ "given", "a", "construct", "or", "describe", "query", "return", "a", "graph", "of", "triples", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/finders.rb#L151-L154
train
Swirrl/tripod
lib/tripod/finders.rb
Tripod::Finders.ClassMethods._create_and_hydrate_resources_from_sparql
def _create_and_hydrate_resources_from_sparql(select_sparql, opts={}) # TODO: Optimization?: if return_graph option is false, then don't do this next line? uris_and_graphs = _select_uris_and_graphs(select_sparql, :uri_variable => opts[:uri_variable], :graph_variable => opts[:graph_variable]) #there are no resources if there are no uris and graphs if uris_and_graphs.empty? [] else construct_query = _construct_query_for_uris_and_graphs(uris_and_graphs) graph = _graph_of_triples_from_construct_or_describe(construct_query) _resources_from_graph(graph, uris_and_graphs) end end
ruby
def _create_and_hydrate_resources_from_sparql(select_sparql, opts={}) # TODO: Optimization?: if return_graph option is false, then don't do this next line? uris_and_graphs = _select_uris_and_graphs(select_sparql, :uri_variable => opts[:uri_variable], :graph_variable => opts[:graph_variable]) #there are no resources if there are no uris and graphs if uris_and_graphs.empty? [] else construct_query = _construct_query_for_uris_and_graphs(uris_and_graphs) graph = _graph_of_triples_from_construct_or_describe(construct_query) _resources_from_graph(graph, uris_and_graphs) end end
[ "def", "_create_and_hydrate_resources_from_sparql", "(", "select_sparql", ",", "opts", "=", "{", "}", ")", "uris_and_graphs", "=", "_select_uris_and_graphs", "(", "select_sparql", ",", ":uri_variable", "=>", "opts", "[", ":uri_variable", "]", ",", ":graph_variable", "=>", "opts", "[", ":graph_variable", "]", ")", "if", "uris_and_graphs", ".", "empty?", "[", "]", "else", "construct_query", "=", "_construct_query_for_uris_and_graphs", "(", "uris_and_graphs", ")", "graph", "=", "_graph_of_triples_from_construct_or_describe", "(", "construct_query", ")", "_resources_from_graph", "(", "graph", ",", "uris_and_graphs", ")", "end", "end" ]
Given a select query, perform a DESCRIBE query to get a graph of data from which we create and hydrate a collection of resources. @option options [ String ] uri_variable The name of the uri variable in the query, if not 'uri' @option options [ String ] graph_variable The name of the uri variable in the query, if not 'graph'
[ "Given", "a", "select", "query", "perform", "a", "DESCRIBE", "query", "to", "get", "a", "graph", "of", "data", "from", "which", "we", "create", "and", "hydrate", "a", "collection", "of", "resources", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/finders.rb#L161-L173
train
Swirrl/tripod
lib/tripod/finders.rb
Tripod::Finders.ClassMethods._construct_query_for_uris_and_graphs
def _construct_query_for_uris_and_graphs(uris_and_graphs) value_pairs = uris_and_graphs.map do |(uri, graph)| u = RDF::URI.new(uri).to_base g = graph ? RDF::URI.new(graph).to_base : 'UNDEF' "(#{u} #{g})" end query = "CONSTRUCT { ?uri ?p ?o . #{ self.all_triples_construct("?uri") }} WHERE { GRAPH ?g { ?uri ?p ?o . #{ self.all_triples_where("?uri") } VALUES (?uri ?g) { #{ value_pairs.join(' ') } } } }" end
ruby
def _construct_query_for_uris_and_graphs(uris_and_graphs) value_pairs = uris_and_graphs.map do |(uri, graph)| u = RDF::URI.new(uri).to_base g = graph ? RDF::URI.new(graph).to_base : 'UNDEF' "(#{u} #{g})" end query = "CONSTRUCT { ?uri ?p ?o . #{ self.all_triples_construct("?uri") }} WHERE { GRAPH ?g { ?uri ?p ?o . #{ self.all_triples_where("?uri") } VALUES (?uri ?g) { #{ value_pairs.join(' ') } } } }" end
[ "def", "_construct_query_for_uris_and_graphs", "(", "uris_and_graphs", ")", "value_pairs", "=", "uris_and_graphs", ".", "map", "do", "|", "(", "uri", ",", "graph", ")", "|", "u", "=", "RDF", "::", "URI", ".", "new", "(", "uri", ")", ".", "to_base", "g", "=", "graph", "?", "RDF", "::", "URI", ".", "new", "(", "graph", ")", ".", "to_base", ":", "'UNDEF'", "\"(#{u} #{g})\"", "end", "query", "=", "\"CONSTRUCT { ?uri ?p ?o . #{ self.all_triples_construct(\"?uri\") }} WHERE { GRAPH ?g { ?uri ?p ?o . #{ self.all_triples_where(\"?uri\") } VALUES (?uri ?g) { #{ value_pairs.join(' ') } } } }\"", "end" ]
Generate a CONSTRUCT query for the given uri and graph pairs.
[ "Generate", "a", "CONSTRUCT", "query", "for", "the", "given", "uri", "and", "graph", "pairs", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/finders.rb#L196-L203
train
Swirrl/tripod
lib/tripod/finders.rb
Tripod::Finders.ClassMethods._raw_describe_select_results
def _raw_describe_select_results(select_sparql, opts={}) accept_header = opts[:accept_header] || Tripod.ntriples_header_str query = _describe_query_for_select(select_sparql, :uri_variable => opts[:uri_variable]) Tripod::SparqlClient::Query.query(query, accept_header) end
ruby
def _raw_describe_select_results(select_sparql, opts={}) accept_header = opts[:accept_header] || Tripod.ntriples_header_str query = _describe_query_for_select(select_sparql, :uri_variable => opts[:uri_variable]) Tripod::SparqlClient::Query.query(query, accept_header) end
[ "def", "_raw_describe_select_results", "(", "select_sparql", ",", "opts", "=", "{", "}", ")", "accept_header", "=", "opts", "[", ":accept_header", "]", "||", "Tripod", ".", "ntriples_header_str", "query", "=", "_describe_query_for_select", "(", "select_sparql", ",", ":uri_variable", "=>", "opts", "[", ":uri_variable", "]", ")", "Tripod", "::", "SparqlClient", "::", "Query", ".", "query", "(", "query", ",", "accept_header", ")", "end" ]
For a select query, get a raw serialisation of the DESCRIPTION of the resources from the database. @option options [ String ] uri_variable The name of the uri variable in the query, if not 'uri' @option options [ String ] accept_header The http accept header (default application/n-triples)
[ "For", "a", "select", "query", "get", "a", "raw", "serialisation", "of", "the", "DESCRIPTION", "of", "the", "resources", "from", "the", "database", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/finders.rb#L209-L213
train
Swirrl/tripod
lib/tripod/resource_collection.rb
Tripod.ResourceCollection.to_nt
def to_nt time_serialization('nt') do if @criteria @criteria.serialize(:return_graph => @return_graph, :accept_header => Tripod.ntriples_header_str) elsif @sparql_query_str && @resource_class # run the query as a describe. @resource_class._raw_describe_select_results(@sparql_query_str, :accept_header => Tripod.ntriples_header_str) else # for n-triples we can just concatenate them nt = "" resources.each do |resource| nt += resource.to_nt end nt end end end
ruby
def to_nt time_serialization('nt') do if @criteria @criteria.serialize(:return_graph => @return_graph, :accept_header => Tripod.ntriples_header_str) elsif @sparql_query_str && @resource_class # run the query as a describe. @resource_class._raw_describe_select_results(@sparql_query_str, :accept_header => Tripod.ntriples_header_str) else # for n-triples we can just concatenate them nt = "" resources.each do |resource| nt += resource.to_nt end nt end end end
[ "def", "to_nt", "time_serialization", "(", "'nt'", ")", "do", "if", "@criteria", "@criteria", ".", "serialize", "(", ":return_graph", "=>", "@return_graph", ",", ":accept_header", "=>", "Tripod", ".", "ntriples_header_str", ")", "elsif", "@sparql_query_str", "&&", "@resource_class", "@resource_class", ".", "_raw_describe_select_results", "(", "@sparql_query_str", ",", ":accept_header", "=>", "Tripod", ".", "ntriples_header_str", ")", "else", "nt", "=", "\"\"", "resources", ".", "each", "do", "|", "resource", "|", "nt", "+=", "resource", ".", "to_nt", "end", "nt", "end", "end", "end" ]
for n-triples we can just concatenate them
[ "for", "n", "-", "triples", "we", "can", "just", "concatenate", "them" ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/resource_collection.rb#L53-L69
train
Swirrl/tripod
lib/tripod/criteria/execution.rb
Tripod.CriteriaExecution.resources
def resources(opts={}) Tripod::ResourceCollection.new( self.resource_class._resources_from_sparql(self.as_query(opts)), # pass in the criteria that was used to generate this collection, as well as whether the user specified return graph :return_graph => (opts.has_key?(:return_graph) ? opts[:return_graph] : true), :criteria => self ) end
ruby
def resources(opts={}) Tripod::ResourceCollection.new( self.resource_class._resources_from_sparql(self.as_query(opts)), # pass in the criteria that was used to generate this collection, as well as whether the user specified return graph :return_graph => (opts.has_key?(:return_graph) ? opts[:return_graph] : true), :criteria => self ) end
[ "def", "resources", "(", "opts", "=", "{", "}", ")", "Tripod", "::", "ResourceCollection", ".", "new", "(", "self", ".", "resource_class", ".", "_resources_from_sparql", "(", "self", ".", "as_query", "(", "opts", ")", ")", ",", ":return_graph", "=>", "(", "opts", ".", "has_key?", "(", ":return_graph", ")", "?", "opts", "[", ":return_graph", "]", ":", "true", ")", ",", ":criteria", "=>", "self", ")", "end" ]
Execute the query and return a +ResourceCollection+ of all hydrated resources +ResourceCollection+ is an +Enumerable+, Array-like object. @option options [ String ] return_graph Indicates whether to return the graph as one of the variables.
[ "Execute", "the", "query", "and", "return", "a", "+", "ResourceCollection", "+", "of", "all", "hydrated", "resources", "+", "ResourceCollection", "+", "is", "an", "+", "Enumerable", "+", "Array", "-", "like", "object", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/criteria/execution.rb#L13-L20
train
Swirrl/tripod
lib/tripod/criteria/execution.rb
Tripod.CriteriaExecution.first
def first(opts={}) sq = Tripod::SparqlQuery.new(self.as_query(opts)) first_sparql = sq.as_first_query_str self.resource_class._resources_from_sparql(first_sparql).first end
ruby
def first(opts={}) sq = Tripod::SparqlQuery.new(self.as_query(opts)) first_sparql = sq.as_first_query_str self.resource_class._resources_from_sparql(first_sparql).first end
[ "def", "first", "(", "opts", "=", "{", "}", ")", "sq", "=", "Tripod", "::", "SparqlQuery", ".", "new", "(", "self", ".", "as_query", "(", "opts", ")", ")", "first_sparql", "=", "sq", ".", "as_first_query_str", "self", ".", "resource_class", ".", "_resources_from_sparql", "(", "first_sparql", ")", ".", "first", "end" ]
Execute the query and return the first result as a hydrated resource @option options [ String ] return_graph Indicates whether to return the graph as one of the variables.
[ "Execute", "the", "query", "and", "return", "the", "first", "result", "as", "a", "hydrated", "resource" ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/criteria/execution.rb#L34-L38
train
Swirrl/tripod
lib/tripod/criteria/execution.rb
Tripod.CriteriaExecution.count
def count(opts={}) sq = Tripod::SparqlQuery.new(self.as_query(opts)) count_sparql = sq.as_count_query_str result = Tripod::SparqlClient::Query.select(count_sparql) if result.length > 0 result[0]["tripod_count_var"]["value"].to_i else return 0 end end
ruby
def count(opts={}) sq = Tripod::SparqlQuery.new(self.as_query(opts)) count_sparql = sq.as_count_query_str result = Tripod::SparqlClient::Query.select(count_sparql) if result.length > 0 result[0]["tripod_count_var"]["value"].to_i else return 0 end end
[ "def", "count", "(", "opts", "=", "{", "}", ")", "sq", "=", "Tripod", "::", "SparqlQuery", ".", "new", "(", "self", ".", "as_query", "(", "opts", ")", ")", "count_sparql", "=", "sq", ".", "as_count_query_str", "result", "=", "Tripod", "::", "SparqlClient", "::", "Query", ".", "select", "(", "count_sparql", ")", "if", "result", ".", "length", ">", "0", "result", "[", "0", "]", "[", "\"tripod_count_var\"", "]", "[", "\"value\"", "]", ".", "to_i", "else", "return", "0", "end", "end" ]
Return how many records the current criteria would return @option options [ String ] return_graph Indicates whether to return the graph as one of the variables.
[ "Return", "how", "many", "records", "the", "current", "criteria", "would", "return" ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/criteria/execution.rb#L43-L53
train
Swirrl/tripod
lib/tripod/criteria/execution.rb
Tripod.CriteriaExecution.as_query
def as_query(opts={}) Tripod.logger.debug("TRIPOD: building select query for criteria...") return_graph = opts.has_key?(:return_graph) ? opts[:return_graph] : true Tripod.logger.debug("TRIPOD: with return_graph: #{return_graph.inspect}") select_query = "SELECT DISTINCT ?uri " if graph_lambdas.empty? if return_graph # if we are returning the graph, select it as a variable, and include either the <graph> or ?graph in the where clause if graph_uri select_query += "(<#{graph_uri}> as ?graph) WHERE { GRAPH <#{graph_uri}> { " else select_query += "?graph WHERE { GRAPH ?graph { " end else select_query += "WHERE { " # if we're not returning the graph, only restrict by the <graph> if there's one set at class level select_query += "GRAPH <#{graph_uri}> { " if graph_uri end select_query += self.query_where_clauses.join(" . ") select_query += " } " select_query += "} " if return_graph || graph_uri # close the graph clause else # whip through the graph lambdas and add into the query # we have multiple graphs so the above does not apply select_query += "WHERE { " graph_lambdas.each do |lambda_item| select_query += "GRAPH ?g { " select_query += lambda_item.call select_query += " } " end select_query += self.query_where_clauses.join(" . ") select_query += " } " end select_query += self.extra_clauses.join(" ") select_query += [order_clause, limit_clause, offset_clause].join(" ") select_query.strip end
ruby
def as_query(opts={}) Tripod.logger.debug("TRIPOD: building select query for criteria...") return_graph = opts.has_key?(:return_graph) ? opts[:return_graph] : true Tripod.logger.debug("TRIPOD: with return_graph: #{return_graph.inspect}") select_query = "SELECT DISTINCT ?uri " if graph_lambdas.empty? if return_graph # if we are returning the graph, select it as a variable, and include either the <graph> or ?graph in the where clause if graph_uri select_query += "(<#{graph_uri}> as ?graph) WHERE { GRAPH <#{graph_uri}> { " else select_query += "?graph WHERE { GRAPH ?graph { " end else select_query += "WHERE { " # if we're not returning the graph, only restrict by the <graph> if there's one set at class level select_query += "GRAPH <#{graph_uri}> { " if graph_uri end select_query += self.query_where_clauses.join(" . ") select_query += " } " select_query += "} " if return_graph || graph_uri # close the graph clause else # whip through the graph lambdas and add into the query # we have multiple graphs so the above does not apply select_query += "WHERE { " graph_lambdas.each do |lambda_item| select_query += "GRAPH ?g { " select_query += lambda_item.call select_query += " } " end select_query += self.query_where_clauses.join(" . ") select_query += " } " end select_query += self.extra_clauses.join(" ") select_query += [order_clause, limit_clause, offset_clause].join(" ") select_query.strip end
[ "def", "as_query", "(", "opts", "=", "{", "}", ")", "Tripod", ".", "logger", ".", "debug", "(", "\"TRIPOD: building select query for criteria...\"", ")", "return_graph", "=", "opts", ".", "has_key?", "(", ":return_graph", ")", "?", "opts", "[", ":return_graph", "]", ":", "true", "Tripod", ".", "logger", ".", "debug", "(", "\"TRIPOD: with return_graph: #{return_graph.inspect}\"", ")", "select_query", "=", "\"SELECT DISTINCT ?uri \"", "if", "graph_lambdas", ".", "empty?", "if", "return_graph", "if", "graph_uri", "select_query", "+=", "\"(<#{graph_uri}> as ?graph) WHERE { GRAPH <#{graph_uri}> { \"", "else", "select_query", "+=", "\"?graph WHERE { GRAPH ?graph { \"", "end", "else", "select_query", "+=", "\"WHERE { \"", "select_query", "+=", "\"GRAPH <#{graph_uri}> { \"", "if", "graph_uri", "end", "select_query", "+=", "self", ".", "query_where_clauses", ".", "join", "(", "\" . \"", ")", "select_query", "+=", "\" } \"", "select_query", "+=", "\"} \"", "if", "return_graph", "||", "graph_uri", "else", "select_query", "+=", "\"WHERE { \"", "graph_lambdas", ".", "each", "do", "|", "lambda_item", "|", "select_query", "+=", "\"GRAPH ?g { \"", "select_query", "+=", "lambda_item", ".", "call", "select_query", "+=", "\" } \"", "end", "select_query", "+=", "self", ".", "query_where_clauses", ".", "join", "(", "\" . \"", ")", "select_query", "+=", "\" } \"", "end", "select_query", "+=", "self", ".", "extra_clauses", ".", "join", "(", "\" \"", ")", "select_query", "+=", "[", "order_clause", ",", "limit_clause", ",", "offset_clause", "]", ".", "join", "(", "\" \"", ")", "select_query", ".", "strip", "end" ]
turn this criteria into a query
[ "turn", "this", "criteria", "into", "a", "query" ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/criteria/execution.rb#L56-L104
train
Swirrl/tripod
lib/tripod/repository.rb
Tripod::Repository.ClassMethods.add_data_to_repository
def add_data_to_repository(graph, repo=nil) repo ||= RDF::Repository.new() graph.each_statement do |statement| repo << statement end repo end
ruby
def add_data_to_repository(graph, repo=nil) repo ||= RDF::Repository.new() graph.each_statement do |statement| repo << statement end repo end
[ "def", "add_data_to_repository", "(", "graph", ",", "repo", "=", "nil", ")", "repo", "||=", "RDF", "::", "Repository", ".", "new", "(", ")", "graph", ".", "each_statement", "do", "|", "statement", "|", "repo", "<<", "statement", "end", "repo", "end" ]
for triples in the graph passed in, add them to the passed in repository obj, and return the repository objects  if no repository passed, make a new one.
[ "for", "triples", "in", "the", "graph", "passed", "in", "add", "them", "to", "the", "passed", "in", "repository", "obj", "and", "return", "the", "repository", "objects", "if", "no", "repository", "passed", "make", "a", "new", "one", "." ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/repository.rb#L75-L84
train
Swirrl/tripod
lib/tripod/criteria.rb
Tripod.Criteria.graph
def graph(graph_uri, &block) if block_given? self.graph_lambdas ||= [] self.graph_lambdas << block self else self.graph_uri = graph_uri.to_s self end end
ruby
def graph(graph_uri, &block) if block_given? self.graph_lambdas ||= [] self.graph_lambdas << block self else self.graph_uri = graph_uri.to_s self end end
[ "def", "graph", "(", "graph_uri", ",", "&", "block", ")", "if", "block_given?", "self", ".", "graph_lambdas", "||=", "[", "]", "self", ".", "graph_lambdas", "<<", "block", "self", "else", "self", ".", "graph_uri", "=", "graph_uri", ".", "to_s", "self", "end", "end" ]
Restrict this query to the graph uri passed in You may also pass a block to an unbound graph, ?g then chain a where clause to the criteria returned to bind ?g @example .graph(RDF::URI.new('http://graphoid') @example .graph('http://graphoid') @example .graph(nil) { "?s ?p ?o" }.where("?uri ?p ?g") @param [ String, RDF::URI ] The graph uri @param [ Block ] A string to be executed within an unbound graph, ?g @return [ Tripod::Criteria ] A criteria object
[ "Restrict", "this", "query", "to", "the", "graph", "uri", "passed", "in", "You", "may", "also", "pass", "a", "block", "to", "an", "unbound", "graph", "?g", "then", "chain", "a", "where", "clause", "to", "the", "criteria", "returned", "to", "bind", "?g" ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/criteria.rb#L101-L111
train
Swirrl/tripod
lib/tripod/links.rb
Tripod::Links.ClassMethods.linked_from_for
def linked_from_for(name, incoming_field_name, options) Tripod::Links::LinkedFrom.new(name, incoming_field_name, options) end
ruby
def linked_from_for(name, incoming_field_name, options) Tripod::Links::LinkedFrom.new(name, incoming_field_name, options) end
[ "def", "linked_from_for", "(", "name", ",", "incoming_field_name", ",", "options", ")", "Tripod", "::", "Links", "::", "LinkedFrom", ".", "new", "(", "name", ",", "incoming_field_name", ",", "options", ")", "end" ]
instantiates and returns a new LinkedFrom
[ "instantiates", "and", "returns", "a", "new", "LinkedFrom" ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/links.rb#L164-L166
train
Swirrl/tripod
lib/tripod/links.rb
Tripod::Links.ClassMethods.linked_to_for
def linked_to_for(name, predicate, options) Tripod::Links::LinkedTo.new(name, predicate, options) end
ruby
def linked_to_for(name, predicate, options) Tripod::Links::LinkedTo.new(name, predicate, options) end
[ "def", "linked_to_for", "(", "name", ",", "predicate", ",", "options", ")", "Tripod", "::", "Links", "::", "LinkedTo", ".", "new", "(", "name", ",", "predicate", ",", "options", ")", "end" ]
instantiates and returns a new LinkTo
[ "instantiates", "and", "returns", "a", "new", "LinkTo" ]
00bb42c67b68e5c6843b9883cd5c69a318f3b72b
https://github.com/Swirrl/tripod/blob/00bb42c67b68e5c6843b9883cd5c69a318f3b72b/lib/tripod/links.rb#L169-L171
train
story-branch/story_branch
lib/story_branch/main.rb
StoryBranch.Main.validate_branch_name
def validate_branch_name(name, id) if GitUtils.branch_for_story_exists? id prompt.error("An existing branch has the same story id: #{id}") return false end if GitUtils.existing_branch? name prompt.error('This name is very similar to an existing branch. Avoid confusion and use a more unique name.') return false end true end
ruby
def validate_branch_name(name, id) if GitUtils.branch_for_story_exists? id prompt.error("An existing branch has the same story id: #{id}") return false end if GitUtils.existing_branch? name prompt.error('This name is very similar to an existing branch. Avoid confusion and use a more unique name.') return false end true end
[ "def", "validate_branch_name", "(", "name", ",", "id", ")", "if", "GitUtils", ".", "branch_for_story_exists?", "id", "prompt", ".", "error", "(", "\"An existing branch has the same story id: #{id}\"", ")", "return", "false", "end", "if", "GitUtils", ".", "existing_branch?", "name", "prompt", ".", "error", "(", "'This name is very similar to an existing branch. Avoid confusion and use a more unique name.'", ")", "return", "false", "end", "true", "end" ]
Branch name validation
[ "Branch", "name", "validation" ]
2ad2aa94f89b5a278c4f4ea32db7bccfb1ab05d7
https://github.com/story-branch/story_branch/blob/2ad2aa94f89b5a278c4f4ea32db7bccfb1ab05d7/lib/story_branch/main.rb#L178-L188
train
bernerdschaefer/akephalos
lib/akephalos/node.rb
Akephalos.Node.value
def value case tag_name when "select" if self[:multiple] selected_options.map { |option| option.value } else selected_option = @_node.selected_options.first selected_option ? Node.new(selected_option).value : nil end when "option" self[:value] || text when "textarea" @_node.getText else self[:value] end end
ruby
def value case tag_name when "select" if self[:multiple] selected_options.map { |option| option.value } else selected_option = @_node.selected_options.first selected_option ? Node.new(selected_option).value : nil end when "option" self[:value] || text when "textarea" @_node.getText else self[:value] end end
[ "def", "value", "case", "tag_name", "when", "\"select\"", "if", "self", "[", ":multiple", "]", "selected_options", ".", "map", "{", "|", "option", "|", "option", ".", "value", "}", "else", "selected_option", "=", "@_node", ".", "selected_options", ".", "first", "selected_option", "?", "Node", ".", "new", "(", "selected_option", ")", ".", "value", ":", "nil", "end", "when", "\"option\"", "self", "[", ":value", "]", "||", "text", "when", "\"textarea\"", "@_node", ".", "getText", "else", "self", "[", ":value", "]", "end", "end" ]
Return the value of a form element. If the element is a select box and has "multiple" declared as an attribute, then all selected options will be returned as an array. @return [String, Array<String>] the node's value
[ "Return", "the", "value", "of", "a", "form", "element", ".", "If", "the", "element", "is", "a", "select", "box", "and", "has", "multiple", "declared", "as", "an", "attribute", "then", "all", "selected", "options", "will", "be", "returned", "as", "an", "array", "." ]
80103301ebe1609b90de04a8e4f6092def818585
https://github.com/bernerdschaefer/akephalos/blob/80103301ebe1609b90de04a8e4f6092def818585/lib/akephalos/node.rb#L40-L56
train
bernerdschaefer/akephalos
lib/akephalos/node.rb
Akephalos.Node.value=
def value=(value) case tag_name when "textarea" @_node.setText("") type(value) when "input" if file_input? @_node.setValueAttribute(value) else @_node.setValueAttribute("") type(value) end end end
ruby
def value=(value) case tag_name when "textarea" @_node.setText("") type(value) when "input" if file_input? @_node.setValueAttribute(value) else @_node.setValueAttribute("") type(value) end end end
[ "def", "value", "=", "(", "value", ")", "case", "tag_name", "when", "\"textarea\"", "@_node", ".", "setText", "(", "\"\"", ")", "type", "(", "value", ")", "when", "\"input\"", "if", "file_input?", "@_node", ".", "setValueAttribute", "(", "value", ")", "else", "@_node", ".", "setValueAttribute", "(", "\"\"", ")", "type", "(", "value", ")", "end", "end", "end" ]
Set the value of the form input. @param [String] value
[ "Set", "the", "value", "of", "the", "form", "input", "." ]
80103301ebe1609b90de04a8e4f6092def818585
https://github.com/bernerdschaefer/akephalos/blob/80103301ebe1609b90de04a8e4f6092def818585/lib/akephalos/node.rb#L61-L74
train
bernerdschaefer/akephalos
lib/akephalos/node.rb
Akephalos.Node.click
def click @_node.click @_node.getPage.getEnclosingWindow.getJobManager.waitForJobs(1000) @_node.getPage.getEnclosingWindow.getJobManager.waitForJobsStartingBefore(1000) end
ruby
def click @_node.click @_node.getPage.getEnclosingWindow.getJobManager.waitForJobs(1000) @_node.getPage.getEnclosingWindow.getJobManager.waitForJobsStartingBefore(1000) end
[ "def", "click", "@_node", ".", "click", "@_node", ".", "getPage", ".", "getEnclosingWindow", ".", "getJobManager", ".", "waitForJobs", "(", "1000", ")", "@_node", ".", "getPage", ".", "getEnclosingWindow", ".", "getJobManager", ".", "waitForJobsStartingBefore", "(", "1000", ")", "end" ]
Click the node and then wait for any triggered JavaScript callbacks to fire.
[ "Click", "the", "node", "and", "then", "wait", "for", "any", "triggered", "JavaScript", "callbacks", "to", "fire", "." ]
80103301ebe1609b90de04a8e4f6092def818585
https://github.com/bernerdschaefer/akephalos/blob/80103301ebe1609b90de04a8e4f6092def818585/lib/akephalos/node.rb#L150-L154
train
phcdevworks/multi-tenancy-devise
app/controllers/mtdevise/accounts_controller.rb
Mtdevise.AccountsController.create
def create account = if user_signed_in? Mtdevise::Account.create(account_params) else Mtdevise::Account.create_with_owner(account_params) end @account = account if account.valid? flash[:success] = "Your account has been successfully created." if user_signed_in? account.owner = current_user account.users << current_user account.save redirect_to mtdevise.accounts_path else sign_in account.owner redirect_to mtdevise.root_url(:subdomain => account.subdomain) end else flash[:error] = "Sorry, your account could not be created." render :new end end
ruby
def create account = if user_signed_in? Mtdevise::Account.create(account_params) else Mtdevise::Account.create_with_owner(account_params) end @account = account if account.valid? flash[:success] = "Your account has been successfully created." if user_signed_in? account.owner = current_user account.users << current_user account.save redirect_to mtdevise.accounts_path else sign_in account.owner redirect_to mtdevise.root_url(:subdomain => account.subdomain) end else flash[:error] = "Sorry, your account could not be created." render :new end end
[ "def", "create", "account", "=", "if", "user_signed_in?", "Mtdevise", "::", "Account", ".", "create", "(", "account_params", ")", "else", "Mtdevise", "::", "Account", ".", "create_with_owner", "(", "account_params", ")", "end", "@account", "=", "account", "if", "account", ".", "valid?", "flash", "[", ":success", "]", "=", "\"Your account has been successfully created.\"", "if", "user_signed_in?", "account", ".", "owner", "=", "current_user", "account", ".", "users", "<<", "current_user", "account", ".", "save", "redirect_to", "mtdevise", ".", "accounts_path", "else", "sign_in", "account", ".", "owner", "redirect_to", "mtdevise", ".", "root_url", "(", ":subdomain", "=>", "account", ".", "subdomain", ")", "end", "else", "flash", "[", ":error", "]", "=", "\"Sorry, your account could not be created.\"", "render", ":new", "end", "end" ]
Accounts Create action
[ "Accounts", "Create", "action" ]
e0a6e4582a8f415539ab598863c5e4cde2cde2cd
https://github.com/phcdevworks/multi-tenancy-devise/blob/e0a6e4582a8f415539ab598863c5e4cde2cde2cd/app/controllers/mtdevise/accounts_controller.rb#L23-L50
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.get_ws_api_version
def get_ws_api_version # remove everything down to host:port host_url = @api_url.split('/api') @http.set_url(host_url[0]) begin # get the api version response = @http.get('/api') response[1] rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end ensure # reset the url @http.set_url(@api_url) end
ruby
def get_ws_api_version # remove everything down to host:port host_url = @api_url.split('/api') @http.set_url(host_url[0]) begin # get the api version response = @http.get('/api') response[1] rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end ensure # reset the url @http.set_url(@api_url) end
[ "def", "get_ws_api_version", "host_url", "=", "@api_url", ".", "split", "(", "'/api'", ")", "@http", ".", "set_url", "(", "host_url", "[", "0", "]", ")", "begin", "response", "=", "@http", ".", "get", "(", "'/api'", ")", "response", "[", "1", "]", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "ensure", "@http", ".", "set_url", "(", "@api_url", ")", "end" ]
Get the 3PAR WS API version. ==== Returns WSAPI version hash
[ "Get", "the", "3PAR", "WS", "API", "version", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L133-L148
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.create_flash_cache
def create_flash_cache(size_in_gib, mode = nil) begin @flash_cache.create_flash_cache(size_in_gib, mode) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def create_flash_cache(size_in_gib, mode = nil) begin @flash_cache.create_flash_cache(size_in_gib, mode) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "create_flash_cache", "(", "size_in_gib", ",", "mode", "=", "nil", ")", "begin", "@flash_cache", ".", "create_flash_cache", "(", "size_in_gib", ",", "mode", ")", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Creates a new FlashCache ==== Attributes * size_in_gib - Specifies the node pair size of the Flash Cache on the system type size_in_gib: Integer * mode - Values supported Simulator: 1, Real: 2 (default) type mode: Integer ==== Raises * Hpe3parSdk::HTTPBadRequest - NO_SPACE - Not enough space is available for the operation. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_EXCEEDS_RANGE - A JSON input object contains a name-value pair with a numeric value that exceeds the expected range. Flash Cache exceeds the expected range. The HTTP ref member contains the name. * Hpe3parSdk::HTTPConflict - EXISTENT_FLASH_CACHE - The Flash Cache already exists. * Hpe3parSdk::HTTPForbidden - FLASH_CACHE_NOT_SUPPORTED - Flash Cache is not supported. * Hpe3parSdk::HTTPBadRequest - INV_FLASH_CACHE_SIZE - Invalid Flash Cache size. The size must be a multiple of 16 G.
[ "Creates", "a", "new", "FlashCache" ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L186-L194
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.get_flash_cache
def get_flash_cache begin @flash_cache.get_flash_cache rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def get_flash_cache begin @flash_cache.get_flash_cache rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "get_flash_cache", "begin", "@flash_cache", ".", "get_flash_cache", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Get Flash Cache information ==== Returns FlashCache - Details of the specified flash cache
[ "Get", "Flash", "Cache", "information" ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L201-L208
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.delete_flash_cache
def delete_flash_cache begin @flash_cache.delete_flash_cache rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def delete_flash_cache begin @flash_cache.delete_flash_cache rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "delete_flash_cache", "begin", "@flash_cache", ".", "delete_flash_cache", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Deletes an existing Flash Cache ==== Raises * Hpe3parSdk::HTTPForbidden - FLASH_CACHE_IS_BEING_REMOVED - Unable to delete the Flash Cache, the Flash Cache is being removed. * Hpe3parSdk::HTTPForbidden - FLASH_CACHE_NOT_SUPPORTED - Flash Cache is not supported on this system. * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_FLASH_CACHE - The Flash Cache does not exist.
[ "Deletes", "an", "existing", "Flash", "Cache" ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L220-L227
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.get_overall_system_capacity
def get_overall_system_capacity begin response = @http.get('/capacity') response[1] rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def get_overall_system_capacity begin response = @http.get('/capacity') response[1] rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "get_overall_system_capacity", "begin", "response", "=", "@http", ".", "get", "(", "'/capacity'", ")", "response", "[", "1", "]", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Gets the overall system capacity for the 3PAR server. ==== Returns Hash of system capacity information capacity = { "allCapacity"=> { # Overall system capacity # includes FC, NL, SSD # device types "totalMiB"=>20054016, # Total system capacity # in MiB "allocated"=>{ # Allocated space info "totalAllocatedMiB"=>12535808, # Total allocated # capacity "volumes"=> { # Volume capacity info "totalVolumesMiB"=>10919936, # Total capacity # allocated to volumes "nonCPGsMiB"=> 0, # Total non-CPG capacity "nonCPGUserMiB"=> 0, # The capacity allocated # to non-CPG user space "nonCPGSnapshotMiB"=>0, # The capacity allocated # to non-CPG snapshot # volumes "nonCPGAdminMiB"=> 0, # The capacity allocated # to non-CPG # administrative volumes "CPGsMiB"=>10919936, # Total capacity # allocated to CPGs "CPGUserMiB"=>7205538, # User CPG space "CPGUserUsedMiB"=>7092550, # The CPG allocated to # user space that is # in use "CPGUserUnusedMiB"=>112988, # The CPG allocated to # user space that is not # in use "CPGSnapshotMiB"=>2411870, # Snapshot CPG space "CPGSnapshotUsedMiB"=>210256, # CPG allocated to # snapshot that is in use "CPGSnapshotUnusedMiB"=>2201614, # CPG allocated to # snapshot space that is # not in use "CPGAdminMiB"=>1302528, # Administrative volume # CPG space "CPGAdminUsedMiB"=> 115200, # The CPG allocated to # administrative space # that is in use "CPGAdminUnusedMiB"=>1187328, # The CPG allocated to # administrative space # that is not in use "unmappedMiB"=>0 # Allocated volume space # that is unmapped }, "system"=> { # System capacity info "totalSystemMiB"=> 1615872, # System space capacity "internalMiB"=>780288, # The system capacity # allocated to internal # resources "spareMiB"=> 835584, # Total spare capacity "spareUsedMiB"=> 0, # The system capacity # allocated to spare resources # in use "spareUnusedMiB"=> 835584 # The system capacity # allocated to spare resources # that are unused } }, "freeMiB"=> 7518208, # Free capacity "freeInitializedMiB"=> 7518208, # Free initialized capacity "freeUninitializedMiB"=> 0, # Free uninitialized capacity "unavailableCapacityMiB"=> 0, # Unavailable capacity in MiB "failedCapacityMiB"=> 0 # Failed capacity in MiB }, "FCCapacity"=> { # System capacity from FC devices only ... # Same structure as above }, "NLCapacity"=> { # System capacity from NL devices only ... # Same structure as above }, "SSDCapacity"=> { # System capacity from SSD devices only ... # Same structure as above } }
[ "Gets", "the", "overall", "system", "capacity", "for", "the", "3PAR", "server", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L328-L336
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.get_all_tasks
def get_all_tasks begin @task.get_all_tasks rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def get_all_tasks begin @task.get_all_tasks rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "get_all_tasks", "begin", "@task", ".", "get_all_tasks", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Get the list of all 3PAR Tasks ==== Returns Array of Task
[ "Get", "the", "list", "of", "all", "3PAR", "Tasks" ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L357-L364
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.get_task
def get_task(task_id) begin @task.get_task(task_id) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def get_task(task_id) begin @task.get_task(task_id) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "get_task", "(", "task_id", ")", "begin", "@task", ".", "get_task", "(", "task_id", ")", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Get the status of a 3PAR Task ==== Attributes * task_id - the task id type task_id: Integer ==== Returns Task ==== Raises * Hpe3parSdk::HTTPBadRequest - INV_INPUT_BELOW_RANGE - Bad Request Task ID must be a positive value. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_EXCEEDS_RANGE - Bad Request Task ID is too large. * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_TASK - Task with the specified Task ID does not exist. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_WRONG_TYPE - Task ID is not an integer.
[ "Get", "the", "status", "of", "a", "3PAR", "Task" ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L387-L394
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.create_vlun
def create_vlun(volume_name, lun = nil, host_name = nil, port_pos = nil, no_vcn = false, override_lower_priority = false, auto = false) begin @vlun.create_vlun(volume_name, host_name, lun, port_pos, no_vcn, override_lower_priority, auto) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def create_vlun(volume_name, lun = nil, host_name = nil, port_pos = nil, no_vcn = false, override_lower_priority = false, auto = false) begin @vlun.create_vlun(volume_name, host_name, lun, port_pos, no_vcn, override_lower_priority, auto) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "create_vlun", "(", "volume_name", ",", "lun", "=", "nil", ",", "host_name", "=", "nil", ",", "port_pos", "=", "nil", ",", "no_vcn", "=", "false", ",", "override_lower_priority", "=", "false", ",", "auto", "=", "false", ")", "begin", "@vlun", ".", "create_vlun", "(", "volume_name", ",", "host_name", ",", "lun", ",", "port_pos", ",", "no_vcn", ",", "override_lower_priority", ",", "auto", ")", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Creates a new VLUN. When creating a VLUN, the volumeName is required. The lun member is not required if auto is set to True. Either hostname or portPos (or both in the case of matched sets) is also required. The noVcn and overrideLowerPriority members are optional. * volume_name: Name of the volume to be exported type volume_name: String * lun: LUN id type lun: Integer * host_name: Name of the host which the volume is to be exported. type host_name: String * port_pos: System port of VLUN exported to. It includes node number, slot number, and card port number type port_pos: Hash port_pos = {'node'=> 1, # System node (0-7) 'slot'=> 2, # PCI bus slot in the node (0-5) 'port'=> 1} # Port number on the FC card (0-4) * no_vcn: A VLUN change notification (VCN) not be issued after export (-novcn). type no_vcn: Boolean * override_lower_priority: Existing lower priority VLUNs will be overridden (-ovrd). Use only if hostname member exists. type override_lower_priority: Boolean ==== Returns VLUN id ==== Raises * Hpe3parSdk::HTTPBadRequest - INV_INPUT_ MISSING_REQUIRED - Missing volume or hostname or lunid. * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_VOL MISSING_REQUIRED - Specified volume does not exist. * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_HOST - Specified hostname not found. * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_PORT - Specified port does not exist.
[ "Creates", "a", "new", "VLUN", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L442-L449
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.get_vluns
def get_vluns begin @vlun.get_vluns rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def get_vluns begin @vlun.get_vluns rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "get_vluns", "begin", "@vlun", ".", "get_vluns", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Gets VLUNs. ==== Returns Array of VLUN objects
[ "Gets", "VLUNs", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L456-L463
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.get_vlun
def get_vlun(volume_name) begin @vlun.get_vlun(volume_name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def get_vlun(volume_name) begin @vlun.get_vlun(volume_name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "get_vlun", "(", "volume_name", ")", "begin", "@vlun", ".", "get_vlun", "(", "volume_name", ")", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Gets information about a VLUN. ==== Attributes * volume_name: The volume name of the VLUN to find type volume_name: String ==== Returns VLUN object ==== Raises * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_VLUN - VLUN doesn't exist
[ "Gets", "information", "about", "a", "VLUN", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L480-L487
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.delete_vlun
def delete_vlun(volume_name, lun_id, host_name = nil, port = nil) begin @vlun.delete_vlun(volume_name, lun_id, host_name, port) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def delete_vlun(volume_name, lun_id, host_name = nil, port = nil) begin @vlun.delete_vlun(volume_name, lun_id, host_name, port) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "delete_vlun", "(", "volume_name", ",", "lun_id", ",", "host_name", "=", "nil", ",", "port", "=", "nil", ")", "begin", "@vlun", ".", "delete_vlun", "(", "volume_name", ",", "lun_id", ",", "host_name", ",", "port", ")", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Deletes a VLUN. ==== Attributes * volume_name: Volume name of the VLUN type volume_name: String * lun_id: LUN ID type lun_id: Integer * host_name: Name of the host which the volume is exported. For VLUN of port type,the value is empty type host_name: String * port: Specifies the system port of the VLUN export. It includes the system node number, PCI bus slot number, and card port number on the FC card in the format<node>:<slot>:<cardPort> type port: Hash port = {'node'=> 1, # System node (0-7) 'slot'=> 2, # PCI bus slot in the node (0-5) 'port'=>1} # Port number on the FC card (0-4) ==== Raises * Hpe3parSdk::HTTPBadRequest - INV_INPUT_MISSING_REQUIRED - Incomplete VLUN info. Missing volumeName or lun, or both hostname and port. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_PORT_SELECTION - Specified port is invalid. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_EXCEEDS_RANGE - The LUN specified exceeds expected range. * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_HOST - The host does not exist * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_VLUN - The VLUN does not exist * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_PORT - The port does not exist * Hpe3parSdk::HTTPForbidden - PERM_DENIED - Permission denied
[ "Deletes", "a", "VLUN", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L523-L530
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.query_qos_rules
def query_qos_rules begin @qos.query_qos_rules rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def query_qos_rules begin @qos.query_qos_rules rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "query_qos_rules", "begin", "@qos", ".", "query_qos_rules", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Gets QoS Rules. ==== Returns Array of QoSRule objects
[ "Gets", "QoS", "Rules", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L538-L545
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.query_qos_rule
def query_qos_rule(target_name, target_type = 'vvset') begin @qos.query_qos_rule(target_name, target_type) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def query_qos_rule(target_name, target_type = 'vvset') begin @qos.query_qos_rule(target_name, target_type) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "query_qos_rule", "(", "target_name", ",", "target_type", "=", "'vvset'", ")", "begin", "@qos", ".", "query_qos_rule", "(", "target_name", ",", "target_type", ")", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Queries a QoS rule ==== Attributes * target_name : Name of the target. When targetType is sys, target name must be sys:all_others. type target_name: String * target_type : Target type is vvset or sys type target_type: String ==== Returns QoSRule object ==== Raises * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_QOS_RULE - QoS rule does not exist. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_ILLEGAL_CHAR - Illegal character in the input.
[ "Queries", "a", "QoS", "rule" ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L565-L572
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.modify_qos_rules
def modify_qos_rules(target_name, qos_rules, target_type = QoStargetTypeConstants::VVSET) if @current_version < @min_version && !qos_rules.nil? qos_rules.delete_if { |key, _value| key == :latencyGoaluSecs } end begin @qos.modify_qos_rules(target_name, qos_rules, target_type) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def modify_qos_rules(target_name, qos_rules, target_type = QoStargetTypeConstants::VVSET) if @current_version < @min_version && !qos_rules.nil? qos_rules.delete_if { |key, _value| key == :latencyGoaluSecs } end begin @qos.modify_qos_rules(target_name, qos_rules, target_type) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "modify_qos_rules", "(", "target_name", ",", "qos_rules", ",", "target_type", "=", "QoStargetTypeConstants", "::", "VVSET", ")", "if", "@current_version", "<", "@min_version", "&&", "!", "qos_rules", ".", "nil?", "qos_rules", ".", "delete_if", "{", "|", "key", ",", "_value", "|", "key", "==", ":latencyGoaluSecs", "}", "end", "begin", "@qos", ".", "modify_qos_rules", "(", "target_name", ",", "qos_rules", ",", "target_type", ")", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Modifies an existing QOS rules The QoS rule can be applied to VV sets. By using sys:all_others, you can apply the rule to all volumes in the system for which no QoS rule has been defined. ioMinGoal and ioMaxLimit must be used together to set I/O limits. Similarly, bwMinGoalKB and bwMaxLimitKB must be used together. If ioMaxLimitOP is set to 2 (no limit), ioMinGoalOP must also be to set to 2 (zero), and vice versa. They cannot be set to 'none' individually. Similarly, if bwMaxLimitOP is set to 2 (no limit), then bwMinGoalOP must also be set to 2. If ioMaxLimitOP is set to 1 (no limit), ioMinGoalOP must also be to set to 1 (zero) and vice versa. Similarly, if bwMaxLimitOP is set to 1 (zero), then bwMinGoalOP must also be set to 1. The ioMinGoalOP and ioMaxLimitOP fields take precedence over the ioMinGoal and ioMaxLimit fields. The bwMinGoalOP and bwMaxLimitOP fields take precedence over the bwMinGoalKB and bwMaxLimitKB fields ==== Attributes * target_name: Name of the target object on which the QoS rule will be created. type target_name: String * target_type: Type of QoS target, either vvset or sys.Refer Hpe3parSdk::QoStargetTypeConstants for complete enumeration type target_type: String * qos_rules: QoS options type qos_rules: Hash qos_rules = { 'priority'=> 2, # Refer Hpe3parSdk::QoSpriorityEnumeration for complete enumeration 'bwMinGoalKB'=> 1024, # bandwidth rate minimum goal in # kilobytes per second 'bwMaxLimitKB'=> 1024, # bandwidth rate maximum limit in # kilobytes per second 'ioMinGoal'=> 10000, # I/O-per-second minimum goal. 'ioMaxLimit'=> 2000000, # I/0-per-second maximum limit 'enable'=> True, # QoS rule for target enabled? 'bwMinGoalOP'=> 1, # zero none operation enum, when set to # 1, bandwidth minimum goal is 0 # when set to 2, the bandwidth minimum # goal is none (NoLimit) 'bwMaxLimitOP'=> 1, # zero none operation enum, when set to # 1, bandwidth maximum limit is 0 # when set to 2, the bandwidth maximum # limit is none (NoLimit) 'ioMinGoalOP'=> 1, # zero none operation enum, when set to # 1, I/O minimum goal minimum goal is 0 # when set to 2, the I/O minimum goal is # none (NoLimit) 'ioMaxLimitOP'=> 1, # zero none operation enum, when set to # 1, I/O maximum limit is 0 # when set to 2, the I/O maximum limit # is none (NoLimit) 'latencyGoal'=> 5000, # Latency goal in milliseconds 'defaultLatency'=> false# Use latencyGoal or defaultLatency? } ==== Raises * Hpe3parSdk::HTTPBadRequest INV_INPUT_EXCEEDS_RANGE - Invalid input: number exceeds expected range. * Hpe3parSdk::HTTPNotFound NON_EXISTENT_QOS_RULE - QoS rule does not exists. * Hpe3parSdk::HTTPBadRequest INV_INPUT_ILLEGAL_CHAR - Illegal character in the input. * Hpe3parSdk::HTTPBadRequest EXISTENT_QOS_RULE - QoS rule already exists. * Hpe3parSdk::HTTPBadRequest INV_INPUT_IO_MIN_GOAL_GRT_MAX_LIMIT - I/O-per-second maximum limit should be greater than the minimum goal. * Hpe3parSdk::HTTPBadRequest INV_INPUT_BW_MIN_GOAL_GRT_MAX_LIMIT - Bandwidth maximum limit should be greater than the minimum goal. * Hpe3parSdk::HTTPBadRequest INV_INPUT_BELOW_RANGE - I/O-per-second limit is below range. Bandwidth limit is below range. * Hpe3parSdk::HTTPBadRequest UNLICENSED_FEATURE - The system is not licensed for QoS.
[ "Modifies", "an", "existing", "QOS", "rules" ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L747-L757
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.delete_qos_rules
def delete_qos_rules(target_name, target_type = QoStargetTypeConstants::VVSET) begin @qos.delete_qos_rules(target_name, target_type) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def delete_qos_rules(target_name, target_type = QoStargetTypeConstants::VVSET) begin @qos.delete_qos_rules(target_name, target_type) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "delete_qos_rules", "(", "target_name", ",", "target_type", "=", "QoStargetTypeConstants", "::", "VVSET", ")", "begin", "@qos", ".", "delete_qos_rules", "(", "target_name", ",", "target_type", ")", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Deletes QoS rules. ==== Attributes * target_name: Name of the target. When target_type is sys, target_name must be sys:all_others. type target_name: String * target_type: target type is vvset or sys type target_type: String ==== Raises * Hpe3parSdk::HTTPNotFound NON_EXISTENT_QOS_RULE - QoS rule does not exist. * Hpe3parSdk::HTTPBadRequest INV_INPUT_ILLEGAL_CHAR - Illegal character in the input
[ "Deletes", "QoS", "rules", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L774-L781
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.get_hosts
def get_hosts begin @host.get_hosts rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def get_hosts begin @host.get_hosts rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "get_hosts", "begin", "@host", ".", "get_hosts", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Gets all hosts. ==== Returns Array of Host.
[ "Gets", "all", "hosts", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L788-L795
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.get_host
def get_host(name) begin @host.get_host(name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def get_host(name) begin @host.get_host(name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "get_host", "(", "name", ")", "begin", "@host", ".", "get_host", "(", "name", ")", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Gets host information by name. ==== Attributes * name - The name of the host to find. type name: String ==== Returns Host. ==== Raises * Hpe3parSdk::HTTPBadRequest - INV_INPUT - Invalid URI syntax. * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_HOST - Host not found. * Hpe3parSdk::HTTPInternalServerError - INT_SERV_ERR - Internal server error. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_ILLEGAL_CHAR - Host name contains invalid character.
[ "Gets", "host", "information", "by", "name", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L818-L825
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.create_host
def create_host(name, iscsi_names = nil, fcwwns = nil, optional = nil) begin @host.create_host(name, iscsi_names, fcwwns, optional) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def create_host(name, iscsi_names = nil, fcwwns = nil, optional = nil) begin @host.create_host(name, iscsi_names, fcwwns, optional) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "create_host", "(", "name", ",", "iscsi_names", "=", "nil", ",", "fcwwns", "=", "nil", ",", "optional", "=", "nil", ")", "begin", "@host", ".", "create_host", "(", "name", ",", "iscsi_names", ",", "fcwwns", ",", "optional", ")", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Creates a new Host. ==== Attributes * name - The name of the host. type name: String * iscsi_names - Array of iSCSI iqns. type iscsi_names: Array * fcwwns - Array of Fibre Channel World Wide Names. type fcwwns: Array * optional - The optional stuff. type optional: Hash optional = { 'persona'=> 1, # Refer Hpe3parSdk::HostPersona for complete enumeration. # 3.1.3 default: Generic-ALUA # 3.1.2 default: General 'domain'=> 'myDomain', # Create the host in the # specified domain, or default # domain if unspecified. 'forceTearDown'=> false, # If True, force to tear down # low-priority VLUN exports. 'descriptors'=> {'location'=> 'earth', # The host's location 'IPAddr'=> '10.10.10.10', # The host's IP address 'os'=> 'linux', # The operating system running on the host. 'model'=> 'ex', # The host's model 'contact'=> 'Smith', # The host's owner and contact 'comment'=> "Joe's box"} # Additional host information } ==== Raises * Hpe3parSdk::HTTPForbidden - PERM_DENIED - Permission denied. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_MISSING_REQUIRED - Name not specified. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_PARAM_CONFLICT - FCWWNs and iSCSINames are both specified. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_EXCEEDS_LENGTH - Host name, domain name, or iSCSI name is too long. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_EMPTY_STR - Input string (for domain name, iSCSI name, etc.) is empty. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_ILLEGAL_CHAR - Any error from host-name or domain-name parsing. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_TOO_MANY_WWN_OR_iSCSI - More than 1024 WWNs or iSCSI names are specified. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_WRONG_TYPE - The length of WWN is not 16. WWN specification contains non-hexadecimal digit. * Hpe3parSdk::HTTPConflict - EXISTENT_PATH - host WWN/iSCSI name already used by another host. * Hpe3parSdk::HTTPConflict - EXISTENT_HOST - host name is already used. * Hpe3parSdk::HTTPBadRequest - NO_SPACE - No space to create host.
[ "Creates", "a", "new", "Host", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L881-L888
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.modify_host
def modify_host(name, mod_request) begin @host.modify_host(name, mod_request) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def modify_host(name, mod_request) begin @host.modify_host(name, mod_request) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "modify_host", "(", "name", ",", "mod_request", ")", "begin", "@host", ".", "modify_host", "(", "name", ",", "mod_request", ")", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Modifies an existing Host. ==== Attributes * name - Name of the host. type name: String * mod_request - Objects for host modification request. type mod_request: Hash mod_request = { 'newName'=> 'myNewName', # New name of the host 'pathOperation'=> 1, # Refer Hpe3parSdk::HostEditOperation for complete enumeration 'FCWWNs'=> [], # One or more WWN to set for the host. 'iSCSINames'=> [], # One or more iSCSI names to set for the host. 'forcePathRemoval'=> false, # If True, remove SSN(s) or # iSCSI(s) even if there are # VLUNs exported to host 'persona'=> 1, # Refer Hpe3parSdk::HostPersona for complete enumeration. 'descriptors'=> {'location'=> 'earth', # The host's location 'IPAddr'=> '10.10.10.10', # The host's IP address 'os'=> 'linux', # The operating system running on the host. 'model'=> 'ex', # The host's model 'contact'=> 'Smith', # The host's owner and contact 'comment'=> 'Joes box'} # Additional host information 'chapOperation'=> 1, # Refer Hpe3parSdk::HostEditOperation for complete enumeration 'chapOperationMode'=> TARGET, # Refer Hpe3parSdk::ChapOperationMode for complete enumeration 'chapName'=> 'MyChapName', # The chap name 'chapSecret'=> 'xyz', # The chap secret for the host or the target 'chapSecretHex'=> false, # If True, the chapSecret is treated as Hex. 'chapRemoveTargetOnly'=> true # If True, then remove target chap only } ==== Raises * Hpe3parSdk::HTTPBadRequest - INV_INPUT - Missing host name. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_PARAM_CONFLICT - Both iSCSINames & FCWWNs are specified. (lot of other possibilities). * Hpe3parSdk::HTTPBadRequest - INV_INPUT_ONE_REQUIRED - iSCSINames or FCWwns missing. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_ONE_REQUIRED - No path operation specified. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_BAD_ENUM_VALUE - Invalid enum value. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_MISSING_REQUIRED - Required fields missing. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_EXCEEDS_LENGTH - Host descriptor argument length, new host name, or iSCSI name is too long. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_ILLEGAL_CHAR - Error parsing host or iSCSI name. * Hpe3parSdk::HTTPConflict - EXISTENT_HOST - New host name is already used. * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_HOST - Host to be modified does not exist. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_TOO_MANY_WWN_OR_iSCSI - More than 1024 WWNs or iSCSI names are specified. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_WRONG_TYPE - Input value is of the wrong type. * Hpe3parSdk::HTTPConflict - EXISTENT_PATH - WWN or iSCSI name is already claimed by other host. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_BAD_LENGTH - CHAP hex secret length is not 16 bytes, or chap ASCII secret length is not 12 to 16 characters. * Hpe3parSdk::HTTPNotFound - NO_INITIATOR_CHAP - Setting target CHAP without initiator CHAP. * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_CHAP - Remove non-existing CHAP. * Hpe3parSdk::HTTPConflict - NON_UNIQUE_CHAP_SECRET - CHAP secret is not unique. * Hpe3parSdk::HTTPConflict - EXPORTED_VLUN - Setting persona with active export; remove a host path on an active export. * Hpe3parSdk::HTTPBadRequest - NON_EXISTENT_PATH - Remove a non-existing path. * Hpe3parSdk::HTTPConflict - LUN_HOSTPERSONA_CONFLICT - LUN number and persona capability conflict. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_DUP_PATH - Duplicate path specified.
[ "Modifies", "an", "existing", "Host", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L966-L973
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.delete_host
def delete_host(name) begin @host.delete_host(name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def delete_host(name) begin @host.delete_host(name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "delete_host", "(", "name", ")", "begin", "@host", ".", "delete_host", "(", "name", ")", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Deletes a host. ==== Attributes * name - The name of host to be deleted. type name: String ==== Raises * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_HOST - Host not found * Hpe3parSdk::HTTPConflict - HOST_IN_SET - Host is a member of a set
[ "Deletes", "a", "host", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L988-L995
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.query_host_by_fc_path
def query_host_by_fc_path(wwn = nil) begin @host.query_host_by_fc_path(wwn) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def query_host_by_fc_path(wwn = nil) begin @host.query_host_by_fc_path(wwn) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "query_host_by_fc_path", "(", "wwn", "=", "nil", ")", "begin", "@host", ".", "query_host_by_fc_path", "(", "wwn", ")", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Finds the host with the specified FC WWN path. ==== Attributes * wwn - Lookup based on WWN. type wwn: String ==== Returns Host with specified FC WWN. ==== Raises * Hpe3parSdk::HTTPBadRequest - INV_INPUT - Invalid URI syntax. * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_HOST - HOST Not Found * Hpe3parSdk::HTTPInternalServerError - INTERNAL_SERVER_ERR - Internal server error. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_ILLEGAL_CHAR - Host name contains invalid character.
[ "Finds", "the", "host", "with", "the", "specified", "FC", "WWN", "path", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L1018-L1025
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.query_host_by_iscsi_path
def query_host_by_iscsi_path(iqn = nil) begin @host.query_host_by_iscsi_path(iqn) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def query_host_by_iscsi_path(iqn = nil) begin @host.query_host_by_iscsi_path(iqn) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "query_host_by_iscsi_path", "(", "iqn", "=", "nil", ")", "begin", "@host", ".", "query_host_by_iscsi_path", "(", "iqn", ")", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Finds the host with the specified iSCSI initiator. ==== Attributes * iqn - Lookup based on iSCSI initiator. type iqn: String ==== Returns Host with specified IQN. ==== Raises * Hpe3parSdk::HTTPBadRequest - INV_INPUT - Invalid URI syntax. * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_HOST - The specified host not found. * Hpe3parSdk::HTTPInternalServerError - INTERNAL_SERVER_ERR - Internal server error. * Hpe3parSdk::HTTPBadRequest - INV_INPUT_ILLEGAL_CHAR - The host name contains invalid character.
[ "Finds", "the", "host", "with", "the", "specified", "iSCSI", "initiator", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L1048-L1055
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.get_host_sets
def get_host_sets begin @host_set.get_host_sets rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def get_host_sets begin @host_set.get_host_sets rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "get_host_sets", "begin", "@host_set", ".", "get_host_sets", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Gets all host sets. ==== Returns Array of HostSet.
[ "Gets", "all", "host", "sets", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L1062-L1069
train
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.delete_host_set
def delete_host_set(name) begin @host_set.delete_host_set(name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
def delete_host_set(name) begin @host_set.delete_host_set(name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
[ "def", "delete_host_set", "(", "name", ")", "begin", "@host_set", ".", "delete_host_set", "(", "name", ")", "rescue", "=>", "ex", "Util", ".", "log_exception", "(", "ex", ",", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", ")", "raise", "ex", "end", "end" ]
Deletes a HostSet. ==== Attributes * name - The hostset to delete. type name: String ==== Raises * Hpe3parSdk::HTTPNotFound - NON_EXISTENT_SET - The set does not exists. * Hpe3parSdk::HTTPConflict - EXPORTED_VLUN - The host set has exported VLUNs.
[ "Deletes", "a", "HostSet", "." ]
f8cfc6e597741be593cf7fe013accadf982ee68b
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L1122-L1129
train