repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
akerl/basiccache
lib/basiccache/caches/cache.rb
BasicCache.Cache.[]
def [](key = nil) key ||= BasicCache.caller_name raise KeyError, 'Key not cached' unless include? key.to_sym @store[key.to_sym] end
ruby
def [](key = nil) key ||= BasicCache.caller_name raise KeyError, 'Key not cached' unless include? key.to_sym @store[key.to_sym] end
[ "def", "[]", "(", "key", "=", "nil", ")", "key", "||=", "BasicCache", ".", "caller_name", "raise", "KeyError", ",", "'Key not cached'", "unless", "include?", "key", ".", "to_sym", "@store", "[", "key", ".", "to_sym", "]", "end" ]
Retrieve cached value
[ "Retrieve", "cached", "value" ]
ac9c60218f2479aedf7f398f1dc2bae70b6d7fa3
https://github.com/akerl/basiccache/blob/ac9c60218f2479aedf7f398f1dc2bae70b6d7fa3/lib/basiccache/caches/cache.rb#L50-L54
train
TonFw/br_open_data
lib/br_open_data/chamber/service.rb
BROpenData::Chamber.Service.setup_propositions
def setup_propositions(params) self.params = { sigla: params[:sigla], numero: params[:numero], ano: params[:ano], datApresentacaoIni: params[:datApresentacaoIni], generoAutor: params[:generoAutor], datApresentacaoFim: params[:datApresentacaoFim], parteNomeAutor: params[:parteNomeAutor], idTipoAutor: params[:idTipoAutor], siglaUFAutor: params[:siglaUFAutor], codEstado: params[:codEstado], codOrgaoEstado: params[:codOrgaoEstado], emTramitacao: params[:emTramitacao], siglaPartidoAutor: params[:siglaPartidoAutor] } end
ruby
def setup_propositions(params) self.params = { sigla: params[:sigla], numero: params[:numero], ano: params[:ano], datApresentacaoIni: params[:datApresentacaoIni], generoAutor: params[:generoAutor], datApresentacaoFim: params[:datApresentacaoFim], parteNomeAutor: params[:parteNomeAutor], idTipoAutor: params[:idTipoAutor], siglaUFAutor: params[:siglaUFAutor], codEstado: params[:codEstado], codOrgaoEstado: params[:codOrgaoEstado], emTramitacao: params[:emTramitacao], siglaPartidoAutor: params[:siglaPartidoAutor] } end
[ "def", "setup_propositions", "(", "params", ")", "self", ".", "params", "=", "{", "sigla", ":", "params", "[", ":sigla", "]", ",", "numero", ":", "params", "[", ":numero", "]", ",", "ano", ":", "params", "[", ":ano", "]", ",", "datApresentacaoIni", ":", "params", "[", ":datApresentacaoIni", "]", ",", "generoAutor", ":", "params", "[", ":generoAutor", "]", ",", "datApresentacaoFim", ":", "params", "[", ":datApresentacaoFim", "]", ",", "parteNomeAutor", ":", "params", "[", ":parteNomeAutor", "]", ",", "idTipoAutor", ":", "params", "[", ":idTipoAutor", "]", ",", "siglaUFAutor", ":", "params", "[", ":siglaUFAutor", "]", ",", "codEstado", ":", "params", "[", ":codEstado", "]", ",", "codOrgaoEstado", ":", "params", "[", ":codOrgaoEstado", "]", ",", "emTramitacao", ":", "params", "[", ":emTramitacao", "]", ",", "siglaPartidoAutor", ":", "params", "[", ":siglaPartidoAutor", "]", "}", "end" ]
SetUp the params to be not nil
[ "SetUp", "the", "params", "to", "be", "not", "nil" ]
c0ddfbf0b38137aa4246d634468520a755248dae
https://github.com/TonFw/br_open_data/blob/c0ddfbf0b38137aa4246d634468520a755248dae/lib/br_open_data/chamber/service.rb#L21-L28
train
barkerest/incline
lib/incline/extensions/jbuilder_template.rb
Incline::Extensions.JbuilderTemplate.api_errors!
def api_errors!(model_name, model_errors) base_error = model_errors[:base] field_errors = model_errors.reject{ |k,_| k == :base } unless base_error.blank? set! 'error', "#{model_name.humanize} #{base_error.map{|e| h(e.to_s)}.join("<br>\n#{model_name.humanize} ")}" end unless field_errors.blank? set! 'fieldErrors' do array! field_errors do |k,v| set! 'name', "#{model_name}.#{k}" set! 'status', v.is_a?(::Array) ? "#{k.to_s.humanize} #{v.map{|e| h(e.to_s)}.join("<br>\n#{k.to_s.humanize} ")}" : "#{k.to_s.humanize} #{h v.to_s}" end end end end
ruby
def api_errors!(model_name, model_errors) base_error = model_errors[:base] field_errors = model_errors.reject{ |k,_| k == :base } unless base_error.blank? set! 'error', "#{model_name.humanize} #{base_error.map{|e| h(e.to_s)}.join("<br>\n#{model_name.humanize} ")}" end unless field_errors.blank? set! 'fieldErrors' do array! field_errors do |k,v| set! 'name', "#{model_name}.#{k}" set! 'status', v.is_a?(::Array) ? "#{k.to_s.humanize} #{v.map{|e| h(e.to_s)}.join("<br>\n#{k.to_s.humanize} ")}" : "#{k.to_s.humanize} #{h v.to_s}" end end end end
[ "def", "api_errors!", "(", "model_name", ",", "model_errors", ")", "base_error", "=", "model_errors", "[", ":base", "]", "field_errors", "=", "model_errors", ".", "reject", "{", "|", "k", ",", "_", "|", "k", "==", ":base", "}", "unless", "base_error", ".", "blank?", "set!", "'error'", ",", "\"#{model_name.humanize} #{base_error.map{|e| h(e.to_s)}.join(\"<br>\\n#{model_name.humanize} \")}\"", "end", "unless", "field_errors", ".", "blank?", "set!", "'fieldErrors'", "do", "array!", "field_errors", "do", "|", "k", ",", "v", "|", "set!", "'name'", ",", "\"#{model_name}.#{k}\"", "set!", "'status'", ",", "v", ".", "is_a?", "(", "::", "Array", ")", "?", "\"#{k.to_s.humanize} #{v.map{|e| h(e.to_s)}.join(\"<br>\\n#{k.to_s.humanize} \")}\"", ":", "\"#{k.to_s.humanize} #{h v.to_s}\"", "end", "end", "end", "end" ]
List out the errors for the model. model_name:: The singular name for the model (e.g. - "user_account") model_errors:: The errors collection from the model. json.api_errors! "user_account", user.errors
[ "List", "out", "the", "errors", "for", "the", "model", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/jbuilder_template.rb#L17-L33
train
wedesoft/multiarray
lib/multiarray/rgb.rb
Hornetseye.RGB_.assign
def assign(value) value = value.simplify if @value.r.respond_to? :assign @value.r.assign value.get.r else @value.r = value.get.r end if @value.g.respond_to? :assign @value.g.assign value.get.g else @value.g = value.get.g end if @value.b.respond_to? :assign @value.b.assign value.get.b else @value.b = value.get.b end value end
ruby
def assign(value) value = value.simplify if @value.r.respond_to? :assign @value.r.assign value.get.r else @value.r = value.get.r end if @value.g.respond_to? :assign @value.g.assign value.get.g else @value.g = value.get.g end if @value.b.respond_to? :assign @value.b.assign value.get.b else @value.b = value.get.b end value end
[ "def", "assign", "(", "value", ")", "value", "=", "value", ".", "simplify", "if", "@value", ".", "r", ".", "respond_to?", ":assign", "@value", ".", "r", ".", "assign", "value", ".", "get", ".", "r", "else", "@value", ".", "r", "=", "value", ".", "get", ".", "r", "end", "if", "@value", ".", "g", ".", "respond_to?", ":assign", "@value", ".", "g", ".", "assign", "value", ".", "get", ".", "g", "else", "@value", ".", "g", "=", "value", ".", "get", ".", "g", "end", "if", "@value", ".", "b", ".", "respond_to?", ":assign", "@value", ".", "b", ".", "assign", "value", ".", "get", ".", "b", "else", "@value", ".", "b", "=", "value", ".", "get", ".", "b", "end", "value", "end" ]
Constructor for native RGB value @param [RGB] value Initial RGB value. Duplicate object @return [RGB_] Duplicate of +self+. Store new value in this object @param [Object] value New value for this object. @return [Object] Returns +value+. @private
[ "Constructor", "for", "native", "RGB", "value" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/rgb.rb#L428-L446
train
wedesoft/multiarray
lib/multiarray/rgb.rb
Hornetseye.Node.r_with_decompose
def r_with_decompose if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy] r_without_decompose elsif typecode < RGB_ decompose 0 else self end end
ruby
def r_with_decompose if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy] r_without_decompose elsif typecode < RGB_ decompose 0 else self end end
[ "def", "r_with_decompose", "if", "typecode", "==", "OBJECT", "or", "is_a?", "(", "Variable", ")", "or", "Thread", ".", "current", "[", ":lazy", "]", "r_without_decompose", "elsif", "typecode", "<", "RGB_", "decompose", "0", "else", "self", "end", "end" ]
Fast extraction for red channel of RGB array @return [Node] Array with red channel.
[ "Fast", "extraction", "for", "red", "channel", "of", "RGB", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/rgb.rb#L531-L539
train
wedesoft/multiarray
lib/multiarray/rgb.rb
Hornetseye.Node.g_with_decompose
def g_with_decompose if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy] g_without_decompose elsif typecode < RGB_ decompose 1 else self end end
ruby
def g_with_decompose if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy] g_without_decompose elsif typecode < RGB_ decompose 1 else self end end
[ "def", "g_with_decompose", "if", "typecode", "==", "OBJECT", "or", "is_a?", "(", "Variable", ")", "or", "Thread", ".", "current", "[", ":lazy", "]", "g_without_decompose", "elsif", "typecode", "<", "RGB_", "decompose", "1", "else", "self", "end", "end" ]
Fast extraction for green channel of RGB array @return [Node] Array with green channel.
[ "Fast", "extraction", "for", "green", "channel", "of", "RGB", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/rgb.rb#L563-L571
train
wedesoft/multiarray
lib/multiarray/rgb.rb
Hornetseye.Node.b_with_decompose
def b_with_decompose if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy] b_without_decompose elsif typecode < RGB_ decompose 2 else self end end
ruby
def b_with_decompose if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy] b_without_decompose elsif typecode < RGB_ decompose 2 else self end end
[ "def", "b_with_decompose", "if", "typecode", "==", "OBJECT", "or", "is_a?", "(", "Variable", ")", "or", "Thread", ".", "current", "[", ":lazy", "]", "b_without_decompose", "elsif", "typecode", "<", "RGB_", "decompose", "2", "else", "self", "end", "end" ]
Fast extraction for blue channel of RGB array @return [Node] Array with blue channel.
[ "Fast", "extraction", "for", "blue", "channel", "of", "RGB", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/rgb.rb#L595-L603
train
wedesoft/multiarray
lib/multiarray/rgb.rb
Hornetseye.Node.b=
def b=(value) if typecode < RGB_ decompose( 2 )[] = value elsif typecode == OBJECT self[] = Hornetseye::lazy do r * RGB.new( 1, 0, 0 ) + g * RGB.new( 0, 1, 0 ) + value * RGB.new( 0, 0, 1 ) end else raise "Cannot assign blue channel to elements of type #{typecode.inspect}" end end
ruby
def b=(value) if typecode < RGB_ decompose( 2 )[] = value elsif typecode == OBJECT self[] = Hornetseye::lazy do r * RGB.new( 1, 0, 0 ) + g * RGB.new( 0, 1, 0 ) + value * RGB.new( 0, 0, 1 ) end else raise "Cannot assign blue channel to elements of type #{typecode.inspect}" end end
[ "def", "b", "=", "(", "value", ")", "if", "typecode", "<", "RGB_", "decompose", "(", "2", ")", "[", "]", "=", "value", "elsif", "typecode", "==", "OBJECT", "self", "[", "]", "=", "Hornetseye", "::", "lazy", "do", "r", "*", "RGB", ".", "new", "(", "1", ",", "0", ",", "0", ")", "+", "g", "*", "RGB", ".", "new", "(", "0", ",", "1", ",", "0", ")", "+", "value", "*", "RGB", ".", "new", "(", "0", ",", "0", ",", "1", ")", "end", "else", "raise", "\"Cannot assign blue channel to elements of type #{typecode.inspect}\"", "end", "end" ]
Assignment for blue channel values of RGB array @param [Object] Value or array of values to assign to blue channel. @return [Object] Returns +value+.
[ "Assignment", "for", "blue", "channel", "values", "of", "RGB", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/rgb.rb#L612-L622
train
wedesoft/multiarray
lib/multiarray/rgb.rb
Hornetseye.Node.histogram_with_rgb
def histogram_with_rgb( *ret_shape ) if typecode < RGB_ [ r, g, b ].histogram *ret_shape else histogram_without_rgb *ret_shape end end
ruby
def histogram_with_rgb( *ret_shape ) if typecode < RGB_ [ r, g, b ].histogram *ret_shape else histogram_without_rgb *ret_shape end end
[ "def", "histogram_with_rgb", "(", "*", "ret_shape", ")", "if", "typecode", "<", "RGB_", "[", "r", ",", "g", ",", "b", "]", ".", "histogram", "*", "ret_shape", "else", "histogram_without_rgb", "*", "ret_shape", "end", "end" ]
Compute colour histogram of this array The array is decomposed to its colour channels and a histogram is computed. @overload histogram( *ret_shape, options = {} ) @param [Array<Integer>] ret_shape Dimensions of resulting histogram. @option options [Node] :weight (Hornetseye::UINT(1)) Weights for computing the histogram. @option options [Boolean] :safe (true) Do a boundary check before creating the histogram. @return [Node] The histogram.
[ "Compute", "colour", "histogram", "of", "this", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/rgb.rb#L649-L655
train
wedesoft/multiarray
lib/multiarray/rgb.rb
Hornetseye.Node.lut_with_rgb
def lut_with_rgb( table, options = {} ) if typecode < RGB_ [ r, g, b ].lut table, options else lut_without_rgb table, options end end
ruby
def lut_with_rgb( table, options = {} ) if typecode < RGB_ [ r, g, b ].lut table, options else lut_without_rgb table, options end end
[ "def", "lut_with_rgb", "(", "table", ",", "options", "=", "{", "}", ")", "if", "typecode", "<", "RGB_", "[", "r", ",", "g", ",", "b", "]", ".", "lut", "table", ",", "options", "else", "lut_without_rgb", "table", ",", "options", "end", "end" ]
Perform element-wise lookup with colour values @param [Node] table The lookup table (LUT). @option options [Boolean] :safe (true) Do a boundary check before creating the element-wise lookup. @return [Node] The result of the lookup operation.
[ "Perform", "element", "-", "wise", "lookup", "with", "colour", "values" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/rgb.rb#L666-L672
train
barkerest/incline
lib/incline/extensions/form_builder.rb
Incline::Extensions.FormBuilder.currency_field
def currency_field(method, options = {}) # get the symbol for the field. sym = options.delete(:currency_symbol) || '$' # get the value if (val = object.send(method)) options[:value] = number_with_precision val, precision: 2, delimiter: ',' end # build the field fld = text_field(method, options) # return the value. "<div class=\"input-symbol\"><span>#{CGI::escape_html sym}</span>#{fld}</div>".html_safe end
ruby
def currency_field(method, options = {}) # get the symbol for the field. sym = options.delete(:currency_symbol) || '$' # get the value if (val = object.send(method)) options[:value] = number_with_precision val, precision: 2, delimiter: ',' end # build the field fld = text_field(method, options) # return the value. "<div class=\"input-symbol\"><span>#{CGI::escape_html sym}</span>#{fld}</div>".html_safe end
[ "def", "currency_field", "(", "method", ",", "options", "=", "{", "}", ")", "sym", "=", "options", ".", "delete", "(", ":currency_symbol", ")", "||", "'$'", "if", "(", "val", "=", "object", ".", "send", "(", "method", ")", ")", "options", "[", ":value", "]", "=", "number_with_precision", "val", ",", "precision", ":", "2", ",", "delimiter", ":", "','", "end", "fld", "=", "text_field", "(", "method", ",", "options", ")", "\"<div class=\\\"input-symbol\\\"><span>#{CGI::escape_html sym}</span>#{fld}</div>\"", ".", "html_safe", "end" ]
Creates a currency entry field. *Valid options:* currency_symbol:: A string used to prefix the input field. Defaults to '$'. All other options will be passed through to the {FormHelper#text_field}[http://apidock.com/rails/ActionView/Helpers/FormHelper/text_field] method. The value will be formatted with comma delimiters and two decimal places. f.currency :pay_rate
[ "Creates", "a", "currency", "entry", "field", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/form_builder.rb#L247-L261
train
barkerest/incline
lib/incline/extensions/form_builder.rb
Incline::Extensions.FormBuilder.text_form_group
def text_form_group(method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = label_w_small(method, lopt) fld = gopt[:wrap].call(text_field(method, fopt)) form_group lbl, fld, gopt end
ruby
def text_form_group(method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = label_w_small(method, lopt) fld = gopt[:wrap].call(text_field(method, fopt)) form_group lbl, fld, gopt end
[ "def", "text_form_group", "(", "method", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "options", ")", "lbl", "=", "label_w_small", "(", "method", ",", "lopt", ")", "fld", "=", "gopt", "[", ":wrap", "]", ".", "call", "(", "text_field", "(", "method", ",", "fopt", ")", ")", "form_group", "lbl", ",", "fld", ",", "gopt", "end" ]
Creates a standard form group with a label and text field. The +options+ is a hash containing label, field, and group options. Prefix label options with +label_+ and field options with +field_+. All other options will apply to the group itself. Group options: class:: The CSS class for the form group. Defaults to 'form-group'. style:: Any styles to apply to the form group. For label options, see #label_w_small. For field options, see {FormHelper#text_field}[http://apidock.com/rails/ActionView/Helpers/FormHelper/text_field].
[ "Creates", "a", "standard", "form", "group", "with", "a", "label", "and", "text", "field", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/form_builder.rb#L302-L307
train
barkerest/incline
lib/incline/extensions/form_builder.rb
Incline::Extensions.FormBuilder.password_form_group
def password_form_group(method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = label_w_small(method, lopt) fld = gopt[:wrap].call(password_field(method, fopt)) form_group lbl, fld, gopt end
ruby
def password_form_group(method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = label_w_small(method, lopt) fld = gopt[:wrap].call(password_field(method, fopt)) form_group lbl, fld, gopt end
[ "def", "password_form_group", "(", "method", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "options", ")", "lbl", "=", "label_w_small", "(", "method", ",", "lopt", ")", "fld", "=", "gopt", "[", ":wrap", "]", ".", "call", "(", "password_field", "(", "method", ",", "fopt", ")", ")", "form_group", "lbl", ",", "fld", ",", "gopt", "end" ]
Creates a standard form group with a label and password field. The +options+ is a hash containing label, field, and group options. Prefix label options with +label_+ and field options with +field_+. All other options will apply to the group itself. Group options: class:: The CSS class for the form group. Defaults to 'form-group'. style:: Any styles to apply to the form group. For label options, see #label_w_small. For field options, see {FormHelper#password_field}[http://apidock.com/rails/ActionView/Helpers/FormHelper/password_field].
[ "Creates", "a", "standard", "form", "group", "with", "a", "label", "and", "password", "field", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/form_builder.rb#L327-L332
train
barkerest/incline
lib/incline/extensions/form_builder.rb
Incline::Extensions.FormBuilder.textarea_form_group
def textarea_form_group(method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = label_w_small method, lopt fld = gopt[:wrap].call(text_area(method, fopt)) form_group lbl, fld, gopt end
ruby
def textarea_form_group(method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = label_w_small method, lopt fld = gopt[:wrap].call(text_area(method, fopt)) form_group lbl, fld, gopt end
[ "def", "textarea_form_group", "(", "method", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "options", ")", "lbl", "=", "label_w_small", "method", ",", "lopt", "fld", "=", "gopt", "[", ":wrap", "]", ".", "call", "(", "text_area", "(", "method", ",", "fopt", ")", ")", "form_group", "lbl", ",", "fld", ",", "gopt", "end" ]
Creates a form group including a label and a text area. The +options+ is a hash containing label, field, and group options. Prefix label options with +label_+ and field options with +field_+. All other options will apply to the group itself. Group options: class:: The CSS class for the form group. Defaults to 'form-group'. style:: Any styles to apply to the form group. For label options, see #label_w_small. For field options, see {FormHelper#text_area}[http://apidock.com/rails/ActionView/Helpers/FormHelper/text_area].
[ "Creates", "a", "form", "group", "including", "a", "label", "and", "a", "text", "area", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/form_builder.rb#L352-L357
train
barkerest/incline
lib/incline/extensions/form_builder.rb
Incline::Extensions.FormBuilder.currency_form_group
def currency_form_group(method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = label_w_small(method, lopt) fld = gopt[:wrap].call(currency_field(method, fopt)) form_group lbl, fld, gopt end
ruby
def currency_form_group(method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = label_w_small(method, lopt) fld = gopt[:wrap].call(currency_field(method, fopt)) form_group lbl, fld, gopt end
[ "def", "currency_form_group", "(", "method", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "options", ")", "lbl", "=", "label_w_small", "(", "method", ",", "lopt", ")", "fld", "=", "gopt", "[", ":wrap", "]", ".", "call", "(", "currency_field", "(", "method", ",", "fopt", ")", ")", "form_group", "lbl", ",", "fld", ",", "gopt", "end" ]
Creates a standard form group with a label and currency field. The +options+ is a hash containing label, field, and group options. Prefix label options with +label_+ and field options with +field_+. All other options will apply to the group itself. Group options: class:: The CSS class for the form group. Defaults to 'form-group'. style:: Any styles to apply to the form group. For label options, see #label_w_small. For field options, see #currency_field.
[ "Creates", "a", "standard", "form", "group", "with", "a", "label", "and", "currency", "field", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/form_builder.rb#L377-L382
train
barkerest/incline
lib/incline/extensions/form_builder.rb
Incline::Extensions.FormBuilder.static_form_group
def static_form_group(method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = label_w_small(method, lopt) fld = gopt[:wrap].call("<input type=\"text\" class=\"form-control disabled\" readonly=\"readonly\" value=\"#{CGI::escape_html(fopt[:value] || object.send(method))}\">") form_group lbl, fld, gopt end
ruby
def static_form_group(method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = label_w_small(method, lopt) fld = gopt[:wrap].call("<input type=\"text\" class=\"form-control disabled\" readonly=\"readonly\" value=\"#{CGI::escape_html(fopt[:value] || object.send(method))}\">") form_group lbl, fld, gopt end
[ "def", "static_form_group", "(", "method", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "options", ")", "lbl", "=", "label_w_small", "(", "method", ",", "lopt", ")", "fld", "=", "gopt", "[", ":wrap", "]", ".", "call", "(", "\"<input type=\\\"text\\\" class=\\\"form-control disabled\\\" readonly=\\\"readonly\\\" value=\\\"#{CGI::escape_html(fopt[:value] || object.send(method))}\\\">\"", ")", "form_group", "lbl", ",", "fld", ",", "gopt", "end" ]
Creates a standard form group with a label and a static text field. The +options+ is a hash containing label, field, and group options. Prefix label options with +label_+ and field options with +field_+. All other options will apply to the group itself. Group options: class:: The CSS class for the form group. Defaults to 'form-group'. style:: Any styles to apply to the form group. For label options, see #label_w_small. Field options: value:: Allows you to specify a value for the static field, otherwise the value from +method+ will be used.
[ "Creates", "a", "standard", "form", "group", "with", "a", "label", "and", "a", "static", "text", "field", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/form_builder.rb#L406-L411
train
barkerest/incline
lib/incline/extensions/form_builder.rb
Incline::Extensions.FormBuilder.datepicker_form_group
def datepicker_form_group(method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = label_w_small(method, lopt) fld = gopt[:wrap].call(date_picker(method, fopt)) form_group lbl, fld, gopt end
ruby
def datepicker_form_group(method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = label_w_small(method, lopt) fld = gopt[:wrap].call(date_picker(method, fopt)) form_group lbl, fld, gopt end
[ "def", "datepicker_form_group", "(", "method", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "options", ")", "lbl", "=", "label_w_small", "(", "method", ",", "lopt", ")", "fld", "=", "gopt", "[", ":wrap", "]", ".", "call", "(", "date_picker", "(", "method", ",", "fopt", ")", ")", "form_group", "lbl", ",", "fld", ",", "gopt", "end" ]
Creates a standard form group with a datepicker field. The +options+ is a hash containing label, field, and group options. Prefix label options with +label_+ and field options with +field_+. All other options will apply to the group itself. Group options: class:: The CSS class for the form group. Defaults to 'form-group'. style:: Any styles to apply to the form group. For label options, see #label_w_small. For field options, see #date_picker.
[ "Creates", "a", "standard", "form", "group", "with", "a", "datepicker", "field", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/form_builder.rb#L431-L436
train
barkerest/incline
lib/incline/extensions/form_builder.rb
Incline::Extensions.FormBuilder.multi_input_form_group
def multi_input_form_group(methods, options = {}) gopt, lopt, fopt = split_form_group_options(options) lopt[:text] ||= gopt[:label] if lopt[:text].blank? lopt[:text] = methods.map {|k,_| k.to_s.humanize }.join(', ') end lbl = label_w_small(methods.map{|k,_| k}.first, lopt) fld = gopt[:wrap].call(multi_input(methods, fopt)) form_group lbl, fld, gopt end
ruby
def multi_input_form_group(methods, options = {}) gopt, lopt, fopt = split_form_group_options(options) lopt[:text] ||= gopt[:label] if lopt[:text].blank? lopt[:text] = methods.map {|k,_| k.to_s.humanize }.join(', ') end lbl = label_w_small(methods.map{|k,_| k}.first, lopt) fld = gopt[:wrap].call(multi_input(methods, fopt)) form_group lbl, fld, gopt end
[ "def", "multi_input_form_group", "(", "methods", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "options", ")", "lopt", "[", ":text", "]", "||=", "gopt", "[", ":label", "]", "if", "lopt", "[", ":text", "]", ".", "blank?", "lopt", "[", ":text", "]", "=", "methods", ".", "map", "{", "|", "k", ",", "_", "|", "k", ".", "to_s", ".", "humanize", "}", ".", "join", "(", "', '", ")", "end", "lbl", "=", "label_w_small", "(", "methods", ".", "map", "{", "|", "k", ",", "_", "|", "k", "}", ".", "first", ",", "lopt", ")", "fld", "=", "gopt", "[", ":wrap", "]", ".", "call", "(", "multi_input", "(", "methods", ",", "fopt", ")", ")", "form_group", "lbl", ",", "fld", ",", "gopt", "end" ]
Creates a standard form group with a multiple input control. The +options+ is a hash containing label, field, and group options. Prefix label options with +label_+ and field options with +field_+. All other options will apply to the group itself. Group options: class:: The CSS class for the form group. Defaults to 'form-group'. style:: Any styles to apply to the form group. For label options, see #label_w_small. For field options, see #multi_input_field.
[ "Creates", "a", "standard", "form", "group", "with", "a", "multiple", "input", "control", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/form_builder.rb#L456-L465
train
barkerest/incline
lib/incline/extensions/form_builder.rb
Incline::Extensions.FormBuilder.check_box_form_group
def check_box_form_group(method, options = {}) gopt, lopt, fopt = split_form_group_options({ class: 'checkbox', field_class: ''}.merge(options)) if gopt[:h_align] gopt[:class] = gopt[:class].blank? ? "col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" : "#{gopt[:class]} col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" end lbl = label method do check_box(method, fopt) + CGI::escape_html(lopt[:text] || method.to_s.humanize) + (lopt[:small_text] ? " <small>(#{CGI::escape_html lopt[:small_text]})</small>" : '').html_safe end "<div class=\"#{gopt[:h_align] ? 'row' : 'form-group'}\"><div class=\"#{gopt[:class]}\">#{lbl}</div></div>".html_safe end
ruby
def check_box_form_group(method, options = {}) gopt, lopt, fopt = split_form_group_options({ class: 'checkbox', field_class: ''}.merge(options)) if gopt[:h_align] gopt[:class] = gopt[:class].blank? ? "col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" : "#{gopt[:class]} col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" end lbl = label method do check_box(method, fopt) + CGI::escape_html(lopt[:text] || method.to_s.humanize) + (lopt[:small_text] ? " <small>(#{CGI::escape_html lopt[:small_text]})</small>" : '').html_safe end "<div class=\"#{gopt[:h_align] ? 'row' : 'form-group'}\"><div class=\"#{gopt[:class]}\">#{lbl}</div></div>".html_safe end
[ "def", "check_box_form_group", "(", "method", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "{", "class", ":", "'checkbox'", ",", "field_class", ":", "''", "}", ".", "merge", "(", "options", ")", ")", "if", "gopt", "[", ":h_align", "]", "gopt", "[", ":class", "]", "=", "gopt", "[", ":class", "]", ".", "blank?", "?", "\"col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}\"", ":", "\"#{gopt[:class]} col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}\"", "end", "lbl", "=", "label", "method", "do", "check_box", "(", "method", ",", "fopt", ")", "+", "CGI", "::", "escape_html", "(", "lopt", "[", ":text", "]", "||", "method", ".", "to_s", ".", "humanize", ")", "+", "(", "lopt", "[", ":small_text", "]", "?", "\" <small>(#{CGI::escape_html lopt[:small_text]})</small>\"", ":", "''", ")", ".", "html_safe", "end", "\"<div class=\\\"#{gopt[:h_align] ? 'row' : 'form-group'}\\\"><div class=\\\"#{gopt[:class]}\\\">#{lbl}</div></div>\"", ".", "html_safe", "end" ]
Creates a standard form group with a checkbox field. The +options+ is a hash containing label, field, and group options. Prefix label options with +label_+ and field options with +field_+. All other options will apply to the group itself. Group options: class:: The CSS class for the form group. h_align:: Create a checkbox aligned to a certain column (1-12) if set. If not set, then a regular form group is generated. For label options, see #label_w_small. For field options, see {FormHelper#check_box}[http://apidock.com/rails/ActionView/Helpers/FormHelper/check_box].
[ "Creates", "a", "standard", "form", "group", "with", "a", "checkbox", "field", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/form_builder.rb#L486-L502
train
barkerest/incline
lib/incline/extensions/form_builder.rb
Incline::Extensions.FormBuilder.recaptcha
def recaptcha(method, options = {}) Incline::Recaptcha::Tag.new(@object_name, method, @template, options).render end
ruby
def recaptcha(method, options = {}) Incline::Recaptcha::Tag.new(@object_name, method, @template, options).render end
[ "def", "recaptcha", "(", "method", ",", "options", "=", "{", "}", ")", "Incline", "::", "Recaptcha", "::", "Tag", ".", "new", "(", "@object_name", ",", "method", ",", "@template", ",", "options", ")", ".", "render", "end" ]
Adds a recaptcha challenge to the form configured to set the specified attribute to the recaptcha response. Valid options: theme:: Can be :dark or :light, defaults to :light. type:: Can be :image or :audio, defaults to :image. size:: Can be :compact or :normal, defaults to :normal. tab_index:: Can be any valid integer if you want a specific tab order, defaults to 0.
[ "Adds", "a", "recaptcha", "challenge", "to", "the", "form", "configured", "to", "set", "the", "specified", "attribute", "to", "the", "recaptcha", "response", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/form_builder.rb#L557-L559
train
gera-gas/cmdlib
lib/cmdlib/application.rb
Cmdlib.App.addopt
def addopt ( opt ) raise TypeError, 'Incorrectly types for option object.' unless opt.instance_of? Cmdlib::Option @options[opt.longname.to_sym] = opt end
ruby
def addopt ( opt ) raise TypeError, 'Incorrectly types for option object.' unless opt.instance_of? Cmdlib::Option @options[opt.longname.to_sym] = opt end
[ "def", "addopt", "(", "opt", ")", "raise", "TypeError", ",", "'Incorrectly types for option object.'", "unless", "opt", ".", "instance_of?", "Cmdlib", "::", "Option", "@options", "[", "opt", ".", "longname", ".", "to_sym", "]", "=", "opt", "end" ]
Add CLICommand object to CLIHandler.
[ "Add", "CLICommand", "object", "to", "CLIHandler", "." ]
2f2a4f99f2de75224bdf02d90ee04112980392b3
https://github.com/gera-gas/cmdlib/blob/2f2a4f99f2de75224bdf02d90ee04112980392b3/lib/cmdlib/application.rb#L36-L41
train
gera-gas/cmdlib
lib/cmdlib/application.rb
Cmdlib.App.display_commands
def display_commands( cmdlist ) maxlen = 0 cmdlist.each do |cmd| maxlen = cmd.name.length if cmd.name.length > maxlen end cmdlist.each do |cmd| print ' ' + cmd.name print "#{' ' * (maxlen - cmd.name.length)} # " puts cmd.brief end end
ruby
def display_commands( cmdlist ) maxlen = 0 cmdlist.each do |cmd| maxlen = cmd.name.length if cmd.name.length > maxlen end cmdlist.each do |cmd| print ' ' + cmd.name print "#{' ' * (maxlen - cmd.name.length)} # " puts cmd.brief end end
[ "def", "display_commands", "(", "cmdlist", ")", "maxlen", "=", "0", "cmdlist", ".", "each", "do", "|", "cmd", "|", "maxlen", "=", "cmd", ".", "name", ".", "length", "if", "cmd", ".", "name", ".", "length", ">", "maxlen", "end", "cmdlist", ".", "each", "do", "|", "cmd", "|", "print", "' '", "+", "cmd", ".", "name", "print", "\"#{' ' * (maxlen - cmd.name.length)} # \"", "puts", "cmd", ".", "brief", "end", "end" ]
Display commands info
[ "Display", "commands", "info" ]
2f2a4f99f2de75224bdf02d90ee04112980392b3
https://github.com/gera-gas/cmdlib/blob/2f2a4f99f2de75224bdf02d90ee04112980392b3/lib/cmdlib/application.rb#L54-L64
train
gera-gas/cmdlib
lib/cmdlib/application.rb
Cmdlib.App.display_options
def display_options( optlist ) maxlen = 0 listout = [] optlist.each_value do |opt| optnames = '' if opt.shortname.length == 0 optnames += ' ' else optnames += OPTION_PREFIX_SHORT + opt.shortname end optnames += ',' optnames += OPTION_PREFIX_LONG + opt.longname if opt.longname.length != 0 optnames += '=[...]' if opt.param == true listout << { :n => optnames, :b => opt.brief } maxlen = optnames.length if optnames.length > maxlen end listout.each do |opt| print ' ' + opt[:n] print "#{' ' * (maxlen - opt[:n].length)} # " puts opt[:b] end end
ruby
def display_options( optlist ) maxlen = 0 listout = [] optlist.each_value do |opt| optnames = '' if opt.shortname.length == 0 optnames += ' ' else optnames += OPTION_PREFIX_SHORT + opt.shortname end optnames += ',' optnames += OPTION_PREFIX_LONG + opt.longname if opt.longname.length != 0 optnames += '=[...]' if opt.param == true listout << { :n => optnames, :b => opt.brief } maxlen = optnames.length if optnames.length > maxlen end listout.each do |opt| print ' ' + opt[:n] print "#{' ' * (maxlen - opt[:n].length)} # " puts opt[:b] end end
[ "def", "display_options", "(", "optlist", ")", "maxlen", "=", "0", "listout", "=", "[", "]", "optlist", ".", "each_value", "do", "|", "opt", "|", "optnames", "=", "''", "if", "opt", ".", "shortname", ".", "length", "==", "0", "optnames", "+=", "' '", "else", "optnames", "+=", "OPTION_PREFIX_SHORT", "+", "opt", ".", "shortname", "end", "optnames", "+=", "','", "optnames", "+=", "OPTION_PREFIX_LONG", "+", "opt", ".", "longname", "if", "opt", ".", "longname", ".", "length", "!=", "0", "optnames", "+=", "'=[...]'", "if", "opt", ".", "param", "==", "true", "listout", "<<", "{", ":n", "=>", "optnames", ",", ":b", "=>", "opt", ".", "brief", "}", "maxlen", "=", "optnames", ".", "length", "if", "optnames", ".", "length", ">", "maxlen", "end", "listout", ".", "each", "do", "|", "opt", "|", "print", "' '", "+", "opt", "[", ":n", "]", "print", "\"#{' ' * (maxlen - opt[:n].length)} # \"", "puts", "opt", "[", ":b", "]", "end", "end" ]
Display options info
[ "Display", "options", "info" ]
2f2a4f99f2de75224bdf02d90ee04112980392b3
https://github.com/gera-gas/cmdlib/blob/2f2a4f99f2de75224bdf02d90ee04112980392b3/lib/cmdlib/application.rb#L68-L89
train
gera-gas/cmdlib
lib/cmdlib/application.rb
Cmdlib.App.run
def run option_parser @options # Check on include version request. if @options[:version].value then puts "#{@name}, version #{@version}" exit end # Check on include help request. if ARGV[0] == 'help' or ARGV[0] == '--help' or ARGV[0] == '-h' then # Help arguments apsent, well then display information about application. if ARGV.size == 1 then puts puts "*** #{@name} ***".center(80) # Display about info. if @about.size > 0 then puts '** ABOUT:' @about.each do |line| puts " #{line}" end end # Display usage info. if @usage.size > 0 then puts puts '** USAGE:' @usage.each do |line| puts " #{line}" end end # Display options info. puts puts '** OPTIONS:' display_options @options # Display commands info if @commands.size > 0 then @commands.each do |c| c.init end puts puts '** COMMANDS:' display_commands @commands puts puts "For details, type: help [COMMAND]" end puts # Help arguments exist, find command in application command list. else ARGV.delete_at( 0 ) cmd = command_select if ARGV.size != 0 then puts "fatal error: unknown command '#{ARGV[0]}'" exit end # Display describe information on command. puts puts Cmdlib::Describe.outtitle( cmd.name ) puts " #{cmd.brief}" if cmd.details.size > 0 then puts puts '** DETAILS:' cmd.details.each do |e| puts " #{e}" end end if cmd.example.size > 0 then puts puts '** EXAMPLE:' cmd.example.each do |e| puts " #{e}" end end # Display options info. if cmd.options.size > 0 then puts puts '** OPTIONS:' display_options cmd.options end # Display commands info. if cmd.subcmd.size > 0 then cmd.subcmd.each do |c| c.init end puts puts '** SUBCOMMANDS:' display_commands cmd.subcmd puts puts "For details, type: help #{cmd.name} [SUBCOMMAND]" end puts end exit end # Handling default command (if exist her). if @default != nil then option_excess if ARGV.size < @default.argnum then puts "fatal error: to few arguments for programm, use <help>." else @default.handler( @options, ARGV ) end exit end # Handling commands. cmd = command_select if cmd == nil then puts "fatal error: unknown command or command miss, use <help>." exit end if ARGV.size < cmd.argnum then puts "fatal error: to few arguments for command, use: <help> <command name>." exit end # Scaning options fir this command option_parser cmd.options option_excess #cmd.init cmd.handler( @options, ARGV ) exit end
ruby
def run option_parser @options # Check on include version request. if @options[:version].value then puts "#{@name}, version #{@version}" exit end # Check on include help request. if ARGV[0] == 'help' or ARGV[0] == '--help' or ARGV[0] == '-h' then # Help arguments apsent, well then display information about application. if ARGV.size == 1 then puts puts "*** #{@name} ***".center(80) # Display about info. if @about.size > 0 then puts '** ABOUT:' @about.each do |line| puts " #{line}" end end # Display usage info. if @usage.size > 0 then puts puts '** USAGE:' @usage.each do |line| puts " #{line}" end end # Display options info. puts puts '** OPTIONS:' display_options @options # Display commands info if @commands.size > 0 then @commands.each do |c| c.init end puts puts '** COMMANDS:' display_commands @commands puts puts "For details, type: help [COMMAND]" end puts # Help arguments exist, find command in application command list. else ARGV.delete_at( 0 ) cmd = command_select if ARGV.size != 0 then puts "fatal error: unknown command '#{ARGV[0]}'" exit end # Display describe information on command. puts puts Cmdlib::Describe.outtitle( cmd.name ) puts " #{cmd.brief}" if cmd.details.size > 0 then puts puts '** DETAILS:' cmd.details.each do |e| puts " #{e}" end end if cmd.example.size > 0 then puts puts '** EXAMPLE:' cmd.example.each do |e| puts " #{e}" end end # Display options info. if cmd.options.size > 0 then puts puts '** OPTIONS:' display_options cmd.options end # Display commands info. if cmd.subcmd.size > 0 then cmd.subcmd.each do |c| c.init end puts puts '** SUBCOMMANDS:' display_commands cmd.subcmd puts puts "For details, type: help #{cmd.name} [SUBCOMMAND]" end puts end exit end # Handling default command (if exist her). if @default != nil then option_excess if ARGV.size < @default.argnum then puts "fatal error: to few arguments for programm, use <help>." else @default.handler( @options, ARGV ) end exit end # Handling commands. cmd = command_select if cmd == nil then puts "fatal error: unknown command or command miss, use <help>." exit end if ARGV.size < cmd.argnum then puts "fatal error: to few arguments for command, use: <help> <command name>." exit end # Scaning options fir this command option_parser cmd.options option_excess #cmd.init cmd.handler( @options, ARGV ) exit end
[ "def", "run", "option_parser", "@options", "if", "@options", "[", ":version", "]", ".", "value", "then", "puts", "\"#{@name}, version #{@version}\"", "exit", "end", "if", "ARGV", "[", "0", "]", "==", "'help'", "or", "ARGV", "[", "0", "]", "==", "'--help'", "or", "ARGV", "[", "0", "]", "==", "'-h'", "then", "if", "ARGV", ".", "size", "==", "1", "then", "puts", "puts", "\"*** #{@name} ***\"", ".", "center", "(", "80", ")", "if", "@about", ".", "size", ">", "0", "then", "puts", "'** ABOUT:'", "@about", ".", "each", "do", "|", "line", "|", "puts", "\" #{line}\"", "end", "end", "if", "@usage", ".", "size", ">", "0", "then", "puts", "puts", "'** USAGE:'", "@usage", ".", "each", "do", "|", "line", "|", "puts", "\" #{line}\"", "end", "end", "puts", "puts", "'** OPTIONS:'", "display_options", "@options", "if", "@commands", ".", "size", ">", "0", "then", "@commands", ".", "each", "do", "|", "c", "|", "c", ".", "init", "end", "puts", "puts", "'** COMMANDS:'", "display_commands", "@commands", "puts", "puts", "\"For details, type: help [COMMAND]\"", "end", "puts", "else", "ARGV", ".", "delete_at", "(", "0", ")", "cmd", "=", "command_select", "if", "ARGV", ".", "size", "!=", "0", "then", "puts", "\"fatal error: unknown command '#{ARGV[0]}'\"", "exit", "end", "puts", "puts", "Cmdlib", "::", "Describe", ".", "outtitle", "(", "cmd", ".", "name", ")", "puts", "\" #{cmd.brief}\"", "if", "cmd", ".", "details", ".", "size", ">", "0", "then", "puts", "puts", "'** DETAILS:'", "cmd", ".", "details", ".", "each", "do", "|", "e", "|", "puts", "\" #{e}\"", "end", "end", "if", "cmd", ".", "example", ".", "size", ">", "0", "then", "puts", "puts", "'** EXAMPLE:'", "cmd", ".", "example", ".", "each", "do", "|", "e", "|", "puts", "\" #{e}\"", "end", "end", "if", "cmd", ".", "options", ".", "size", ">", "0", "then", "puts", "puts", "'** OPTIONS:'", "display_options", "cmd", ".", "options", "end", "if", "cmd", ".", "subcmd", ".", "size", ">", "0", "then", "cmd", ".", "subcmd", ".", "each", "do", "|", "c", "|", "c", ".", "init", "end", "puts", "puts", "'** SUBCOMMANDS:'", "display_commands", "cmd", ".", "subcmd", "puts", "puts", "\"For details, type: help #{cmd.name} [SUBCOMMAND]\"", "end", "puts", "end", "exit", "end", "if", "@default", "!=", "nil", "then", "option_excess", "if", "ARGV", ".", "size", "<", "@default", ".", "argnum", "then", "puts", "\"fatal error: to few arguments for programm, use <help>.\"", "else", "@default", ".", "handler", "(", "@options", ",", "ARGV", ")", "end", "exit", "end", "cmd", "=", "command_select", "if", "cmd", "==", "nil", "then", "puts", "\"fatal error: unknown command or command miss, use <help>.\"", "exit", "end", "if", "ARGV", ".", "size", "<", "cmd", ".", "argnum", "then", "puts", "\"fatal error: to few arguments for command, use: <help> <command name>.\"", "exit", "end", "option_parser", "cmd", ".", "options", "option_excess", "cmd", ".", "handler", "(", "@options", ",", "ARGV", ")", "exit", "end" ]
Main method to run application.
[ "Main", "method", "to", "run", "application", "." ]
2f2a4f99f2de75224bdf02d90ee04112980392b3
https://github.com/gera-gas/cmdlib/blob/2f2a4f99f2de75224bdf02d90ee04112980392b3/lib/cmdlib/application.rb#L93-L210
train
gera-gas/cmdlib
lib/cmdlib/application.rb
Cmdlib.App.command_select
def command_select command = command_search( @commands, ARGV[0] ) if command != nil then # remove command name from ARGV and search next. ARGV.delete_at( 0 ) ARGV.each do |arg| cmd = command_search( command.subcmd, arg ) break if cmd == nil ARGV.delete_at( 0 ) command = cmd end end return command end
ruby
def command_select command = command_search( @commands, ARGV[0] ) if command != nil then # remove command name from ARGV and search next. ARGV.delete_at( 0 ) ARGV.each do |arg| cmd = command_search( command.subcmd, arg ) break if cmd == nil ARGV.delete_at( 0 ) command = cmd end end return command end
[ "def", "command_select", "command", "=", "command_search", "(", "@commands", ",", "ARGV", "[", "0", "]", ")", "if", "command", "!=", "nil", "then", "ARGV", ".", "delete_at", "(", "0", ")", "ARGV", ".", "each", "do", "|", "arg", "|", "cmd", "=", "command_search", "(", "command", ".", "subcmd", ",", "arg", ")", "break", "if", "cmd", "==", "nil", "ARGV", ".", "delete_at", "(", "0", ")", "command", "=", "cmd", "end", "end", "return", "command", "end" ]
Select and return command object in application.
[ "Select", "and", "return", "command", "object", "in", "application", "." ]
2f2a4f99f2de75224bdf02d90ee04112980392b3
https://github.com/gera-gas/cmdlib/blob/2f2a4f99f2de75224bdf02d90ee04112980392b3/lib/cmdlib/application.rb#L228-L241
train
gera-gas/cmdlib
lib/cmdlib/application.rb
Cmdlib.App.option_excess
def option_excess ARGV.each do |opt| o = getopt( opt ) if o[:n] != '' then puts "fatal error: unknown option '#{o[:t]}#{o[:n]}'" exit end end end
ruby
def option_excess ARGV.each do |opt| o = getopt( opt ) if o[:n] != '' then puts "fatal error: unknown option '#{o[:t]}#{o[:n]}'" exit end end end
[ "def", "option_excess", "ARGV", ".", "each", "do", "|", "opt", "|", "o", "=", "getopt", "(", "opt", ")", "if", "o", "[", ":n", "]", "!=", "''", "then", "puts", "\"fatal error: unknown option '#{o[:t]}#{o[:n]}'\"", "exit", "end", "end", "end" ]
Check ARGV to exess options.
[ "Check", "ARGV", "to", "exess", "options", "." ]
2f2a4f99f2de75224bdf02d90ee04112980392b3
https://github.com/gera-gas/cmdlib/blob/2f2a4f99f2de75224bdf02d90ee04112980392b3/lib/cmdlib/application.rb#L268-L276
train
gera-gas/cmdlib
lib/cmdlib/application.rb
Cmdlib.App.option_parser
def option_parser( optlist ) return if optlist.size == 0 deletelist = [] # search option in argument list. ARGV.each_with_index do |opt,i| o = getopt( opt ) if o[:n] != '' and o[:n] != 'h' and o[:n] != 'help' o[:i] = i # Search in application list result = option_search( o, optlist ) if result != nil then deletelist << opt result = option_set( o, optlist[result] ) deletelist << result if result != '' end end end # delete option from ARGV. deletelist.each do |n| ARGV.delete( n ) end end
ruby
def option_parser( optlist ) return if optlist.size == 0 deletelist = [] # search option in argument list. ARGV.each_with_index do |opt,i| o = getopt( opt ) if o[:n] != '' and o[:n] != 'h' and o[:n] != 'help' o[:i] = i # Search in application list result = option_search( o, optlist ) if result != nil then deletelist << opt result = option_set( o, optlist[result] ) deletelist << result if result != '' end end end # delete option from ARGV. deletelist.each do |n| ARGV.delete( n ) end end
[ "def", "option_parser", "(", "optlist", ")", "return", "if", "optlist", ".", "size", "==", "0", "deletelist", "=", "[", "]", "ARGV", ".", "each_with_index", "do", "|", "opt", ",", "i", "|", "o", "=", "getopt", "(", "opt", ")", "if", "o", "[", ":n", "]", "!=", "''", "and", "o", "[", ":n", "]", "!=", "'h'", "and", "o", "[", ":n", "]", "!=", "'help'", "o", "[", ":i", "]", "=", "i", "result", "=", "option_search", "(", "o", ",", "optlist", ")", "if", "result", "!=", "nil", "then", "deletelist", "<<", "opt", "result", "=", "option_set", "(", "o", ",", "optlist", "[", "result", "]", ")", "deletelist", "<<", "result", "if", "result", "!=", "''", "end", "end", "end", "deletelist", ".", "each", "do", "|", "n", "|", "ARGV", ".", "delete", "(", "n", ")", "end", "end" ]
Parsing options in command line.
[ "Parsing", "options", "in", "command", "line", "." ]
2f2a4f99f2de75224bdf02d90ee04112980392b3
https://github.com/gera-gas/cmdlib/blob/2f2a4f99f2de75224bdf02d90ee04112980392b3/lib/cmdlib/application.rb#L345-L366
train
outcomesinsights/dbtap
lib/dbtap/tapper.rb
Dbtap.Tapper.run
def run puts (1..tests.length).to_s tests.each_with_index do |test, i| begin if test.is_ok? ok(test, i) else not_ok(test, i) end rescue Sequel::DatabaseError puts $!.sql raise $! end end end
ruby
def run puts (1..tests.length).to_s tests.each_with_index do |test, i| begin if test.is_ok? ok(test, i) else not_ok(test, i) end rescue Sequel::DatabaseError puts $!.sql raise $! end end end
[ "def", "run", "puts", "(", "1", "..", "tests", ".", "length", ")", ".", "to_s", "tests", ".", "each_with_index", "do", "|", "test", ",", "i", "|", "begin", "if", "test", ".", "is_ok?", "ok", "(", "test", ",", "i", ")", "else", "not_ok", "(", "test", ",", "i", ")", "end", "rescue", "Sequel", "::", "DatabaseError", "puts", "$!", ".", "sql", "raise", "$!", "end", "end", "end" ]
Drives the evaluation of each test, emitting TAP-compliant messages for each test
[ "Drives", "the", "evaluation", "of", "each", "test", "emitting", "TAP", "-", "compliant", "messages", "for", "each", "test" ]
aa3b623fd7fc0668098c1c73dd69141afbbc1ea3
https://github.com/outcomesinsights/dbtap/blob/aa3b623fd7fc0668098c1c73dd69141afbbc1ea3/lib/dbtap/tapper.rb#L18-L32
train
outcomesinsights/dbtap
lib/dbtap/tapper.rb
Dbtap.Tapper.ok
def ok(test, i) message = "ok #{i + 1}" message += ' - ' + test.name if test.name puts message end
ruby
def ok(test, i) message = "ok #{i + 1}" message += ' - ' + test.name if test.name puts message end
[ "def", "ok", "(", "test", ",", "i", ")", "message", "=", "\"ok #{i + 1}\"", "message", "+=", "' - '", "+", "test", ".", "name", "if", "test", ".", "name", "puts", "message", "end" ]
Emits a TAP-compliant OK message
[ "Emits", "a", "TAP", "-", "compliant", "OK", "message" ]
aa3b623fd7fc0668098c1c73dd69141afbbc1ea3
https://github.com/outcomesinsights/dbtap/blob/aa3b623fd7fc0668098c1c73dd69141afbbc1ea3/lib/dbtap/tapper.rb#L36-L40
train
outcomesinsights/dbtap
lib/dbtap/tapper.rb
Dbtap.Tapper.not_ok
def not_ok(test, i) message = "not ok #{i + 1}" message += ' - ' + test.name if test.name message += "\n " + test.errors.join("\n ") if test.errors puts message end
ruby
def not_ok(test, i) message = "not ok #{i + 1}" message += ' - ' + test.name if test.name message += "\n " + test.errors.join("\n ") if test.errors puts message end
[ "def", "not_ok", "(", "test", ",", "i", ")", "message", "=", "\"not ok #{i + 1}\"", "message", "+=", "' - '", "+", "test", ".", "name", "if", "test", ".", "name", "message", "+=", "\"\\n \"", "+", "test", ".", "errors", ".", "join", "(", "\"\\n \"", ")", "if", "test", ".", "errors", "puts", "message", "end" ]
Emits a TAP-compliant NOT OK message
[ "Emits", "a", "TAP", "-", "compliant", "NOT", "OK", "message" ]
aa3b623fd7fc0668098c1c73dd69141afbbc1ea3
https://github.com/outcomesinsights/dbtap/blob/aa3b623fd7fc0668098c1c73dd69141afbbc1ea3/lib/dbtap/tapper.rb#L43-L48
train
nrser/nrser.rb
lib/nrser/decorate.rb
NRSER.Decorate.resolve_method
def resolve_method name:, default_type: nil name_string = name.to_s # .gsub( /\A\@\@/, '.' ).gsub( /\A\@/, '#' ) case name_string when Meta::Names::Method::Bare bare_name = Meta::Names::Method::Bare.new name_string case default_type&.to_sym when nil raise NRSER::ArgumentError.new \ "When `default_type:` param is `nil` `name:` must start with '.'", "or '#'", name: name when :singleton, :class method bare_name when :instance instance_method bare_name else raise NRSER::ArgumentError.new \ "`default_type:` param must be `nil`, `:instance`, `:singleton` or", "`:class`, found", default_type.inspect, name: name, default_type: default_type end when Meta::Names::Method::Singleton method Meta::Names::Method::Singleton.new( name_string ).bare_name when Meta::Names::Method::Instance instance_method Meta::Names::Method::Instance.new( name_string ).bare_name else raise NRSER::ArgumentError.new \ "`name:` does not look like a method name:", name.inspect end end
ruby
def resolve_method name:, default_type: nil name_string = name.to_s # .gsub( /\A\@\@/, '.' ).gsub( /\A\@/, '#' ) case name_string when Meta::Names::Method::Bare bare_name = Meta::Names::Method::Bare.new name_string case default_type&.to_sym when nil raise NRSER::ArgumentError.new \ "When `default_type:` param is `nil` `name:` must start with '.'", "or '#'", name: name when :singleton, :class method bare_name when :instance instance_method bare_name else raise NRSER::ArgumentError.new \ "`default_type:` param must be `nil`, `:instance`, `:singleton` or", "`:class`, found", default_type.inspect, name: name, default_type: default_type end when Meta::Names::Method::Singleton method Meta::Names::Method::Singleton.new( name_string ).bare_name when Meta::Names::Method::Instance instance_method Meta::Names::Method::Instance.new( name_string ).bare_name else raise NRSER::ArgumentError.new \ "`name:` does not look like a method name:", name.inspect end end
[ "def", "resolve_method", "name", ":", ",", "default_type", ":", "nil", "name_string", "=", "name", ".", "to_s", "case", "name_string", "when", "Meta", "::", "Names", "::", "Method", "::", "Bare", "bare_name", "=", "Meta", "::", "Names", "::", "Method", "::", "Bare", ".", "new", "name_string", "case", "default_type", "&.", "to_sym", "when", "nil", "raise", "NRSER", "::", "ArgumentError", ".", "new", "\"When `default_type:` param is `nil` `name:` must start with '.'\"", ",", "\"or '#'\"", ",", "name", ":", "name", "when", ":singleton", ",", ":class", "method", "bare_name", "when", ":instance", "instance_method", "bare_name", "else", "raise", "NRSER", "::", "ArgumentError", ".", "new", "\"`default_type:` param must be `nil`, `:instance`, `:singleton` or\"", ",", "\"`:class`, found\"", ",", "default_type", ".", "inspect", ",", "name", ":", "name", ",", "default_type", ":", "default_type", "end", "when", "Meta", "::", "Names", "::", "Method", "::", "Singleton", "method", "Meta", "::", "Names", "::", "Method", "::", "Singleton", ".", "new", "(", "name_string", ")", ".", "bare_name", "when", "Meta", "::", "Names", "::", "Method", "::", "Instance", "instance_method", "Meta", "::", "Names", "::", "Method", "::", "Instance", ".", "new", "(", "name_string", ")", ".", "bare_name", "else", "raise", "NRSER", "::", "ArgumentError", ".", "new", "\"`name:` does not look like a method name:\"", ",", "name", ".", "inspect", "end", "end" ]
Resolve a method name to a reference object. @param [#to_s] name The method name, preferably prefixed with `.` or `#` to indicate if it's a singleton or class method. @param [nil | :singleton | :class | :instance | #to_sym ] default_type Identifies singleton/instance methods when the name doesn't. `:singleton` and `:class` mean the same thing. Tries to convert values to symbols before matching them. If `nil`, `name:` **MUST** identify the method type by prefix. @return [ ::Method | ::UnboundMethod ] The method object. @raise [NRSER::ArgumentError]
[ "Resolve", "a", "method", "name", "to", "a", "reference", "object", "." ]
7db9a729ec65894dfac13fd50851beae8b809738
https://github.com/nrser/nrser.rb/blob/7db9a729ec65894dfac13fd50851beae8b809738/lib/nrser/decorate.rb#L49-L88
train
cbetta/snapshotify
lib/snapshotify/url.rb
Snapshotify.Url.parse_uri
def parse_uri self.uri = URI.parse(raw_url) uri.path = "/" if uri.path.empty? uri.fragment = nil # if this fails, mark the URL as invalid rescue self.valid = false end
ruby
def parse_uri self.uri = URI.parse(raw_url) uri.path = "/" if uri.path.empty? uri.fragment = nil # if this fails, mark the URL as invalid rescue self.valid = false end
[ "def", "parse_uri", "self", ".", "uri", "=", "URI", ".", "parse", "(", "raw_url", ")", "uri", ".", "path", "=", "\"/\"", "if", "uri", ".", "path", ".", "empty?", "uri", ".", "fragment", "=", "nil", "rescue", "self", ".", "valid", "=", "false", "end" ]
Parse the raw URL as a URI object
[ "Parse", "the", "raw", "URL", "as", "a", "URI", "object" ]
7f5553f4281ffc5bf0e54da1141574bd15af45b6
https://github.com/cbetta/snapshotify/blob/7f5553f4281ffc5bf0e54da1141574bd15af45b6/lib/snapshotify/url.rb#L76-L83
train
bblack16/bblib-ruby
lib/bblib/core/mixins/family_tree.rb
BBLib.FamilyTree.descendants
def descendants(include_singletons = false) return _inherited_by.map { |c| [c, c.descendants] }.flatten.uniq if BBLib.in_opal? ObjectSpace.each_object(Class).select do |c| (include_singletons || !c.singleton_class?) && c < self end end
ruby
def descendants(include_singletons = false) return _inherited_by.map { |c| [c, c.descendants] }.flatten.uniq if BBLib.in_opal? ObjectSpace.each_object(Class).select do |c| (include_singletons || !c.singleton_class?) && c < self end end
[ "def", "descendants", "(", "include_singletons", "=", "false", ")", "return", "_inherited_by", ".", "map", "{", "|", "c", "|", "[", "c", ",", "c", ".", "descendants", "]", "}", ".", "flatten", ".", "uniq", "if", "BBLib", ".", "in_opal?", "ObjectSpace", ".", "each_object", "(", "Class", ")", ".", "select", "do", "|", "c", "|", "(", "include_singletons", "||", "!", "c", ".", "singleton_class?", ")", "&&", "c", "<", "self", "end", "end" ]
Return all classes that inherit from this class
[ "Return", "all", "classes", "that", "inherit", "from", "this", "class" ]
274eedeb583cc56243884fd041645488d5bd08a9
https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/core/mixins/family_tree.rb#L8-L13
train
bblack16/bblib-ruby
lib/bblib/core/mixins/family_tree.rb
BBLib.FamilyTree.direct_descendants
def direct_descendants(include_singletons = false) return _inherited_by if BBLib.in_opal? ObjectSpace.each_object(Class).select do |c| (include_singletons || !c.singleton_class?) && c.ancestors[1..-1].find { |k| k.is_a?(Class) } == self end end
ruby
def direct_descendants(include_singletons = false) return _inherited_by if BBLib.in_opal? ObjectSpace.each_object(Class).select do |c| (include_singletons || !c.singleton_class?) && c.ancestors[1..-1].find { |k| k.is_a?(Class) } == self end end
[ "def", "direct_descendants", "(", "include_singletons", "=", "false", ")", "return", "_inherited_by", "if", "BBLib", ".", "in_opal?", "ObjectSpace", ".", "each_object", "(", "Class", ")", ".", "select", "do", "|", "c", "|", "(", "include_singletons", "||", "!", "c", ".", "singleton_class?", ")", "&&", "c", ".", "ancestors", "[", "1", "..", "-", "1", "]", ".", "find", "{", "|", "k", "|", "k", ".", "is_a?", "(", "Class", ")", "}", "==", "self", "end", "end" ]
Return all classes that directly inherit from this class
[ "Return", "all", "classes", "that", "directly", "inherit", "from", "this", "class" ]
274eedeb583cc56243884fd041645488d5bd08a9
https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/core/mixins/family_tree.rb#L18-L23
train
bblack16/bblib-ruby
lib/bblib/core/mixins/family_tree.rb
BBLib.FamilyTree.instances
def instances(descendants = true) inst = ObjectSpace.each_object(self).to_a descendants ? inst : inst.select { |i| i.class == self } end
ruby
def instances(descendants = true) inst = ObjectSpace.each_object(self).to_a descendants ? inst : inst.select { |i| i.class == self } end
[ "def", "instances", "(", "descendants", "=", "true", ")", "inst", "=", "ObjectSpace", ".", "each_object", "(", "self", ")", ".", "to_a", "descendants", "?", "inst", ":", "inst", ".", "select", "{", "|", "i", "|", "i", ".", "class", "==", "self", "}", "end" ]
Return all live instances of the class Passing false will not include instances of sub classes
[ "Return", "all", "live", "instances", "of", "the", "class", "Passing", "false", "will", "not", "include", "instances", "of", "sub", "classes" ]
274eedeb583cc56243884fd041645488d5bd08a9
https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/core/mixins/family_tree.rb#L27-L30
train
DigitPaint/html_mockup
lib/html_mockup/release/scm/git.rb
HtmlMockup::Release::Scm.Git.find_git_dir
def find_git_dir(path) path = Pathname.new(path).realpath while path.parent != path && !(path + ".git").directory? path = path.parent end path = path + ".git" raise "Could not find suitable .git dir in #{path}" if !path.directory? path end
ruby
def find_git_dir(path) path = Pathname.new(path).realpath while path.parent != path && !(path + ".git").directory? path = path.parent end path = path + ".git" raise "Could not find suitable .git dir in #{path}" if !path.directory? path end
[ "def", "find_git_dir", "(", "path", ")", "path", "=", "Pathname", ".", "new", "(", "path", ")", ".", "realpath", "while", "path", ".", "parent", "!=", "path", "&&", "!", "(", "path", "+", "\".git\"", ")", ".", "directory?", "path", "=", "path", ".", "parent", "end", "path", "=", "path", "+", "\".git\"", "raise", "\"Could not find suitable .git dir in #{path}\"", "if", "!", "path", ".", "directory?", "path", "end" ]
Find the git dir
[ "Find", "the", "git", "dir" ]
976edadc01216b82a8cea177f53fb32559eaf41e
https://github.com/DigitPaint/html_mockup/blob/976edadc01216b82a8cea177f53fb32559eaf41e/lib/html_mockup/release/scm/git.rb#L86-L97
train
davidrichards/gearbox
lib/gearbox/rdf_collection.rb
Gearbox.RDFCollection.has_key?
def has_key?(key, opts={}) key = normalize_key(key) if opts.fetch(:normalize, true) @source.has_key?(key) end
ruby
def has_key?(key, opts={}) key = normalize_key(key) if opts.fetch(:normalize, true) @source.has_key?(key) end
[ "def", "has_key?", "(", "key", ",", "opts", "=", "{", "}", ")", "key", "=", "normalize_key", "(", "key", ")", "if", "opts", ".", "fetch", "(", ":normalize", ",", "true", ")", "@source", ".", "has_key?", "(", "key", ")", "end" ]
Lookup whether the key exists. @param [String, Symbol] key @param [Hash, nil] opts. :normalize => false will lookup the key as provided. @return [Boolean]
[ "Lookup", "whether", "the", "key", "exists", "." ]
322e1a44394b6323d849c5e65acad66cdf284aac
https://github.com/davidrichards/gearbox/blob/322e1a44394b6323d849c5e65acad66cdf284aac/lib/gearbox/rdf_collection.rb#L55-L58
train
jinx/core
lib/jinx/importer.rb
Jinx.Importer.const_missing
def const_missing(sym) # Load the class definitions in the source directory, if necessary. # If a load is performed as a result of referencing the given symbol, # then dereference the class constant again after the load, since the class # might have been loaded or referenced during the load. unless defined? @introspected then configure_importer load_definitions return const_get(sym) end # Append the symbol to the package to make the Java class name. logger.debug { "Detecting whether #{sym} is a #{self} Java class..." } klass = @packages.detect_value do |pkg| begin java_import "#{pkg}.#{sym}" rescue NameError nil end end if klass then logger.debug { "Added #{klass} to the #{self} module." } else # Not a Java class; print a log message and pass along the error. logger.debug { "#{sym} is not recognized as a #{self} Java class." } super end # Introspect the Java class meta-data, if necessary. unless introspected?(klass) then add_metadata(klass) # Print the class meta-data. logger.info(klass.pp_s) end klass end
ruby
def const_missing(sym) # Load the class definitions in the source directory, if necessary. # If a load is performed as a result of referencing the given symbol, # then dereference the class constant again after the load, since the class # might have been loaded or referenced during the load. unless defined? @introspected then configure_importer load_definitions return const_get(sym) end # Append the symbol to the package to make the Java class name. logger.debug { "Detecting whether #{sym} is a #{self} Java class..." } klass = @packages.detect_value do |pkg| begin java_import "#{pkg}.#{sym}" rescue NameError nil end end if klass then logger.debug { "Added #{klass} to the #{self} module." } else # Not a Java class; print a log message and pass along the error. logger.debug { "#{sym} is not recognized as a #{self} Java class." } super end # Introspect the Java class meta-data, if necessary. unless introspected?(klass) then add_metadata(klass) # Print the class meta-data. logger.info(klass.pp_s) end klass end
[ "def", "const_missing", "(", "sym", ")", "unless", "defined?", "@introspected", "then", "configure_importer", "load_definitions", "return", "const_get", "(", "sym", ")", "end", "logger", ".", "debug", "{", "\"Detecting whether #{sym} is a #{self} Java class...\"", "}", "klass", "=", "@packages", ".", "detect_value", "do", "|", "pkg", "|", "begin", "java_import", "\"#{pkg}.#{sym}\"", "rescue", "NameError", "nil", "end", "end", "if", "klass", "then", "logger", ".", "debug", "{", "\"Added #{klass} to the #{self} module.\"", "}", "else", "logger", ".", "debug", "{", "\"#{sym} is not recognized as a #{self} Java class.\"", "}", "super", "end", "unless", "introspected?", "(", "klass", ")", "then", "add_metadata", "(", "klass", ")", "logger", ".", "info", "(", "klass", ".", "pp_s", ")", "end", "klass", "end" ]
Imports a Java class constant on demand. If the class does not already include this module's mixin, then the mixin is included in the class. @param [Symbol, String] sym the missing constant @return [Class] the imported class @raise [NameError] if the symbol is not an importable Java class
[ "Imports", "a", "Java", "class", "constant", "on", "demand", ".", "If", "the", "class", "does", "not", "already", "include", "this", "module", "s", "mixin", "then", "the", "mixin", "is", "included", "in", "the", "class", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/importer.rb#L48-L84
train
jinx/core
lib/jinx/importer.rb
Jinx.Importer.configure_importer
def configure_importer # The default package conforms to the JRuby convention for mapping a package name # to a module name. @packages ||= [name.split('::').map { |n| n.downcase }.join('.')] @packages.each do |pkg| begin eval "java_package Java::#{pkg}" rescue Exception => e raise ArgumentError.new("#{self} Java package #{pkg} not found - #{$!}") end end # The introspected classes. @introspected = Set.new # The name => file hash for file definitions that are not in the packages. @unresolved_defs = {} end
ruby
def configure_importer # The default package conforms to the JRuby convention for mapping a package name # to a module name. @packages ||= [name.split('::').map { |n| n.downcase }.join('.')] @packages.each do |pkg| begin eval "java_package Java::#{pkg}" rescue Exception => e raise ArgumentError.new("#{self} Java package #{pkg} not found - #{$!}") end end # The introspected classes. @introspected = Set.new # The name => file hash for file definitions that are not in the packages. @unresolved_defs = {} end
[ "def", "configure_importer", "@packages", "||=", "[", "name", ".", "split", "(", "'::'", ")", ".", "map", "{", "|", "n", "|", "n", ".", "downcase", "}", ".", "join", "(", "'.'", ")", "]", "@packages", ".", "each", "do", "|", "pkg", "|", "begin", "eval", "\"java_package Java::#{pkg}\"", "rescue", "Exception", "=>", "e", "raise", "ArgumentError", ".", "new", "(", "\"#{self} Java package #{pkg} not found - #{$!}\"", ")", "end", "end", "@introspected", "=", "Set", ".", "new", "@unresolved_defs", "=", "{", "}", "end" ]
Initializes this importer on demand. This method is called the first time a class is referenced.
[ "Initializes", "this", "importer", "on", "demand", ".", "This", "method", "is", "called", "the", "first", "time", "a", "class", "is", "referenced", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/importer.rb#L109-L124
train
jinx/core
lib/jinx/importer.rb
Jinx.Importer.load_dir
def load_dir(dir) logger.debug { "Loading the class definitions in #{dir}..." } # Import the classes. srcs = sources(dir) # Introspect and load the classes in reverse class order, i.e. superclass before subclass. klasses = srcs.keys.transitive_closure { |k| [k.superclass] }.select { |k| srcs[k] }.reverse # Introspect the classes as necessary. klasses.each { |klass| add_metadata(klass) unless introspected?(klass) } # Load the classes. klasses.each do |klass| file = srcs[klass] load_definition(klass, file) end logger.debug { "Loaded the class definitions in #{dir}." } end
ruby
def load_dir(dir) logger.debug { "Loading the class definitions in #{dir}..." } # Import the classes. srcs = sources(dir) # Introspect and load the classes in reverse class order, i.e. superclass before subclass. klasses = srcs.keys.transitive_closure { |k| [k.superclass] }.select { |k| srcs[k] }.reverse # Introspect the classes as necessary. klasses.each { |klass| add_metadata(klass) unless introspected?(klass) } # Load the classes. klasses.each do |klass| file = srcs[klass] load_definition(klass, file) end logger.debug { "Loaded the class definitions in #{dir}." } end
[ "def", "load_dir", "(", "dir", ")", "logger", ".", "debug", "{", "\"Loading the class definitions in #{dir}...\"", "}", "srcs", "=", "sources", "(", "dir", ")", "klasses", "=", "srcs", ".", "keys", ".", "transitive_closure", "{", "|", "k", "|", "[", "k", ".", "superclass", "]", "}", ".", "select", "{", "|", "k", "|", "srcs", "[", "k", "]", "}", ".", "reverse", "klasses", ".", "each", "{", "|", "klass", "|", "add_metadata", "(", "klass", ")", "unless", "introspected?", "(", "klass", ")", "}", "klasses", ".", "each", "do", "|", "klass", "|", "file", "=", "srcs", "[", "klass", "]", "load_definition", "(", "klass", ",", "file", ")", "end", "logger", ".", "debug", "{", "\"Loaded the class definitions in #{dir}.\"", "}", "end" ]
Loads the Ruby source files in the given directory. @param [String] dir the source directory
[ "Loads", "the", "Ruby", "source", "files", "in", "the", "given", "directory", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/importer.rb#L160-L174
train
jinx/core
lib/jinx/importer.rb
Jinx.Importer.add_metadata
def add_metadata(klass) logger.debug("Adding #{self}::#{klass.qp} metadata...") # Mark the class as introspected. Do this first to preclude a recursive loop back # into this method when the references are introspected below. @introspected << klass # Add the superclass meta-data if necessary. add_superclass_metadata(klass) # Include this resource module into the class, unless this has already occurred. unless klass < self then m = self klass.class_eval { include m } end # Import the class into this resource module, unless this has already occurred. name = klass.name.demodulize unless const_defined?(name) then java_import(klass.java_class.name) end # Add introspection capability to the class. md_mod = @metadata_module || Metadata logger.debug { "Extending #{self}::#{klass.qp} with #{md_mod.name}..." } klass.extend(md_mod) # Set the class domain module. klass.domain_module = self # Introspect the Java properties. klass.introspect # Add the {attribute => value} initializer. klass.add_attribute_value_initializer if Class === klass # Add referenced domain class metadata as necessary. klass.each_property do |prop| ref = prop.type if ref.nil? then raise MetadataError.new("#{self} #{prop} domain type is unknown.") end if introspectible?(ref) then logger.debug { "Introspecting the #{klass.qp} #{prop} reference type #{ref.qp}..." } add_metadata(ref) end end # If the class has a definition file but does not resolve to a standard package, then # load it now based on the demodulized class name match. file = @unresolved_defs[name] load_definition(klass, file) if file logger.debug("#{self}::#{klass.qp} metadata added.") end
ruby
def add_metadata(klass) logger.debug("Adding #{self}::#{klass.qp} metadata...") # Mark the class as introspected. Do this first to preclude a recursive loop back # into this method when the references are introspected below. @introspected << klass # Add the superclass meta-data if necessary. add_superclass_metadata(klass) # Include this resource module into the class, unless this has already occurred. unless klass < self then m = self klass.class_eval { include m } end # Import the class into this resource module, unless this has already occurred. name = klass.name.demodulize unless const_defined?(name) then java_import(klass.java_class.name) end # Add introspection capability to the class. md_mod = @metadata_module || Metadata logger.debug { "Extending #{self}::#{klass.qp} with #{md_mod.name}..." } klass.extend(md_mod) # Set the class domain module. klass.domain_module = self # Introspect the Java properties. klass.introspect # Add the {attribute => value} initializer. klass.add_attribute_value_initializer if Class === klass # Add referenced domain class metadata as necessary. klass.each_property do |prop| ref = prop.type if ref.nil? then raise MetadataError.new("#{self} #{prop} domain type is unknown.") end if introspectible?(ref) then logger.debug { "Introspecting the #{klass.qp} #{prop} reference type #{ref.qp}..." } add_metadata(ref) end end # If the class has a definition file but does not resolve to a standard package, then # load it now based on the demodulized class name match. file = @unresolved_defs[name] load_definition(klass, file) if file logger.debug("#{self}::#{klass.qp} metadata added.") end
[ "def", "add_metadata", "(", "klass", ")", "logger", ".", "debug", "(", "\"Adding #{self}::#{klass.qp} metadata...\"", ")", "@introspected", "<<", "klass", "add_superclass_metadata", "(", "klass", ")", "unless", "klass", "<", "self", "then", "m", "=", "self", "klass", ".", "class_eval", "{", "include", "m", "}", "end", "name", "=", "klass", ".", "name", ".", "demodulize", "unless", "const_defined?", "(", "name", ")", "then", "java_import", "(", "klass", ".", "java_class", ".", "name", ")", "end", "md_mod", "=", "@metadata_module", "||", "Metadata", "logger", ".", "debug", "{", "\"Extending #{self}::#{klass.qp} with #{md_mod.name}...\"", "}", "klass", ".", "extend", "(", "md_mod", ")", "klass", ".", "domain_module", "=", "self", "klass", ".", "introspect", "klass", ".", "add_attribute_value_initializer", "if", "Class", "===", "klass", "klass", ".", "each_property", "do", "|", "prop", "|", "ref", "=", "prop", ".", "type", "if", "ref", ".", "nil?", "then", "raise", "MetadataError", ".", "new", "(", "\"#{self} #{prop} domain type is unknown.\"", ")", "end", "if", "introspectible?", "(", "ref", ")", "then", "logger", ".", "debug", "{", "\"Introspecting the #{klass.qp} #{prop} reference type #{ref.qp}...\"", "}", "add_metadata", "(", "ref", ")", "end", "end", "file", "=", "@unresolved_defs", "[", "name", "]", "load_definition", "(", "klass", ",", "file", ")", "if", "file", "logger", ".", "debug", "(", "\"#{self}::#{klass.qp} metadata added.\"", ")", "end" ]
Introspects the given class meta-data. @param [Class] klass the Java class or interface to introspect
[ "Introspects", "the", "given", "class", "meta", "-", "data", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/importer.rb#L230-L272
train
Thermatix/ruta
lib/ruta/route.rb
Ruta.Route.get
def get params=nil path = if params paramaterize params.dup else @url end { path: path, title: self.flags.fetch(:title){nil}, params: params_hash(params), route: self } end
ruby
def get params=nil path = if params paramaterize params.dup else @url end { path: path, title: self.flags.fetch(:title){nil}, params: params_hash(params), route: self } end
[ "def", "get", "params", "=", "nil", "path", "=", "if", "params", "paramaterize", "params", ".", "dup", "else", "@url", "end", "{", "path", ":", "path", ",", "title", ":", "self", ".", "flags", ".", "fetch", "(", ":title", ")", "{", "nil", "}", ",", "params", ":", "params_hash", "(", "params", ")", ",", "route", ":", "self", "}", "end" ]
get route hash and paramaterize url if needed @param [Array<String,Number,Boolean>] params to replace named params in the returned url @return [Symbol => Number,String,Route] hash specificly formatted: { url: of the route with named params replaced, title: the name of page if the url has one, params: a list of all the params used in the route, route: the #Route object }
[ "get", "route", "hash", "and", "paramaterize", "url", "if", "needed" ]
b4a6e3bc7c0c4b66c804023d638b173e3f61e157
https://github.com/Thermatix/ruta/blob/b4a6e3bc7c0c4b66c804023d638b173e3f61e157/lib/ruta/route.rb#L78-L90
train
Thermatix/ruta
lib/ruta/route.rb
Ruta.Route.match
def match(path) if match = @regexp.match(path) params = {} @named.each_with_index { |name, i| params[name] = match[i + 1] } if @type == :handlers { path: path, title: self.flags.fetch(:title){nil}, params: params, route: self } else false end end
ruby
def match(path) if match = @regexp.match(path) params = {} @named.each_with_index { |name, i| params[name] = match[i + 1] } if @type == :handlers { path: path, title: self.flags.fetch(:title){nil}, params: params, route: self } else false end end
[ "def", "match", "(", "path", ")", "if", "match", "=", "@regexp", ".", "match", "(", "path", ")", "params", "=", "{", "}", "@named", ".", "each_with_index", "{", "|", "name", ",", "i", "|", "params", "[", "name", "]", "=", "match", "[", "i", "+", "1", "]", "}", "if", "@type", "==", ":handlers", "{", "path", ":", "path", ",", "title", ":", "self", ".", "flags", ".", "fetch", "(", ":title", ")", "{", "nil", "}", ",", "params", ":", "params", ",", "route", ":", "self", "}", "else", "false", "end", "end" ]
match this route against a given path @param [String,Regex] path to match against @return [Hash,false] (see #get) or false if there is no match
[ "match", "this", "route", "against", "a", "given", "path" ]
b4a6e3bc7c0c4b66c804023d638b173e3f61e157
https://github.com/Thermatix/ruta/blob/b4a6e3bc7c0c4b66c804023d638b173e3f61e157/lib/ruta/route.rb#L96-L109
train
Thermatix/ruta
lib/ruta/route.rb
Ruta.Route.execute_handler
def execute_handler params={},path=nil case @type when :handlers @handlers.each do |handler_ident| handler = @context_ref.handlers.fetch(handler_ident) {raise "handler #{handler_ident} doesn't exist in context #{@context_ref.ref}"} component = handler.(params,path||@url,&:call) Context.current_context = @context_ref.ref if component.class == Proc component.call else Context.renderer.call(component,handler_ident) end Context.current_context = :no_context end when :context Context.wipe Context.render handlers History.push(@context_ref.ref,"",[],@context_ref.ref) end end
ruby
def execute_handler params={},path=nil case @type when :handlers @handlers.each do |handler_ident| handler = @context_ref.handlers.fetch(handler_ident) {raise "handler #{handler_ident} doesn't exist in context #{@context_ref.ref}"} component = handler.(params,path||@url,&:call) Context.current_context = @context_ref.ref if component.class == Proc component.call else Context.renderer.call(component,handler_ident) end Context.current_context = :no_context end when :context Context.wipe Context.render handlers History.push(@context_ref.ref,"",[],@context_ref.ref) end end
[ "def", "execute_handler", "params", "=", "{", "}", ",", "path", "=", "nil", "case", "@type", "when", ":handlers", "@handlers", ".", "each", "do", "|", "handler_ident", "|", "handler", "=", "@context_ref", ".", "handlers", ".", "fetch", "(", "handler_ident", ")", "{", "raise", "\"handler #{handler_ident} doesn't exist in context #{@context_ref.ref}\"", "}", "component", "=", "handler", ".", "(", "params", ",", "path", "||", "@url", ",", "&", ":call", ")", "Context", ".", "current_context", "=", "@context_ref", ".", "ref", "if", "component", ".", "class", "==", "Proc", "component", ".", "call", "else", "Context", ".", "renderer", ".", "call", "(", "component", ",", "handler_ident", ")", "end", "Context", ".", "current_context", "=", ":no_context", "end", "when", ":context", "Context", ".", "wipe", "Context", ".", "render", "handlers", "History", ".", "push", "(", "@context_ref", ".", "ref", ",", "\"\"", ",", "[", "]", ",", "@context_ref", ".", "ref", ")", "end", "end" ]
execute's route's associated handlers @param [Symbol => String] params from the route with there respective keys @param [String] path containing params placed into there respective named positions
[ "execute", "s", "route", "s", "associated", "handlers" ]
b4a6e3bc7c0c4b66c804023d638b173e3f61e157
https://github.com/Thermatix/ruta/blob/b4a6e3bc7c0c4b66c804023d638b173e3f61e157/lib/ruta/route.rb#L115-L134
train
sealink/dependent_restrict
lib/dependent_restrict.rb
DependentRestrict.ClassMethods.has_one
def has_one(*args, &extension) options = args.extract_options! || {} if VALID_DEPENDENTS.include?(options[:dependent].try(:to_sym)) reflection = if active_record_4? association_id, scope = *args restrict_create_reflection(:has_one, association_id, scope || {}, options, self) else association_id = args[0] create_reflection(:has_one, association_id, options, self) end add_dependency_callback!(reflection, options) end args << options super(*args, &extension) end
ruby
def has_one(*args, &extension) options = args.extract_options! || {} if VALID_DEPENDENTS.include?(options[:dependent].try(:to_sym)) reflection = if active_record_4? association_id, scope = *args restrict_create_reflection(:has_one, association_id, scope || {}, options, self) else association_id = args[0] create_reflection(:has_one, association_id, options, self) end add_dependency_callback!(reflection, options) end args << options super(*args, &extension) end
[ "def", "has_one", "(", "*", "args", ",", "&", "extension", ")", "options", "=", "args", ".", "extract_options!", "||", "{", "}", "if", "VALID_DEPENDENTS", ".", "include?", "(", "options", "[", ":dependent", "]", ".", "try", "(", ":to_sym", ")", ")", "reflection", "=", "if", "active_record_4?", "association_id", ",", "scope", "=", "*", "args", "restrict_create_reflection", "(", ":has_one", ",", "association_id", ",", "scope", "||", "{", "}", ",", "options", ",", "self", ")", "else", "association_id", "=", "args", "[", "0", "]", "create_reflection", "(", ":has_one", ",", "association_id", ",", "options", ",", "self", ")", "end", "add_dependency_callback!", "(", "reflection", ",", "options", ")", "end", "args", "<<", "options", "super", "(", "*", "args", ",", "&", "extension", ")", "end" ]
We should be aliasing configure_dependency_for_has_many but that method is private so we can't. We alias has_many instead trying to be as fair as we can to the original behaviour.
[ "We", "should", "be", "aliasing", "configure_dependency_for_has_many", "but", "that", "method", "is", "private", "so", "we", "can", "t", ".", "We", "alias", "has_many", "instead", "trying", "to", "be", "as", "fair", "as", "we", "can", "to", "the", "original", "behaviour", "." ]
443a0c30194eaa262ff07cb05cfd499d20a76fb9
https://github.com/sealink/dependent_restrict/blob/443a0c30194eaa262ff07cb05cfd499d20a76fb9/lib/dependent_restrict.rb#L19-L33
train
robertwahler/mutagem
lib/mutagem/task.rb
Mutagem.Task.run
def run pipe = IO.popen(@cmd + " 2>&1") @pid = pipe.pid begin @output = pipe.readlines pipe.close @exitstatus = $?.exitstatus rescue => e @exception = e end end
ruby
def run pipe = IO.popen(@cmd + " 2>&1") @pid = pipe.pid begin @output = pipe.readlines pipe.close @exitstatus = $?.exitstatus rescue => e @exception = e end end
[ "def", "run", "pipe", "=", "IO", ".", "popen", "(", "@cmd", "+", "\" 2>&1\"", ")", "@pid", "=", "pipe", ".", "pid", "begin", "@output", "=", "pipe", ".", "readlines", "pipe", ".", "close", "@exitstatus", "=", "$?", ".", "exitstatus", "rescue", "=>", "e", "@exception", "=", "e", "end", "end" ]
run the cmd
[ "run", "the", "cmd" ]
75ac2f7fd307f575d81114b32e1a3b09c526e01d
https://github.com/robertwahler/mutagem/blob/75ac2f7fd307f575d81114b32e1a3b09c526e01d/lib/mutagem/task.rb#L49-L59
train
zeke/ratpack
lib/sinatra/ratpack.rb
Sinatra.Ratpack.link_to
def link_to(content,href=nil,options={}) href ||= content options.update :href => url_for(href) content_tag :a, content, options end
ruby
def link_to(content,href=nil,options={}) href ||= content options.update :href => url_for(href) content_tag :a, content, options end
[ "def", "link_to", "(", "content", ",", "href", "=", "nil", ",", "options", "=", "{", "}", ")", "href", "||=", "content", "options", ".", "update", ":href", "=>", "url_for", "(", "href", ")", "content_tag", ":a", ",", "content", ",", "options", "end" ]
Works like link_to, but href is optional. If no href supplied, content is used as href link_to "grub", "/food", :class => "eats" # <a href="/food" class="eats">grub</a> link_to "http://foo.com" # <a href="http://foo.com">http://foo.com</a> link_to "home" # <a href="/home">home</a>
[ "Works", "like", "link_to", "but", "href", "is", "optional", ".", "If", "no", "href", "supplied", "content", "is", "used", "as", "href" ]
51a8b329fe0af4c24441cc5ed6d836111ba9c0a3
https://github.com/zeke/ratpack/blob/51a8b329fe0af4c24441cc5ed6d836111ba9c0a3/lib/sinatra/ratpack.rb#L64-L68
train
kukushkin/aerogel-core
lib/aerogel/core/reloader.rb
Aerogel.Reloader.check!
def check! return unless @files @file_list = file_list( @files ) new_signature = signature( @file_list ) if @signature != new_signature # reload file list puts "* Aerogel::Reloader reloading: #{@file_list}, group: #{@group}" if @group # invoke :before group actions Aerogel::Reloader.reloaders.select{|r| r.group == @group && r.opts[:before] }.each do |r| r.action.call @file_list end end @action.call @file_list @signature = new_signature if @group # invoke :after group actions Aerogel::Reloader.reloaders.select{|r| r.group == @group && r.opts[:after] }.each do |r| r.action.call @file_list end end end end
ruby
def check! return unless @files @file_list = file_list( @files ) new_signature = signature( @file_list ) if @signature != new_signature # reload file list puts "* Aerogel::Reloader reloading: #{@file_list}, group: #{@group}" if @group # invoke :before group actions Aerogel::Reloader.reloaders.select{|r| r.group == @group && r.opts[:before] }.each do |r| r.action.call @file_list end end @action.call @file_list @signature = new_signature if @group # invoke :after group actions Aerogel::Reloader.reloaders.select{|r| r.group == @group && r.opts[:after] }.each do |r| r.action.call @file_list end end end end
[ "def", "check!", "return", "unless", "@files", "@file_list", "=", "file_list", "(", "@files", ")", "new_signature", "=", "signature", "(", "@file_list", ")", "if", "@signature", "!=", "new_signature", "puts", "\"* Aerogel::Reloader reloading: #{@file_list}, group: #{@group}\"", "if", "@group", "Aerogel", "::", "Reloader", ".", "reloaders", ".", "select", "{", "|", "r", "|", "r", ".", "group", "==", "@group", "&&", "r", ".", "opts", "[", ":before", "]", "}", ".", "each", "do", "|", "r", "|", "r", ".", "action", ".", "call", "@file_list", "end", "end", "@action", ".", "call", "@file_list", "@signature", "=", "new_signature", "if", "@group", "Aerogel", "::", "Reloader", ".", "reloaders", ".", "select", "{", "|", "r", "|", "r", ".", "group", "==", "@group", "&&", "r", ".", "opts", "[", ":after", "]", "}", ".", "each", "do", "|", "r", "|", "r", ".", "action", ".", "call", "@file_list", "end", "end", "end", "end" ]
Checks if files are changed and reloads if so.
[ "Checks", "if", "files", "are", "changed", "and", "reloads", "if", "so", "." ]
e156af6b237c410c1ee75e5cdf1b10075e7fbb8b
https://github.com/kukushkin/aerogel-core/blob/e156af6b237c410c1ee75e5cdf1b10075e7fbb8b/lib/aerogel/core/reloader.rb#L68-L90
train
kukushkin/aerogel-core
lib/aerogel/core/reloader.rb
Aerogel.Reloader.file_list
def file_list( files ) case files when String [files] when Array files when Proc files.call # result should respond to #each else [] end end
ruby
def file_list( files ) case files when String [files] when Array files when Proc files.call # result should respond to #each else [] end end
[ "def", "file_list", "(", "files", ")", "case", "files", "when", "String", "[", "files", "]", "when", "Array", "files", "when", "Proc", "files", ".", "call", "else", "[", "]", "end", "end" ]
Re-calculates file list
[ "Re", "-", "calculates", "file", "list" ]
e156af6b237c410c1ee75e5cdf1b10075e7fbb8b
https://github.com/kukushkin/aerogel-core/blob/e156af6b237c410c1ee75e5cdf1b10075e7fbb8b/lib/aerogel/core/reloader.rb#L94-L105
train
inside-track/remi
lib/remi/dsl.rb
Remi.Dsl.dsl_eval
def dsl_eval(dsl, fallback_dsl, *args, &block) exec_in_proxy_context(dsl, fallback_dsl, Docile::FallbackContextProxy, *args, &block) dsl end
ruby
def dsl_eval(dsl, fallback_dsl, *args, &block) exec_in_proxy_context(dsl, fallback_dsl, Docile::FallbackContextProxy, *args, &block) dsl end
[ "def", "dsl_eval", "(", "dsl", ",", "fallback_dsl", ",", "*", "args", ",", "&", "block", ")", "exec_in_proxy_context", "(", "dsl", ",", "fallback_dsl", ",", "Docile", "::", "FallbackContextProxy", ",", "*", "args", ",", "&", "block", ")", "dsl", "end" ]
Execute a block in the context of an object whose methods represent the commands in a DSL. @note Use with an *imperative* DSL (commands modify the context object) Use this method to execute an *imperative* DSL, which means that: 1. Each command mutates the state of the DSL context object 2. The return value of each command is ignored 3. The final return value is the original context object @param dsl [Object] context object whose methods make up the DSL @param fallback_dsl [Object] context object that the DSL should fallback to @param args [Array] arguments to be passed to the block @param block [Proc] the block of DSL commands to be executed against the `dsl` context object @return [Object] the `dsl` context object after executing the block
[ "Execute", "a", "block", "in", "the", "context", "of", "an", "object", "whose", "methods", "represent", "the", "commands", "in", "a", "DSL", "." ]
f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7
https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/dsl.rb#L63-L66
train
LAS-IT/equitrac_utilities
lib/equitrac_utilities/user_actions.rb
EquitracUtilities.UserActions.user_modify
def user_modify(attribs) defaults = {user_name: "!", min_bal: "!", email: "!", dept_name: "!", pimary_pin: "!", secondary_pin: "!", quota: "!", alternate_pin: "!", home_server: "!", locked: "!", location: "!", default_bc: "!", additional_info: "!", home_folder: "!"} attribs = defaults.merge(attribs) attribs = check_atrribs(attribs) "modify ur #{attribs[:user_id]} \"#{attribs[:user_name]}\"" + " #{attribs[:min_bal]} #{attribs[:email]} #{attribs[:dept_name]}" + " #{attribs[:primary_pin]} #{attribs[:secondary_pin]}" + " #{attribs[:quota]} #{attribs[:alternate_pin]}" + " #{attribs[:home_server]} #{attribs[:locked]}" + " #{attribs[:location]} #{attribs[:default_bc]}" + " #{attribs[:additional_info]} #{attribs[:home_folder]}" end
ruby
def user_modify(attribs) defaults = {user_name: "!", min_bal: "!", email: "!", dept_name: "!", pimary_pin: "!", secondary_pin: "!", quota: "!", alternate_pin: "!", home_server: "!", locked: "!", location: "!", default_bc: "!", additional_info: "!", home_folder: "!"} attribs = defaults.merge(attribs) attribs = check_atrribs(attribs) "modify ur #{attribs[:user_id]} \"#{attribs[:user_name]}\"" + " #{attribs[:min_bal]} #{attribs[:email]} #{attribs[:dept_name]}" + " #{attribs[:primary_pin]} #{attribs[:secondary_pin]}" + " #{attribs[:quota]} #{attribs[:alternate_pin]}" + " #{attribs[:home_server]} #{attribs[:locked]}" + " #{attribs[:location]} #{attribs[:default_bc]}" + " #{attribs[:additional_info]} #{attribs[:home_folder]}" end
[ "def", "user_modify", "(", "attribs", ")", "defaults", "=", "{", "user_name", ":", "\"!\"", ",", "min_bal", ":", "\"!\"", ",", "email", ":", "\"!\"", ",", "dept_name", ":", "\"!\"", ",", "pimary_pin", ":", "\"!\"", ",", "secondary_pin", ":", "\"!\"", ",", "quota", ":", "\"!\"", ",", "alternate_pin", ":", "\"!\"", ",", "home_server", ":", "\"!\"", ",", "locked", ":", "\"!\"", ",", "location", ":", "\"!\"", ",", "default_bc", ":", "\"!\"", ",", "additional_info", ":", "\"!\"", ",", "home_folder", ":", "\"!\"", "}", "attribs", "=", "defaults", ".", "merge", "(", "attribs", ")", "attribs", "=", "check_atrribs", "(", "attribs", ")", "\"modify ur #{attribs[:user_id]} \\\"#{attribs[:user_name]}\\\"\"", "+", "\" #{attribs[:min_bal]} #{attribs[:email]} #{attribs[:dept_name]}\"", "+", "\" #{attribs[:primary_pin]} #{attribs[:secondary_pin]}\"", "+", "\" #{attribs[:quota]} #{attribs[:alternate_pin]}\"", "+", "\" #{attribs[:home_server]} #{attribs[:locked]}\"", "+", "\" #{attribs[:location]} #{attribs[:default_bc]}\"", "+", "\" #{attribs[:additional_info]} #{attribs[:home_folder]}\"", "end" ]
Process to lock a user in the Equitrac System @param attr [Hash] this attribute MUST include: { user_id: "userid" } @return [String] Formatted for EQCmd.exe command execution
[ "Process", "to", "lock", "a", "user", "in", "the", "Equitrac", "System" ]
98eb25da612ccd0c1010c18d5a726e130184df66
https://github.com/LAS-IT/equitrac_utilities/blob/98eb25da612ccd0c1010c18d5a726e130184df66/lib/equitrac_utilities/user_actions.rb#L130-L145
train
LAS-IT/equitrac_utilities
lib/equitrac_utilities/user_actions.rb
EquitracUtilities.UserActions.user_adjust_set
def user_adjust_set(attribs) defaults = {new_bal: 0.0, description: nil} attribs = defaults.merge(attribs) attribs = check_atrribs(attribs) "adjust ur #{attribs[:user_id]} set #{attribs[:new_bal]} #{attribs[:description]}" end
ruby
def user_adjust_set(attribs) defaults = {new_bal: 0.0, description: nil} attribs = defaults.merge(attribs) attribs = check_atrribs(attribs) "adjust ur #{attribs[:user_id]} set #{attribs[:new_bal]} #{attribs[:description]}" end
[ "def", "user_adjust_set", "(", "attribs", ")", "defaults", "=", "{", "new_bal", ":", "0.0", ",", "description", ":", "nil", "}", "attribs", "=", "defaults", ".", "merge", "(", "attribs", ")", "attribs", "=", "check_atrribs", "(", "attribs", ")", "\"adjust ur #{attribs[:user_id]} set #{attribs[:new_bal]} #{attribs[:description]}\"", "end" ]
Process to set a new balance for a user in the Equitrac System @param attr [Hash] this attribute MUST include: { user_id: "userid" } @note attr new_bal defaults to 0, if not included in the attributes @return [String] Formatted for EQCmd.exe command execution
[ "Process", "to", "set", "a", "new", "balance", "for", "a", "user", "in", "the", "Equitrac", "System" ]
98eb25da612ccd0c1010c18d5a726e130184df66
https://github.com/LAS-IT/equitrac_utilities/blob/98eb25da612ccd0c1010c18d5a726e130184df66/lib/equitrac_utilities/user_actions.rb#L152-L157
train
fwolfst/kalindar
lib/kalindar/event.rb
Kalindar.Event.start_time_f
def start_time_f day #puts "start #{start_time} : #{start_time.class} #{start_time.to_date} #{day}" if dtstart.class == Date # whole day "" elsif start_time.to_date == day.to_date start_time.strftime('%H:%M') else "..." end end
ruby
def start_time_f day #puts "start #{start_time} : #{start_time.class} #{start_time.to_date} #{day}" if dtstart.class == Date # whole day "" elsif start_time.to_date == day.to_date start_time.strftime('%H:%M') else "..." end end
[ "def", "start_time_f", "day", "if", "dtstart", ".", "class", "==", "Date", "\"\"", "elsif", "start_time", ".", "to_date", "==", "day", ".", "to_date", "start_time", ".", "strftime", "(", "'%H:%M'", ")", "else", "\"...\"", "end", "end" ]
Time it starts at day, or '...'
[ "Time", "it", "starts", "at", "day", "or", "..." ]
8c81f0bc85ac8f7d0fc43b8e25eff6c08329b2c9
https://github.com/fwolfst/kalindar/blob/8c81f0bc85ac8f7d0fc43b8e25eff6c08329b2c9/lib/kalindar/event.rb#L20-L30
train
fwolfst/kalindar
lib/kalindar/event.rb
Kalindar.Event.finish_time_f
def finish_time_f day if dtend.class == Date # whole day "" elsif finish_time.to_date == day.to_date finish_time.strftime('%H:%M') else return "..." end end
ruby
def finish_time_f day if dtend.class == Date # whole day "" elsif finish_time.to_date == day.to_date finish_time.strftime('%H:%M') else return "..." end end
[ "def", "finish_time_f", "day", "if", "dtend", ".", "class", "==", "Date", "\"\"", "elsif", "finish_time", ".", "to_date", "==", "day", ".", "to_date", "finish_time", ".", "strftime", "(", "'%H:%M'", ")", "else", "return", "\"...\"", "end", "end" ]
Time it finishes at day, or '...'
[ "Time", "it", "finishes", "at", "day", "or", "..." ]
8c81f0bc85ac8f7d0fc43b8e25eff6c08329b2c9
https://github.com/fwolfst/kalindar/blob/8c81f0bc85ac8f7d0fc43b8e25eff6c08329b2c9/lib/kalindar/event.rb#L33-L42
train
fwolfst/kalindar
lib/kalindar/event.rb
Kalindar.Event.time_f
def time_f day start = start_time_f day finish = finish_time_f day if start == finish && start == "" # whole day "" elsif start == finish && start == "..." "..." else "#{start_time_f day} - #{finish_time_f day}" end end
ruby
def time_f day start = start_time_f day finish = finish_time_f day if start == finish && start == "" # whole day "" elsif start == finish && start == "..." "..." else "#{start_time_f day} - #{finish_time_f day}" end end
[ "def", "time_f", "day", "start", "=", "start_time_f", "day", "finish", "=", "finish_time_f", "day", "if", "start", "==", "finish", "&&", "start", "==", "\"\"", "\"\"", "elsif", "start", "==", "finish", "&&", "start", "==", "\"...\"", "\"...\"", "else", "\"#{start_time_f day} - #{finish_time_f day}\"", "end", "end" ]
Time it finishes and or starts at day, or '...'
[ "Time", "it", "finishes", "and", "or", "starts", "at", "day", "or", "..." ]
8c81f0bc85ac8f7d0fc43b8e25eff6c08329b2c9
https://github.com/fwolfst/kalindar/blob/8c81f0bc85ac8f7d0fc43b8e25eff6c08329b2c9/lib/kalindar/event.rb#L45-L56
train
riddopic/garcun
lib/garcon/task/executor_options.rb
Garcon.ExecutorOptions.get_executor_from
def get_executor_from(opts = {}) if (executor = opts[:executor]).is_a? Symbol case opts[:executor] when :fast Garcon.global_fast_executor when :io Garcon.global_io_executor when :immediate Garcon::ImmediateExecutor.new else raise ArgumentError, "executor '#{executor}' not recognized" end elsif opts[:executor] opts[:executor] else nil end end
ruby
def get_executor_from(opts = {}) if (executor = opts[:executor]).is_a? Symbol case opts[:executor] when :fast Garcon.global_fast_executor when :io Garcon.global_io_executor when :immediate Garcon::ImmediateExecutor.new else raise ArgumentError, "executor '#{executor}' not recognized" end elsif opts[:executor] opts[:executor] else nil end end
[ "def", "get_executor_from", "(", "opts", "=", "{", "}", ")", "if", "(", "executor", "=", "opts", "[", ":executor", "]", ")", ".", "is_a?", "Symbol", "case", "opts", "[", ":executor", "]", "when", ":fast", "Garcon", ".", "global_fast_executor", "when", ":io", "Garcon", ".", "global_io_executor", "when", ":immediate", "Garcon", "::", "ImmediateExecutor", ".", "new", "else", "raise", "ArgumentError", ",", "\"executor '#{executor}' not recognized\"", "end", "elsif", "opts", "[", ":executor", "]", "opts", "[", ":executor", "]", "else", "nil", "end", "end" ]
Get the requested `Executor` based on the values set in the options hash. @param [Hash] opts The options defining the requested executor. @option opts [Executor] :executor When set use the given `Executor` instance. Three special values are also supported: `:fast` returns the global fast executor, `:io` returns the global io executor, and `:immediate` returns a new `ImmediateExecutor` object. @return [Executor, nil] The requested thread pool, or nil when no option specified. @!visibility private
[ "Get", "the", "requested", "Executor", "based", "on", "the", "values", "set", "in", "the", "options", "hash", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/executor_options.rb#L40-L57
train
delano/familia
lib/familia/tools.rb
Familia.Tools.rename
def rename(filter, source_uri, target_uri=nil, &each_key) target_uri ||= source_uri move_keys filter, source_uri, target_uri if source_uri != target_uri source_keys = Familia.redis(source_uri).keys(filter) puts "Renaming #{source_keys.size} keys from #{source_uri} (filter: #{filter})" source_keys.each_with_index do |key,idx| Familia.trace :RENAME1, Familia.redis(source_uri), "#{key}", '' type = Familia.redis(source_uri).type key ttl = Familia.redis(source_uri).ttl key newkey = each_key.call(idx, type, key, ttl) unless each_key.nil? Familia.trace :RENAME2, Familia.redis(source_uri), "#{key} -> #{newkey}", caller[0] ret = Familia.redis(source_uri).renamenx key, newkey end end
ruby
def rename(filter, source_uri, target_uri=nil, &each_key) target_uri ||= source_uri move_keys filter, source_uri, target_uri if source_uri != target_uri source_keys = Familia.redis(source_uri).keys(filter) puts "Renaming #{source_keys.size} keys from #{source_uri} (filter: #{filter})" source_keys.each_with_index do |key,idx| Familia.trace :RENAME1, Familia.redis(source_uri), "#{key}", '' type = Familia.redis(source_uri).type key ttl = Familia.redis(source_uri).ttl key newkey = each_key.call(idx, type, key, ttl) unless each_key.nil? Familia.trace :RENAME2, Familia.redis(source_uri), "#{key} -> #{newkey}", caller[0] ret = Familia.redis(source_uri).renamenx key, newkey end end
[ "def", "rename", "(", "filter", ",", "source_uri", ",", "target_uri", "=", "nil", ",", "&", "each_key", ")", "target_uri", "||=", "source_uri", "move_keys", "filter", ",", "source_uri", ",", "target_uri", "if", "source_uri", "!=", "target_uri", "source_keys", "=", "Familia", ".", "redis", "(", "source_uri", ")", ".", "keys", "(", "filter", ")", "puts", "\"Renaming #{source_keys.size} keys from #{source_uri} (filter: #{filter})\"", "source_keys", ".", "each_with_index", "do", "|", "key", ",", "idx", "|", "Familia", ".", "trace", ":RENAME1", ",", "Familia", ".", "redis", "(", "source_uri", ")", ",", "\"#{key}\"", ",", "''", "type", "=", "Familia", ".", "redis", "(", "source_uri", ")", ".", "type", "key", "ttl", "=", "Familia", ".", "redis", "(", "source_uri", ")", ".", "ttl", "key", "newkey", "=", "each_key", ".", "call", "(", "idx", ",", "type", ",", "key", ",", "ttl", ")", "unless", "each_key", ".", "nil?", "Familia", ".", "trace", ":RENAME2", ",", "Familia", ".", "redis", "(", "source_uri", ")", ",", "\"#{key} -> #{newkey}\"", ",", "caller", "[", "0", "]", "ret", "=", "Familia", ".", "redis", "(", "source_uri", ")", ".", "renamenx", "key", ",", "newkey", "end", "end" ]
Use the return value from each_key as the new key name
[ "Use", "the", "return", "value", "from", "each_key", "as", "the", "new", "key", "name" ]
4ecb29e796c86611c5d37e1924729fb562eeb529
https://github.com/delano/familia/blob/4ecb29e796c86611c5d37e1924729fb562eeb529/lib/familia/tools.rb#L34-L47
train
mrsimonfletcher/roroacms
app/models/roroacms/comment.rb
Roroacms.Comment.deal_with_abnormalaties
def deal_with_abnormalaties self.comment = comment.to_s.gsub(%r{</?[^>]+?>}, '').gsub(/<script.*?>[\s\S]*<\/script>/i, "") if !self.website.blank? website = self.website.sub(/^https?\:\/\//, '').sub(/^www./,'') unless self.website[/\Awww.\/\//] || self.website[/\Awww.\/\//] website = "www.#{website}" end self.website = "http://#{website}" end end
ruby
def deal_with_abnormalaties self.comment = comment.to_s.gsub(%r{</?[^>]+?>}, '').gsub(/<script.*?>[\s\S]*<\/script>/i, "") if !self.website.blank? website = self.website.sub(/^https?\:\/\//, '').sub(/^www./,'') unless self.website[/\Awww.\/\//] || self.website[/\Awww.\/\//] website = "www.#{website}" end self.website = "http://#{website}" end end
[ "def", "deal_with_abnormalaties", "self", ".", "comment", "=", "comment", ".", "to_s", ".", "gsub", "(", "%r{", "}", ",", "''", ")", ".", "gsub", "(", "/", "\\s", "\\S", "\\/", "/i", ",", "\"\"", ")", "if", "!", "self", ".", "website", ".", "blank?", "website", "=", "self", ".", "website", ".", "sub", "(", "/", "\\:", "\\/", "\\/", "/", ",", "''", ")", ".", "sub", "(", "/", "/", ",", "''", ")", "unless", "self", ".", "website", "[", "/", "\\A", "\\/", "\\/", "/", "]", "||", "self", ".", "website", "[", "/", "\\A", "\\/", "\\/", "/", "]", "website", "=", "\"www.#{website}\"", "end", "self", ".", "website", "=", "\"http://#{website}\"", "end", "end" ]
strip any sort of html, we don't want javascrpt injection
[ "strip", "any", "sort", "of", "html", "we", "don", "t", "want", "javascrpt", "injection" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/models/roroacms/comment.rb#L65-L74
train
kindlinglabs/bullring
lib/bullring/util/server_registry.rb
Bullring.ServerRegistry.lease_server!
def lease_server! begin if num_current_generation_servers < MAX_SERVERS_PER_GENERATION && registry_open? start_a_server end lease_server rescue ServerOffline => e Bullring.logger.debug {"Lost connection with a server, retrying..."} retry end end
ruby
def lease_server! begin if num_current_generation_servers < MAX_SERVERS_PER_GENERATION && registry_open? start_a_server end lease_server rescue ServerOffline => e Bullring.logger.debug {"Lost connection with a server, retrying..."} retry end end
[ "def", "lease_server!", "begin", "if", "num_current_generation_servers", "<", "MAX_SERVERS_PER_GENERATION", "&&", "registry_open?", "start_a_server", "end", "lease_server", "rescue", "ServerOffline", "=>", "e", "Bullring", ".", "logger", ".", "debug", "{", "\"Lost connection with a server, retrying...\"", "}", "retry", "end", "end" ]
First starts up a server if needed then blocks until it is available and returns it
[ "First", "starts", "up", "a", "server", "if", "needed", "then", "blocks", "until", "it", "is", "available", "and", "returns", "it" ]
30ea55f7ad3de4c8af710d141cf5dfda0f9c8a44
https://github.com/kindlinglabs/bullring/blob/30ea55f7ad3de4c8af710d141cf5dfda0f9c8a44/lib/bullring/util/server_registry.rb#L113-L124
train
Floppy/currentcost-ruby
lib/currentcost/meter.rb
CurrentCost.Meter.update
def update(message) unless message.nil? # Parse reading from message @latest_reading = Reading.from_xml(message) # Inform observers changed notify_observers(@latest_reading) end rescue CurrentCost::ParseError nil end
ruby
def update(message) unless message.nil? # Parse reading from message @latest_reading = Reading.from_xml(message) # Inform observers changed notify_observers(@latest_reading) end rescue CurrentCost::ParseError nil end
[ "def", "update", "(", "message", ")", "unless", "message", ".", "nil?", "@latest_reading", "=", "Reading", ".", "from_xml", "(", "message", ")", "changed", "notify_observers", "(", "@latest_reading", ")", "end", "rescue", "CurrentCost", "::", "ParseError", "nil", "end" ]
Internal use only, client code does not need to use this function. Informs the Meter object that a new message has been received by the serial port.
[ "Internal", "use", "only", "client", "code", "does", "not", "need", "to", "use", "this", "function", ".", "Informs", "the", "Meter", "object", "that", "a", "new", "message", "has", "been", "received", "by", "the", "serial", "port", "." ]
10be0a4193511c2cb08612d155e81e078e63def0
https://github.com/Floppy/currentcost-ruby/blob/10be0a4193511c2cb08612d155e81e078e63def0/lib/currentcost/meter.rb#L53-L63
train
espresse/orientdb_binary
lib/orientdb_binary/database.rb
OrientdbBinary.Database.open
def open conn = connection.protocol::DbOpen.new(params(name: @name, storage: @storage, user: @user, password: @password)).process(connection) @session = conn[:session] || OrientdbBinary::OperationTypes::NEW_SESSION @clusters = conn[:clusters] self end
ruby
def open conn = connection.protocol::DbOpen.new(params(name: @name, storage: @storage, user: @user, password: @password)).process(connection) @session = conn[:session] || OrientdbBinary::OperationTypes::NEW_SESSION @clusters = conn[:clusters] self end
[ "def", "open", "conn", "=", "connection", ".", "protocol", "::", "DbOpen", ".", "new", "(", "params", "(", "name", ":", "@name", ",", "storage", ":", "@storage", ",", "user", ":", "@user", ",", "password", ":", "@password", ")", ")", ".", "process", "(", "connection", ")", "@session", "=", "conn", "[", ":session", "]", "||", "OrientdbBinary", "::", "OperationTypes", "::", "NEW_SESSION", "@clusters", "=", "conn", "[", ":clusters", "]", "self", "end" ]
Initializes connection to database @since 1.0 Opens connection to database @since 1.0
[ "Initializes", "connection", "to", "database" ]
b7f791c07a56eb6b551bed375504379487e28894
https://github.com/espresse/orientdb_binary/blob/b7f791c07a56eb6b551bed375504379487e28894/lib/orientdb_binary/database.rb#L25-L31
train
espresse/orientdb_binary
lib/orientdb_binary/database.rb
OrientdbBinary.Database.reload
def reload answer = connection.protocol::DbReload.new(params).process(connection) @clusters = answer[:clusters] self end
ruby
def reload answer = connection.protocol::DbReload.new(params).process(connection) @clusters = answer[:clusters] self end
[ "def", "reload", "answer", "=", "connection", ".", "protocol", "::", "DbReload", ".", "new", "(", "params", ")", ".", "process", "(", "connection", ")", "@clusters", "=", "answer", "[", ":clusters", "]", "self", "end" ]
Reloads information about database. @since 1.0
[ "Reloads", "information", "about", "database", "." ]
b7f791c07a56eb6b551bed375504379487e28894
https://github.com/espresse/orientdb_binary/blob/b7f791c07a56eb6b551bed375504379487e28894/lib/orientdb_binary/database.rb#L54-L58
train
elektronaut/sendregning
lib/sendregning/client.rb
Sendregning.Client.send_invoice
def send_invoice(invoice) response = post_xml(invoice.to_xml, {:action => 'send', :type => 'invoice'}) InvoiceParser.parse(response, invoice) end
ruby
def send_invoice(invoice) response = post_xml(invoice.to_xml, {:action => 'send', :type => 'invoice'}) InvoiceParser.parse(response, invoice) end
[ "def", "send_invoice", "(", "invoice", ")", "response", "=", "post_xml", "(", "invoice", ".", "to_xml", ",", "{", ":action", "=>", "'send'", ",", ":type", "=>", "'invoice'", "}", ")", "InvoiceParser", ".", "parse", "(", "response", ",", "invoice", ")", "end" ]
Sends an invoice
[ "Sends", "an", "invoice" ]
2b7eb61d5b2e1ee149935773b8917b4ab47f5447
https://github.com/elektronaut/sendregning/blob/2b7eb61d5b2e1ee149935773b8917b4ab47f5447/lib/sendregning/client.rb#L49-L52
train
elektronaut/sendregning
lib/sendregning/client.rb
Sendregning.Client.find_invoice
def find_invoice(invoice_id) builder = Builder::XmlMarkup.new(:indent=>2) builder.instruct! :xml, :version=>"1.0", :encoding=>"UTF-8" request_xml = builder.select do |select| select.invoiceNumbers do |numbers| numbers.invoiceNumber invoice_id end end response = post_xml(request_xml, {:action => 'select', :type => 'invoice'}) InvoiceParser.parse(response) rescue nil end
ruby
def find_invoice(invoice_id) builder = Builder::XmlMarkup.new(:indent=>2) builder.instruct! :xml, :version=>"1.0", :encoding=>"UTF-8" request_xml = builder.select do |select| select.invoiceNumbers do |numbers| numbers.invoiceNumber invoice_id end end response = post_xml(request_xml, {:action => 'select', :type => 'invoice'}) InvoiceParser.parse(response) rescue nil end
[ "def", "find_invoice", "(", "invoice_id", ")", "builder", "=", "Builder", "::", "XmlMarkup", ".", "new", "(", ":indent", "=>", "2", ")", "builder", ".", "instruct!", ":xml", ",", ":version", "=>", "\"1.0\"", ",", ":encoding", "=>", "\"UTF-8\"", "request_xml", "=", "builder", ".", "select", "do", "|", "select", "|", "select", ".", "invoiceNumbers", "do", "|", "numbers", "|", "numbers", ".", "invoiceNumber", "invoice_id", "end", "end", "response", "=", "post_xml", "(", "request_xml", ",", "{", ":action", "=>", "'select'", ",", ":type", "=>", "'invoice'", "}", ")", "InvoiceParser", ".", "parse", "(", "response", ")", "rescue", "nil", "end" ]
Finds an invoice by invoice number
[ "Finds", "an", "invoice", "by", "invoice", "number" ]
2b7eb61d5b2e1ee149935773b8917b4ab47f5447
https://github.com/elektronaut/sendregning/blob/2b7eb61d5b2e1ee149935773b8917b4ab47f5447/lib/sendregning/client.rb#L55-L65
train
akerl/logcabin
lib/logcabin/dircollection.rb
LogCabin.DirCollection.find_file
def find_file(name) @load_path.each do |dir| file_path = File.join(dir, "#{name}.rb") return file_path if File.exist? file_path end raise("Module #{name} not found") end
ruby
def find_file(name) @load_path.each do |dir| file_path = File.join(dir, "#{name}.rb") return file_path if File.exist? file_path end raise("Module #{name} not found") end
[ "def", "find_file", "(", "name", ")", "@load_path", ".", "each", "do", "|", "dir", "|", "file_path", "=", "File", ".", "join", "(", "dir", ",", "\"#{name}.rb\"", ")", "return", "file_path", "if", "File", ".", "exist?", "file_path", "end", "raise", "(", "\"Module #{name} not found\"", ")", "end" ]
Check module path for module
[ "Check", "module", "path", "for", "module" ]
a0c793f4047f3a80fd232c582ecce55139092b8e
https://github.com/akerl/logcabin/blob/a0c793f4047f3a80fd232c582ecce55139092b8e/lib/logcabin/dircollection.rb#L23-L29
train
NYULibraries/figs
lib/figs/directory_flattener.rb
Figs.DirectoryFlattener.flattened_filenames
def flattened_filenames(filenames) # Expect an array of filenames return otherwise return filenames if !filenames.is_a?(Array) # Iterate through array filenames.map! do |filename| # Flatten if its a file, flatten if a dir. Dir.exist?(filename) ? directory_to_filenames(filename) : filename end # Flattern the array and remove all nils filenames.flatten.compact end
ruby
def flattened_filenames(filenames) # Expect an array of filenames return otherwise return filenames if !filenames.is_a?(Array) # Iterate through array filenames.map! do |filename| # Flatten if its a file, flatten if a dir. Dir.exist?(filename) ? directory_to_filenames(filename) : filename end # Flattern the array and remove all nils filenames.flatten.compact end
[ "def", "flattened_filenames", "(", "filenames", ")", "return", "filenames", "if", "!", "filenames", ".", "is_a?", "(", "Array", ")", "filenames", ".", "map!", "do", "|", "filename", "|", "Dir", ".", "exist?", "(", "filename", ")", "?", "directory_to_filenames", "(", "filename", ")", ":", "filename", "end", "filenames", ".", "flatten", ".", "compact", "end" ]
Creates an array consisting of only files contained in a directory and its subdirectories. Expects an array of filenames or dirnames or a combination of both.
[ "Creates", "an", "array", "consisting", "of", "only", "files", "contained", "in", "a", "directory", "and", "its", "subdirectories", "." ]
24484450a93f5927a0a1ac227a8ad572b70c1337
https://github.com/NYULibraries/figs/blob/24484450a93f5927a0a1ac227a8ad572b70c1337/lib/figs/directory_flattener.rb#L14-L24
train
NYULibraries/figs
lib/figs/directory_flattener.rb
Figs.DirectoryFlattener.flatten_files
def flatten_files(directoryname,filename) # If the filename turns out to be a directory... if Dir.exist?("#{directoryname}/#{filename}") # do a recursive call to the parent method, unless the directory is . or .. directory_to_filenames("#{directoryname}/#{filename}") unless ['.','..'].include?(filename) else # Otherwise check if its actually a file and return its filepath. "#{directoryname}/#{filename}" if File.exists?("#{directoryname}/#{filename}") end end
ruby
def flatten_files(directoryname,filename) # If the filename turns out to be a directory... if Dir.exist?("#{directoryname}/#{filename}") # do a recursive call to the parent method, unless the directory is . or .. directory_to_filenames("#{directoryname}/#{filename}") unless ['.','..'].include?(filename) else # Otherwise check if its actually a file and return its filepath. "#{directoryname}/#{filename}" if File.exists?("#{directoryname}/#{filename}") end end
[ "def", "flatten_files", "(", "directoryname", ",", "filename", ")", "if", "Dir", ".", "exist?", "(", "\"#{directoryname}/#{filename}\"", ")", "directory_to_filenames", "(", "\"#{directoryname}/#{filename}\"", ")", "unless", "[", "'.'", ",", "'..'", "]", ".", "include?", "(", "filename", ")", "else", "\"#{directoryname}/#{filename}\"", "if", "File", ".", "exists?", "(", "\"#{directoryname}/#{filename}\"", ")", "end", "end" ]
Expects the directory path and filename, checks to see if its another directory or filename, if directory, calls directory_to_filenames.
[ "Expects", "the", "directory", "path", "and", "filename", "checks", "to", "see", "if", "its", "another", "directory", "or", "filename", "if", "directory", "calls", "directory_to_filenames", "." ]
24484450a93f5927a0a1ac227a8ad572b70c1337
https://github.com/NYULibraries/figs/blob/24484450a93f5927a0a1ac227a8ad572b70c1337/lib/figs/directory_flattener.rb#L40-L49
train
tongueroo/balancer
lib/balancer/profile.rb
Balancer.Profile.profile_name
def profile_name # allow user to specify the path also if @options[:profile] && File.exist?(@options[:profile]) filename_profile = File.basename(@options[:profile], '.yml') end name = derandomize(@name) if File.exist?(profile_file(name)) name_profile = name end filename_profile || @options[:profile] || name_profile || # conventional profile is the name of the elb "default" end
ruby
def profile_name # allow user to specify the path also if @options[:profile] && File.exist?(@options[:profile]) filename_profile = File.basename(@options[:profile], '.yml') end name = derandomize(@name) if File.exist?(profile_file(name)) name_profile = name end filename_profile || @options[:profile] || name_profile || # conventional profile is the name of the elb "default" end
[ "def", "profile_name", "if", "@options", "[", ":profile", "]", "&&", "File", ".", "exist?", "(", "@options", "[", ":profile", "]", ")", "filename_profile", "=", "File", ".", "basename", "(", "@options", "[", ":profile", "]", ",", "'.yml'", ")", "end", "name", "=", "derandomize", "(", "@name", ")", "if", "File", ".", "exist?", "(", "profile_file", "(", "name", ")", ")", "name_profile", "=", "name", "end", "filename_profile", "||", "@options", "[", ":profile", "]", "||", "name_profile", "||", "\"default\"", "end" ]
Determines a valid profile_name. Falls back to default
[ "Determines", "a", "valid", "profile_name", ".", "Falls", "back", "to", "default" ]
c149498e78f73b1dc0a433cc693ec4327c409bab
https://github.com/tongueroo/balancer/blob/c149498e78f73b1dc0a433cc693ec4327c409bab/lib/balancer/profile.rb#L44-L59
train
barkerest/barkest_core
app/models/barkest_core/ms_sql_db_definition.rb
BarkestCore.MsSqlDbDefinition.add_source
def add_source(sql) sql_def = BarkestCore::MsSqlDefinition.new(sql, '') sql_def.instance_variable_set(:@source_location, "::#{sql_def.name}::") add_sql_def sql_def nil end
ruby
def add_source(sql) sql_def = BarkestCore::MsSqlDefinition.new(sql, '') sql_def.instance_variable_set(:@source_location, "::#{sql_def.name}::") add_sql_def sql_def nil end
[ "def", "add_source", "(", "sql", ")", "sql_def", "=", "BarkestCore", "::", "MsSqlDefinition", ".", "new", "(", "sql", ",", "''", ")", "sql_def", ".", "instance_variable_set", "(", ":@source_location", ",", "\"::#{sql_def.name}::\"", ")", "add_sql_def", "sql_def", "nil", "end" ]
Adds a source using a specific timestamp. The first line of the SQL should be a comment specifying the timestamp for the source. -- 2016-12-19 15:45 -- 2016-12-19 -- 201612191545 -- 20161219 The timestamp will be converted into a 12-digit number, if time is not specified it will be right-padded with zeroes to get to the 12-digit number. The +sql+ should be a valid create/alter table/view/function statement.
[ "Adds", "a", "source", "using", "a", "specific", "timestamp", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/ms_sql_db_definition.rb#L113-L118
train
barkerest/barkest_core
app/models/barkest_core/ms_sql_db_definition.rb
BarkestCore.MsSqlDbDefinition.add_source_path
def add_source_path(path) raise 'path must be a string' unless path.is_a?(String) path = File.expand_path(path) raise 'cannot add root path' if path == '/' path = path[0...-1] if path[-1] == '/' unless @source_paths.include?(path) @source_paths << path if Dir.exist?(path) Dir.glob("#{path}/*.sql").each do |source| add_sql_def BarkestCore::MsSqlDefinition.new(File.read(source), source, File.mtime(source)) end end end nil end
ruby
def add_source_path(path) raise 'path must be a string' unless path.is_a?(String) path = File.expand_path(path) raise 'cannot add root path' if path == '/' path = path[0...-1] if path[-1] == '/' unless @source_paths.include?(path) @source_paths << path if Dir.exist?(path) Dir.glob("#{path}/*.sql").each do |source| add_sql_def BarkestCore::MsSqlDefinition.new(File.read(source), source, File.mtime(source)) end end end nil end
[ "def", "add_source_path", "(", "path", ")", "raise", "'path must be a string'", "unless", "path", ".", "is_a?", "(", "String", ")", "path", "=", "File", ".", "expand_path", "(", "path", ")", "raise", "'cannot add root path'", "if", "path", "==", "'/'", "path", "=", "path", "[", "0", "...", "-", "1", "]", "if", "path", "[", "-", "1", "]", "==", "'/'", "unless", "@source_paths", ".", "include?", "(", "path", ")", "@source_paths", "<<", "path", "if", "Dir", ".", "exist?", "(", "path", ")", "Dir", ".", "glob", "(", "\"#{path}/*.sql\"", ")", ".", "each", "do", "|", "source", "|", "add_sql_def", "BarkestCore", "::", "MsSqlDefinition", ".", "new", "(", "File", ".", "read", "(", "source", ")", ",", "source", ",", "File", ".", "mtime", "(", "source", ")", ")", "end", "end", "end", "nil", "end" ]
Adds all SQL files found in the specified directory to the sources for this updater. The +path+ should contain the SQL files. If there are subdirectories, you should include them individually. The source files should specify a timestamp in the first comment. -- 2016-12-19 15:45 -- 2016-12-19 -- 201612191545 -- 20161219 The timestamp will be converted into a 12-digit number, if time is not specified it will be right-padded with zeroes to get to the 12-digit number.
[ "Adds", "all", "SQL", "files", "found", "in", "the", "specified", "directory", "to", "the", "sources", "for", "this", "updater", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/ms_sql_db_definition.rb#L144-L162
train
inside-track/remi
lib/remi/data_subjects/sftp_file.rb
Remi.Extractor::SftpFile.extract
def extract begin_connection entries.map do |entry| local_file = File.join(@local_path, entry.name) logger.info "Downloading #{entry.name} to #{local_file}" sftp_retry { sftp_session.download!(File.join(@remote_path, entry.name), local_file) } local_file end ensure end_connection end
ruby
def extract begin_connection entries.map do |entry| local_file = File.join(@local_path, entry.name) logger.info "Downloading #{entry.name} to #{local_file}" sftp_retry { sftp_session.download!(File.join(@remote_path, entry.name), local_file) } local_file end ensure end_connection end
[ "def", "extract", "begin_connection", "entries", ".", "map", "do", "|", "entry", "|", "local_file", "=", "File", ".", "join", "(", "@local_path", ",", "entry", ".", "name", ")", "logger", ".", "info", "\"Downloading #{entry.name} to #{local_file}\"", "sftp_retry", "{", "sftp_session", ".", "download!", "(", "File", ".", "join", "(", "@remote_path", ",", "entry", ".", "name", ")", ",", "local_file", ")", "}", "local_file", "end", "ensure", "end_connection", "end" ]
Called to extract files from the source filesystem. @return [Array<String>] An array of paths to a local copy of the files extacted
[ "Called", "to", "extract", "files", "from", "the", "source", "filesystem", "." ]
f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7
https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/data_subjects/sftp_file.rb#L99-L110
train
inside-track/remi
lib/remi/data_subjects/sftp_file.rb
Remi.Loader::SftpFile.load
def load(data) begin_connection logger.info "Uploading #{data} to #{@username}@#{@host}: #{@remote_path}" sftp_retry { sftp_session.upload! data, @remote_path } true ensure end_connection end
ruby
def load(data) begin_connection logger.info "Uploading #{data} to #{@username}@#{@host}: #{@remote_path}" sftp_retry { sftp_session.upload! data, @remote_path } true ensure end_connection end
[ "def", "load", "(", "data", ")", "begin_connection", "logger", ".", "info", "\"Uploading #{data} to #{@username}@#{@host}: #{@remote_path}\"", "sftp_retry", "{", "sftp_session", ".", "upload!", "data", ",", "@remote_path", "}", "true", "ensure", "end_connection", "end" ]
Copies data to the SFTP Server @param data [Object] The path to the file in the temporary work location @return [true] On success
[ "Copies", "data", "to", "the", "SFTP", "Server" ]
f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7
https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/data_subjects/sftp_file.rb#L189-L198
train
vecerek/css_compare
lib/css_compare/exec.rb
CssCompare.Comparison.run
def run result = CssCompare::Engine.new(@options) .parse! .equal? write_output(result.to_s + "\n", @options[:output]) end
ruby
def run result = CssCompare::Engine.new(@options) .parse! .equal? write_output(result.to_s + "\n", @options[:output]) end
[ "def", "run", "result", "=", "CssCompare", "::", "Engine", ".", "new", "(", "@options", ")", ".", "parse!", ".", "equal?", "write_output", "(", "result", ".", "to_s", "+", "\"\\n\"", ",", "@options", "[", ":output", "]", ")", "end" ]
Runs the comparison.
[ "Runs", "the", "comparison", "." ]
b87237a908c2c2f1c659d1160e8b266d594667dd
https://github.com/vecerek/css_compare/blob/b87237a908c2c2f1c659d1160e8b266d594667dd/lib/css_compare/exec.rb#L104-L109
train
tanema/ghost_in_the_post
lib/ghost_in_the_post/phantom_transform.rb
GhostInThePost.PhantomTransform.html_file
def html_file(html) file = Tempfile.new(['ghost_in_the_post', '.html'], encoding: Encoding::UTF_8) file.write(html) file.close #closing the file makes it accessible by phantom file end
ruby
def html_file(html) file = Tempfile.new(['ghost_in_the_post', '.html'], encoding: Encoding::UTF_8) file.write(html) file.close #closing the file makes it accessible by phantom file end
[ "def", "html_file", "(", "html", ")", "file", "=", "Tempfile", ".", "new", "(", "[", "'ghost_in_the_post'", ",", "'.html'", "]", ",", "encoding", ":", "Encoding", "::", "UTF_8", ")", "file", ".", "write", "(", "html", ")", "file", ".", "close", "file", "end" ]
generate a tempfile with all the html that we need so that phantom can inject easily and not have to max out a single command
[ "generate", "a", "tempfile", "with", "all", "the", "html", "that", "we", "need", "so", "that", "phantom", "can", "inject", "easily", "and", "not", "have", "to", "max", "out", "a", "single", "command" ]
e47c5d8371141241699f5ba7dd743e60fa739573
https://github.com/tanema/ghost_in_the_post/blob/e47c5d8371141241699f5ba7dd743e60fa739573/lib/ghost_in_the_post/phantom_transform.rb#L49-L54
train
rjoberon/bibsonomy-ruby
lib/bibsonomy/csl.rb
BibSonomy.CSL.render
def render(grouping, name, tags, count) # get posts from BibSonomy posts = JSON.parse(@bibsonomy.get_posts(grouping, name, 'publication', tags, 0, count)) # render them with citeproc cp = CiteProc::Processor.new style: @style, format: 'html' cp.import posts # to check for duplicate file names file_names = [] # filter posts by group # 2017-05-30, rja, disabled until group information is returned by the API # posts.delete_if do |v| # if v["group"] == @group # true # else # print("WARN: " + v["group"]) # false # end # end # sort posts by year sorted_keys = posts.keys.sort { |a,b| get_sort_posts(posts[b], posts[a]) } result = "" # print first heading last_year = 0 if @year_headings and sorted_keys.length > 0 last_year = get_year(posts[sorted_keys[0]]) result += "<h3>" + last_year + "</h3>" end result += "<ul class='#{@css_class}'>\n" for post_id in sorted_keys post = posts[post_id] # print heading if @year_headings year = get_year(post) if year != last_year last_year = year result += "</ul>\n<h3>" + last_year + "</h3>\n<ul class='#{@css_class}'>\n" end end # render metadata csl = cp.render(:bibliography, id: post_id) result += "<li class='" + post["type"] + "'>#{csl[0]}" # extract the post's id intra_hash, user_name = get_intra_hash(post_id) # optional parts options = [] # attach documents if @pdf_dir for doc in get_public_docs(post["documents"]) # fileHash, fileName, md5hash, userName file_path = get_document(@bibsonomy, intra_hash, user_name, doc, @pdf_dir, file_names) options << "<a href='#{file_path}'>PDF</a>" end end # attach DOI doi = post["DOI"] if @doi_link and doi != "" doi, doi_url = get_doi(doi) options << "DOI:<a href='#{doi_url}'>#{doi}</a>" end # attach URL url = post["URL"] if @url_link and url != "" options << "<a href='#{url}'>URL</a>" end # attach BibTeX if @bibtex_link options << "<a href='https://www.bibsonomy.org/bib/publication/#{intra_hash}/#{user_name}'>BibTeX</a>" end # attach link to BibSonomy if @bibsonomy_link options << "<a href='https://www.bibsonomy.org/publication/#{intra_hash}/#{user_name}'>BibSonomy</a>" end # attach options if options.length > 0 result += " <span class='opt'>[" + options.join(@opt_sep) + "]</span>" end # attach Altmetric badge if @altmetric_badge_type and doi != "" doi, doi_url = get_doi(doi) result += "<div class='altmetric-embed' data-badge-type='#{@altmetric_badge_type}' data-doi='#{doi}'></div>" end result += "</li>\n" end result += "</ul>\n" return result end
ruby
def render(grouping, name, tags, count) # get posts from BibSonomy posts = JSON.parse(@bibsonomy.get_posts(grouping, name, 'publication', tags, 0, count)) # render them with citeproc cp = CiteProc::Processor.new style: @style, format: 'html' cp.import posts # to check for duplicate file names file_names = [] # filter posts by group # 2017-05-30, rja, disabled until group information is returned by the API # posts.delete_if do |v| # if v["group"] == @group # true # else # print("WARN: " + v["group"]) # false # end # end # sort posts by year sorted_keys = posts.keys.sort { |a,b| get_sort_posts(posts[b], posts[a]) } result = "" # print first heading last_year = 0 if @year_headings and sorted_keys.length > 0 last_year = get_year(posts[sorted_keys[0]]) result += "<h3>" + last_year + "</h3>" end result += "<ul class='#{@css_class}'>\n" for post_id in sorted_keys post = posts[post_id] # print heading if @year_headings year = get_year(post) if year != last_year last_year = year result += "</ul>\n<h3>" + last_year + "</h3>\n<ul class='#{@css_class}'>\n" end end # render metadata csl = cp.render(:bibliography, id: post_id) result += "<li class='" + post["type"] + "'>#{csl[0]}" # extract the post's id intra_hash, user_name = get_intra_hash(post_id) # optional parts options = [] # attach documents if @pdf_dir for doc in get_public_docs(post["documents"]) # fileHash, fileName, md5hash, userName file_path = get_document(@bibsonomy, intra_hash, user_name, doc, @pdf_dir, file_names) options << "<a href='#{file_path}'>PDF</a>" end end # attach DOI doi = post["DOI"] if @doi_link and doi != "" doi, doi_url = get_doi(doi) options << "DOI:<a href='#{doi_url}'>#{doi}</a>" end # attach URL url = post["URL"] if @url_link and url != "" options << "<a href='#{url}'>URL</a>" end # attach BibTeX if @bibtex_link options << "<a href='https://www.bibsonomy.org/bib/publication/#{intra_hash}/#{user_name}'>BibTeX</a>" end # attach link to BibSonomy if @bibsonomy_link options << "<a href='https://www.bibsonomy.org/publication/#{intra_hash}/#{user_name}'>BibSonomy</a>" end # attach options if options.length > 0 result += " <span class='opt'>[" + options.join(@opt_sep) + "]</span>" end # attach Altmetric badge if @altmetric_badge_type and doi != "" doi, doi_url = get_doi(doi) result += "<div class='altmetric-embed' data-badge-type='#{@altmetric_badge_type}' data-doi='#{doi}'></div>" end result += "</li>\n" end result += "</ul>\n" return result end
[ "def", "render", "(", "grouping", ",", "name", ",", "tags", ",", "count", ")", "posts", "=", "JSON", ".", "parse", "(", "@bibsonomy", ".", "get_posts", "(", "grouping", ",", "name", ",", "'publication'", ",", "tags", ",", "0", ",", "count", ")", ")", "cp", "=", "CiteProc", "::", "Processor", ".", "new", "style", ":", "@style", ",", "format", ":", "'html'", "cp", ".", "import", "posts", "file_names", "=", "[", "]", "sorted_keys", "=", "posts", ".", "keys", ".", "sort", "{", "|", "a", ",", "b", "|", "get_sort_posts", "(", "posts", "[", "b", "]", ",", "posts", "[", "a", "]", ")", "}", "result", "=", "\"\"", "last_year", "=", "0", "if", "@year_headings", "and", "sorted_keys", ".", "length", ">", "0", "last_year", "=", "get_year", "(", "posts", "[", "sorted_keys", "[", "0", "]", "]", ")", "result", "+=", "\"<h3>\"", "+", "last_year", "+", "\"</h3>\"", "end", "result", "+=", "\"<ul class='#{@css_class}'>\\n\"", "for", "post_id", "in", "sorted_keys", "post", "=", "posts", "[", "post_id", "]", "if", "@year_headings", "year", "=", "get_year", "(", "post", ")", "if", "year", "!=", "last_year", "last_year", "=", "year", "result", "+=", "\"</ul>\\n<h3>\"", "+", "last_year", "+", "\"</h3>\\n<ul class='#{@css_class}'>\\n\"", "end", "end", "csl", "=", "cp", ".", "render", "(", ":bibliography", ",", "id", ":", "post_id", ")", "result", "+=", "\"<li class='\"", "+", "post", "[", "\"type\"", "]", "+", "\"'>#{csl[0]}\"", "intra_hash", ",", "user_name", "=", "get_intra_hash", "(", "post_id", ")", "options", "=", "[", "]", "if", "@pdf_dir", "for", "doc", "in", "get_public_docs", "(", "post", "[", "\"documents\"", "]", ")", "file_path", "=", "get_document", "(", "@bibsonomy", ",", "intra_hash", ",", "user_name", ",", "doc", ",", "@pdf_dir", ",", "file_names", ")", "options", "<<", "\"<a href='#{file_path}'>PDF</a>\"", "end", "end", "doi", "=", "post", "[", "\"DOI\"", "]", "if", "@doi_link", "and", "doi", "!=", "\"\"", "doi", ",", "doi_url", "=", "get_doi", "(", "doi", ")", "options", "<<", "\"DOI:<a href='#{doi_url}'>#{doi}</a>\"", "end", "url", "=", "post", "[", "\"URL\"", "]", "if", "@url_link", "and", "url", "!=", "\"\"", "options", "<<", "\"<a href='#{url}'>URL</a>\"", "end", "if", "@bibtex_link", "options", "<<", "\"<a href='https://www.bibsonomy.org/bib/publication/#{intra_hash}/#{user_name}'>BibTeX</a>\"", "end", "if", "@bibsonomy_link", "options", "<<", "\"<a href='https://www.bibsonomy.org/publication/#{intra_hash}/#{user_name}'>BibSonomy</a>\"", "end", "if", "options", ".", "length", ">", "0", "result", "+=", "\" <span class='opt'>[\"", "+", "options", ".", "join", "(", "@opt_sep", ")", "+", "\"]</span>\"", "end", "if", "@altmetric_badge_type", "and", "doi", "!=", "\"\"", "doi", ",", "doi_url", "=", "get_doi", "(", "doi", ")", "result", "+=", "\"<div class='altmetric-embed' data-badge-type='#{@altmetric_badge_type}' data-doi='#{doi}'></div>\"", "end", "result", "+=", "\"</li>\\n\"", "end", "result", "+=", "\"</ul>\\n\"", "return", "result", "end" ]
Create a new BibSonomy instance. @param user_name [String] the BibSonomy user name @param api_key [String] the API key of the user (get at https://www.bibsonomy.org/settings?selTab=1) Download `count` posts for the given `user` and `tag(s)` and render them with {http://citationstyles.org/ CSL}. @param grouping [String] the type of the name (either "user" or "group") @param name [String] the name of the group or user @param tags [Array<String>] the tags that all posts must contain (can be empty) @param count [Integer] number of posts to download @return [String] the rendered posts as HTML
[ "Create", "a", "new", "BibSonomy", "instance", "." ]
15afed3f32e434d28576ac62ecf3cfd8a392e055
https://github.com/rjoberon/bibsonomy-ruby/blob/15afed3f32e434d28576ac62ecf3cfd8a392e055/lib/bibsonomy/csl.rb#L123-L224
train
rjoberon/bibsonomy-ruby
lib/bibsonomy/csl.rb
BibSonomy.CSL.get_public_docs
def get_public_docs(documents) result = [] for doc in documents file_name = doc["fileName"] if file_name.end_with? ".pdf" if documents.length < 2 or file_name.end_with? @public_doc_postfix result << doc end end end return result end
ruby
def get_public_docs(documents) result = [] for doc in documents file_name = doc["fileName"] if file_name.end_with? ".pdf" if documents.length < 2 or file_name.end_with? @public_doc_postfix result << doc end end end return result end
[ "def", "get_public_docs", "(", "documents", ")", "result", "=", "[", "]", "for", "doc", "in", "documents", "file_name", "=", "doc", "[", "\"fileName\"", "]", "if", "file_name", ".", "end_with?", "\".pdf\"", "if", "documents", ".", "length", "<", "2", "or", "file_name", ".", "end_with?", "@public_doc_postfix", "result", "<<", "doc", "end", "end", "end", "return", "result", "end" ]
only show PDF files
[ "only", "show", "PDF", "files" ]
15afed3f32e434d28576ac62ecf3cfd8a392e055
https://github.com/rjoberon/bibsonomy-ruby/blob/15afed3f32e434d28576ac62ecf3cfd8a392e055/lib/bibsonomy/csl.rb#L277-L288
train
riddopic/garcun
lib/garcon/chef/chef_helpers.rb
Garcon.ChefHelpers.find_by
def find_by(type, filter, single = true, &block) nodes = [] env = node.chef_environment if node.public_send(Inflections.pluralize(type.to_s)).include? filter nodes << node end if !single || nodes.empty? search(:node, "#{type}:#{filter} AND chef_environment:#{env}") do |n| nodes << n end end if block_given? nodes.each { |n| yield n } else single ? nodes.first : nodes end end
ruby
def find_by(type, filter, single = true, &block) nodes = [] env = node.chef_environment if node.public_send(Inflections.pluralize(type.to_s)).include? filter nodes << node end if !single || nodes.empty? search(:node, "#{type}:#{filter} AND chef_environment:#{env}") do |n| nodes << n end end if block_given? nodes.each { |n| yield n } else single ? nodes.first : nodes end end
[ "def", "find_by", "(", "type", ",", "filter", ",", "single", "=", "true", ",", "&", "block", ")", "nodes", "=", "[", "]", "env", "=", "node", ".", "chef_environment", "if", "node", ".", "public_send", "(", "Inflections", ".", "pluralize", "(", "type", ".", "to_s", ")", ")", ".", "include?", "filter", "nodes", "<<", "node", "end", "if", "!", "single", "||", "nodes", ".", "empty?", "search", "(", ":node", ",", "\"#{type}:#{filter} AND chef_environment:#{env}\"", ")", "do", "|", "n", "|", "nodes", "<<", "n", "end", "end", "if", "block_given?", "nodes", ".", "each", "{", "|", "n", "|", "yield", "n", "}", "else", "single", "?", "nodes", ".", "first", ":", "nodes", "end", "end" ]
Search for a matching node by a given role or tag. @param [Symbol] type The filter type, can be `:role` or `:tag`. @param [String] filter The role or tag to filter on. @param [Boolean] single True if we should return only a single match, or false to return all of the matches. @yield an optional block to enumerate over the nodes. @return [Array, Proc] The value of the passed block or node. @api public
[ "Search", "for", "a", "matching", "node", "by", "a", "given", "role", "or", "tag", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/chef_helpers.rb#L72-L89
train
riddopic/garcun
lib/garcon/chef/chef_helpers.rb
Garcon.ChefHelpers.cookbook_version
def cookbook_version(name = nil) cookbook = name.nil? ? cookbook_name : name node.run_context.cookbook_collection[cookbook].metadata.version end
ruby
def cookbook_version(name = nil) cookbook = name.nil? ? cookbook_name : name node.run_context.cookbook_collection[cookbook].metadata.version end
[ "def", "cookbook_version", "(", "name", "=", "nil", ")", "cookbook", "=", "name", ".", "nil?", "?", "cookbook_name", ":", "name", "node", ".", "run_context", ".", "cookbook_collection", "[", "cookbook", "]", ".", "metadata", ".", "version", "end" ]
Retrieve the version number of the cookbook in the run list. @param name [String] name of cookbook to retrieve the version on. @return [Integer] version of the cookbook. @api public
[ "Retrieve", "the", "version", "number", "of", "the", "cookbook", "in", "the", "run", "list", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/chef_helpers.rb#L183-L186
train
riddopic/garcun
lib/garcon/chef/chef_helpers.rb
Garcon.ChefHelpers.file_cache_path
def file_cache_path(*args) if args.nil? Chef::Config[:file_cache_path] else ::File.join(Chef::Config[:file_cache_path], args) end end
ruby
def file_cache_path(*args) if args.nil? Chef::Config[:file_cache_path] else ::File.join(Chef::Config[:file_cache_path], args) end end
[ "def", "file_cache_path", "(", "*", "args", ")", "if", "args", ".", "nil?", "Chef", "::", "Config", "[", ":file_cache_path", "]", "else", "::", "File", ".", "join", "(", "Chef", "::", "Config", "[", ":file_cache_path", "]", ",", "args", ")", "end", "end" ]
Shortcut to return cache path, if you pass in a file it will return the file with the cache path. @example file_cache_path => "/var/chef/cache/" file_cache_path 'patch.tar.gz' => "/var/chef/cache/patch.tar.gz" file_cache_path "#{node[:name]}-backup.tar.gz" => "/var/chef/cache/c20d24209cc8-backup.tar.gz" @param [String] args name of file to return path with file @return [String] @api public
[ "Shortcut", "to", "return", "cache", "path", "if", "you", "pass", "in", "a", "file", "it", "will", "return", "the", "file", "with", "the", "cache", "path", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/chef_helpers.rb#L207-L213
train
riddopic/garcun
lib/garcon/chef/chef_helpers.rb
Garcon.ChefHelpers._?
def _?(*args, &block) if args.empty? && block_given? yield self else resp = public_send(*args[0], &block) if respond_to?(args.first) return nil if resp.nil? !!resp == resp ? args[1] : [args[1], resp] end end
ruby
def _?(*args, &block) if args.empty? && block_given? yield self else resp = public_send(*args[0], &block) if respond_to?(args.first) return nil if resp.nil? !!resp == resp ? args[1] : [args[1], resp] end end
[ "def", "_?", "(", "*", "args", ",", "&", "block", ")", "if", "args", ".", "empty?", "&&", "block_given?", "yield", "self", "else", "resp", "=", "public_send", "(", "*", "args", "[", "0", "]", ",", "&", "block", ")", "if", "respond_to?", "(", "args", ".", "first", ")", "return", "nil", "if", "resp", ".", "nil?", "!", "!", "resp", "==", "resp", "?", "args", "[", "1", "]", ":", "[", "args", "[", "1", "]", ",", "resp", "]", "end", "end" ]
Invokes the public method whose name goes as first argument just like `public_send` does, except that if the receiver does not respond to it the call returns `nil` rather than raising an exception. @note `_?` is defined on `Object`. Therefore, it won't work with instances of classes that do not have `Object` among their ancestors, like direct subclasses of `BasicObject`. @param [String] object The object to send the method to. @param [Symbol] method The method to send to the object. @api public
[ "Invokes", "the", "public", "method", "whose", "name", "goes", "as", "first", "argument", "just", "like", "public_send", "does", "except", "that", "if", "the", "receiver", "does", "not", "respond", "to", "it", "the", "call", "returns", "nil", "rather", "than", "raising", "an", "exception", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/chef_helpers.rb#L230-L238
train
riddopic/garcun
lib/garcon/chef/chef_helpers.rb
Garcon.ChefHelpers.zip_hash
def zip_hash(col1, col2) col1.zip(col2).inject({}) { |r, i| r[i[0]] = i[1]; r } end
ruby
def zip_hash(col1, col2) col1.zip(col2).inject({}) { |r, i| r[i[0]] = i[1]; r } end
[ "def", "zip_hash", "(", "col1", ",", "col2", ")", "col1", ".", "zip", "(", "col2", ")", ".", "inject", "(", "{", "}", ")", "{", "|", "r", ",", "i", "|", "r", "[", "i", "[", "0", "]", "]", "=", "i", "[", "1", "]", ";", "r", "}", "end" ]
Returns a hash using col1 as keys and col2 as values. @example zip_hash([:name, :age, :sex], ['Earl', 30, 'male']) => { :age => 30, :name => "Earl", :sex => "male" } @param [Array] col1 Containing the keys. @param [Array] col2 Values for hash. @return [Hash]
[ "Returns", "a", "hash", "using", "col1", "as", "keys", "and", "col2", "as", "values", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/chef_helpers.rb#L282-L284
train
riddopic/garcun
lib/garcon/chef/chef_helpers.rb
Garcon.ChefHelpers.with_tmp_dir
def with_tmp_dir(&block) Dir.mktmpdir(SecureRandom.hex(3)) do |tmp_dir| Dir.chdir(tmp_dir, &block) end end
ruby
def with_tmp_dir(&block) Dir.mktmpdir(SecureRandom.hex(3)) do |tmp_dir| Dir.chdir(tmp_dir, &block) end end
[ "def", "with_tmp_dir", "(", "&", "block", ")", "Dir", ".", "mktmpdir", "(", "SecureRandom", ".", "hex", "(", "3", ")", ")", "do", "|", "tmp_dir", "|", "Dir", ".", "chdir", "(", "tmp_dir", ",", "&", "block", ")", "end", "end" ]
Creates a temp directory executing the block provided. When done the temp directory and all it's contents are garbage collected. @yield [Proc] block A block that will be run @return [Object] Result of the block operation @api public
[ "Creates", "a", "temp", "directory", "executing", "the", "block", "provided", ".", "When", "done", "the", "temp", "directory", "and", "all", "it", "s", "contents", "are", "garbage", "collected", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/chef_helpers.rb#L307-L311
train
KatanaCode/evvnt
lib/evvnt/class_template_methods.rb
Evvnt.ClassTemplateMethods.create
def create(**params) path = nest_path_within_parent(plural_resource_path, params) api_request(:post, path, params: params) end
ruby
def create(**params) path = nest_path_within_parent(plural_resource_path, params) api_request(:post, path, params: params) end
[ "def", "create", "(", "**", "params", ")", "path", "=", "nest_path_within_parent", "(", "plural_resource_path", ",", "params", ")", "api_request", "(", ":post", ",", "path", ",", "params", ":", "params", ")", "end" ]
Template method for creating a new record on the API. params - A Hash of params to send to the API. Returns {Evvnt::Base} subclass
[ "Template", "method", "for", "creating", "a", "new", "record", "on", "the", "API", "." ]
e13f6d84af09a71819356620fb25685a6cd159c9
https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/class_template_methods.rb#L18-L21
train
KatanaCode/evvnt
lib/evvnt/class_template_methods.rb
Evvnt.ClassTemplateMethods.index
def index(**params) params.stringify_keys! path = nest_path_within_parent(plural_resource_path, params) api_request(:get, path, params: params) end
ruby
def index(**params) params.stringify_keys! path = nest_path_within_parent(plural_resource_path, params) api_request(:get, path, params: params) end
[ "def", "index", "(", "**", "params", ")", "params", ".", "stringify_keys!", "path", "=", "nest_path_within_parent", "(", "plural_resource_path", ",", "params", ")", "api_request", "(", ":get", ",", "path", ",", "params", ":", "params", ")", "end" ]
Template method for fetching an index of record from the API. params - A Hash of params to send to the API. Returns Array
[ "Template", "method", "for", "fetching", "an", "index", "of", "record", "from", "the", "API", "." ]
e13f6d84af09a71819356620fb25685a6cd159c9
https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/class_template_methods.rb#L28-L32
train
KatanaCode/evvnt
lib/evvnt/class_template_methods.rb
Evvnt.ClassTemplateMethods.show
def show(record_id = nil, **params) if record_id.nil? && !singular_resource? raise ArgumentError, "record_id cannot be nil" end path = nest_path_within_parent(singular_path_for_record(record_id, params), params) api_request(:get, path, params: params) end
ruby
def show(record_id = nil, **params) if record_id.nil? && !singular_resource? raise ArgumentError, "record_id cannot be nil" end path = nest_path_within_parent(singular_path_for_record(record_id, params), params) api_request(:get, path, params: params) end
[ "def", "show", "(", "record_id", "=", "nil", ",", "**", "params", ")", "if", "record_id", ".", "nil?", "&&", "!", "singular_resource?", "raise", "ArgumentError", ",", "\"record_id cannot be nil\"", "end", "path", "=", "nest_path_within_parent", "(", "singular_path_for_record", "(", "record_id", ",", "params", ")", ",", "params", ")", "api_request", "(", ":get", ",", "path", ",", "params", ":", "params", ")", "end" ]
Template method for creating a given record record_id - An Integer or String representing the record ID on the API. params - A Hash of params to send to the API. Returns {Evvnt::Base} subclass
[ "Template", "method", "for", "creating", "a", "given", "record" ]
e13f6d84af09a71819356620fb25685a6cd159c9
https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/class_template_methods.rb#L40-L46
train
Fire-Dragon-DoL/fried-schema
lib/fried/schema/attribute/define_writer.rb
Fried::Schema::Attribute.DefineWriter.call
def call(definition, klass) is_a = is[definition.type] define_writer(definition, is_a, klass) end
ruby
def call(definition, klass) is_a = is[definition.type] define_writer(definition, is_a, klass) end
[ "def", "call", "(", "definition", ",", "klass", ")", "is_a", "=", "is", "[", "definition", ".", "type", "]", "define_writer", "(", "definition", ",", "is_a", ",", "klass", ")", "end" ]
Creates write method with type-checking @param definition [Definition] @param klass [Class, Module] @return [Definition]
[ "Creates", "write", "method", "with", "type", "-", "checking" ]
85c5a093f319fc0f0d242264fdd7a2acfd805eea
https://github.com/Fire-Dragon-DoL/fried-schema/blob/85c5a093f319fc0f0d242264fdd7a2acfd805eea/lib/fried/schema/attribute/define_writer.rb#L26-L29
train
jakewendt/rails_extension
lib/rails_extension/action_controller_extension/routing.rb
RailsExtension::ActionControllerExtension::Routing.ClassMethods.assert_no_route
def assert_no_route(verb,action,args={}) test "#{brand}no route to #{verb} #{action} #{args}" do assert_raise(ActionController::RoutingError){ send(verb,action,args) } end end
ruby
def assert_no_route(verb,action,args={}) test "#{brand}no route to #{verb} #{action} #{args}" do assert_raise(ActionController::RoutingError){ send(verb,action,args) } end end
[ "def", "assert_no_route", "(", "verb", ",", "action", ",", "args", "=", "{", "}", ")", "test", "\"#{brand}no route to #{verb} #{action} #{args}\"", "do", "assert_raise", "(", "ActionController", "::", "RoutingError", ")", "{", "send", "(", "verb", ",", "action", ",", "args", ")", "}", "end", "end" ]
def assert_route end
[ "def", "assert_route", "end" ]
310774fea4a07821aee8f87b9f30d2b4b0bbe548
https://github.com/jakewendt/rails_extension/blob/310774fea4a07821aee8f87b9f30d2b4b0bbe548/lib/rails_extension/action_controller_extension/routing.rb#L12-L18
train
fdp-A4/richcss-cli
lib/richcss/richcss_ui.rb
Richcss.RichUI.debug
def debug(depth = 0) if debug? debug_info = yield debug_info = debug_info.inspect unless debug_info.is_a?(String) STDERR.puts debug_info.split("\n").map {|s| " " * depth + s } end end
ruby
def debug(depth = 0) if debug? debug_info = yield debug_info = debug_info.inspect unless debug_info.is_a?(String) STDERR.puts debug_info.split("\n").map {|s| " " * depth + s } end end
[ "def", "debug", "(", "depth", "=", "0", ")", "if", "debug?", "debug_info", "=", "yield", "debug_info", "=", "debug_info", ".", "inspect", "unless", "debug_info", ".", "is_a?", "(", "String", ")", "STDERR", ".", "puts", "debug_info", ".", "split", "(", "\"\\n\"", ")", ".", "map", "{", "|", "s", "|", "\" \"", "*", "depth", "+", "s", "}", "end", "end" ]
Conveys debug information to the user. @param [Integer] depth the current depth of the resolution process. @return [void]
[ "Conveys", "debug", "information", "to", "the", "user", "." ]
804f154032e223bae8f9884eb9aec91144d49494
https://github.com/fdp-A4/richcss-cli/blob/804f154032e223bae8f9884eb9aec91144d49494/lib/richcss/richcss_ui.rb#L10-L16
train
codescrum/bebox
lib/bebox/commands/role_commands.rb
Bebox.RoleCommands.role_list_command
def role_list_command(role_command) role_command.desc _('cli.role.list.desc') role_command.command :list do |role_list_command| role_list_command.action do |global_options,options,args| roles = Bebox::Role.list(project_root) title _('cli.role.list.current_roles') roles.map{|role| msg(role)} warn(_('cli.role.list.no_roles')) if roles.empty? linebreak end end end
ruby
def role_list_command(role_command) role_command.desc _('cli.role.list.desc') role_command.command :list do |role_list_command| role_list_command.action do |global_options,options,args| roles = Bebox::Role.list(project_root) title _('cli.role.list.current_roles') roles.map{|role| msg(role)} warn(_('cli.role.list.no_roles')) if roles.empty? linebreak end end end
[ "def", "role_list_command", "(", "role_command", ")", "role_command", ".", "desc", "_", "(", "'cli.role.list.desc'", ")", "role_command", ".", "command", ":list", "do", "|", "role_list_command", "|", "role_list_command", ".", "action", "do", "|", "global_options", ",", "options", ",", "args", "|", "roles", "=", "Bebox", "::", "Role", ".", "list", "(", "project_root", ")", "title", "_", "(", "'cli.role.list.current_roles'", ")", "roles", ".", "map", "{", "|", "role", "|", "msg", "(", "role", ")", "}", "warn", "(", "_", "(", "'cli.role.list.no_roles'", ")", ")", "if", "roles", ".", "empty?", "linebreak", "end", "end", "end" ]
Role list command
[ "Role", "list", "command" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/role_commands.rb#L21-L32
train
codescrum/bebox
lib/bebox/commands/role_commands.rb
Bebox.RoleCommands.role_new_command
def role_new_command(role_command) role_command.desc _('cli.role.new.desc') role_command.arg_name "[name]" role_command.command :new do |role_new_command| role_new_command.action do |global_options,options,args| help_now!(error(_('cli.role.new.name_arg_missing'))) if args.count == 0 Bebox::RoleWizard.new.create_new_role(project_root, args.first) end end end
ruby
def role_new_command(role_command) role_command.desc _('cli.role.new.desc') role_command.arg_name "[name]" role_command.command :new do |role_new_command| role_new_command.action do |global_options,options,args| help_now!(error(_('cli.role.new.name_arg_missing'))) if args.count == 0 Bebox::RoleWizard.new.create_new_role(project_root, args.first) end end end
[ "def", "role_new_command", "(", "role_command", ")", "role_command", ".", "desc", "_", "(", "'cli.role.new.desc'", ")", "role_command", ".", "arg_name", "\"[name]\"", "role_command", ".", "command", ":new", "do", "|", "role_new_command", "|", "role_new_command", ".", "action", "do", "|", "global_options", ",", "options", ",", "args", "|", "help_now!", "(", "error", "(", "_", "(", "'cli.role.new.name_arg_missing'", ")", ")", ")", "if", "args", ".", "count", "==", "0", "Bebox", "::", "RoleWizard", ".", "new", ".", "create_new_role", "(", "project_root", ",", "args", ".", "first", ")", "end", "end", "end" ]
Role new command
[ "Role", "new", "command" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/role_commands.rb#L35-L44
train
codescrum/bebox
lib/bebox/commands/role_commands.rb
Bebox.RoleCommands.generate_role_command
def generate_role_command(role_command, command, send_command, description) role_command.desc description role_command.command command do |generated_command| generated_command.action do |global_options,options,args| Bebox::RoleWizard.new.send(send_command, project_root) end end end
ruby
def generate_role_command(role_command, command, send_command, description) role_command.desc description role_command.command command do |generated_command| generated_command.action do |global_options,options,args| Bebox::RoleWizard.new.send(send_command, project_root) end end end
[ "def", "generate_role_command", "(", "role_command", ",", "command", ",", "send_command", ",", "description", ")", "role_command", ".", "desc", "description", "role_command", ".", "command", "command", "do", "|", "generated_command", "|", "generated_command", ".", "action", "do", "|", "global_options", ",", "options", ",", "args", "|", "Bebox", "::", "RoleWizard", ".", "new", ".", "send", "(", "send_command", ",", "project_root", ")", "end", "end", "end" ]
For add_profile remove_profile and remove_role commands
[ "For", "add_profile", "remove_profile", "and", "remove_role", "commands" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/role_commands.rb#L53-L60
train
codescrum/bebox
lib/bebox/commands/role_commands.rb
Bebox.RoleCommands.role_list_profiles_command
def role_list_profiles_command(role_command) role_command.desc _('cli.role.list_profiles.desc') role_command.arg_name "[role_name]" role_command.command :list_profiles do |list_profiles_command| list_profiles_command.action do |global_options,options,args| help_now!(error(_('cli.role.list_profiles.name_arg_missing'))) if args.count == 0 role = args.first print_profiles(role, Bebox::Role.list_profiles(project_root, role)) end end end
ruby
def role_list_profiles_command(role_command) role_command.desc _('cli.role.list_profiles.desc') role_command.arg_name "[role_name]" role_command.command :list_profiles do |list_profiles_command| list_profiles_command.action do |global_options,options,args| help_now!(error(_('cli.role.list_profiles.name_arg_missing'))) if args.count == 0 role = args.first print_profiles(role, Bebox::Role.list_profiles(project_root, role)) end end end
[ "def", "role_list_profiles_command", "(", "role_command", ")", "role_command", ".", "desc", "_", "(", "'cli.role.list_profiles.desc'", ")", "role_command", ".", "arg_name", "\"[role_name]\"", "role_command", ".", "command", ":list_profiles", "do", "|", "list_profiles_command", "|", "list_profiles_command", ".", "action", "do", "|", "global_options", ",", "options", ",", "args", "|", "help_now!", "(", "error", "(", "_", "(", "'cli.role.list_profiles.name_arg_missing'", ")", ")", ")", "if", "args", ".", "count", "==", "0", "role", "=", "args", ".", "first", "print_profiles", "(", "role", ",", "Bebox", "::", "Role", ".", "list_profiles", "(", "project_root", ",", "role", ")", ")", "end", "end", "end" ]
Role list profiles command
[ "Role", "list", "profiles", "command" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/role_commands.rb#L63-L73
train
fugroup/pushfile
lib/pushfile/util.rb
Pushfile.Util.filename
def filename(name) # Replace space with underscore and downcase extension pre, dot, ext = name.rpartition('.') name = "#{pre.gsub(' ', '_')}.#{ext.downcase}" # Remove illegal characters # http://stackoverflow.com/questions/13517100/whats-the-difference-between-palpha-i-and-pl-i-in-ruby name = name.gsub(%r{[^\p{L}\-\_\.0-9]}, '') name end
ruby
def filename(name) # Replace space with underscore and downcase extension pre, dot, ext = name.rpartition('.') name = "#{pre.gsub(' ', '_')}.#{ext.downcase}" # Remove illegal characters # http://stackoverflow.com/questions/13517100/whats-the-difference-between-palpha-i-and-pl-i-in-ruby name = name.gsub(%r{[^\p{L}\-\_\.0-9]}, '') name end
[ "def", "filename", "(", "name", ")", "pre", ",", "dot", ",", "ext", "=", "name", ".", "rpartition", "(", "'.'", ")", "name", "=", "\"#{pre.gsub(' ', '_')}.#{ext.downcase}\"", "name", "=", "name", ".", "gsub", "(", "%r{", "\\p", "\\-", "\\_", "\\.", "}", ",", "''", ")", "name", "end" ]
Make sure the file name is valid
[ "Make", "sure", "the", "file", "name", "is", "valid" ]
dd06bd6b023514a1446544986b1ce85b7bae3f78
https://github.com/fugroup/pushfile/blob/dd06bd6b023514a1446544986b1ce85b7bae3f78/lib/pushfile/util.rb#L5-L15
train
riddopic/garcun
lib/garcon/utility/memstash.rb
Garcon.MemStash.load
def load(data) @monitor.synchronize do data.each do |key, value| expire! store(key, val) end end end
ruby
def load(data) @monitor.synchronize do data.each do |key, value| expire! store(key, val) end end end
[ "def", "load", "(", "data", ")", "@monitor", ".", "synchronize", "do", "data", ".", "each", "do", "|", "key", ",", "value", "|", "expire!", "store", "(", "key", ",", "val", ")", "end", "end", "end" ]
Initializes the cache. @param [Hash] opts The options to configure the cache. @option opts [Integer] :max_entries Maximum number of elements in the cache. @option opts [Numeric] :ttl Maximum time, in seconds, for a value to stay in the cache. @option opts [Numeric] :tti Maximum time, in seconds, for a value to stay in the cache without being accessed. @option opts [Integer] :interval Number of cache operations between calls to {#expire!}. Loads a hash of data into the stash. @param [Hash] data Hash of data with either String or Symbol keys. @return nothing.
[ "Initializes", "the", "cache", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/memstash.rb#L114-L121
train
riddopic/garcun
lib/garcon/utility/memstash.rb
Garcon.MemStash.fetch
def fetch(key) @monitor.synchronize do found, value = get(key) found ? value : store(key, yield) end end
ruby
def fetch(key) @monitor.synchronize do found, value = get(key) found ? value : store(key, yield) end end
[ "def", "fetch", "(", "key", ")", "@monitor", ".", "synchronize", "do", "found", ",", "value", "=", "get", "(", "key", ")", "found", "?", "value", ":", "store", "(", "key", ",", "yield", ")", "end", "end" ]
Retrieves a value from the cache, if available and not expired, or yields to a block that calculates the value to be stored in the cache. @param [Object] key The key to look up or store at. @yield yields when the value is not present. @yieldreturn [Object] The value to store in the cache. @return [Object] The value at the key.
[ "Retrieves", "a", "value", "from", "the", "cache", "if", "available", "and", "not", "expired", "or", "yields", "to", "a", "block", "that", "calculates", "the", "value", "to", "be", "stored", "in", "the", "cache", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/memstash.rb#L137-L142
train
riddopic/garcun
lib/garcon/utility/memstash.rb
Garcon.MemStash.delete
def delete(key) @monitor.synchronize do entry = @stash.delete(key) if entry @expires_at.delete(entry) entry.value else nil end end end
ruby
def delete(key) @monitor.synchronize do entry = @stash.delete(key) if entry @expires_at.delete(entry) entry.value else nil end end end
[ "def", "delete", "(", "key", ")", "@monitor", ".", "synchronize", "do", "entry", "=", "@stash", ".", "delete", "(", "key", ")", "if", "entry", "@expires_at", ".", "delete", "(", "entry", ")", "entry", ".", "value", "else", "nil", "end", "end", "end" ]
Removes a value from the cache. @param [Object] key The key to remove. @return [Object, nil] The value at the key, when present, or `nil`.
[ "Removes", "a", "value", "from", "the", "cache", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/memstash.rb#L187-L197
train
rubyworks/richunits
lib/richunits/duration.rb
RichUnits.Duration.reset_segments
def reset_segments(segmentA=nil, segmentB=nil) if !segmentA @segments = [:days, :hours, :minutes, :seconds] elsif !segmentB case segmentA when Array @segments = segmentA.map{ |p| (p.to_s.downcase.chomp('s') + 's').to_sym } raise ArgumentError unless @segments.all?{ |s| SEGMENTS.include?(s) } else f = SEGMENTS.index(segmentA) @segments = SEGMENTS[f..0] end else # segmentA && segmentB f = SEGMENTS.index(segmentA) t = SEGMENTS.index(segmentB) @segments = SEGMENTS[f..t] end end
ruby
def reset_segments(segmentA=nil, segmentB=nil) if !segmentA @segments = [:days, :hours, :minutes, :seconds] elsif !segmentB case segmentA when Array @segments = segmentA.map{ |p| (p.to_s.downcase.chomp('s') + 's').to_sym } raise ArgumentError unless @segments.all?{ |s| SEGMENTS.include?(s) } else f = SEGMENTS.index(segmentA) @segments = SEGMENTS[f..0] end else # segmentA && segmentB f = SEGMENTS.index(segmentA) t = SEGMENTS.index(segmentB) @segments = SEGMENTS[f..t] end end
[ "def", "reset_segments", "(", "segmentA", "=", "nil", ",", "segmentB", "=", "nil", ")", "if", "!", "segmentA", "@segments", "=", "[", ":days", ",", ":hours", ",", ":minutes", ",", ":seconds", "]", "elsif", "!", "segmentB", "case", "segmentA", "when", "Array", "@segments", "=", "segmentA", ".", "map", "{", "|", "p", "|", "(", "p", ".", "to_s", ".", "downcase", ".", "chomp", "(", "'s'", ")", "+", "'s'", ")", ".", "to_sym", "}", "raise", "ArgumentError", "unless", "@segments", ".", "all?", "{", "|", "s", "|", "SEGMENTS", ".", "include?", "(", "s", ")", "}", "else", "f", "=", "SEGMENTS", ".", "index", "(", "segmentA", ")", "@segments", "=", "SEGMENTS", "[", "f", "..", "0", "]", "end", "else", "f", "=", "SEGMENTS", ".", "index", "(", "segmentA", ")", "t", "=", "SEGMENTS", ".", "index", "(", "segmentB", ")", "@segments", "=", "SEGMENTS", "[", "f", "..", "t", "]", "end", "end" ]
Reset segments. call-seq: reset_segments(max-period) reset_segments(max-period, min-period) reset_segments([period1, period2, ...])
[ "Reset", "segments", "." ]
c92bec173fc63798013defdd9a1727b0d1d65d46
https://github.com/rubyworks/richunits/blob/c92bec173fc63798013defdd9a1727b0d1d65d46/lib/richunits/duration.rb#L46-L63
train
rubyworks/richunits
lib/richunits/duration.rb
RichUnits.Duration.strftime
def strftime(fmt) h = to_h hx = { 'y' => h[:years] , 'w' => h[:weeks] , 'd' => h[:days] , 'h' => h[:hours] , 'm' => h[:minutes], 's' => h[:seconds], 't' => total, 'x' => to_s } fmt.gsub(/%?%(w|d|h|m|s|t|x)/) do |match| hx[match[1..1]] end.gsub('%%', '%') end
ruby
def strftime(fmt) h = to_h hx = { 'y' => h[:years] , 'w' => h[:weeks] , 'd' => h[:days] , 'h' => h[:hours] , 'm' => h[:minutes], 's' => h[:seconds], 't' => total, 'x' => to_s } fmt.gsub(/%?%(w|d|h|m|s|t|x)/) do |match| hx[match[1..1]] end.gsub('%%', '%') end
[ "def", "strftime", "(", "fmt", ")", "h", "=", "to_h", "hx", "=", "{", "'y'", "=>", "h", "[", ":years", "]", ",", "'w'", "=>", "h", "[", ":weeks", "]", ",", "'d'", "=>", "h", "[", ":days", "]", ",", "'h'", "=>", "h", "[", ":hours", "]", ",", "'m'", "=>", "h", "[", ":minutes", "]", ",", "'s'", "=>", "h", "[", ":seconds", "]", ",", "'t'", "=>", "total", ",", "'x'", "=>", "to_s", "}", "fmt", ".", "gsub", "(", "/", "/", ")", "do", "|", "match", "|", "hx", "[", "match", "[", "1", "..", "1", "]", "]", "end", ".", "gsub", "(", "'%%'", ",", "'%'", ")", "end" ]
Format duration. *Identifiers* %w -- Number of weeks %d -- Number of days %h -- Number of hours %m -- Number of minutes %s -- Number of seconds %t -- Total number of seconds %x -- Duration#to_s %% -- Literal `%' character *Example* d = Duration.new(:weeks => 10, :days => 7) => #<Duration: 11 weeks> d.strftime("It's been %w weeks!") => "It's been 11 weeks!"
[ "Format", "duration", "." ]
c92bec173fc63798013defdd9a1727b0d1d65d46
https://github.com/rubyworks/richunits/blob/c92bec173fc63798013defdd9a1727b0d1d65d46/lib/richunits/duration.rb#L191-L206
train
barkerest/barkest_core
app/helpers/barkest_core/recaptcha_helper.rb
BarkestCore.RecaptchaHelper.verify_recaptcha_challenge
def verify_recaptcha_challenge(model = nil) # always true in tests. return true if recaptcha_disabled? # model must respond to the 'errors' message and the result of that must respond to 'add' if !model || !model.respond_to?('errors') || !model.send('errors').respond_to?('add') model = nil end begin recaptcha = nil http = Net::HTTP remote_ip = (request.respond_to?('remote_ip') && request.send('remote_ip')) || (env && env['REMOTE_ADDR']) verify_hash = { secret: recaptcha_secret_key, remoteip: remote_ip, response: params['g-recaptcha-response'] } Timeout::timeout(5) do uri = URI.parse('https://www.google.com/recaptcha/api/siteverify') http_instance = http.new(uri.host, uri.port) if uri.port == 443 http_instance.use_ssl = true http_instance.verify_mode = OpenSSL::SSL::VERIFY_NONE end request = Net::HTTP::Post.new(uri.request_uri) request.set_form_data(verify_hash) recaptcha = http_instance.request(request) end answer = JSON.parse(recaptcha.body) if answer['success'].to_s.downcase == 'true' return true else if model model.errors.add(:base, 'Recaptcha verification failed.') end return false end rescue Timeout::Error if model model.errors.add(:base, 'Recaptcha unreachable.') end end end
ruby
def verify_recaptcha_challenge(model = nil) # always true in tests. return true if recaptcha_disabled? # model must respond to the 'errors' message and the result of that must respond to 'add' if !model || !model.respond_to?('errors') || !model.send('errors').respond_to?('add') model = nil end begin recaptcha = nil http = Net::HTTP remote_ip = (request.respond_to?('remote_ip') && request.send('remote_ip')) || (env && env['REMOTE_ADDR']) verify_hash = { secret: recaptcha_secret_key, remoteip: remote_ip, response: params['g-recaptcha-response'] } Timeout::timeout(5) do uri = URI.parse('https://www.google.com/recaptcha/api/siteverify') http_instance = http.new(uri.host, uri.port) if uri.port == 443 http_instance.use_ssl = true http_instance.verify_mode = OpenSSL::SSL::VERIFY_NONE end request = Net::HTTP::Post.new(uri.request_uri) request.set_form_data(verify_hash) recaptcha = http_instance.request(request) end answer = JSON.parse(recaptcha.body) if answer['success'].to_s.downcase == 'true' return true else if model model.errors.add(:base, 'Recaptcha verification failed.') end return false end rescue Timeout::Error if model model.errors.add(:base, 'Recaptcha unreachable.') end end end
[ "def", "verify_recaptcha_challenge", "(", "model", "=", "nil", ")", "return", "true", "if", "recaptcha_disabled?", "if", "!", "model", "||", "!", "model", ".", "respond_to?", "(", "'errors'", ")", "||", "!", "model", ".", "send", "(", "'errors'", ")", ".", "respond_to?", "(", "'add'", ")", "model", "=", "nil", "end", "begin", "recaptcha", "=", "nil", "http", "=", "Net", "::", "HTTP", "remote_ip", "=", "(", "request", ".", "respond_to?", "(", "'remote_ip'", ")", "&&", "request", ".", "send", "(", "'remote_ip'", ")", ")", "||", "(", "env", "&&", "env", "[", "'REMOTE_ADDR'", "]", ")", "verify_hash", "=", "{", "secret", ":", "recaptcha_secret_key", ",", "remoteip", ":", "remote_ip", ",", "response", ":", "params", "[", "'g-recaptcha-response'", "]", "}", "Timeout", "::", "timeout", "(", "5", ")", "do", "uri", "=", "URI", ".", "parse", "(", "'https://www.google.com/recaptcha/api/siteverify'", ")", "http_instance", "=", "http", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "if", "uri", ".", "port", "==", "443", "http_instance", ".", "use_ssl", "=", "true", "http_instance", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "end", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ".", "request_uri", ")", "request", ".", "set_form_data", "(", "verify_hash", ")", "recaptcha", "=", "http_instance", ".", "request", "(", "request", ")", "end", "answer", "=", "JSON", ".", "parse", "(", "recaptcha", ".", "body", ")", "if", "answer", "[", "'success'", "]", ".", "to_s", ".", "downcase", "==", "'true'", "return", "true", "else", "if", "model", "model", ".", "errors", ".", "add", "(", ":base", ",", "'Recaptcha verification failed.'", ")", "end", "return", "false", "end", "rescue", "Timeout", "::", "Error", "if", "model", "model", ".", "errors", ".", "add", "(", ":base", ",", "'Recaptcha unreachable.'", ")", "end", "end", "end" ]
Verifies the response from a recaptcha challenge in a controller. It will return true if the recaptcha challenge passed. It always returns true in the 'test' environment. If a +model+ is provided, then an error will be added to the model if the challenge fails. Because this is handled outside of the model (since it's based on the request and not the model), you should first check if the model is valid and then verify the recaptcha challenge to ensure you don't lose the recaptcha error message. if model.valid? && verify_recaptcha_challenge(model) model.save redirect_to :show, id: model else render 'edit' end
[ "Verifies", "the", "response", "from", "a", "recaptcha", "challenge", "in", "a", "controller", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/recaptcha_helper.rb#L63-L112
train
Referly/better_sqs
spec/support/mocks.rb
SqsMocks.MockClient.get_queue_attributes
def get_queue_attributes(queue_url: nil, attribute_names: nil) r = MockResponse.new if attribute_names == "All" r.attributes = FAUX_ATTRIBUTES else attribute_names.each do |attribute_name| r.attributes[attribute_name] = FAUX_ATTRIBUTES[attribute_name] end end r end
ruby
def get_queue_attributes(queue_url: nil, attribute_names: nil) r = MockResponse.new if attribute_names == "All" r.attributes = FAUX_ATTRIBUTES else attribute_names.each do |attribute_name| r.attributes[attribute_name] = FAUX_ATTRIBUTES[attribute_name] end end r end
[ "def", "get_queue_attributes", "(", "queue_url", ":", "nil", ",", "attribute_names", ":", "nil", ")", "r", "=", "MockResponse", ".", "new", "if", "attribute_names", "==", "\"All\"", "r", ".", "attributes", "=", "FAUX_ATTRIBUTES", "else", "attribute_names", ".", "each", "do", "|", "attribute_name", "|", "r", ".", "attributes", "[", "attribute_name", "]", "=", "FAUX_ATTRIBUTES", "[", "attribute_name", "]", "end", "end", "r", "end" ]
Just a static mock of the get_queue_attributes API
[ "Just", "a", "static", "mock", "of", "the", "get_queue_attributes", "API" ]
c1e20bf5c079df1b65e6ed7702a2449ab2e991ba
https://github.com/Referly/better_sqs/blob/c1e20bf5c079df1b65e6ed7702a2449ab2e991ba/spec/support/mocks.rb#L80-L90
train