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 |
---|---|---|---|---|---|---|---|---|---|---|---|
bsm/pbio | lib/pbio/delimited.rb | PBIO.Delimited.read | def read(klass)
size = Delimited.read_uvarint(io)
klass.decode io.read(size) unless size.zero?
end | ruby | def read(klass)
size = Delimited.read_uvarint(io)
klass.decode io.read(size) unless size.zero?
end | [
"def",
"read",
"(",
"klass",
")",
"size",
"=",
"Delimited",
".",
"read_uvarint",
"(",
"io",
")",
"klass",
".",
"decode",
"io",
".",
"read",
"(",
"size",
")",
"unless",
"size",
".",
"zero?",
"end"
] | Reads the next message | [
"Reads",
"the",
"next",
"message"
] | 683e621b31080a415c0cdc9ca0d574a6b03b3f79 | https://github.com/bsm/pbio/blob/683e621b31080a415c0cdc9ca0d574a6b03b3f79/lib/pbio/delimited.rb#L50-L53 | train |
synthesist/panoptimon | lib/panoptimon/monitor.rb | Panoptimon.Monitor._dirjson | def _dirjson (x)
x = Pathname.new(x)
x.entries.find_all {|f| f.to_s =~ /\.json$/i}.
map {|f| x + f}
end | ruby | def _dirjson (x)
x = Pathname.new(x)
x.entries.find_all {|f| f.to_s =~ /\.json$/i}.
map {|f| x + f}
end | [
"def",
"_dirjson",
"(",
"x",
")",
"x",
"=",
"Pathname",
".",
"new",
"(",
"x",
")",
"x",
".",
"entries",
".",
"find_all",
"{",
"|",
"f",
"|",
"f",
".",
"to_s",
"=~",
"/",
"\\.",
"/i",
"}",
".",
"map",
"{",
"|",
"f",
"|",
"x",
"+",
"f",
"}",
"end"
] | Search directories for JSON files | [
"Search",
"directories",
"for",
"JSON",
"files"
] | 9346c221ae95aaa6528232a04a92478f7c9a5e15 | https://github.com/synthesist/panoptimon/blob/9346c221ae95aaa6528232a04a92478f7c9a5e15/lib/panoptimon/monitor.rb#L24-L28 | train |
jarhart/rattler | lib/rattler.rb | Rattler.HelperMethods.compile_parser | def compile_parser(*args)
options = @@defaults.dup
grammar = nil
for arg in args
case arg
when Hash then options.merge!(arg)
when String then grammar = arg
end
end
base_class = options.delete(:class) ||
(Rattler::Runtime::const_get @@parser_types[options[:type]])
Rattler::Compiler.compile_parser(base_class, grammar, options)
end | ruby | def compile_parser(*args)
options = @@defaults.dup
grammar = nil
for arg in args
case arg
when Hash then options.merge!(arg)
when String then grammar = arg
end
end
base_class = options.delete(:class) ||
(Rattler::Runtime::const_get @@parser_types[options[:type]])
Rattler::Compiler.compile_parser(base_class, grammar, options)
end | [
"def",
"compile_parser",
"(",
"*",
"args",
")",
"options",
"=",
"@@defaults",
".",
"dup",
"grammar",
"=",
"nil",
"for",
"arg",
"in",
"args",
"case",
"arg",
"when",
"Hash",
"then",
"options",
".",
"merge!",
"(",
"arg",
")",
"when",
"String",
"then",
"grammar",
"=",
"arg",
"end",
"end",
"base_class",
"=",
"options",
".",
"delete",
"(",
":class",
")",
"||",
"(",
"Rattler",
"::",
"Runtime",
"::",
"const_get",
"@@parser_types",
"[",
"options",
"[",
":type",
"]",
"]",
")",
"Rattler",
"::",
"Compiler",
".",
"compile_parser",
"(",
"base_class",
",",
"grammar",
",",
"options",
")",
"end"
] | Define a parser with the given grammar and compile it into a parser class
using the given options
@return [Class] a new parser class | [
"Define",
"a",
"parser",
"with",
"the",
"given",
"grammar",
"and",
"compile",
"it",
"into",
"a",
"parser",
"class",
"using",
"the",
"given",
"options"
] | 8b4efde2a05e9e790955bb635d4a1a9615893719 | https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler.rb#L29-L41 | train |
Fedcomp/any_sms | lib/any_sms/configuration.rb | AnySMS.Configuration.default_backend= | def default_backend=(value)
raise ArgumentError, "default_backend must be a symbol!" unless value.is_a? Symbol
unless @backends.keys.include? value
raise ArgumentError, "Unregistered backend cannot be set as default!"
end
@default_backend = value
end | ruby | def default_backend=(value)
raise ArgumentError, "default_backend must be a symbol!" unless value.is_a? Symbol
unless @backends.keys.include? value
raise ArgumentError, "Unregistered backend cannot be set as default!"
end
@default_backend = value
end | [
"def",
"default_backend",
"=",
"(",
"value",
")",
"raise",
"ArgumentError",
",",
"\"default_backend must be a symbol!\"",
"unless",
"value",
".",
"is_a?",
"Symbol",
"unless",
"@backends",
".",
"keys",
".",
"include?",
"value",
"raise",
"ArgumentError",
",",
"\"Unregistered backend cannot be set as default!\"",
"end",
"@default_backend",
"=",
"value",
"end"
] | Specify default sms backend. It must be registered.
@param value [Symbol] Backend key which will be used as default | [
"Specify",
"default",
"sms",
"backend",
".",
"It",
"must",
"be",
"registered",
"."
] | c8a2483acc5b263b47a00b4d64d3114b43ff2342 | https://github.com/Fedcomp/any_sms/blob/c8a2483acc5b263b47a00b4d64d3114b43ff2342/lib/any_sms/configuration.rb#L34-L42 | train |
Fedcomp/any_sms | lib/any_sms/configuration.rb | AnySMS.Configuration.register_backend | def register_backend(key, classname, params = {})
raise ArgumentError, "backend key must be a symbol!" unless key.is_a? Symbol
unless classname.class == Class
raise ArgumentError, "backend class must be class (not instance or string)"
end
unless classname.method_defined? :send_sms
raise ArgumentError, "backend must provide method send_sms"
end
define_backend(key, classname, params)
end | ruby | def register_backend(key, classname, params = {})
raise ArgumentError, "backend key must be a symbol!" unless key.is_a? Symbol
unless classname.class == Class
raise ArgumentError, "backend class must be class (not instance or string)"
end
unless classname.method_defined? :send_sms
raise ArgumentError, "backend must provide method send_sms"
end
define_backend(key, classname, params)
end | [
"def",
"register_backend",
"(",
"key",
",",
"classname",
",",
"params",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"\"backend key must be a symbol!\"",
"unless",
"key",
".",
"is_a?",
"Symbol",
"unless",
"classname",
".",
"class",
"==",
"Class",
"raise",
"ArgumentError",
",",
"\"backend class must be class (not instance or string)\"",
"end",
"unless",
"classname",
".",
"method_defined?",
":send_sms",
"raise",
"ArgumentError",
",",
"\"backend must provide method send_sms\"",
"end",
"define_backend",
"(",
"key",
",",
"classname",
",",
"params",
")",
"end"
] | Register sms provider backend
@param key [Symbol] Key for acessing backend in any part of AnySMS
@param classname [Class] Real class implementation of sms backend
@param params [Hash]
Optional params for backend. Useful for passing tokens and options | [
"Register",
"sms",
"provider",
"backend"
] | c8a2483acc5b263b47a00b4d64d3114b43ff2342 | https://github.com/Fedcomp/any_sms/blob/c8a2483acc5b263b47a00b4d64d3114b43ff2342/lib/any_sms/configuration.rb#L50-L62 | train |
mssola/cconfig | lib/cconfig/cconfig.rb | CConfig.Config.fetch | def fetch
cfg = File.file?(@default) ? YAML.load_file(@default) : {}
local = fetch_local
hsh = strict_merge_with_env(default: cfg, local: local, prefix: @prefix)
hsh.extend(::CConfig::HashUtils::Extensions)
hsh.defaults = cfg
hsh
end | ruby | def fetch
cfg = File.file?(@default) ? YAML.load_file(@default) : {}
local = fetch_local
hsh = strict_merge_with_env(default: cfg, local: local, prefix: @prefix)
hsh.extend(::CConfig::HashUtils::Extensions)
hsh.defaults = cfg
hsh
end | [
"def",
"fetch",
"cfg",
"=",
"File",
".",
"file?",
"(",
"@default",
")",
"?",
"YAML",
".",
"load_file",
"(",
"@default",
")",
":",
"{",
"}",
"local",
"=",
"fetch_local",
"hsh",
"=",
"strict_merge_with_env",
"(",
"default",
":",
"cfg",
",",
"local",
":",
"local",
",",
"prefix",
":",
"@prefix",
")",
"hsh",
".",
"extend",
"(",
"::",
"CConfig",
"::",
"HashUtils",
"::",
"Extensions",
")",
"hsh",
".",
"defaults",
"=",
"cfg",
"hsh",
"end"
] | Instantiate an object with `default` as the path to the default
configuration, `local` as the alternate file, and `prefix` as the prefix
for environment variables. The `prefix` will take "cconfig" as the default.
Note: the `local` value will be discarded in favor of the
`#{prefix}_LOCAL_CONFIG_PATH` environment variable if it was set.
Returns a hash with the app configuration contained in it. | [
"Instantiate",
"an",
"object",
"with",
"default",
"as",
"the",
"path",
"to",
"the",
"default",
"configuration",
"local",
"as",
"the",
"alternate",
"file",
"and",
"prefix",
"as",
"the",
"prefix",
"for",
"environment",
"variables",
".",
"The",
"prefix",
"will",
"take",
"cconfig",
"as",
"the",
"default",
"."
] | 793fb743cdcc064a96fb911bc17483fa0d343056 | https://github.com/mssola/cconfig/blob/793fb743cdcc064a96fb911bc17483fa0d343056/lib/cconfig/cconfig.rb#L45-L53 | train |
mssola/cconfig | lib/cconfig/cconfig.rb | CConfig.Config.fetch_local | def fetch_local
if File.file?(@local)
# Check for bad user input in the local config.yml file.
local = YAML.load_file(@local)
raise FormatError unless local.is_a?(::Hash)
local
else
{}
end
end | ruby | def fetch_local
if File.file?(@local)
# Check for bad user input in the local config.yml file.
local = YAML.load_file(@local)
raise FormatError unless local.is_a?(::Hash)
local
else
{}
end
end | [
"def",
"fetch_local",
"if",
"File",
".",
"file?",
"(",
"@local",
")",
"local",
"=",
"YAML",
".",
"load_file",
"(",
"@local",
")",
"raise",
"FormatError",
"unless",
"local",
".",
"is_a?",
"(",
"::",
"Hash",
")",
"local",
"else",
"{",
"}",
"end",
"end"
] | Returns a hash with the alternate values that have to override the default
ones. | [
"Returns",
"a",
"hash",
"with",
"the",
"alternate",
"values",
"that",
"have",
"to",
"override",
"the",
"default",
"ones",
"."
] | 793fb743cdcc064a96fb911bc17483fa0d343056 | https://github.com/mssola/cconfig/blob/793fb743cdcc064a96fb911bc17483fa0d343056/lib/cconfig/cconfig.rb#L64-L74 | train |
m4n/validates_captcha | lib/validates_captcha/form_helper.rb | ValidatesCaptcha.FormHelper.captcha_challenge | def captcha_challenge(object_name, options = {})
options.symbolize_keys!
object = options.delete(:object)
sanitized_object_name = object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
ValidatesCaptcha.provider.render_challenge sanitized_object_name, object, options
end | ruby | def captcha_challenge(object_name, options = {})
options.symbolize_keys!
object = options.delete(:object)
sanitized_object_name = object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
ValidatesCaptcha.provider.render_challenge sanitized_object_name, object, options
end | [
"def",
"captcha_challenge",
"(",
"object_name",
",",
"options",
"=",
"{",
"}",
")",
"options",
".",
"symbolize_keys!",
"object",
"=",
"options",
".",
"delete",
"(",
":object",
")",
"sanitized_object_name",
"=",
"object_name",
".",
"to_s",
".",
"gsub",
"(",
"/",
"\\]",
"\\[",
"/",
",",
"\"_\"",
")",
".",
"sub",
"(",
"/",
"/",
",",
"\"\"",
")",
"ValidatesCaptcha",
".",
"provider",
".",
"render_challenge",
"sanitized_object_name",
",",
"object",
",",
"options",
"end"
] | Returns the captcha challenge.
Internally calls the +render_challenge+ method of ValidatesCaptcha#provider. | [
"Returns",
"the",
"captcha",
"challenge",
"."
] | 6537953bd81860ac07694b1a8e1cd32b2a24240c | https://github.com/m4n/validates_captcha/blob/6537953bd81860ac07694b1a8e1cd32b2a24240c/lib/validates_captcha/form_helper.rb#L6-L13 | train |
m4n/validates_captcha | lib/validates_captcha/form_helper.rb | ValidatesCaptcha.FormHelper.captcha_field | def captcha_field(object_name, options = {})
options.delete(:id)
hidden_field(object_name, :captcha_challenge, options) + text_field(object_name, :captcha_solution, options)
end | ruby | def captcha_field(object_name, options = {})
options.delete(:id)
hidden_field(object_name, :captcha_challenge, options) + text_field(object_name, :captcha_solution, options)
end | [
"def",
"captcha_field",
"(",
"object_name",
",",
"options",
"=",
"{",
"}",
")",
"options",
".",
"delete",
"(",
":id",
")",
"hidden_field",
"(",
"object_name",
",",
":captcha_challenge",
",",
"options",
")",
"+",
"text_field",
"(",
"object_name",
",",
":captcha_solution",
",",
"options",
")",
"end"
] | Returns an input tag of the "text" type tailored for entering the captcha solution.
Internally calls Rails' #text_field helper method, passing the +object_name+ and
+options+ arguments. | [
"Returns",
"an",
"input",
"tag",
"of",
"the",
"text",
"type",
"tailored",
"for",
"entering",
"the",
"captcha",
"solution",
"."
] | 6537953bd81860ac07694b1a8e1cd32b2a24240c | https://github.com/m4n/validates_captcha/blob/6537953bd81860ac07694b1a8e1cd32b2a24240c/lib/validates_captcha/form_helper.rb#L19-L23 | train |
m4n/validates_captcha | lib/validates_captcha/form_helper.rb | ValidatesCaptcha.FormHelper.regenerate_captcha_challenge_link | def regenerate_captcha_challenge_link(object_name, options = {}, html_options = {})
options.symbolize_keys!
object = options.delete(:object)
sanitized_object_name = object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
ValidatesCaptcha.provider.render_regenerate_challenge_link sanitized_object_name, object, options, html_options
end | ruby | def regenerate_captcha_challenge_link(object_name, options = {}, html_options = {})
options.symbolize_keys!
object = options.delete(:object)
sanitized_object_name = object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
ValidatesCaptcha.provider.render_regenerate_challenge_link sanitized_object_name, object, options, html_options
end | [
"def",
"regenerate_captcha_challenge_link",
"(",
"object_name",
",",
"options",
"=",
"{",
"}",
",",
"html_options",
"=",
"{",
"}",
")",
"options",
".",
"symbolize_keys!",
"object",
"=",
"options",
".",
"delete",
"(",
":object",
")",
"sanitized_object_name",
"=",
"object_name",
".",
"to_s",
".",
"gsub",
"(",
"/",
"\\]",
"\\[",
"/",
",",
"\"_\"",
")",
".",
"sub",
"(",
"/",
"/",
",",
"\"\"",
")",
"ValidatesCaptcha",
".",
"provider",
".",
"render_regenerate_challenge_link",
"sanitized_object_name",
",",
"object",
",",
"options",
",",
"html_options",
"end"
] | By default, returns an anchor tag that makes an AJAX request to fetch a new captcha challenge and updates
the current challenge after the request is complete.
Internally calls +render_regenerate_challenge_link+ method of ValidatesCaptcha#provider. | [
"By",
"default",
"returns",
"an",
"anchor",
"tag",
"that",
"makes",
"an",
"AJAX",
"request",
"to",
"fetch",
"a",
"new",
"captcha",
"challenge",
"and",
"updates",
"the",
"current",
"challenge",
"after",
"the",
"request",
"is",
"complete",
"."
] | 6537953bd81860ac07694b1a8e1cd32b2a24240c | https://github.com/m4n/validates_captcha/blob/6537953bd81860ac07694b1a8e1cd32b2a24240c/lib/validates_captcha/form_helper.rb#L29-L36 | train |
jduckett/duck_map | lib/duck_map/sitemap_object.rb | DuckMap.SitemapObject.sitemap_capture_segments | def sitemap_capture_segments(segment_mappings = {}, segments = [])
values = {}
# do nothing if there are no segments to work on
if segments.kind_of?(Array)
# first, look for mappings
unless segment_mappings.blank?
segments.each do |key|
attribute_name = segment_mappings[key.to_sym].blank? ? key : segment_mappings[key.to_sym]
if self.respond_to?(attribute_name)
values[key] = self.send(attribute_name)
end
end
end
# second, look for attributes that have not already been found.
segments.each do |key|
unless values.has_key?(key)
if self.respond_to?(key)
values[key] = self.send(key)
end
end
end
end
return values
end | ruby | def sitemap_capture_segments(segment_mappings = {}, segments = [])
values = {}
# do nothing if there are no segments to work on
if segments.kind_of?(Array)
# first, look for mappings
unless segment_mappings.blank?
segments.each do |key|
attribute_name = segment_mappings[key.to_sym].blank? ? key : segment_mappings[key.to_sym]
if self.respond_to?(attribute_name)
values[key] = self.send(attribute_name)
end
end
end
# second, look for attributes that have not already been found.
segments.each do |key|
unless values.has_key?(key)
if self.respond_to?(key)
values[key] = self.send(key)
end
end
end
end
return values
end | [
"def",
"sitemap_capture_segments",
"(",
"segment_mappings",
"=",
"{",
"}",
",",
"segments",
"=",
"[",
"]",
")",
"values",
"=",
"{",
"}",
"if",
"segments",
".",
"kind_of?",
"(",
"Array",
")",
"unless",
"segment_mappings",
".",
"blank?",
"segments",
".",
"each",
"do",
"|",
"key",
"|",
"attribute_name",
"=",
"segment_mappings",
"[",
"key",
".",
"to_sym",
"]",
".",
"blank?",
"?",
"key",
":",
"segment_mappings",
"[",
"key",
".",
"to_sym",
"]",
"if",
"self",
".",
"respond_to?",
"(",
"attribute_name",
")",
"values",
"[",
"key",
"]",
"=",
"self",
".",
"send",
"(",
"attribute_name",
")",
"end",
"end",
"end",
"segments",
".",
"each",
"do",
"|",
"key",
"|",
"unless",
"values",
".",
"has_key?",
"(",
"key",
")",
"if",
"self",
".",
"respond_to?",
"(",
"key",
")",
"values",
"[",
"key",
"]",
"=",
"self",
".",
"send",
"(",
"key",
")",
"end",
"end",
"end",
"end",
"return",
"values",
"end"
] | Segment keys are placeholders for the values that are plugged into a named route when it is constructed.
The following Rails route has a two segment keys: :id and :format.
book GET /books/:id(.:format) books#show
:id is the row.id of a Book and :format is the extension to be used when constructing a path or url.
book_path(1) #=> /book/1
book_path(1, "html") #=> /book/1.html
book_path(id: 1, format: "html") #=> /book/1.html
book_path(id: 2, format: "xml") #=> /book/2.xml
sitemap_capture_segments attempts to populate a Hash with values associated with the required segment keys.
row = Book.create(title: "Duck is a self-proclaimed resident moron...")
puts row.id #=> 1
row.sitemap_capture_segments(nil, [:id]) #=> {:id => 1}
You have the ability to map attributes of an object to segment keys. This could be useful for routes
that do not follow standard convention or cases where you have some deeply nested resources.
class BooksController < ApplicationController
sitemap_segments :show, id: :my_id
end
class Book < ActiveRecord::Base
attr_accessible :my_id, :author, :title
before_save :generate_my_id
def generate_my_id
# do some magic
self.my_id = 2
end
end
row = Book.create(title: "Please ignore the first title :)")
puts row.id #=> 1
puts row.my_id #=> 2
# normally, you would get the attributes via:
# controller.sitemap_attributes("show")[:segments]
attributes = {id: :my_id}
row.sitemap_capture_segments(attributes, [:id]) #=> {:id => 2}
Segment values are obtained in two stages.
- Stage one asks the current object (controller or model) for attributes from segment_mappings and
places those key/values in the returning hash.
- Stage two asks the current object (controller or model) for attributes from segments array
that have not already been found via segment_mappings and places those key/values in the returning hash.
@param [Hash] segment_mappings A Hash containing one-to-one attribute mappings for segment keys to object attributes.
@param [Array] segments The segments Array of a Rails Route.
return [Hash] | [
"Segment",
"keys",
"are",
"placeholders",
"for",
"the",
"values",
"that",
"are",
"plugged",
"into",
"a",
"named",
"route",
"when",
"it",
"is",
"constructed",
"."
] | c510acfa95e8ad4afb1501366058ae88a73704df | https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/sitemap_object.rb#L424-L457 | train |
OpenBEL/bel_parser | lib/bel_parser/ast_generator.rb | BELParser.ASTGenerator.each | def each # rubocop:disable MethodLength
if block_given?
line_number = 1
expanded_line = nil
map_lines(@io.each_line.lazy).each do |line|
if line.end_with?(LINE_CONTINUATOR)
expanded_line = "#{expanded_line}#{line.chomp(LINE_CONTINUATOR)}"
else
expanded_line = "#{expanded_line}#{line}"
ast_results = []
PARSERS.map do |parser|
parser.parse(expanded_line) { |ast| ast_results << ast }
end
yield [line_number, expanded_line, ast_results]
line_number += 1
expanded_line = nil
end
end
else
enum_for(:each)
end
end | ruby | def each # rubocop:disable MethodLength
if block_given?
line_number = 1
expanded_line = nil
map_lines(@io.each_line.lazy).each do |line|
if line.end_with?(LINE_CONTINUATOR)
expanded_line = "#{expanded_line}#{line.chomp(LINE_CONTINUATOR)}"
else
expanded_line = "#{expanded_line}#{line}"
ast_results = []
PARSERS.map do |parser|
parser.parse(expanded_line) { |ast| ast_results << ast }
end
yield [line_number, expanded_line, ast_results]
line_number += 1
expanded_line = nil
end
end
else
enum_for(:each)
end
end | [
"def",
"each",
"if",
"block_given?",
"line_number",
"=",
"1",
"expanded_line",
"=",
"nil",
"map_lines",
"(",
"@io",
".",
"each_line",
".",
"lazy",
")",
".",
"each",
"do",
"|",
"line",
"|",
"if",
"line",
".",
"end_with?",
"(",
"LINE_CONTINUATOR",
")",
"expanded_line",
"=",
"\"#{expanded_line}#{line.chomp(LINE_CONTINUATOR)}\"",
"else",
"expanded_line",
"=",
"\"#{expanded_line}#{line}\"",
"ast_results",
"=",
"[",
"]",
"PARSERS",
".",
"map",
"do",
"|",
"parser",
"|",
"parser",
".",
"parse",
"(",
"expanded_line",
")",
"{",
"|",
"ast",
"|",
"ast_results",
"<<",
"ast",
"}",
"end",
"yield",
"[",
"line_number",
",",
"expanded_line",
",",
"ast_results",
"]",
"line_number",
"+=",
"1",
"expanded_line",
"=",
"nil",
"end",
"end",
"else",
"enum_for",
"(",
":each",
")",
"end",
"end"
] | Yields AST results for each line of the IO.
@example Receive AST results in given block.
# doctest setup require 'bel_parser' self.class.include AST::Sexp
# example usage line_io = StringIO.new("\"AKT1\"\n") line =
nil ast_res = nil ::BELParser::ASTGenerator.new.each(line_io)
{ |(line_number, line, results)|
# do something
}
@example Receive AST results as an enumerator.
# doctest setup require 'bel_parser' self.class.include AST::Sexp
# example usage line_io = StringIO.new("\"AKT1\"\n") line,
ast_res = ::BELParser::ASTGenerator.new.each(line_io).first.to_a
@param [IO] io the IO-object to read each line from @yield
[[Integer, String, Array<AST::Node>]] yields line number, line,
and AST results as an {Array}
@return [IO, #<Enumerator: #<BELParser::ASTGenerator#each>] the {IO}
object is returned if a block is given, otherwise an
{Enumerator} object is returned that can be iterated with
{Enumerator#each} | [
"Yields",
"AST",
"results",
"for",
"each",
"line",
"of",
"the",
"IO",
"."
] | f0a35de93c300abff76c22e54696a83d22a4fbc9 | https://github.com/OpenBEL/bel_parser/blob/f0a35de93c300abff76c22e54696a83d22a4fbc9/lib/bel_parser/ast_generator.rb#L48-L72 | train |
pwnall/ether_ping | lib/ether_ping/client.rb | EtherPing.Client.ping | def ping(data, timeout = 1)
if data.kind_of? Numeric
data = "\0" * data
end
# Pad data to have at least 64 bytes.
data += "\0" * (64 - data.length) if data.length < 64
ping_packet = [@dest_mac, @source_mac, @ether_type, data].join
response = nil
receive_ts = nil
send_ts = nil
begin
Timeout.timeout timeout do
send_ts = Time.now
@socket.send ping_packet, 0
response = @socket.recv ping_packet.length * 2
receive_ts = Time.now
end
rescue Timeout::Error
response = nil
end
return false unless response
response_packet = [@source_mac, @dest_mac, @ether_type, data].join
response == response_packet ? receive_ts - send_ts :
[response, response_packet]
end | ruby | def ping(data, timeout = 1)
if data.kind_of? Numeric
data = "\0" * data
end
# Pad data to have at least 64 bytes.
data += "\0" * (64 - data.length) if data.length < 64
ping_packet = [@dest_mac, @source_mac, @ether_type, data].join
response = nil
receive_ts = nil
send_ts = nil
begin
Timeout.timeout timeout do
send_ts = Time.now
@socket.send ping_packet, 0
response = @socket.recv ping_packet.length * 2
receive_ts = Time.now
end
rescue Timeout::Error
response = nil
end
return false unless response
response_packet = [@source_mac, @dest_mac, @ether_type, data].join
response == response_packet ? receive_ts - send_ts :
[response, response_packet]
end | [
"def",
"ping",
"(",
"data",
",",
"timeout",
"=",
"1",
")",
"if",
"data",
".",
"kind_of?",
"Numeric",
"data",
"=",
"\"\\0\"",
"*",
"data",
"end",
"data",
"+=",
"\"\\0\"",
"*",
"(",
"64",
"-",
"data",
".",
"length",
")",
"if",
"data",
".",
"length",
"<",
"64",
"ping_packet",
"=",
"[",
"@dest_mac",
",",
"@source_mac",
",",
"@ether_type",
",",
"data",
"]",
".",
"join",
"response",
"=",
"nil",
"receive_ts",
"=",
"nil",
"send_ts",
"=",
"nil",
"begin",
"Timeout",
".",
"timeout",
"timeout",
"do",
"send_ts",
"=",
"Time",
".",
"now",
"@socket",
".",
"send",
"ping_packet",
",",
"0",
"response",
"=",
"@socket",
".",
"recv",
"ping_packet",
".",
"length",
"*",
"2",
"receive_ts",
"=",
"Time",
".",
"now",
"end",
"rescue",
"Timeout",
"::",
"Error",
"response",
"=",
"nil",
"end",
"return",
"false",
"unless",
"response",
"response_packet",
"=",
"[",
"@source_mac",
",",
"@dest_mac",
",",
"@ether_type",
",",
"data",
"]",
".",
"join",
"response",
"==",
"response_packet",
"?",
"receive_ts",
"-",
"send_ts",
":",
"[",
"response",
",",
"response_packet",
"]",
"end"
] | Pings over raw Ethernet sockets.
Returns a Number representing the ping latency (in seconds) if the ping
response matches, an array of [expected, received] strings if it doesn't
match, and false if the ping times out. | [
"Pings",
"over",
"raw",
"Ethernet",
"sockets",
"."
] | 3f61b40963adc74188ff9dbf7722850dadb32365 | https://github.com/pwnall/ether_ping/blob/3f61b40963adc74188ff9dbf7722850dadb32365/lib/ether_ping/client.rb#L24-L51 | train |
kch/dominion | lib/dominion/domain_suffix_rule.rb | Dominion.DomainSuffixRule.=~ | def =~(domain)
labels.zip(domain.labels).all? { |r, d| ["*", d].include? r }
end | ruby | def =~(domain)
labels.zip(domain.labels).all? { |r, d| ["*", d].include? r }
end | [
"def",
"=~",
"(",
"domain",
")",
"labels",
".",
"zip",
"(",
"domain",
".",
"labels",
")",
".",
"all?",
"{",
"|",
"r",
",",
"d",
"|",
"[",
"\"*\"",
",",
"d",
"]",
".",
"include?",
"r",
"}",
"end"
] | match against a domain name. the domain must be an instance of DomainName | [
"match",
"against",
"a",
"domain",
"name",
".",
"the",
"domain",
"must",
"be",
"an",
"instance",
"of",
"DomainName"
] | ecdd6ff6edcf1c4658fa4e4736de32854ea492dd | https://github.com/kch/dominion/blob/ecdd6ff6edcf1c4658fa4e4736de32854ea492dd/lib/dominion/domain_suffix_rule.rb#L16-L18 | train |
jimeh/time_ext | lib/time_ext/iterations.rb | TimeExt.Iterations.each | def each(unit, options = {}, &block)
iterate(unit, options.merge(:map_result => false), &block)
end | ruby | def each(unit, options = {}, &block)
iterate(unit, options.merge(:map_result => false), &block)
end | [
"def",
"each",
"(",
"unit",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"iterate",
"(",
"unit",
",",
"options",
".",
"merge",
"(",
":map_result",
"=>",
"false",
")",
",",
"&",
"block",
")",
"end"
] | Executes passed block for each "unit" of time specified, with a new time object for each interval passed to the block. | [
"Executes",
"passed",
"block",
"for",
"each",
"unit",
"of",
"time",
"specified",
"with",
"a",
"new",
"time",
"object",
"for",
"each",
"interval",
"passed",
"to",
"the",
"block",
"."
] | 53fed4fb33c4fe5948cbc609eaf2319a9b05b1db | https://github.com/jimeh/time_ext/blob/53fed4fb33c4fe5948cbc609eaf2319a9b05b1db/lib/time_ext/iterations.rb#L65-L67 | train |
jimeh/time_ext | lib/time_ext/iterations.rb | TimeExt.Iterations.beginning_of_each | def beginning_of_each(unit, options = {}, &block)
iterate(unit, options.merge(:map_result => false, :beginning_of => true), &block)
end | ruby | def beginning_of_each(unit, options = {}, &block)
iterate(unit, options.merge(:map_result => false, :beginning_of => true), &block)
end | [
"def",
"beginning_of_each",
"(",
"unit",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"iterate",
"(",
"unit",
",",
"options",
".",
"merge",
"(",
":map_result",
"=>",
"false",
",",
":beginning_of",
"=>",
"true",
")",
",",
"&",
"block",
")",
"end"
] | Executes passed block for each "unit" of time specified, with a new time object set to the beginning of "unit" for each interval passed to the block. | [
"Executes",
"passed",
"block",
"for",
"each",
"unit",
"of",
"time",
"specified",
"with",
"a",
"new",
"time",
"object",
"set",
"to",
"the",
"beginning",
"of",
"unit",
"for",
"each",
"interval",
"passed",
"to",
"the",
"block",
"."
] | 53fed4fb33c4fe5948cbc609eaf2319a9b05b1db | https://github.com/jimeh/time_ext/blob/53fed4fb33c4fe5948cbc609eaf2319a9b05b1db/lib/time_ext/iterations.rb#L70-L72 | train |
jimeh/time_ext | lib/time_ext/iterations.rb | TimeExt.Iterations.map_each | def map_each(unit, options = {}, &block)
iterate(unit, options.merge(:map_result => true), &block)
end | ruby | def map_each(unit, options = {}, &block)
iterate(unit, options.merge(:map_result => true), &block)
end | [
"def",
"map_each",
"(",
"unit",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"iterate",
"(",
"unit",
",",
"options",
".",
"merge",
"(",
":map_result",
"=>",
"true",
")",
",",
"&",
"block",
")",
"end"
] | Executes passed block for each "unit" of time specified, returning an array with the return values from the passed block. | [
"Executes",
"passed",
"block",
"for",
"each",
"unit",
"of",
"time",
"specified",
"returning",
"an",
"array",
"with",
"the",
"return",
"values",
"from",
"the",
"passed",
"block",
"."
] | 53fed4fb33c4fe5948cbc609eaf2319a9b05b1db | https://github.com/jimeh/time_ext/blob/53fed4fb33c4fe5948cbc609eaf2319a9b05b1db/lib/time_ext/iterations.rb#L75-L77 | train |
jimeh/time_ext | lib/time_ext/iterations.rb | TimeExt.Iterations.map_beginning_of_each | def map_beginning_of_each(unit, options = {}, &block)
iterate(unit, options.merge(:map_result => true, :beginning_of => true), &block)
end | ruby | def map_beginning_of_each(unit, options = {}, &block)
iterate(unit, options.merge(:map_result => true, :beginning_of => true), &block)
end | [
"def",
"map_beginning_of_each",
"(",
"unit",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"iterate",
"(",
"unit",
",",
"options",
".",
"merge",
"(",
":map_result",
"=>",
"true",
",",
":beginning_of",
"=>",
"true",
")",
",",
"&",
"block",
")",
"end"
] | Executes passed block for each "unit" of time specified, returning an array with the return values from passed block. Additionally the time object passed into the block is set to the beginning of specified "unit". | [
"Executes",
"passed",
"block",
"for",
"each",
"unit",
"of",
"time",
"specified",
"returning",
"an",
"array",
"with",
"the",
"return",
"values",
"from",
"passed",
"block",
".",
"Additionally",
"the",
"time",
"object",
"passed",
"into",
"the",
"block",
"is",
"set",
"to",
"the",
"beginning",
"of",
"specified",
"unit",
"."
] | 53fed4fb33c4fe5948cbc609eaf2319a9b05b1db | https://github.com/jimeh/time_ext/blob/53fed4fb33c4fe5948cbc609eaf2319a9b05b1db/lib/time_ext/iterations.rb#L80-L82 | train |
Burgestrand/mellon | lib/mellon/utils.rb | Mellon.Utils.build_info | def build_info(key, options = {})
options = DEFAULT_OPTIONS.merge(options)
note_type = TYPES.fetch(options.fetch(:type, :note).to_s)
account_name = options.fetch(:account_name, "")
service_name = options.fetch(:service_name, key)
label = options.fetch(:label, service_name)
{
account_name: account_name,
service_name: service_name,
label: label,
kind: note_type.fetch(:kind),
type: note_type.fetch(:type),
}
end | ruby | def build_info(key, options = {})
options = DEFAULT_OPTIONS.merge(options)
note_type = TYPES.fetch(options.fetch(:type, :note).to_s)
account_name = options.fetch(:account_name, "")
service_name = options.fetch(:service_name, key)
label = options.fetch(:label, service_name)
{
account_name: account_name,
service_name: service_name,
label: label,
kind: note_type.fetch(:kind),
type: note_type.fetch(:type),
}
end | [
"def",
"build_info",
"(",
"key",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"DEFAULT_OPTIONS",
".",
"merge",
"(",
"options",
")",
"note_type",
"=",
"TYPES",
".",
"fetch",
"(",
"options",
".",
"fetch",
"(",
":type",
",",
":note",
")",
".",
"to_s",
")",
"account_name",
"=",
"options",
".",
"fetch",
"(",
":account_name",
",",
"\"\"",
")",
"service_name",
"=",
"options",
".",
"fetch",
"(",
":service_name",
",",
"key",
")",
"label",
"=",
"options",
".",
"fetch",
"(",
":label",
",",
"service_name",
")",
"{",
"account_name",
":",
"account_name",
",",
"service_name",
":",
"service_name",
",",
"label",
":",
"label",
",",
"kind",
":",
"note_type",
".",
"fetch",
"(",
":kind",
")",
",",
"type",
":",
"note_type",
".",
"fetch",
"(",
":type",
")",
",",
"}",
"end"
] | Build an entry info hash.
@param [String] key
@param [Hash] options
@return [Hash] | [
"Build",
"an",
"entry",
"info",
"hash",
"."
] | 4ded7e28fee192a777605e5f9dcd3b1bd05770ef | https://github.com/Burgestrand/mellon/blob/4ded7e28fee192a777605e5f9dcd3b1bd05770ef/lib/mellon/utils.rb#L14-L29 | train |
Burgestrand/mellon | lib/mellon/utils.rb | Mellon.Utils.parse_contents | def parse_contents(password_string)
unpacked = password_string[/password: 0x([a-f0-9]+)/i, 1]
password = if unpacked
[unpacked].pack("H*")
else
password_string[/password: "(.+)"/m, 1]
end
password ||= ""
parsed = Plist.parse_xml(password.force_encoding("".encoding))
if parsed and parsed["NOTE"]
parsed["NOTE"]
else
password
end
end | ruby | def parse_contents(password_string)
unpacked = password_string[/password: 0x([a-f0-9]+)/i, 1]
password = if unpacked
[unpacked].pack("H*")
else
password_string[/password: "(.+)"/m, 1]
end
password ||= ""
parsed = Plist.parse_xml(password.force_encoding("".encoding))
if parsed and parsed["NOTE"]
parsed["NOTE"]
else
password
end
end | [
"def",
"parse_contents",
"(",
"password_string",
")",
"unpacked",
"=",
"password_string",
"[",
"/",
"/i",
",",
"1",
"]",
"password",
"=",
"if",
"unpacked",
"[",
"unpacked",
"]",
".",
"pack",
"(",
"\"H*\"",
")",
"else",
"password_string",
"[",
"/",
"/m",
",",
"1",
"]",
"end",
"password",
"||=",
"\"\"",
"parsed",
"=",
"Plist",
".",
"parse_xml",
"(",
"password",
".",
"force_encoding",
"(",
"\"\"",
".",
"encoding",
")",
")",
"if",
"parsed",
"and",
"parsed",
"[",
"\"NOTE\"",
"]",
"parsed",
"[",
"\"NOTE\"",
"]",
"else",
"password",
"end",
"end"
] | Parse entry contents.
@param [String]
@return [String] | [
"Parse",
"entry",
"contents",
"."
] | 4ded7e28fee192a777605e5f9dcd3b1bd05770ef | https://github.com/Burgestrand/mellon/blob/4ded7e28fee192a777605e5f9dcd3b1bd05770ef/lib/mellon/utils.rb#L77-L94 | train |
melborne/maliq | lib/maliq/file_utils.rb | Maliq.FileUtils.split | def split(path, marker=nil)
marker ||= SPLIT_MARKER
content = File.read(path)
filename = File.basename(path, '.*')
yfm, content = retrieveYFM(content)
contents = [filename] + content.split(marker)
prev_name = filename
contents.each_slice(2).with({}) do |(fname, text), h|
fname = prev_name = create_filename(prev_name) if fname.strip.empty?
h[fname.strip] = yfm + text
end
end | ruby | def split(path, marker=nil)
marker ||= SPLIT_MARKER
content = File.read(path)
filename = File.basename(path, '.*')
yfm, content = retrieveYFM(content)
contents = [filename] + content.split(marker)
prev_name = filename
contents.each_slice(2).with({}) do |(fname, text), h|
fname = prev_name = create_filename(prev_name) if fname.strip.empty?
h[fname.strip] = yfm + text
end
end | [
"def",
"split",
"(",
"path",
",",
"marker",
"=",
"nil",
")",
"marker",
"||=",
"SPLIT_MARKER",
"content",
"=",
"File",
".",
"read",
"(",
"path",
")",
"filename",
"=",
"File",
".",
"basename",
"(",
"path",
",",
"'.*'",
")",
"yfm",
",",
"content",
"=",
"retrieveYFM",
"(",
"content",
")",
"contents",
"=",
"[",
"filename",
"]",
"+",
"content",
".",
"split",
"(",
"marker",
")",
"prev_name",
"=",
"filename",
"contents",
".",
"each_slice",
"(",
"2",
")",
".",
"with",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"fname",
",",
"text",
")",
",",
"h",
"|",
"fname",
"=",
"prev_name",
"=",
"create_filename",
"(",
"prev_name",
")",
"if",
"fname",
".",
"strip",
".",
"empty?",
"h",
"[",
"fname",
".",
"strip",
"]",
"=",
"yfm",
"+",
"text",
"end",
"end"
] | Split a file with SPLIT_MARKER.
Returns a Hash of filename key with its content. | [
"Split",
"a",
"file",
"with",
"SPLIT_MARKER",
".",
"Returns",
"a",
"Hash",
"of",
"filename",
"key",
"with",
"its",
"content",
"."
] | c53f020f5a71e60fcb6df60cef981691cb92428f | https://github.com/melborne/maliq/blob/c53f020f5a71e60fcb6df60cef981691cb92428f/lib/maliq/file_utils.rb#L20-L31 | train |
bilus/akasha | lib/akasha/aggregate.rb | Akasha.Aggregate.apply_events | def apply_events(events)
events.each do |event|
method_name = event_handler(event)
public_send(method_name, event.data) if respond_to?(method_name)
end
@revision = events.last&.revision.to_i if events.last.respond_to?(:revision)
end | ruby | def apply_events(events)
events.each do |event|
method_name = event_handler(event)
public_send(method_name, event.data) if respond_to?(method_name)
end
@revision = events.last&.revision.to_i if events.last.respond_to?(:revision)
end | [
"def",
"apply_events",
"(",
"events",
")",
"events",
".",
"each",
"do",
"|",
"event",
"|",
"method_name",
"=",
"event_handler",
"(",
"event",
")",
"public_send",
"(",
"method_name",
",",
"event",
".",
"data",
")",
"if",
"respond_to?",
"(",
"method_name",
")",
"end",
"@revision",
"=",
"events",
".",
"last",
"&.",
"revision",
".",
"to_i",
"if",
"events",
".",
"last",
".",
"respond_to?",
"(",
":revision",
")",
"end"
] | Replay events, building up the state of the aggregate.
Used by Repository. | [
"Replay",
"events",
"building",
"up",
"the",
"state",
"of",
"the",
"aggregate",
".",
"Used",
"by",
"Repository",
"."
] | 5fadefc249f520ae909b762956ac23a6f916b021 | https://github.com/bilus/akasha/blob/5fadefc249f520ae909b762956ac23a6f916b021/lib/akasha/aggregate.rb#L32-L38 | train |
dalehamel/ruby-pandoc | lib/ruby-pandoc/dependencies.rb | RubyPandoc.Dependencies.get_pandoc | def get_pandoc
return if has_pandoc
Dir.mktmpdir do |dir|
Dir.chdir(dir) do
system("wget #{PANDOC_URL} -O pandoc.deb")
system("sudo dpkg -i pandoc.deb")
end
end
end | ruby | def get_pandoc
return if has_pandoc
Dir.mktmpdir do |dir|
Dir.chdir(dir) do
system("wget #{PANDOC_URL} -O pandoc.deb")
system("sudo dpkg -i pandoc.deb")
end
end
end | [
"def",
"get_pandoc",
"return",
"if",
"has_pandoc",
"Dir",
".",
"mktmpdir",
"do",
"|",
"dir",
"|",
"Dir",
".",
"chdir",
"(",
"dir",
")",
"do",
"system",
"(",
"\"wget #{PANDOC_URL} -O pandoc.deb\"",
")",
"system",
"(",
"\"sudo dpkg -i pandoc.deb\"",
")",
"end",
"end",
"end"
] | FIXME make this conditional to different types of platforms | [
"FIXME",
"make",
"this",
"conditional",
"to",
"different",
"types",
"of",
"platforms"
] | 43a4081c137bc9b7308651dd616e571b63b5ad6a | https://github.com/dalehamel/ruby-pandoc/blob/43a4081c137bc9b7308651dd616e571b63b5ad6a/lib/ruby-pandoc/dependencies.rb#L46-L54 | train |
olarivain/xcodebuilder | lib/xcode_builder.rb | XcodeBuilder.XcodeBuilder.build | def build
clean unless @configuration.skip_clean
# update the long version number with the date
@configuration.timestamp_plist if @configuration.timestamp_build
print "Building Project..."
success = xcodebuild @configuration.build_arguments, "build"
raise "** BUILD FAILED **" unless success
puts "Done"
end | ruby | def build
clean unless @configuration.skip_clean
# update the long version number with the date
@configuration.timestamp_plist if @configuration.timestamp_build
print "Building Project..."
success = xcodebuild @configuration.build_arguments, "build"
raise "** BUILD FAILED **" unless success
puts "Done"
end | [
"def",
"build",
"clean",
"unless",
"@configuration",
".",
"skip_clean",
"@configuration",
".",
"timestamp_plist",
"if",
"@configuration",
".",
"timestamp_build",
"print",
"\"Building Project...\"",
"success",
"=",
"xcodebuild",
"@configuration",
".",
"build_arguments",
",",
"\"build\"",
"raise",
"\"** BUILD FAILED **\"",
"unless",
"success",
"puts",
"\"Done\"",
"end"
] | desc "Build the beta release of the app" | [
"desc",
"Build",
"the",
"beta",
"release",
"of",
"the",
"app"
] | d6b1b7d589261dfd066e77906999ae7bf841d99f | https://github.com/olarivain/xcodebuilder/blob/d6b1b7d589261dfd066e77906999ae7bf841d99f/lib/xcode_builder.rb#L69-L79 | train |
olarivain/xcodebuilder | lib/xcode_builder.rb | XcodeBuilder.XcodeBuilder.pod_dry_run | def pod_dry_run
print "Pod dry run..."
repos = resolved_repos.join ","
result = system "pod lib lint #{@configuration.podspec_file} --allow-warnings --sources=#{repos}"
raise "** Pod dry run failed **" if !result
puts "Done"
end | ruby | def pod_dry_run
print "Pod dry run..."
repos = resolved_repos.join ","
result = system "pod lib lint #{@configuration.podspec_file} --allow-warnings --sources=#{repos}"
raise "** Pod dry run failed **" if !result
puts "Done"
end | [
"def",
"pod_dry_run",
"print",
"\"Pod dry run...\"",
"repos",
"=",
"resolved_repos",
".",
"join",
"\",\"",
"result",
"=",
"system",
"\"pod lib lint #{@configuration.podspec_file} --allow-warnings --sources=#{repos}\"",
"raise",
"\"** Pod dry run failed **\"",
"if",
"!",
"result",
"puts",
"\"Done\"",
"end"
] | runs a pod dry run before tagging | [
"runs",
"a",
"pod",
"dry",
"run",
"before",
"tagging"
] | d6b1b7d589261dfd066e77906999ae7bf841d99f | https://github.com/olarivain/xcodebuilder/blob/d6b1b7d589261dfd066e77906999ae7bf841d99f/lib/xcode_builder.rb#L199-L205 | train |
nextmat/hetchy | lib/hetchy/dataset.rb | Hetchy.Dataset.percentile | def percentile(perc)
if perc > 100.0 || perc < 0.0
raise InvalidPercentile, "percentile must be between 0.0 and 100.0"
end
return 0.0 if data.empty?
rank = (perc / 100.0) * (size + 1)
return data[0] if rank < 1
return data[-1] if rank > size
return data[rank - 1] if rank == Integer(rank)
weighted_average_for(rank)
end | ruby | def percentile(perc)
if perc > 100.0 || perc < 0.0
raise InvalidPercentile, "percentile must be between 0.0 and 100.0"
end
return 0.0 if data.empty?
rank = (perc / 100.0) * (size + 1)
return data[0] if rank < 1
return data[-1] if rank > size
return data[rank - 1] if rank == Integer(rank)
weighted_average_for(rank)
end | [
"def",
"percentile",
"(",
"perc",
")",
"if",
"perc",
">",
"100.0",
"||",
"perc",
"<",
"0.0",
"raise",
"InvalidPercentile",
",",
"\"percentile must be between 0.0 and 100.0\"",
"end",
"return",
"0.0",
"if",
"data",
".",
"empty?",
"rank",
"=",
"(",
"perc",
"/",
"100.0",
")",
"*",
"(",
"size",
"+",
"1",
")",
"return",
"data",
"[",
"0",
"]",
"if",
"rank",
"<",
"1",
"return",
"data",
"[",
"-",
"1",
"]",
"if",
"rank",
">",
"size",
"return",
"data",
"[",
"rank",
"-",
"1",
"]",
"if",
"rank",
"==",
"Integer",
"(",
"rank",
")",
"weighted_average_for",
"(",
"rank",
")",
"end"
] | Generate a percentile for the data set.
@example
snapshot.percentile(95)
snapshot.percentile(99.9) | [
"Generate",
"a",
"percentile",
"for",
"the",
"data",
"set",
"."
] | a06c0127351b5a94d71c8d9a8b7ed9c14bddf96f | https://github.com/nextmat/hetchy/blob/a06c0127351b5a94d71c8d9a8b7ed9c14bddf96f/lib/hetchy/dataset.rb#L26-L38 | train |
nextmat/hetchy | lib/hetchy/dataset.rb | Hetchy.Dataset.weighted_average_for | def weighted_average_for(rank)
above = data[rank.to_i]
below = data[rank.to_i - 1]
fractional = rank - rank.floor
below + ((above - below) * fractional)
end | ruby | def weighted_average_for(rank)
above = data[rank.to_i]
below = data[rank.to_i - 1]
fractional = rank - rank.floor
below + ((above - below) * fractional)
end | [
"def",
"weighted_average_for",
"(",
"rank",
")",
"above",
"=",
"data",
"[",
"rank",
".",
"to_i",
"]",
"below",
"=",
"data",
"[",
"rank",
".",
"to_i",
"-",
"1",
"]",
"fractional",
"=",
"rank",
"-",
"rank",
".",
"floor",
"below",
"+",
"(",
"(",
"above",
"-",
"below",
")",
"*",
"fractional",
")",
"end"
] | when rank lands between values, generated a weighted average
of adjacent values | [
"when",
"rank",
"lands",
"between",
"values",
"generated",
"a",
"weighted",
"average",
"of",
"adjacent",
"values"
] | a06c0127351b5a94d71c8d9a8b7ed9c14bddf96f | https://github.com/nextmat/hetchy/blob/a06c0127351b5a94d71c8d9a8b7ed9c14bddf96f/lib/hetchy/dataset.rb#L44-L49 | train |
mikiobraun/jblas-ruby | lib/jblas/mixin_convert.rb | JBLAS.MatrixConvertMixin.to_s | def to_s(fmt=nil, coljoin=', ', rowjoin='; ')
if fmt
x = rows_to_a
'[' + x.map do |r|
if Enumerable === r
r.map {|e| sprintf(fmt, e)}.join(coljoin)
else
sprintf(fmt, r)
end
end.join(rowjoin) + ']'
else
toString
end
end | ruby | def to_s(fmt=nil, coljoin=', ', rowjoin='; ')
if fmt
x = rows_to_a
'[' + x.map do |r|
if Enumerable === r
r.map {|e| sprintf(fmt, e)}.join(coljoin)
else
sprintf(fmt, r)
end
end.join(rowjoin) + ']'
else
toString
end
end | [
"def",
"to_s",
"(",
"fmt",
"=",
"nil",
",",
"coljoin",
"=",
"', '",
",",
"rowjoin",
"=",
"'; '",
")",
"if",
"fmt",
"x",
"=",
"rows_to_a",
"'['",
"+",
"x",
".",
"map",
"do",
"|",
"r",
"|",
"if",
"Enumerable",
"===",
"r",
"r",
".",
"map",
"{",
"|",
"e",
"|",
"sprintf",
"(",
"fmt",
",",
"e",
")",
"}",
".",
"join",
"(",
"coljoin",
")",
"else",
"sprintf",
"(",
"fmt",
",",
"r",
")",
"end",
"end",
".",
"join",
"(",
"rowjoin",
")",
"+",
"']'",
"else",
"toString",
"end",
"end"
] | Convert this matrix to a string.
This methods takes a few extra arguments to control how the result looks
like.
+fmt+ is a format as used by sprintf, +coljoin+ is the string used to
join column, +rowjoin+ is what is used to join rows. For example,
x.to_s('%.1f', ' ', "\n")
Returns a matrix where columns are separated by spaces, rows by newlines
and each element is shown with one digit after the comma. | [
"Convert",
"this",
"matrix",
"to",
"a",
"string",
"."
] | 7233976c9e3b210e30bc36ead2b1e05ab3383fec | https://github.com/mikiobraun/jblas-ruby/blob/7233976c9e3b210e30bc36ead2b1e05ab3383fec/lib/jblas/mixin_convert.rb#L52-L65 | train |
dimakura/cra.ge | lib/cra/services.rb | CRA.Services.by_name_and_dob | def by_name_and_dob(lname, fname, year, month, day)
body = self.gov_talk_request({
service: 'GetDataUsingCriteriaParameter',
message: 'CRAGetDataUsingCriteria',
class: 'CRAGetDataUsingCriteria',
params: {
LastName: lname,
FirstName: fname,
Year: year,
Month: month,
Day: day,
}
})
CRA::PassportInfo.list_with_hash(body)
end | ruby | def by_name_and_dob(lname, fname, year, month, day)
body = self.gov_talk_request({
service: 'GetDataUsingCriteriaParameter',
message: 'CRAGetDataUsingCriteria',
class: 'CRAGetDataUsingCriteria',
params: {
LastName: lname,
FirstName: fname,
Year: year,
Month: month,
Day: day,
}
})
CRA::PassportInfo.list_with_hash(body)
end | [
"def",
"by_name_and_dob",
"(",
"lname",
",",
"fname",
",",
"year",
",",
"month",
",",
"day",
")",
"body",
"=",
"self",
".",
"gov_talk_request",
"(",
"{",
"service",
":",
"'GetDataUsingCriteriaParameter'",
",",
"message",
":",
"'CRAGetDataUsingCriteria'",
",",
"class",
":",
"'CRAGetDataUsingCriteria'",
",",
"params",
":",
"{",
"LastName",
":",
"lname",
",",
"FirstName",
":",
"fname",
",",
"Year",
":",
"year",
",",
"Month",
":",
"month",
",",
"Day",
":",
"day",
",",
"}",
"}",
")",
"CRA",
"::",
"PassportInfo",
".",
"list_with_hash",
"(",
"body",
")",
"end"
] | Returns array of passports. | [
"Returns",
"array",
"of",
"passports",
"."
] | 13a9c40b27cdad93ae9892eb25aaee2deae4f541 | https://github.com/dimakura/cra.ge/blob/13a9c40b27cdad93ae9892eb25aaee2deae4f541/lib/cra/services.rb#L17-L31 | train |
dimakura/cra.ge | lib/cra/services.rb | CRA.Services.by_id_card | def by_id_card(private_number, id_card_serial, id_card_numb)
body = self.gov_talk_request({
service: 'GetDataUsingPrivateNumberAndIdCardParameter',
message: 'GetDataUsingPrivateNumberAndCard',
class: 'GetDataUsingPrivateNumberAndCard',
params: {
PrivateNumber: private_number,
IdCardSerial: id_card_serial,
IdCardNumber: id_card_numb,
}
})
CRA::PassportInfo.init_with_hash(body)
end | ruby | def by_id_card(private_number, id_card_serial, id_card_numb)
body = self.gov_talk_request({
service: 'GetDataUsingPrivateNumberAndIdCardParameter',
message: 'GetDataUsingPrivateNumberAndCard',
class: 'GetDataUsingPrivateNumberAndCard',
params: {
PrivateNumber: private_number,
IdCardSerial: id_card_serial,
IdCardNumber: id_card_numb,
}
})
CRA::PassportInfo.init_with_hash(body)
end | [
"def",
"by_id_card",
"(",
"private_number",
",",
"id_card_serial",
",",
"id_card_numb",
")",
"body",
"=",
"self",
".",
"gov_talk_request",
"(",
"{",
"service",
":",
"'GetDataUsingPrivateNumberAndIdCardParameter'",
",",
"message",
":",
"'GetDataUsingPrivateNumberAndCard'",
",",
"class",
":",
"'GetDataUsingPrivateNumberAndCard'",
",",
"params",
":",
"{",
"PrivateNumber",
":",
"private_number",
",",
"IdCardSerial",
":",
"id_card_serial",
",",
"IdCardNumber",
":",
"id_card_numb",
",",
"}",
"}",
")",
"CRA",
"::",
"PassportInfo",
".",
"init_with_hash",
"(",
"body",
")",
"end"
] | Returns ID card information. | [
"Returns",
"ID",
"card",
"information",
"."
] | 13a9c40b27cdad93ae9892eb25aaee2deae4f541 | https://github.com/dimakura/cra.ge/blob/13a9c40b27cdad93ae9892eb25aaee2deae4f541/lib/cra/services.rb#L34-L46 | train |
dimakura/cra.ge | lib/cra/services.rb | CRA.Services.by_passport | def by_passport(private_number, passport)
body = self.gov_talk_request({
service: 'FetchPersonInfoByPassportNumberUsingCriteriaParameter',
message: 'CRA_FetchInfoByPassportCriteria',
class: 'CRA_FetchInfoByPassportCriteria',
params: {
PrivateNumber: private_number,
Number: passport
}
})
CRA::PassportInfo.init_with_hash(body)
end | ruby | def by_passport(private_number, passport)
body = self.gov_talk_request({
service: 'FetchPersonInfoByPassportNumberUsingCriteriaParameter',
message: 'CRA_FetchInfoByPassportCriteria',
class: 'CRA_FetchInfoByPassportCriteria',
params: {
PrivateNumber: private_number,
Number: passport
}
})
CRA::PassportInfo.init_with_hash(body)
end | [
"def",
"by_passport",
"(",
"private_number",
",",
"passport",
")",
"body",
"=",
"self",
".",
"gov_talk_request",
"(",
"{",
"service",
":",
"'FetchPersonInfoByPassportNumberUsingCriteriaParameter'",
",",
"message",
":",
"'CRA_FetchInfoByPassportCriteria'",
",",
"class",
":",
"'CRA_FetchInfoByPassportCriteria'",
",",
"params",
":",
"{",
"PrivateNumber",
":",
"private_number",
",",
"Number",
":",
"passport",
"}",
"}",
")",
"CRA",
"::",
"PassportInfo",
".",
"init_with_hash",
"(",
"body",
")",
"end"
] | Returns passport information. | [
"Returns",
"passport",
"information",
"."
] | 13a9c40b27cdad93ae9892eb25aaee2deae4f541 | https://github.com/dimakura/cra.ge/blob/13a9c40b27cdad93ae9892eb25aaee2deae4f541/lib/cra/services.rb#L49-L60 | train |
dimakura/cra.ge | lib/cra/services.rb | CRA.Services.address_by_name | def address_by_name(parent_id, name)
body = self.gov_talk_request({
service: 'AddrFindeAddressByNameParameter',
message: 'CRA_AddrFindeAddressByName',
class: 'CRA_AddrFindeAddressByName',
params: {
Id: parent_id,
Word: name,
}
})
CRA::Address.list_from_hash(body['ArrayOfResults']['Results'])
end | ruby | def address_by_name(parent_id, name)
body = self.gov_talk_request({
service: 'AddrFindeAddressByNameParameter',
message: 'CRA_AddrFindeAddressByName',
class: 'CRA_AddrFindeAddressByName',
params: {
Id: parent_id,
Word: name,
}
})
CRA::Address.list_from_hash(body['ArrayOfResults']['Results'])
end | [
"def",
"address_by_name",
"(",
"parent_id",
",",
"name",
")",
"body",
"=",
"self",
".",
"gov_talk_request",
"(",
"{",
"service",
":",
"'AddrFindeAddressByNameParameter'",
",",
"message",
":",
"'CRA_AddrFindeAddressByName'",
",",
"class",
":",
"'CRA_AddrFindeAddressByName'",
",",
"params",
":",
"{",
"Id",
":",
"parent_id",
",",
"Word",
":",
"name",
",",
"}",
"}",
")",
"CRA",
"::",
"Address",
".",
"list_from_hash",
"(",
"body",
"[",
"'ArrayOfResults'",
"]",
"[",
"'Results'",
"]",
")",
"end"
] | Returns array of addresses. | [
"Returns",
"array",
"of",
"addresses",
"."
] | 13a9c40b27cdad93ae9892eb25aaee2deae4f541 | https://github.com/dimakura/cra.ge/blob/13a9c40b27cdad93ae9892eb25aaee2deae4f541/lib/cra/services.rb#L63-L74 | train |
dimakura/cra.ge | lib/cra/services.rb | CRA.Services.address_by_parent | def address_by_parent(parent_id)
body = self.gov_talk_request({
message: 'CRA_AddrGetNodesByParentID',
class: 'CRA_AddrGetNodesByParentID',
params: {
long: parent_id,
}
})
CRA::AddressNode.list_from_hash(body['ArrayOfNodeInfo']['NodeInfo'])
end | ruby | def address_by_parent(parent_id)
body = self.gov_talk_request({
message: 'CRA_AddrGetNodesByParentID',
class: 'CRA_AddrGetNodesByParentID',
params: {
long: parent_id,
}
})
CRA::AddressNode.list_from_hash(body['ArrayOfNodeInfo']['NodeInfo'])
end | [
"def",
"address_by_parent",
"(",
"parent_id",
")",
"body",
"=",
"self",
".",
"gov_talk_request",
"(",
"{",
"message",
":",
"'CRA_AddrGetNodesByParentID'",
",",
"class",
":",
"'CRA_AddrGetNodesByParentID'",
",",
"params",
":",
"{",
"long",
":",
"parent_id",
",",
"}",
"}",
")",
"CRA",
"::",
"AddressNode",
".",
"list_from_hash",
"(",
"body",
"[",
"'ArrayOfNodeInfo'",
"]",
"[",
"'NodeInfo'",
"]",
")",
"end"
] | Returns array of address nodes. | [
"Returns",
"array",
"of",
"address",
"nodes",
"."
] | 13a9c40b27cdad93ae9892eb25aaee2deae4f541 | https://github.com/dimakura/cra.ge/blob/13a9c40b27cdad93ae9892eb25aaee2deae4f541/lib/cra/services.rb#L87-L96 | train |
dimakura/cra.ge | lib/cra/services.rb | CRA.Services.address_info | def address_info(id)
body = self.gov_talk_request({
message: 'CRA_AddrGetAddressInfoByID',
class: 'CRA_AddrGetAddressInfoByID',
params: {
long: id,
}
})
# puts body.to_s
CRA::AddressInfo.init_from_hash(body['AddressInfo'])
end | ruby | def address_info(id)
body = self.gov_talk_request({
message: 'CRA_AddrGetAddressInfoByID',
class: 'CRA_AddrGetAddressInfoByID',
params: {
long: id,
}
})
# puts body.to_s
CRA::AddressInfo.init_from_hash(body['AddressInfo'])
end | [
"def",
"address_info",
"(",
"id",
")",
"body",
"=",
"self",
".",
"gov_talk_request",
"(",
"{",
"message",
":",
"'CRA_AddrGetAddressInfoByID'",
",",
"class",
":",
"'CRA_AddrGetAddressInfoByID'",
",",
"params",
":",
"{",
"long",
":",
"id",
",",
"}",
"}",
")",
"CRA",
"::",
"AddressInfo",
".",
"init_from_hash",
"(",
"body",
"[",
"'AddressInfo'",
"]",
")",
"end"
] | Get address info by it's id. | [
"Get",
"address",
"info",
"by",
"it",
"s",
"id",
"."
] | 13a9c40b27cdad93ae9892eb25aaee2deae4f541 | https://github.com/dimakura/cra.ge/blob/13a9c40b27cdad93ae9892eb25aaee2deae4f541/lib/cra/services.rb#L99-L109 | train |
dimakura/cra.ge | lib/cra/services.rb | CRA.Services.persons_at_address | def persons_at_address(address_id)
body = self.gov_talk_request({
message: 'CRA_GetPersonsAtAddress',
class: 'CRA_GetPersonsAtAddress',
params: {
long: address_id,
}
})
CRA::PersonAtAddress.list_from_hash(body['ArrayOfPersonsAtAddress'])
end | ruby | def persons_at_address(address_id)
body = self.gov_talk_request({
message: 'CRA_GetPersonsAtAddress',
class: 'CRA_GetPersonsAtAddress',
params: {
long: address_id,
}
})
CRA::PersonAtAddress.list_from_hash(body['ArrayOfPersonsAtAddress'])
end | [
"def",
"persons_at_address",
"(",
"address_id",
")",
"body",
"=",
"self",
".",
"gov_talk_request",
"(",
"{",
"message",
":",
"'CRA_GetPersonsAtAddress'",
",",
"class",
":",
"'CRA_GetPersonsAtAddress'",
",",
"params",
":",
"{",
"long",
":",
"address_id",
",",
"}",
"}",
")",
"CRA",
"::",
"PersonAtAddress",
".",
"list_from_hash",
"(",
"body",
"[",
"'ArrayOfPersonsAtAddress'",
"]",
")",
"end"
] | Get persons array at the given address. | [
"Get",
"persons",
"array",
"at",
"the",
"given",
"address",
"."
] | 13a9c40b27cdad93ae9892eb25aaee2deae4f541 | https://github.com/dimakura/cra.ge/blob/13a9c40b27cdad93ae9892eb25aaee2deae4f541/lib/cra/services.rb#L112-L121 | train |
EmmanuelOga/firering | lib/firering/requests.rb | Firering.Requests.user | def user(id, &callback)
http(:get, "/users/#{id}.json") do |data, http|
Firering::User.instantiate(self, data, :user, &callback)
end
end | ruby | def user(id, &callback)
http(:get, "/users/#{id}.json") do |data, http|
Firering::User.instantiate(self, data, :user, &callback)
end
end | [
"def",
"user",
"(",
"id",
",",
"&",
"callback",
")",
"http",
"(",
":get",
",",
"\"/users/#{id}.json\"",
")",
"do",
"|",
"data",
",",
"http",
"|",
"Firering",
"::",
"User",
".",
"instantiate",
"(",
"self",
",",
"data",
",",
":user",
",",
"&",
"callback",
")",
"end",
"end"
] | returns a user by id | [
"returns",
"a",
"user",
"by",
"id"
] | 9e13dc3399f7429713b5213c5ee77bedf01def31 | https://github.com/EmmanuelOga/firering/blob/9e13dc3399f7429713b5213c5ee77bedf01def31/lib/firering/requests.rb#L13-L17 | train |
EmmanuelOga/firering | lib/firering/requests.rb | Firering.Requests.room | def room(id, &callback)
http(:get, "/room/#{id}.json") do |data, http|
Firering::Room.instantiate(self, data, :room, &callback)
end
end | ruby | def room(id, &callback)
http(:get, "/room/#{id}.json") do |data, http|
Firering::Room.instantiate(self, data, :room, &callback)
end
end | [
"def",
"room",
"(",
"id",
",",
"&",
"callback",
")",
"http",
"(",
":get",
",",
"\"/room/#{id}.json\"",
")",
"do",
"|",
"data",
",",
"http",
"|",
"Firering",
"::",
"Room",
".",
"instantiate",
"(",
"self",
",",
"data",
",",
":room",
",",
"&",
"callback",
")",
"end",
"end"
] | returns a room by id | [
"returns",
"a",
"room",
"by",
"id"
] | 9e13dc3399f7429713b5213c5ee77bedf01def31 | https://github.com/EmmanuelOga/firering/blob/9e13dc3399f7429713b5213c5ee77bedf01def31/lib/firering/requests.rb#L20-L24 | train |
EmmanuelOga/firering | lib/firering/requests.rb | Firering.Requests.search_messages | def search_messages(query, &callback)
http(:get, "/search/#{query}.json") do |data, http|
callback.call(data[:messages].map { |msg| Firering::Message.instantiate(self, msg) }) if callback
end
end | ruby | def search_messages(query, &callback)
http(:get, "/search/#{query}.json") do |data, http|
callback.call(data[:messages].map { |msg| Firering::Message.instantiate(self, msg) }) if callback
end
end | [
"def",
"search_messages",
"(",
"query",
",",
"&",
"callback",
")",
"http",
"(",
":get",
",",
"\"/search/#{query}.json\"",
")",
"do",
"|",
"data",
",",
"http",
"|",
"callback",
".",
"call",
"(",
"data",
"[",
":messages",
"]",
".",
"map",
"{",
"|",
"msg",
"|",
"Firering",
"::",
"Message",
".",
"instantiate",
"(",
"self",
",",
"msg",
")",
"}",
")",
"if",
"callback",
"end",
"end"
] | Returns all the messages containing the supplied term. | [
"Returns",
"all",
"the",
"messages",
"containing",
"the",
"supplied",
"term",
"."
] | 9e13dc3399f7429713b5213c5ee77bedf01def31 | https://github.com/EmmanuelOga/firering/blob/9e13dc3399f7429713b5213c5ee77bedf01def31/lib/firering/requests.rb#L40-L44 | train |
EmmanuelOga/firering | lib/firering/requests.rb | Firering.Requests.star_message | def star_message(id, yes_or_no = true, &callback)
http(yes_or_no ? :post : :delete, "/messages/#{id}/star.json") do |data, http|
callback.call(data) if callback
end
end | ruby | def star_message(id, yes_or_no = true, &callback)
http(yes_or_no ? :post : :delete, "/messages/#{id}/star.json") do |data, http|
callback.call(data) if callback
end
end | [
"def",
"star_message",
"(",
"id",
",",
"yes_or_no",
"=",
"true",
",",
"&",
"callback",
")",
"http",
"(",
"yes_or_no",
"?",
":post",
":",
":delete",
",",
"\"/messages/#{id}/star.json\"",
")",
"do",
"|",
"data",
",",
"http",
"|",
"callback",
".",
"call",
"(",
"data",
")",
"if",
"callback",
"end",
"end"
] | Toggles the star next to a message | [
"Toggles",
"the",
"star",
"next",
"to",
"a",
"message"
] | 9e13dc3399f7429713b5213c5ee77bedf01def31 | https://github.com/EmmanuelOga/firering/blob/9e13dc3399f7429713b5213c5ee77bedf01def31/lib/firering/requests.rb#L47-L51 | train |
Tapjoy/slugforge | lib/slugforge/configuration.rb | Slugforge.Configuration.defaults | def defaults
@values = Hash[self.class.options.select { |_, c| c.key?(:default) }.map { |n,c| [n, c[:default]] }].merge(@values)
end | ruby | def defaults
@values = Hash[self.class.options.select { |_, c| c.key?(:default) }.map { |n,c| [n, c[:default]] }].merge(@values)
end | [
"def",
"defaults",
"@values",
"=",
"Hash",
"[",
"self",
".",
"class",
".",
"options",
".",
"select",
"{",
"|",
"_",
",",
"c",
"|",
"c",
".",
"key?",
"(",
":default",
")",
"}",
".",
"map",
"{",
"|",
"n",
",",
"c",
"|",
"[",
"n",
",",
"c",
"[",
":default",
"]",
"]",
"}",
"]",
".",
"merge",
"(",
"@values",
")",
"end"
] | Get a hash of all options with default values. The list of values is initialized with the result. | [
"Get",
"a",
"hash",
"of",
"all",
"options",
"with",
"default",
"values",
".",
"The",
"list",
"of",
"values",
"is",
"initialized",
"with",
"the",
"result",
"."
] | 2e6b3d3022a1172dd7411e2d53b6218ad40d29c8 | https://github.com/Tapjoy/slugforge/blob/2e6b3d3022a1172dd7411e2d53b6218ad40d29c8/lib/slugforge/configuration.rb#L58-L60 | train |
Tapjoy/slugforge | lib/slugforge/configuration.rb | Slugforge.Configuration.read_yaml | def read_yaml(path)
return unless File.exist?(path)
source = YAML.load_file(path)
return unless source.is_a?(Hash)
update_with { |config| read_yaml_key(source, config[:key]) }
end | ruby | def read_yaml(path)
return unless File.exist?(path)
source = YAML.load_file(path)
return unless source.is_a?(Hash)
update_with { |config| read_yaml_key(source, config[:key]) }
end | [
"def",
"read_yaml",
"(",
"path",
")",
"return",
"unless",
"File",
".",
"exist?",
"(",
"path",
")",
"source",
"=",
"YAML",
".",
"load_file",
"(",
"path",
")",
"return",
"unless",
"source",
".",
"is_a?",
"(",
"Hash",
")",
"update_with",
"{",
"|",
"config",
"|",
"read_yaml_key",
"(",
"source",
",",
"config",
"[",
":key",
"]",
")",
"}",
"end"
] | Attempt to read option keys from a YAML file | [
"Attempt",
"to",
"read",
"option",
"keys",
"from",
"a",
"YAML",
"file"
] | 2e6b3d3022a1172dd7411e2d53b6218ad40d29c8 | https://github.com/Tapjoy/slugforge/blob/2e6b3d3022a1172dd7411e2d53b6218ad40d29c8/lib/slugforge/configuration.rb#L88-L94 | train |
Tapjoy/slugforge | lib/slugforge/configuration.rb | Slugforge.Configuration.update_with | def update_with(&blk)
self.class.options.each do |name, config|
value = yield(config)
@values[name] = value unless value.nil?
end
end | ruby | def update_with(&blk)
self.class.options.each do |name, config|
value = yield(config)
@values[name] = value unless value.nil?
end
end | [
"def",
"update_with",
"(",
"&",
"blk",
")",
"self",
".",
"class",
".",
"options",
".",
"each",
"do",
"|",
"name",
",",
"config",
"|",
"value",
"=",
"yield",
"(",
"config",
")",
"@values",
"[",
"name",
"]",
"=",
"value",
"unless",
"value",
".",
"nil?",
"end",
"end"
] | For every option we yield the configuration and expect a value back. If the block returns a value we set the
option to it. | [
"For",
"every",
"option",
"we",
"yield",
"the",
"configuration",
"and",
"expect",
"a",
"value",
"back",
".",
"If",
"the",
"block",
"returns",
"a",
"value",
"we",
"set",
"the",
"option",
"to",
"it",
"."
] | 2e6b3d3022a1172dd7411e2d53b6218ad40d29c8 | https://github.com/Tapjoy/slugforge/blob/2e6b3d3022a1172dd7411e2d53b6218ad40d29c8/lib/slugforge/configuration.rb#L117-L122 | train |
rack-webprofiler/rack-webprofiler | lib/rack/web_profiler/collectors.rb | Rack.WebProfiler::Collectors.add_collector | def add_collector(collector_class)
return collector_class.each { |c| add_collector(c) } if collector_class.is_a? Array
raise ArgumentError, "`collector_class' must be a class" unless collector_class.is_a? Class
unless collector_class.included_modules.include?(Rack::WebProfiler::Collector::DSL)
raise ArgumentError, "#{collector_class.class.name} must be an instance of \"Rack::WebProfiler::Collector::DSL\""
end
definition = collector_class.definition
if definition_by_identifier(definition.identifier)
raise ArgumentError, "A collector with identifier \“#{definition.identifier}\" already exists"
end
return false unless definition.is_enabled?
@collectors[collector_class] = definition
sort_collectors!
end | ruby | def add_collector(collector_class)
return collector_class.each { |c| add_collector(c) } if collector_class.is_a? Array
raise ArgumentError, "`collector_class' must be a class" unless collector_class.is_a? Class
unless collector_class.included_modules.include?(Rack::WebProfiler::Collector::DSL)
raise ArgumentError, "#{collector_class.class.name} must be an instance of \"Rack::WebProfiler::Collector::DSL\""
end
definition = collector_class.definition
if definition_by_identifier(definition.identifier)
raise ArgumentError, "A collector with identifier \“#{definition.identifier}\" already exists"
end
return false unless definition.is_enabled?
@collectors[collector_class] = definition
sort_collectors!
end | [
"def",
"add_collector",
"(",
"collector_class",
")",
"return",
"collector_class",
".",
"each",
"{",
"|",
"c",
"|",
"add_collector",
"(",
"c",
")",
"}",
"if",
"collector_class",
".",
"is_a?",
"Array",
"raise",
"ArgumentError",
",",
"\"`collector_class' must be a class\"",
"unless",
"collector_class",
".",
"is_a?",
"Class",
"unless",
"collector_class",
".",
"included_modules",
".",
"include?",
"(",
"Rack",
"::",
"WebProfiler",
"::",
"Collector",
"::",
"DSL",
")",
"raise",
"ArgumentError",
",",
"\"#{collector_class.class.name} must be an instance of \\\"Rack::WebProfiler::Collector::DSL\\\"\"",
"end",
"definition",
"=",
"collector_class",
".",
"definition",
"if",
"definition_by_identifier",
"(",
"definition",
".",
"identifier",
")",
"raise",
"ArgumentError",
",",
"\"A collector with identifier \\“#{definition.identifier}\\\" already exists\"",
"end",
"return",
"false",
"unless",
"definition",
".",
"is_enabled?",
"@collectors",
"[",
"collector_class",
"]",
"=",
"definition",
"sort_collectors!",
"end"
] | Add a collector.
@param collector_class [Array, Class]
@raise [ArgumentError] if `collector_class' is not a Class or is not an instance of Rack::WebProfiler::Collector::DSL
or a collector with this identifier is already registrered. | [
"Add",
"a",
"collector",
"."
] | bdb411fbb41eeddf612bbde91301ff94b3853a12 | https://github.com/rack-webprofiler/rack-webprofiler/blob/bdb411fbb41eeddf612bbde91301ff94b3853a12/lib/rack/web_profiler/collectors.rb#L40-L61 | train |
rack-webprofiler/rack-webprofiler | lib/rack/web_profiler/collectors.rb | Rack.WebProfiler::Collectors.sort_collectors! | def sort_collectors!
@sorted_collectors = {}
tmp = @collectors.sort_by { |_klass, definition| definition.position }
tmp.each { |_k, v| @sorted_collectors[v.identifier.to_sym] = v }
end | ruby | def sort_collectors!
@sorted_collectors = {}
tmp = @collectors.sort_by { |_klass, definition| definition.position }
tmp.each { |_k, v| @sorted_collectors[v.identifier.to_sym] = v }
end | [
"def",
"sort_collectors!",
"@sorted_collectors",
"=",
"{",
"}",
"tmp",
"=",
"@collectors",
".",
"sort_by",
"{",
"|",
"_klass",
",",
"definition",
"|",
"definition",
".",
"position",
"}",
"tmp",
".",
"each",
"{",
"|",
"_k",
",",
"v",
"|",
"@sorted_collectors",
"[",
"v",
".",
"identifier",
".",
"to_sym",
"]",
"=",
"v",
"}",
"end"
] | Sort collectors by definition identifier. | [
"Sort",
"collectors",
"by",
"definition",
"identifier",
"."
] | bdb411fbb41eeddf612bbde91301ff94b3853a12 | https://github.com/rack-webprofiler/rack-webprofiler/blob/bdb411fbb41eeddf612bbde91301ff94b3853a12/lib/rack/web_profiler/collectors.rb#L88-L93 | train |
bazaarlabs/tvdbr | lib/tvdbr/data_set.rb | Tvdbr.DataSet.normalize_value | def normalize_value(val)
if val.is_a?(Hash)
val = val["__content__"] if val.has_key?("__content__")
val = val.values.first if val.respond_to?(:values) && val.values.one?
val = val.join(" ") if val.respond_to?(:join)
val.to_s
else # any other value
val
end
end | ruby | def normalize_value(val)
if val.is_a?(Hash)
val = val["__content__"] if val.has_key?("__content__")
val = val.values.first if val.respond_to?(:values) && val.values.one?
val = val.join(" ") if val.respond_to?(:join)
val.to_s
else # any other value
val
end
end | [
"def",
"normalize_value",
"(",
"val",
")",
"if",
"val",
".",
"is_a?",
"(",
"Hash",
")",
"val",
"=",
"val",
"[",
"\"__content__\"",
"]",
"if",
"val",
".",
"has_key?",
"(",
"\"__content__\"",
")",
"val",
"=",
"val",
".",
"values",
".",
"first",
"if",
"val",
".",
"respond_to?",
"(",
":values",
")",
"&&",
"val",
".",
"values",
".",
"one?",
"val",
"=",
"val",
".",
"join",
"(",
"\" \"",
")",
"if",
"val",
".",
"respond_to?",
"(",
":join",
")",
"val",
".",
"to_s",
"else",
"val",
"end",
"end"
] | Normalizes a value for the formatted hash values
TVDB hashes should not contain more hashes
Sometimes TVDB returns a hash with content inside which needs to be extracted | [
"Normalizes",
"a",
"value",
"for",
"the",
"formatted",
"hash",
"values",
"TVDB",
"hashes",
"should",
"not",
"contain",
"more",
"hashes",
"Sometimes",
"TVDB",
"returns",
"a",
"hash",
"with",
"content",
"inside",
"which",
"needs",
"to",
"be",
"extracted"
] | be9a1324c8d8051b7063bf7152aa1c53c25b0661 | https://github.com/bazaarlabs/tvdbr/blob/be9a1324c8d8051b7063bf7152aa1c53c25b0661/lib/tvdbr/data_set.rb#L76-L85 | train |
Sology/syswatch | lib/syswatch/cli.rb | SysWatch.CLI.parse_options! | def parse_options!(args)
@options = {}
opts = ::OptionParser.new do |opts|
opts.banner = "Usage: syswatch [options]\n\n Options:"
opts.on("-f", "--foreground", "Do not daemonize, just run in foreground.") do |f|
@options[:foreground] = f
end
opts.on("-v", "--verbose", "Be verbose, print out some messages.") do |v|
@options[:verbose] = v
end
opts.on("-t", "--test", "Test notifications.") do |t|
@options[:test] = t
end
opts.on("-c", "--config [FILE]", "Use a specific config file, instead of `#{SysWatch::DEFAULTS[:config]}`") do |config|
@options[:config] = config
end
end
opts.parse! args
end | ruby | def parse_options!(args)
@options = {}
opts = ::OptionParser.new do |opts|
opts.banner = "Usage: syswatch [options]\n\n Options:"
opts.on("-f", "--foreground", "Do not daemonize, just run in foreground.") do |f|
@options[:foreground] = f
end
opts.on("-v", "--verbose", "Be verbose, print out some messages.") do |v|
@options[:verbose] = v
end
opts.on("-t", "--test", "Test notifications.") do |t|
@options[:test] = t
end
opts.on("-c", "--config [FILE]", "Use a specific config file, instead of `#{SysWatch::DEFAULTS[:config]}`") do |config|
@options[:config] = config
end
end
opts.parse! args
end | [
"def",
"parse_options!",
"(",
"args",
")",
"@options",
"=",
"{",
"}",
"opts",
"=",
"::",
"OptionParser",
".",
"new",
"do",
"|",
"opts",
"|",
"opts",
".",
"banner",
"=",
"\"Usage: syswatch [options]\\n\\n Options:\"",
"opts",
".",
"on",
"(",
"\"-f\"",
",",
"\"--foreground\"",
",",
"\"Do not daemonize, just run in foreground.\"",
")",
"do",
"|",
"f",
"|",
"@options",
"[",
":foreground",
"]",
"=",
"f",
"end",
"opts",
".",
"on",
"(",
"\"-v\"",
",",
"\"--verbose\"",
",",
"\"Be verbose, print out some messages.\"",
")",
"do",
"|",
"v",
"|",
"@options",
"[",
":verbose",
"]",
"=",
"v",
"end",
"opts",
".",
"on",
"(",
"\"-t\"",
",",
"\"--test\"",
",",
"\"Test notifications.\"",
")",
"do",
"|",
"t",
"|",
"@options",
"[",
":test",
"]",
"=",
"t",
"end",
"opts",
".",
"on",
"(",
"\"-c\"",
",",
"\"--config [FILE]\"",
",",
"\"Use a specific config file, instead of `#{SysWatch::DEFAULTS[:config]}`\"",
")",
"do",
"|",
"config",
"|",
"@options",
"[",
":config",
"]",
"=",
"config",
"end",
"end",
"opts",
".",
"parse!",
"args",
"end"
] | Initialize a new system watcher
@param argv [Hash] the command line parameters hash (usually `ARGV`).
@param env [Hash] the environment variables hash (usually `ENV`).
Parse the command line options | [
"Initialize",
"a",
"new",
"system",
"watcher"
] | 75d64d3e93e7d4a506396bb7c0ce2169daca712e | https://github.com/Sology/syswatch/blob/75d64d3e93e7d4a506396bb7c0ce2169daca712e/lib/syswatch/cli.rb#L19-L41 | train |
Tapjoy/slugforge | lib/slugforge/slugins.rb | Slugforge.SluginManager.locate_slugins | def locate_slugins
Gem.refresh
(Gem::Specification.respond_to?(:each) ? Gem::Specification : Gem.source_index.find_name('')).each do |gem|
next if gem.name !~ PREFIX
slugin_name = gem.name.split('-', 2).last
@slugins << Slugin.new(slugin_name, gem.name, gem, true) if !gem_located?(gem.name)
end
@slugins
end | ruby | def locate_slugins
Gem.refresh
(Gem::Specification.respond_to?(:each) ? Gem::Specification : Gem.source_index.find_name('')).each do |gem|
next if gem.name !~ PREFIX
slugin_name = gem.name.split('-', 2).last
@slugins << Slugin.new(slugin_name, gem.name, gem, true) if !gem_located?(gem.name)
end
@slugins
end | [
"def",
"locate_slugins",
"Gem",
".",
"refresh",
"(",
"Gem",
"::",
"Specification",
".",
"respond_to?",
"(",
":each",
")",
"?",
"Gem",
"::",
"Specification",
":",
"Gem",
".",
"source_index",
".",
"find_name",
"(",
"''",
")",
")",
".",
"each",
"do",
"|",
"gem",
"|",
"next",
"if",
"gem",
".",
"name",
"!~",
"PREFIX",
"slugin_name",
"=",
"gem",
".",
"name",
".",
"split",
"(",
"'-'",
",",
"2",
")",
".",
"last",
"@slugins",
"<<",
"Slugin",
".",
"new",
"(",
"slugin_name",
",",
"gem",
".",
"name",
",",
"gem",
",",
"true",
")",
"if",
"!",
"gem_located?",
"(",
"gem",
".",
"name",
")",
"end",
"@slugins",
"end"
] | Find all installed Pry slugins and store them in an internal array. | [
"Find",
"all",
"installed",
"Pry",
"slugins",
"and",
"store",
"them",
"in",
"an",
"internal",
"array",
"."
] | 2e6b3d3022a1172dd7411e2d53b6218ad40d29c8 | https://github.com/Tapjoy/slugforge/blob/2e6b3d3022a1172dd7411e2d53b6218ad40d29c8/lib/slugforge/slugins.rb#L110-L118 | train |
dlangevin/gxapi_rails | lib/gxapi/ostruct.rb | Gxapi.Ostruct.to_hash | def to_hash
ret = {}
@hash.dup.each_pair do |key, val|
ret[key] = self.convert_value_from_ostruct(val)
end
ret
end | ruby | def to_hash
ret = {}
@hash.dup.each_pair do |key, val|
ret[key] = self.convert_value_from_ostruct(val)
end
ret
end | [
"def",
"to_hash",
"ret",
"=",
"{",
"}",
"@hash",
".",
"dup",
".",
"each_pair",
"do",
"|",
"key",
",",
"val",
"|",
"ret",
"[",
"key",
"]",
"=",
"self",
".",
"convert_value_from_ostruct",
"(",
"val",
")",
"end",
"ret",
"end"
] | recursive open struct | [
"recursive",
"open",
"struct"
] | 21361227f0c70118b38f7fa372a18c0ae7aab810 | https://github.com/dlangevin/gxapi_rails/blob/21361227f0c70118b38f7fa372a18c0ae7aab810/lib/gxapi/ostruct.rb#L17-L23 | train |
dlangevin/gxapi_rails | lib/gxapi/ostruct.rb | Gxapi.Ostruct.define_accessors | def define_accessors(field)
# add the generated method
self.generated_methods.module_eval do
define_method(field) do
@hash[field]
end
define_method("#{field}=") do |val|
@hash[field] = val
end
end
end | ruby | def define_accessors(field)
# add the generated method
self.generated_methods.module_eval do
define_method(field) do
@hash[field]
end
define_method("#{field}=") do |val|
@hash[field] = val
end
end
end | [
"def",
"define_accessors",
"(",
"field",
")",
"self",
".",
"generated_methods",
".",
"module_eval",
"do",
"define_method",
"(",
"field",
")",
"do",
"@hash",
"[",
"field",
"]",
"end",
"define_method",
"(",
"\"#{field}=\"",
")",
"do",
"|",
"val",
"|",
"@hash",
"[",
"field",
"]",
"=",
"val",
"end",
"end",
"end"
] | define accessors for an attribute | [
"define",
"accessors",
"for",
"an",
"attribute"
] | 21361227f0c70118b38f7fa372a18c0ae7aab810 | https://github.com/dlangevin/gxapi_rails/blob/21361227f0c70118b38f7fa372a18c0ae7aab810/lib/gxapi/ostruct.rb#L51-L61 | train |
dlangevin/gxapi_rails | lib/gxapi/ostruct.rb | Gxapi.Ostruct.method_missing | def method_missing(meth, *args, &block)
if meth.to_s =~ /=$/
self.define_accessors(meth.to_s.gsub(/=$/,''))
return self.send(meth, *args, &block)
end
super
end | ruby | def method_missing(meth, *args, &block)
if meth.to_s =~ /=$/
self.define_accessors(meth.to_s.gsub(/=$/,''))
return self.send(meth, *args, &block)
end
super
end | [
"def",
"method_missing",
"(",
"meth",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"meth",
".",
"to_s",
"=~",
"/",
"/",
"self",
".",
"define_accessors",
"(",
"meth",
".",
"to_s",
".",
"gsub",
"(",
"/",
"/",
",",
"''",
")",
")",
"return",
"self",
".",
"send",
"(",
"meth",
",",
"*",
"args",
",",
"&",
"block",
")",
"end",
"super",
"end"
] | dynamically define getter and setter when an unknown setter is called | [
"dynamically",
"define",
"getter",
"and",
"setter",
"when",
"an",
"unknown",
"setter",
"is",
"called"
] | 21361227f0c70118b38f7fa372a18c0ae7aab810 | https://github.com/dlangevin/gxapi_rails/blob/21361227f0c70118b38f7fa372a18c0ae7aab810/lib/gxapi/ostruct.rb#L69-L75 | train |
dlangevin/gxapi_rails | lib/gxapi/ostruct.rb | Gxapi.Ostruct.underscore | def underscore(string)
string = string.to_s
string = string[0].downcase + string[1..-1].gsub(/([A-Z])/,'_\1')
string.downcase
end | ruby | def underscore(string)
string = string.to_s
string = string[0].downcase + string[1..-1].gsub(/([A-Z])/,'_\1')
string.downcase
end | [
"def",
"underscore",
"(",
"string",
")",
"string",
"=",
"string",
".",
"to_s",
"string",
"=",
"string",
"[",
"0",
"]",
".",
"downcase",
"+",
"string",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"gsub",
"(",
"/",
"/",
",",
"'_\\1'",
")",
"string",
".",
"downcase",
"end"
] | take a string an convert it from
camelCase to under_scored | [
"take",
"a",
"string",
"an",
"convert",
"it",
"from",
"camelCase",
"to",
"under_scored"
] | 21361227f0c70118b38f7fa372a18c0ae7aab810 | https://github.com/dlangevin/gxapi_rails/blob/21361227f0c70118b38f7fa372a18c0ae7aab810/lib/gxapi/ostruct.rb#L79-L83 | train |
jlinder/nitroapi | lib/nitro_api/batch_calls.rb | NitroApi.BatchCalls.handle_batch_multiple_actions | def handle_batch_multiple_actions
# TODO: improve handling of errors in the batch response
actions = []
@batch.each do |action|
actions << to_query(action[:params])
end
results = really_make_call({'method' => 'batch.run','methodFeed' => JSON.dump(actions)}, :post)
@batch = nil
extract_session_key results
results
end | ruby | def handle_batch_multiple_actions
# TODO: improve handling of errors in the batch response
actions = []
@batch.each do |action|
actions << to_query(action[:params])
end
results = really_make_call({'method' => 'batch.run','methodFeed' => JSON.dump(actions)}, :post)
@batch = nil
extract_session_key results
results
end | [
"def",
"handle_batch_multiple_actions",
"actions",
"=",
"[",
"]",
"@batch",
".",
"each",
"do",
"|",
"action",
"|",
"actions",
"<<",
"to_query",
"(",
"action",
"[",
":params",
"]",
")",
"end",
"results",
"=",
"really_make_call",
"(",
"{",
"'method'",
"=>",
"'batch.run'",
",",
"'methodFeed'",
"=>",
"JSON",
".",
"dump",
"(",
"actions",
")",
"}",
",",
":post",
")",
"@batch",
"=",
"nil",
"extract_session_key",
"results",
"results",
"end"
] | This function handles making the call when there is more than one call in
the batch. | [
"This",
"function",
"handles",
"making",
"the",
"call",
"when",
"there",
"is",
"more",
"than",
"one",
"call",
"in",
"the",
"batch",
"."
] | 9bf51a1988e213ce0020b783d7d375fe8d418638 | https://github.com/jlinder/nitroapi/blob/9bf51a1988e213ce0020b783d7d375fe8d418638/lib/nitro_api/batch_calls.rb#L35-L46 | train |
marcmo/cxxproject | lib/cxxproject/buildingblocks/static_library.rb | Cxxproject.StaticLibrary.convert_to_rake | def convert_to_rake()
object_multitask = prepare_tasks_for_objects()
archiver = @tcs[:ARCHIVER]
res = typed_file_task Rake::Task::LIBRARY, get_task_name => object_multitask do
cmd = calc_command_line
aname = calc_archive_name
Dir.chdir(@project_dir) do
FileUtils.rm(aname) if File.exists?(aname)
# cmd.map! {|c| c.include?(' ') ? "\"#{c}\"" : c }
rd, wr = IO.pipe
cmd << {
:err => wr,
:out => wr
}
sp = spawn(*cmd)
cmd.pop
consoleOutput = ProcessHelper.readOutput(sp, rd, wr)
process_result(cmd, consoleOutput, @tcs[:ARCHIVER][:ERROR_PARSER], "Creating #{aname}")
check_config_file()
end
end
res.tags = tags
enhance_with_additional_files(res)
add_output_dir_dependency(get_task_name, res, true)
add_grouping_tasks(get_task_name)
setup_rake_dependencies(res, object_multitask)
return res
end | ruby | def convert_to_rake()
object_multitask = prepare_tasks_for_objects()
archiver = @tcs[:ARCHIVER]
res = typed_file_task Rake::Task::LIBRARY, get_task_name => object_multitask do
cmd = calc_command_line
aname = calc_archive_name
Dir.chdir(@project_dir) do
FileUtils.rm(aname) if File.exists?(aname)
# cmd.map! {|c| c.include?(' ') ? "\"#{c}\"" : c }
rd, wr = IO.pipe
cmd << {
:err => wr,
:out => wr
}
sp = spawn(*cmd)
cmd.pop
consoleOutput = ProcessHelper.readOutput(sp, rd, wr)
process_result(cmd, consoleOutput, @tcs[:ARCHIVER][:ERROR_PARSER], "Creating #{aname}")
check_config_file()
end
end
res.tags = tags
enhance_with_additional_files(res)
add_output_dir_dependency(get_task_name, res, true)
add_grouping_tasks(get_task_name)
setup_rake_dependencies(res, object_multitask)
return res
end | [
"def",
"convert_to_rake",
"(",
")",
"object_multitask",
"=",
"prepare_tasks_for_objects",
"(",
")",
"archiver",
"=",
"@tcs",
"[",
":ARCHIVER",
"]",
"res",
"=",
"typed_file_task",
"Rake",
"::",
"Task",
"::",
"LIBRARY",
",",
"get_task_name",
"=>",
"object_multitask",
"do",
"cmd",
"=",
"calc_command_line",
"aname",
"=",
"calc_archive_name",
"Dir",
".",
"chdir",
"(",
"@project_dir",
")",
"do",
"FileUtils",
".",
"rm",
"(",
"aname",
")",
"if",
"File",
".",
"exists?",
"(",
"aname",
")",
"rd",
",",
"wr",
"=",
"IO",
".",
"pipe",
"cmd",
"<<",
"{",
":err",
"=>",
"wr",
",",
":out",
"=>",
"wr",
"}",
"sp",
"=",
"spawn",
"(",
"*",
"cmd",
")",
"cmd",
".",
"pop",
"consoleOutput",
"=",
"ProcessHelper",
".",
"readOutput",
"(",
"sp",
",",
"rd",
",",
"wr",
")",
"process_result",
"(",
"cmd",
",",
"consoleOutput",
",",
"@tcs",
"[",
":ARCHIVER",
"]",
"[",
":ERROR_PARSER",
"]",
",",
"\"Creating #{aname}\"",
")",
"check_config_file",
"(",
")",
"end",
"end",
"res",
".",
"tags",
"=",
"tags",
"enhance_with_additional_files",
"(",
"res",
")",
"add_output_dir_dependency",
"(",
"get_task_name",
",",
"res",
",",
"true",
")",
"add_grouping_tasks",
"(",
"get_task_name",
")",
"setup_rake_dependencies",
"(",
"res",
",",
"object_multitask",
")",
"return",
"res",
"end"
] | task that will link the given object files to a static lib | [
"task",
"that",
"will",
"link",
"the",
"given",
"object",
"files",
"to",
"a",
"static",
"lib"
] | 3740a09d6a143acd96bde3d2ff79055a6b810da4 | https://github.com/marcmo/cxxproject/blob/3740a09d6a143acd96bde3d2ff79055a6b810da4/lib/cxxproject/buildingblocks/static_library.rb#L86-L119 | train |
sgillesp/taxonomite | lib/taxonomite/tree.rb | Taxonomite.Tree.ancestors | def ancestors
a = Array.new
self.parent._ancestors(a) unless self.parent.nil?
return a
end | ruby | def ancestors
a = Array.new
self.parent._ancestors(a) unless self.parent.nil?
return a
end | [
"def",
"ancestors",
"a",
"=",
"Array",
".",
"new",
"self",
".",
"parent",
".",
"_ancestors",
"(",
"a",
")",
"unless",
"self",
".",
"parent",
".",
"nil?",
"return",
"a",
"end"
] | return all ancestors of this node | [
"return",
"all",
"ancestors",
"of",
"this",
"node"
] | 731b42d0dfa1f52b39d050026f49b2d205407ff8 | https://github.com/sgillesp/taxonomite/blob/731b42d0dfa1f52b39d050026f49b2d205407ff8/lib/taxonomite/tree.rb#L75-L79 | train |
sgillesp/taxonomite | lib/taxonomite/tree.rb | Taxonomite.Tree.move_children_to_parent | def move_children_to_parent
children.each do |c|
self.parent.children << c
c.parent = self.parent # is this necessary?
end
end | ruby | def move_children_to_parent
children.each do |c|
self.parent.children << c
c.parent = self.parent # is this necessary?
end
end | [
"def",
"move_children_to_parent",
"children",
".",
"each",
"do",
"|",
"c",
"|",
"self",
".",
"parent",
".",
"children",
"<<",
"c",
"c",
".",
"parent",
"=",
"self",
".",
"parent",
"end",
"end"
] | move all children to the parent node
!!! need to perform validations here? | [
"move",
"all",
"children",
"to",
"the",
"parent",
"node",
"!!!",
"need",
"to",
"perform",
"validations",
"here?"
] | 731b42d0dfa1f52b39d050026f49b2d205407ff8 | https://github.com/sgillesp/taxonomite/blob/731b42d0dfa1f52b39d050026f49b2d205407ff8/lib/taxonomite/tree.rb#L123-L128 | train |
sgillesp/taxonomite | lib/taxonomite/tree.rb | Taxonomite.Tree.validate_child! | def validate_child!(ch)
raise InvalidChild.create(self, ch) if (ch == nil)
raise CircularRelation.create(self, ch) if self.descendant_of?(ch)
if base_class.method_defined? :validate_child
self.validate_child(ch) # this should throw an error if not valid
end
end | ruby | def validate_child!(ch)
raise InvalidChild.create(self, ch) if (ch == nil)
raise CircularRelation.create(self, ch) if self.descendant_of?(ch)
if base_class.method_defined? :validate_child
self.validate_child(ch) # this should throw an error if not valid
end
end | [
"def",
"validate_child!",
"(",
"ch",
")",
"raise",
"InvalidChild",
".",
"create",
"(",
"self",
",",
"ch",
")",
"if",
"(",
"ch",
"==",
"nil",
")",
"raise",
"CircularRelation",
".",
"create",
"(",
"self",
",",
"ch",
")",
"if",
"self",
".",
"descendant_of?",
"(",
"ch",
")",
"if",
"base_class",
".",
"method_defined?",
":validate_child",
"self",
".",
"validate_child",
"(",
"ch",
")",
"end",
"end"
] | perform validation on whether this child is an acceptable child or not?
the base_class must have a method 'validate_child?' to implement domain logic there | [
"perform",
"validation",
"on",
"whether",
"this",
"child",
"is",
"an",
"acceptable",
"child",
"or",
"not?",
"the",
"base_class",
"must",
"have",
"a",
"method",
"validate_child?",
"to",
"implement",
"domain",
"logic",
"there"
] | 731b42d0dfa1f52b39d050026f49b2d205407ff8 | https://github.com/sgillesp/taxonomite/blob/731b42d0dfa1f52b39d050026f49b2d205407ff8/lib/taxonomite/tree.rb#L133-L139 | train |
sgillesp/taxonomite | lib/taxonomite/entity.rb | Taxonomite.Entity.do_setup | def do_setup
if (self.taxonomy_node == nil)
self.taxonomy_node = self.respond_to?(:create_taxonomy_node) ? self.create_taxonomy_node : Taxonomite::Node.new
self.taxonomy_node.owner = self
end
end | ruby | def do_setup
if (self.taxonomy_node == nil)
self.taxonomy_node = self.respond_to?(:create_taxonomy_node) ? self.create_taxonomy_node : Taxonomite::Node.new
self.taxonomy_node.owner = self
end
end | [
"def",
"do_setup",
"if",
"(",
"self",
".",
"taxonomy_node",
"==",
"nil",
")",
"self",
".",
"taxonomy_node",
"=",
"self",
".",
"respond_to?",
"(",
":create_taxonomy_node",
")",
"?",
"self",
".",
"create_taxonomy_node",
":",
"Taxonomite",
"::",
"Node",
".",
"new",
"self",
".",
"taxonomy_node",
".",
"owner",
"=",
"self",
"end",
"end"
] | subclasses should overload create_taxonomy_node to create the appropriate Place object and set it up | [
"subclasses",
"should",
"overload",
"create_taxonomy_node",
"to",
"create",
"the",
"appropriate",
"Place",
"object",
"and",
"set",
"it",
"up"
] | 731b42d0dfa1f52b39d050026f49b2d205407ff8 | https://github.com/sgillesp/taxonomite/blob/731b42d0dfa1f52b39d050026f49b2d205407ff8/lib/taxonomite/entity.rb#L28-L33 | train |
carboncalculated/calculated | lib/calculated/service.rb | Calculated.Service.check_response | def check_response(response)
case response.code
when 200, 201
true
when 401
raise Calculated::Session::PermissionDenied.new("Your Request could not be authenticated is your api key valid?")
when 404
raise Calculated::Session::NotFound.new("Resource was not found")
when 412
raise Calculated::Session::MissingParameter.new("Missing Parameter: #{response.body}")
else
raise Calculated::Session::UnknownError.new("super strange type unknown error: #{response.code} :body #{response.body}")
end
end | ruby | def check_response(response)
case response.code
when 200, 201
true
when 401
raise Calculated::Session::PermissionDenied.new("Your Request could not be authenticated is your api key valid?")
when 404
raise Calculated::Session::NotFound.new("Resource was not found")
when 412
raise Calculated::Session::MissingParameter.new("Missing Parameter: #{response.body}")
else
raise Calculated::Session::UnknownError.new("super strange type unknown error: #{response.code} :body #{response.body}")
end
end | [
"def",
"check_response",
"(",
"response",
")",
"case",
"response",
".",
"code",
"when",
"200",
",",
"201",
"true",
"when",
"401",
"raise",
"Calculated",
"::",
"Session",
"::",
"PermissionDenied",
".",
"new",
"(",
"\"Your Request could not be authenticated is your api key valid?\"",
")",
"when",
"404",
"raise",
"Calculated",
"::",
"Session",
"::",
"NotFound",
".",
"new",
"(",
"\"Resource was not found\"",
")",
"when",
"412",
"raise",
"Calculated",
"::",
"Session",
"::",
"MissingParameter",
".",
"new",
"(",
"\"Missing Parameter: #{response.body}\"",
")",
"else",
"raise",
"Calculated",
"::",
"Session",
"::",
"UnknownError",
".",
"new",
"(",
"\"super strange type unknown error: #{response.code} :body #{response.body}\"",
")",
"end",
"end"
] | checking the status code of the response; if we are not authenticated
then authenticate the session
@raise [Calculated::PermissionDenied] if the status code is 403
@raise [Calculated::SessionExpired] if a we get a 401
@raise [Calculated::MissingParameter] if we get something strange | [
"checking",
"the",
"status",
"code",
"of",
"the",
"response",
";",
"if",
"we",
"are",
"not",
"authenticated",
"then",
"authenticate",
"the",
"session"
] | 0234d89b515db26add000f88c594f6d3fb5edd5e | https://github.com/carboncalculated/calculated/blob/0234d89b515db26add000f88c594f6d3fb5edd5e/lib/calculated/service.rb#L34-L47 | train |
ajh/speaky_csv | lib/speaky_csv/attr_import.rb | SpeakyCsv.AttrImport.add_fields | def add_fields(row, attrs)
fields = (@config.fields - @config.export_only_fields).map(&:to_s)
fields.each do |name|
row.has_key? name or next
attrs[name] = row.field name
end
end | ruby | def add_fields(row, attrs)
fields = (@config.fields - @config.export_only_fields).map(&:to_s)
fields.each do |name|
row.has_key? name or next
attrs[name] = row.field name
end
end | [
"def",
"add_fields",
"(",
"row",
",",
"attrs",
")",
"fields",
"=",
"(",
"@config",
".",
"fields",
"-",
"@config",
".",
"export_only_fields",
")",
".",
"map",
"(",
"&",
":to_s",
")",
"fields",
".",
"each",
"do",
"|",
"name",
"|",
"row",
".",
"has_key?",
"name",
"or",
"next",
"attrs",
"[",
"name",
"]",
"=",
"row",
".",
"field",
"name",
"end",
"end"
] | Adds configured fields to attrs | [
"Adds",
"configured",
"fields",
"to",
"attrs"
] | aa16dd8e7dbe2202523b1a7d35a610c174c3fc21 | https://github.com/ajh/speaky_csv/blob/aa16dd8e7dbe2202523b1a7d35a610c174c3fc21/lib/speaky_csv/attr_import.rb#L66-L72 | train |
ajh/speaky_csv | lib/speaky_csv/attr_import.rb | SpeakyCsv.AttrImport.add_has_manys | def add_has_manys(row, attrs)
headers_length = row.headers.compact.length
pairs_start_on_evens = headers_length.even?
(headers_length..row.fields.length).each do |i|
i.send(pairs_start_on_evens ? :even? : :odd?) || next
row[i] || next
m = row[i].match(/^(\w+)_(\d+)_(\w+)$/)
m || next
has_many_name = m[1].pluralize
has_many_index = m[2].to_i
has_many_field = m[3]
has_many_value = row[i + 1]
has_many_config = @config.has_manys[has_many_name.to_sym]
next unless has_many_config
next unless has_many_config.fields.include?(has_many_field.to_sym)
next if has_many_config.export_only_fields.include?(has_many_field.to_sym)
attrs[has_many_name] ||= []
attrs[has_many_name][has_many_index] ||= {}
attrs[has_many_name][has_many_index][has_many_field] = has_many_value
end
end | ruby | def add_has_manys(row, attrs)
headers_length = row.headers.compact.length
pairs_start_on_evens = headers_length.even?
(headers_length..row.fields.length).each do |i|
i.send(pairs_start_on_evens ? :even? : :odd?) || next
row[i] || next
m = row[i].match(/^(\w+)_(\d+)_(\w+)$/)
m || next
has_many_name = m[1].pluralize
has_many_index = m[2].to_i
has_many_field = m[3]
has_many_value = row[i + 1]
has_many_config = @config.has_manys[has_many_name.to_sym]
next unless has_many_config
next unless has_many_config.fields.include?(has_many_field.to_sym)
next if has_many_config.export_only_fields.include?(has_many_field.to_sym)
attrs[has_many_name] ||= []
attrs[has_many_name][has_many_index] ||= {}
attrs[has_many_name][has_many_index][has_many_field] = has_many_value
end
end | [
"def",
"add_has_manys",
"(",
"row",
",",
"attrs",
")",
"headers_length",
"=",
"row",
".",
"headers",
".",
"compact",
".",
"length",
"pairs_start_on_evens",
"=",
"headers_length",
".",
"even?",
"(",
"headers_length",
"..",
"row",
".",
"fields",
".",
"length",
")",
".",
"each",
"do",
"|",
"i",
"|",
"i",
".",
"send",
"(",
"pairs_start_on_evens",
"?",
":even?",
":",
":odd?",
")",
"||",
"next",
"row",
"[",
"i",
"]",
"||",
"next",
"m",
"=",
"row",
"[",
"i",
"]",
".",
"match",
"(",
"/",
"\\w",
"\\d",
"\\w",
"/",
")",
"m",
"||",
"next",
"has_many_name",
"=",
"m",
"[",
"1",
"]",
".",
"pluralize",
"has_many_index",
"=",
"m",
"[",
"2",
"]",
".",
"to_i",
"has_many_field",
"=",
"m",
"[",
"3",
"]",
"has_many_value",
"=",
"row",
"[",
"i",
"+",
"1",
"]",
"has_many_config",
"=",
"@config",
".",
"has_manys",
"[",
"has_many_name",
".",
"to_sym",
"]",
"next",
"unless",
"has_many_config",
"next",
"unless",
"has_many_config",
".",
"fields",
".",
"include?",
"(",
"has_many_field",
".",
"to_sym",
")",
"next",
"if",
"has_many_config",
".",
"export_only_fields",
".",
"include?",
"(",
"has_many_field",
".",
"to_sym",
")",
"attrs",
"[",
"has_many_name",
"]",
"||=",
"[",
"]",
"attrs",
"[",
"has_many_name",
"]",
"[",
"has_many_index",
"]",
"||=",
"{",
"}",
"attrs",
"[",
"has_many_name",
"]",
"[",
"has_many_index",
"]",
"[",
"has_many_field",
"]",
"=",
"has_many_value",
"end",
"end"
] | Adds configured has manys to attrs | [
"Adds",
"configured",
"has",
"manys",
"to",
"attrs"
] | aa16dd8e7dbe2202523b1a7d35a610c174c3fc21 | https://github.com/ajh/speaky_csv/blob/aa16dd8e7dbe2202523b1a7d35a610c174c3fc21/lib/speaky_csv/attr_import.rb#L75-L99 | train |
ajh/speaky_csv | lib/speaky_csv/attr_import.rb | SpeakyCsv.AttrImport.add_has_ones | def add_has_ones(row, attrs)
@config.has_ones.each do |name,assoc_config|
fields = (assoc_config.fields - assoc_config.export_only_fields).map(&:to_s)
fields.each do |f|
csv_name = "#{name}_#{f}"
row.has_key? csv_name or next
(attrs[name.to_s] ||= {})[f] = row.field "#{name}_#{f}"
end
end
end | ruby | def add_has_ones(row, attrs)
@config.has_ones.each do |name,assoc_config|
fields = (assoc_config.fields - assoc_config.export_only_fields).map(&:to_s)
fields.each do |f|
csv_name = "#{name}_#{f}"
row.has_key? csv_name or next
(attrs[name.to_s] ||= {})[f] = row.field "#{name}_#{f}"
end
end
end | [
"def",
"add_has_ones",
"(",
"row",
",",
"attrs",
")",
"@config",
".",
"has_ones",
".",
"each",
"do",
"|",
"name",
",",
"assoc_config",
"|",
"fields",
"=",
"(",
"assoc_config",
".",
"fields",
"-",
"assoc_config",
".",
"export_only_fields",
")",
".",
"map",
"(",
"&",
":to_s",
")",
"fields",
".",
"each",
"do",
"|",
"f",
"|",
"csv_name",
"=",
"\"#{name}_#{f}\"",
"row",
".",
"has_key?",
"csv_name",
"or",
"next",
"(",
"attrs",
"[",
"name",
".",
"to_s",
"]",
"||=",
"{",
"}",
")",
"[",
"f",
"]",
"=",
"row",
".",
"field",
"\"#{name}_#{f}\"",
"end",
"end",
"end"
] | Adds configured has ones to attrs | [
"Adds",
"configured",
"has",
"ones",
"to",
"attrs"
] | aa16dd8e7dbe2202523b1a7d35a610c174c3fc21 | https://github.com/ajh/speaky_csv/blob/aa16dd8e7dbe2202523b1a7d35a610c174c3fc21/lib/speaky_csv/attr_import.rb#L102-L111 | train |
asaaki/sjekksum | lib/sjekksum/damm.rb | Sjekksum.Damm.of | def of number
raise_on_type_mismatch number
digits = convert_number_to_digits(number)
digits.reduce(0){ |check, digit| QUASIGROUP[check][digit] }
end | ruby | def of number
raise_on_type_mismatch number
digits = convert_number_to_digits(number)
digits.reduce(0){ |check, digit| QUASIGROUP[check][digit] }
end | [
"def",
"of",
"number",
"raise_on_type_mismatch",
"number",
"digits",
"=",
"convert_number_to_digits",
"(",
"number",
")",
"digits",
".",
"reduce",
"(",
"0",
")",
"{",
"|",
"check",
",",
"digit",
"|",
"QUASIGROUP",
"[",
"check",
"]",
"[",
"digit",
"]",
"}",
"end"
] | Calculates Damm checksum
@example
Sjekksum::Damm.of(572) #=> 4
@param number [Integer, String] number for which the checksum should be calculated
@return [Integer] calculated checksum | [
"Calculates",
"Damm",
"checksum"
] | 47a21c19dcffc67a3bef11d4f2de7c167fd20087 | https://github.com/asaaki/sjekksum/blob/47a21c19dcffc67a3bef11d4f2de7c167fd20087/lib/sjekksum/damm.rb#L35-L39 | train |
lsegal/yard-sitemap | lib/yard-sitemap.rb | YARD.SitemapGenerator.generate_sitemap | def generate_sitemap(basedir)
sitemap_file = File.join(basedir, 'sitemap.xml')
File.open(sitemap_file, 'w') do |file|
file.write(sitemap_contents(basedir))
end
end | ruby | def generate_sitemap(basedir)
sitemap_file = File.join(basedir, 'sitemap.xml')
File.open(sitemap_file, 'w') do |file|
file.write(sitemap_contents(basedir))
end
end | [
"def",
"generate_sitemap",
"(",
"basedir",
")",
"sitemap_file",
"=",
"File",
".",
"join",
"(",
"basedir",
",",
"'sitemap.xml'",
")",
"File",
".",
"open",
"(",
"sitemap_file",
",",
"'w'",
")",
"do",
"|",
"file",
"|",
"file",
".",
"write",
"(",
"sitemap_contents",
"(",
"basedir",
")",
")",
"end",
"end"
] | Generates a sitemap at +basedir+
@param basedir [String] the location where the sitemap should be generated | [
"Generates",
"a",
"sitemap",
"at",
"+",
"basedir",
"+"
] | 4415320713f0143a21283f0ce5ca2323fc203623 | https://github.com/lsegal/yard-sitemap/blob/4415320713f0143a21283f0ce5ca2323fc203623/lib/yard-sitemap.rb#L9-L14 | train |
billychan/simple_activity | lib/simple_activity/services/activity_processor.rb | SimpleActivity.ActivityProcessor.save | def save
if validate_attrs
Activity.create(activity_attrs).tap do |activity|
Callbacks.run(activity)
end
else
warning
end
end | ruby | def save
if validate_attrs
Activity.create(activity_attrs).tap do |activity|
Callbacks.run(activity)
end
else
warning
end
end | [
"def",
"save",
"if",
"validate_attrs",
"Activity",
".",
"create",
"(",
"activity_attrs",
")",
".",
"tap",
"do",
"|",
"activity",
"|",
"Callbacks",
".",
"run",
"(",
"activity",
")",
"end",
"else",
"warning",
"end",
"end"
] | This class is for internal usage. No need to initialize this manually,
instead use controller methods provided.
When being used as automatical way in controller, e.g. as
after_filter, supply the controller
ActivityProcessor.new(self)
If cache options needs to be attached, ensure the second argument
ActivityProcessor.new(self, nil, foo: 'bar')
When being used manually, normally the target would be provided
ActivityProcessor.new(self, @article, foo: 'bar')
@param controller [Object] The controller object, often self in controller
@param target [Object] The target instance. If nil, it will be found based on
controller.
When supplied manually, target should be free of error, aka,
after controller actiton(create, update etc) success
@param reference [Hash] When required, the second arg "target" should be
there, either object or nil
@return warning
If the target object has any error, the fact is it has not
passed validation yet. Return a warning in logger.
If there is any other errors say absence of current_user, warning
will also be returned from create_activity
@return Valid activity object from create_activity if everything okay
Return nil at this level, but not at #initialize. The reason is not to
throw error on `nil.create_activity`, for validation error of
target is common case. SimpleActivity should let it pass. | [
"This",
"class",
"is",
"for",
"internal",
"usage",
".",
"No",
"need",
"to",
"initialize",
"this",
"manually",
"instead",
"use",
"controller",
"methods",
"provided",
"."
] | fd24768908393e6aeae285834902be05c7b8ce42 | https://github.com/billychan/simple_activity/blob/fd24768908393e6aeae285834902be05c7b8ce42/lib/simple_activity/services/activity_processor.rb#L53-L61 | train |
rack-webprofiler/rack-webprofiler | lib/rack/web_profiler/request.rb | Rack.WebProfiler::Request.http_headers | def http_headers
env.select { |k, _v| (k.start_with?("HTTP_") && k != "HTTP_VERSION") || k == "CONTENT_TYPE" }
.collect { |k, v| [k.sub(/^HTTP_/, ""), v] }
.collect { |k, v| [k.split("_").collect(&:capitalize).join("-"), v] }
end | ruby | def http_headers
env.select { |k, _v| (k.start_with?("HTTP_") && k != "HTTP_VERSION") || k == "CONTENT_TYPE" }
.collect { |k, v| [k.sub(/^HTTP_/, ""), v] }
.collect { |k, v| [k.split("_").collect(&:capitalize).join("-"), v] }
end | [
"def",
"http_headers",
"env",
".",
"select",
"{",
"|",
"k",
",",
"_v",
"|",
"(",
"k",
".",
"start_with?",
"(",
"\"HTTP_\"",
")",
"&&",
"k",
"!=",
"\"HTTP_VERSION\"",
")",
"||",
"k",
"==",
"\"CONTENT_TYPE\"",
"}",
".",
"collect",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"k",
".",
"sub",
"(",
"/",
"/",
",",
"\"\"",
")",
",",
"v",
"]",
"}",
".",
"collect",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"k",
".",
"split",
"(",
"\"_\"",
")",
".",
"collect",
"(",
"&",
":capitalize",
")",
".",
"join",
"(",
"\"-\"",
")",
",",
"v",
"]",
"}",
"end"
] | Get HTTP headers.
@return [Hash] | [
"Get",
"HTTP",
"headers",
"."
] | bdb411fbb41eeddf612bbde91301ff94b3853a12 | https://github.com/rack-webprofiler/rack-webprofiler/blob/bdb411fbb41eeddf612bbde91301ff94b3853a12/lib/rack/web_profiler/request.rb#L7-L11 | train |
rack-webprofiler/rack-webprofiler | lib/rack/web_profiler/request.rb | Rack.WebProfiler::Request.raw | def raw
headers = http_headers.map { |k, v| "#{k}: #{v}\r\n" }.join
format "%s %s %s\r\n%s\r\n%s", request_method.upcase, fullpath, env["SERVER_PROTOCOL"], headers, body_string
end | ruby | def raw
headers = http_headers.map { |k, v| "#{k}: #{v}\r\n" }.join
format "%s %s %s\r\n%s\r\n%s", request_method.upcase, fullpath, env["SERVER_PROTOCOL"], headers, body_string
end | [
"def",
"raw",
"headers",
"=",
"http_headers",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"\"#{k}: #{v}\\r\\n\"",
"}",
".",
"join",
"format",
"\"%s %s %s\\r\\n%s\\r\\n%s\"",
",",
"request_method",
".",
"upcase",
",",
"fullpath",
",",
"env",
"[",
"\"SERVER_PROTOCOL\"",
"]",
",",
"headers",
",",
"body_string",
"end"
] | Get full HTTP request in HTTP format.
@return [String] | [
"Get",
"full",
"HTTP",
"request",
"in",
"HTTP",
"format",
"."
] | bdb411fbb41eeddf612bbde91301ff94b3853a12 | https://github.com/rack-webprofiler/rack-webprofiler/blob/bdb411fbb41eeddf612bbde91301ff94b3853a12/lib/rack/web_profiler/request.rb#L23-L26 | train |
jduckett/duck_map | lib/duck_map/filter_stack.rb | DuckMap.FilterStack.copy_filter | def copy_filter(filter)
buffer = {exclude: {}, include: {}}
filter[:exclude].each do |part|
buffer[:exclude][part[0]] = part[1].dup
end
filter[:include].each do |part|
buffer[:include][part[0]] = part[1].dup
end
return buffer
end | ruby | def copy_filter(filter)
buffer = {exclude: {}, include: {}}
filter[:exclude].each do |part|
buffer[:exclude][part[0]] = part[1].dup
end
filter[:include].each do |part|
buffer[:include][part[0]] = part[1].dup
end
return buffer
end | [
"def",
"copy_filter",
"(",
"filter",
")",
"buffer",
"=",
"{",
"exclude",
":",
"{",
"}",
",",
"include",
":",
"{",
"}",
"}",
"filter",
"[",
":exclude",
"]",
".",
"each",
"do",
"|",
"part",
"|",
"buffer",
"[",
":exclude",
"]",
"[",
"part",
"[",
"0",
"]",
"]",
"=",
"part",
"[",
"1",
"]",
".",
"dup",
"end",
"filter",
"[",
":include",
"]",
".",
"each",
"do",
"|",
"part",
"|",
"buffer",
"[",
":include",
"]",
"[",
"part",
"[",
"0",
"]",
"]",
"=",
"part",
"[",
"1",
"]",
".",
"dup",
"end",
"return",
"buffer",
"end"
] | Copies a filter
@return [Hash] | [
"Copies",
"a",
"filter"
] | c510acfa95e8ad4afb1501366058ae88a73704df | https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/filter_stack.rb#L41-L53 | train |
jduckett/duck_map | lib/duck_map/filter_stack.rb | DuckMap.FilterStack.clear_filter | def clear_filter(section, key)
key = key.kind_of?(Symbol) ? key : key.to_sym
self.current_filter[section][key] = []
return nil
end | ruby | def clear_filter(section, key)
key = key.kind_of?(Symbol) ? key : key.to_sym
self.current_filter[section][key] = []
return nil
end | [
"def",
"clear_filter",
"(",
"section",
",",
"key",
")",
"key",
"=",
"key",
".",
"kind_of?",
"(",
"Symbol",
")",
"?",
"key",
":",
"key",
".",
"to_sym",
"self",
".",
"current_filter",
"[",
"section",
"]",
"[",
"key",
"]",
"=",
"[",
"]",
"return",
"nil",
"end"
] | Clears a single type of filter.
@param [Symbol] section The section of filter to update. :exclude or :include.
@param [Symbol] key The key of filter to update. :actions, :verbs, :names, :controllers.
@return [Nil] | [
"Clears",
"a",
"single",
"type",
"of",
"filter",
"."
] | c510acfa95e8ad4afb1501366058ae88a73704df | https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/filter_stack.rb#L100-L104 | train |
klobuczek/active_node | lib/active_node/graph.rb | ActiveNode.Graph.many? | def many?
if block_given?
to_a.many? { |*block_args| yield(*block_args) }
else
limit_value ? to_a.many? : size > 1
end
end | ruby | def many?
if block_given?
to_a.many? { |*block_args| yield(*block_args) }
else
limit_value ? to_a.many? : size > 1
end
end | [
"def",
"many?",
"if",
"block_given?",
"to_a",
".",
"many?",
"{",
"|",
"*",
"block_args",
"|",
"yield",
"(",
"*",
"block_args",
")",
"}",
"else",
"limit_value",
"?",
"to_a",
".",
"many?",
":",
"size",
">",
"1",
"end",
"end"
] | Returns true if there is more than one record. | [
"Returns",
"true",
"if",
"there",
"is",
"more",
"than",
"one",
"record",
"."
] | c95dc0070f4565c8a72fbdf3f5534f16381d10ba | https://github.com/klobuczek/active_node/blob/c95dc0070f4565c8a72fbdf3f5534f16381d10ba/lib/active_node/graph.rb#L93-L99 | train |
sosedoff/lxc-ruby | lib/lxc/container.rb | LXC.Container.status | def status
output = run("info")
result = output.scan(/^state:\s+([\w]+)|pid:\s+(-?[\d]+)$/).flatten
LXC::Status.new(result.first, result.last)
end | ruby | def status
output = run("info")
result = output.scan(/^state:\s+([\w]+)|pid:\s+(-?[\d]+)$/).flatten
LXC::Status.new(result.first, result.last)
end | [
"def",
"status",
"output",
"=",
"run",
"(",
"\"info\"",
")",
"result",
"=",
"output",
".",
"scan",
"(",
"/",
"\\s",
"\\w",
"\\s",
"\\d",
"/",
")",
".",
"flatten",
"LXC",
"::",
"Status",
".",
"new",
"(",
"result",
".",
"first",
",",
"result",
".",
"last",
")",
"end"
] | Get current status of container
@return [Hash] hash with :state and :pid attributes | [
"Get",
"current",
"status",
"of",
"container"
] | 6d82c2ae3513789b2856d07a156e9131369f95fe | https://github.com/sosedoff/lxc-ruby/blob/6d82c2ae3513789b2856d07a156e9131369f95fe/lib/lxc/container.rb#L20-L25 | train |
sosedoff/lxc-ruby | lib/lxc/container.rb | LXC.Container.wait | def wait(state)
if !LXC::Shell.valid_state?(status.state)
raise ArgumentError, "Invalid container state: #{state}"
end
run("wait", "-s", state)
end | ruby | def wait(state)
if !LXC::Shell.valid_state?(status.state)
raise ArgumentError, "Invalid container state: #{state}"
end
run("wait", "-s", state)
end | [
"def",
"wait",
"(",
"state",
")",
"if",
"!",
"LXC",
"::",
"Shell",
".",
"valid_state?",
"(",
"status",
".",
"state",
")",
"raise",
"ArgumentError",
",",
"\"Invalid container state: #{state}\"",
"end",
"run",
"(",
"\"wait\"",
",",
"\"-s\"",
",",
"state",
")",
"end"
] | Wait for container to change status
@param [String] state name | [
"Wait",
"for",
"container",
"to",
"change",
"status"
] | 6d82c2ae3513789b2856d07a156e9131369f95fe | https://github.com/sosedoff/lxc-ruby/blob/6d82c2ae3513789b2856d07a156e9131369f95fe/lib/lxc/container.rb#L100-L106 | train |
sosedoff/lxc-ruby | lib/lxc/container.rb | LXC.Container.cpu_usage | def cpu_usage
result = run("cgroup", "cpuacct.usage").to_s.strip
result.empty? ? nil : Float("%.4f" % (result.to_i / 1E9))
end | ruby | def cpu_usage
result = run("cgroup", "cpuacct.usage").to_s.strip
result.empty? ? nil : Float("%.4f" % (result.to_i / 1E9))
end | [
"def",
"cpu_usage",
"result",
"=",
"run",
"(",
"\"cgroup\"",
",",
"\"cpuacct.usage\"",
")",
".",
"to_s",
".",
"strip",
"result",
".",
"empty?",
"?",
"nil",
":",
"Float",
"(",
"\"%.4f\"",
"%",
"(",
"result",
".",
"to_i",
"/",
"1E9",
")",
")",
"end"
] | Get container cpu usage in seconds
@return [Float] | [
"Get",
"container",
"cpu",
"usage",
"in",
"seconds"
] | 6d82c2ae3513789b2856d07a156e9131369f95fe | https://github.com/sosedoff/lxc-ruby/blob/6d82c2ae3513789b2856d07a156e9131369f95fe/lib/lxc/container.rb#L129-L132 | train |
sosedoff/lxc-ruby | lib/lxc/container.rb | LXC.Container.processes | def processes
raise ContainerError, "Container is not running" if !running?
str = run("ps", "--", "-eo pid,user,%cpu,%mem,args").strip
lines = str.split("\n") ; lines.delete_at(0)
lines.map { |l| parse_process_line(l) }
end | ruby | def processes
raise ContainerError, "Container is not running" if !running?
str = run("ps", "--", "-eo pid,user,%cpu,%mem,args").strip
lines = str.split("\n") ; lines.delete_at(0)
lines.map { |l| parse_process_line(l) }
end | [
"def",
"processes",
"raise",
"ContainerError",
",",
"\"Container is not running\"",
"if",
"!",
"running?",
"str",
"=",
"run",
"(",
"\"ps\"",
",",
"\"--\"",
",",
"\"-eo pid,user,%cpu,%mem,args\"",
")",
".",
"strip",
"lines",
"=",
"str",
".",
"split",
"(",
"\"\\n\"",
")",
";",
"lines",
".",
"delete_at",
"(",
"0",
")",
"lines",
".",
"map",
"{",
"|",
"l",
"|",
"parse_process_line",
"(",
"l",
")",
"}",
"end"
] | Get container processes
@return [Array] list of all processes | [
"Get",
"container",
"processes"
] | 6d82c2ae3513789b2856d07a156e9131369f95fe | https://github.com/sosedoff/lxc-ruby/blob/6d82c2ae3513789b2856d07a156e9131369f95fe/lib/lxc/container.rb#L136-L142 | train |
sosedoff/lxc-ruby | lib/lxc/container.rb | LXC.Container.create | def create(path)
raise ContainerError, "Container already exists." if exists?
if path.is_a?(Hash)
args = "-n #{name}"
if !!path[:config_file]
unless File.exists?(path[:config_file])
raise ArgumentError, "File #{path[:config_file]} does not exist."
end
args += " -f #{path[:config_file]}"
end
if !!path[:template]
template_dir = path[:template_dir] || "/usr/lib/lxc/templates"
template_path = File.join(template_dir,"lxc-#{path[:template]}")
unless File.exists?(template_path)
raise ArgumentError, "Template #{path[:template]} does not exist."
end
args += " -t #{path[:template]} "
end
args += " -B #{path[:backingstore]}" if !!path[:backingstore]
args += " -- #{path[:template_options].join(" ")}".strip if !!path[:template_options]
LXC.run("create", args)
exists?
else
unless File.exists?(path)
raise ArgumentError, "File #{path} does not exist."
end
LXC.run("create", "-n", name, "-f", path)
exists?
end
end | ruby | def create(path)
raise ContainerError, "Container already exists." if exists?
if path.is_a?(Hash)
args = "-n #{name}"
if !!path[:config_file]
unless File.exists?(path[:config_file])
raise ArgumentError, "File #{path[:config_file]} does not exist."
end
args += " -f #{path[:config_file]}"
end
if !!path[:template]
template_dir = path[:template_dir] || "/usr/lib/lxc/templates"
template_path = File.join(template_dir,"lxc-#{path[:template]}")
unless File.exists?(template_path)
raise ArgumentError, "Template #{path[:template]} does not exist."
end
args += " -t #{path[:template]} "
end
args += " -B #{path[:backingstore]}" if !!path[:backingstore]
args += " -- #{path[:template_options].join(" ")}".strip if !!path[:template_options]
LXC.run("create", args)
exists?
else
unless File.exists?(path)
raise ArgumentError, "File #{path} does not exist."
end
LXC.run("create", "-n", name, "-f", path)
exists?
end
end | [
"def",
"create",
"(",
"path",
")",
"raise",
"ContainerError",
",",
"\"Container already exists.\"",
"if",
"exists?",
"if",
"path",
".",
"is_a?",
"(",
"Hash",
")",
"args",
"=",
"\"-n #{name}\"",
"if",
"!",
"!",
"path",
"[",
":config_file",
"]",
"unless",
"File",
".",
"exists?",
"(",
"path",
"[",
":config_file",
"]",
")",
"raise",
"ArgumentError",
",",
"\"File #{path[:config_file]} does not exist.\"",
"end",
"args",
"+=",
"\" -f #{path[:config_file]}\"",
"end",
"if",
"!",
"!",
"path",
"[",
":template",
"]",
"template_dir",
"=",
"path",
"[",
":template_dir",
"]",
"||",
"\"/usr/lib/lxc/templates\"",
"template_path",
"=",
"File",
".",
"join",
"(",
"template_dir",
",",
"\"lxc-#{path[:template]}\"",
")",
"unless",
"File",
".",
"exists?",
"(",
"template_path",
")",
"raise",
"ArgumentError",
",",
"\"Template #{path[:template]} does not exist.\"",
"end",
"args",
"+=",
"\" -t #{path[:template]} \"",
"end",
"args",
"+=",
"\" -B #{path[:backingstore]}\"",
"if",
"!",
"!",
"path",
"[",
":backingstore",
"]",
"args",
"+=",
"\" -- #{path[:template_options].join(\" \")}\"",
".",
"strip",
"if",
"!",
"!",
"path",
"[",
":template_options",
"]",
"LXC",
".",
"run",
"(",
"\"create\"",
",",
"args",
")",
"exists?",
"else",
"unless",
"File",
".",
"exists?",
"(",
"path",
")",
"raise",
"ArgumentError",
",",
"\"File #{path} does not exist.\"",
"end",
"LXC",
".",
"run",
"(",
"\"create\"",
",",
"\"-n\"",
",",
"name",
",",
"\"-f\"",
",",
"path",
")",
"exists?",
"end",
"end"
] | Create a new container
@param [String] path path to container config file or [Hash] options
@return [Boolean] | [
"Create",
"a",
"new",
"container"
] | 6d82c2ae3513789b2856d07a156e9131369f95fe | https://github.com/sosedoff/lxc-ruby/blob/6d82c2ae3513789b2856d07a156e9131369f95fe/lib/lxc/container.rb#L147-L182 | train |
sosedoff/lxc-ruby | lib/lxc/container.rb | LXC.Container.clone_to | def clone_to(target)
raise ContainerError, "Container does not exist." unless exists?
if LXC.container(target).exists?
raise ContainerError, "New container already exists."
end
LXC.run("clone", "-o", name, "-n", target)
LXC.container(target)
end | ruby | def clone_to(target)
raise ContainerError, "Container does not exist." unless exists?
if LXC.container(target).exists?
raise ContainerError, "New container already exists."
end
LXC.run("clone", "-o", name, "-n", target)
LXC.container(target)
end | [
"def",
"clone_to",
"(",
"target",
")",
"raise",
"ContainerError",
",",
"\"Container does not exist.\"",
"unless",
"exists?",
"if",
"LXC",
".",
"container",
"(",
"target",
")",
".",
"exists?",
"raise",
"ContainerError",
",",
"\"New container already exists.\"",
"end",
"LXC",
".",
"run",
"(",
"\"clone\"",
",",
"\"-o\"",
",",
"name",
",",
"\"-n\"",
",",
"target",
")",
"LXC",
".",
"container",
"(",
"target",
")",
"end"
] | Clone to a new container from self
@param [String] target name of new container
@return [LXC::Container] new container instance | [
"Clone",
"to",
"a",
"new",
"container",
"from",
"self"
] | 6d82c2ae3513789b2856d07a156e9131369f95fe | https://github.com/sosedoff/lxc-ruby/blob/6d82c2ae3513789b2856d07a156e9131369f95fe/lib/lxc/container.rb#L187-L196 | train |
sosedoff/lxc-ruby | lib/lxc/container.rb | LXC.Container.clone_from | def clone_from(source)
raise ContainerError, "Container already exists." if exists?
unless LXC.container(source).exists?
raise ContainerError, "Source container does not exist."
end
run("clone", "-o", source)
exists?
end | ruby | def clone_from(source)
raise ContainerError, "Container already exists." if exists?
unless LXC.container(source).exists?
raise ContainerError, "Source container does not exist."
end
run("clone", "-o", source)
exists?
end | [
"def",
"clone_from",
"(",
"source",
")",
"raise",
"ContainerError",
",",
"\"Container already exists.\"",
"if",
"exists?",
"unless",
"LXC",
".",
"container",
"(",
"source",
")",
".",
"exists?",
"raise",
"ContainerError",
",",
"\"Source container does not exist.\"",
"end",
"run",
"(",
"\"clone\"",
",",
"\"-o\"",
",",
"source",
")",
"exists?",
"end"
] | Create a new container from an existing container
@param [String] source name of existing container
@return [Boolean] | [
"Create",
"a",
"new",
"container",
"from",
"an",
"existing",
"container"
] | 6d82c2ae3513789b2856d07a156e9131369f95fe | https://github.com/sosedoff/lxc-ruby/blob/6d82c2ae3513789b2856d07a156e9131369f95fe/lib/lxc/container.rb#L201-L210 | train |
willfore/cp_mgmt_ruby | lib/cp_mgmt/host.rb | CpMgmt.Host.add | def add(name, ip_address, options={})
client = CpMgmt.configuration.client
CpMgmt.logged_in?
params = {name: name, "ip-address": ip_address}
body = params.merge(options).to_json
response = client.post do |req|
req.url '/web_api/add-host'
req.headers['Content-Type'] = 'application/json'
req.headers['X-chkp-sid'] = ENV.fetch("sid")
req.body = body
end
CpMgmt.transform_response(response)
end | ruby | def add(name, ip_address, options={})
client = CpMgmt.configuration.client
CpMgmt.logged_in?
params = {name: name, "ip-address": ip_address}
body = params.merge(options).to_json
response = client.post do |req|
req.url '/web_api/add-host'
req.headers['Content-Type'] = 'application/json'
req.headers['X-chkp-sid'] = ENV.fetch("sid")
req.body = body
end
CpMgmt.transform_response(response)
end | [
"def",
"add",
"(",
"name",
",",
"ip_address",
",",
"options",
"=",
"{",
"}",
")",
"client",
"=",
"CpMgmt",
".",
"configuration",
".",
"client",
"CpMgmt",
".",
"logged_in?",
"params",
"=",
"{",
"name",
":",
"name",
",",
"\"ip-address\"",
":",
"ip_address",
"}",
"body",
"=",
"params",
".",
"merge",
"(",
"options",
")",
".",
"to_json",
"response",
"=",
"client",
".",
"post",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"'/web_api/add-host'",
"req",
".",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/json'",
"req",
".",
"headers",
"[",
"'X-chkp-sid'",
"]",
"=",
"ENV",
".",
"fetch",
"(",
"\"sid\"",
")",
"req",
".",
"body",
"=",
"body",
"end",
"CpMgmt",
".",
"transform_response",
"(",
"response",
")",
"end"
] | Adds a host | [
"Adds",
"a",
"host"
] | d25f169561f254bd13cc6fa5afa6b362637c1f65 | https://github.com/willfore/cp_mgmt_ruby/blob/d25f169561f254bd13cc6fa5afa6b362637c1f65/lib/cp_mgmt/host.rb#L4-L17 | train |
willfore/cp_mgmt_ruby | lib/cp_mgmt/host.rb | CpMgmt.Host.show | def show(name)
client = CpMgmt.configuration.client
CpMgmt.logged_in?
body = {name: name}.to_json
response = client.post do |req|
req.url '/web_api/show-host'
req.headers['Content-Type'] = 'application/json'
req.headers['X-chkp-sid'] = ENV.fetch("sid")
req.body = body
end
CpMgmt.transform_response(response)
end | ruby | def show(name)
client = CpMgmt.configuration.client
CpMgmt.logged_in?
body = {name: name}.to_json
response = client.post do |req|
req.url '/web_api/show-host'
req.headers['Content-Type'] = 'application/json'
req.headers['X-chkp-sid'] = ENV.fetch("sid")
req.body = body
end
CpMgmt.transform_response(response)
end | [
"def",
"show",
"(",
"name",
")",
"client",
"=",
"CpMgmt",
".",
"configuration",
".",
"client",
"CpMgmt",
".",
"logged_in?",
"body",
"=",
"{",
"name",
":",
"name",
"}",
".",
"to_json",
"response",
"=",
"client",
".",
"post",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"'/web_api/show-host'",
"req",
".",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/json'",
"req",
".",
"headers",
"[",
"'X-chkp-sid'",
"]",
"=",
"ENV",
".",
"fetch",
"(",
"\"sid\"",
")",
"req",
".",
"body",
"=",
"body",
"end",
"CpMgmt",
".",
"transform_response",
"(",
"response",
")",
"end"
] | Shows a host | [
"Shows",
"a",
"host"
] | d25f169561f254bd13cc6fa5afa6b362637c1f65 | https://github.com/willfore/cp_mgmt_ruby/blob/d25f169561f254bd13cc6fa5afa6b362637c1f65/lib/cp_mgmt/host.rb#L35-L47 | train |
willfore/cp_mgmt_ruby | lib/cp_mgmt/host.rb | CpMgmt.Host.show_all | def show_all
client = CpMgmt.configuration.client
CpMgmt.logged_in?
response = client.post do |req|
req.url '/web_api/show-hosts'
req.headers['Content-Type'] = 'application/json'
req.headers['X-chkp-sid'] = ENV.fetch("sid")
req.body = "{}"
end
CpMgmt.transform_response(response)
end | ruby | def show_all
client = CpMgmt.configuration.client
CpMgmt.logged_in?
response = client.post do |req|
req.url '/web_api/show-hosts'
req.headers['Content-Type'] = 'application/json'
req.headers['X-chkp-sid'] = ENV.fetch("sid")
req.body = "{}"
end
CpMgmt.transform_response(response)
end | [
"def",
"show_all",
"client",
"=",
"CpMgmt",
".",
"configuration",
".",
"client",
"CpMgmt",
".",
"logged_in?",
"response",
"=",
"client",
".",
"post",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"'/web_api/show-hosts'",
"req",
".",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/json'",
"req",
".",
"headers",
"[",
"'X-chkp-sid'",
"]",
"=",
"ENV",
".",
"fetch",
"(",
"\"sid\"",
")",
"req",
".",
"body",
"=",
"\"{}\"",
"end",
"CpMgmt",
".",
"transform_response",
"(",
"response",
")",
"end"
] | Shows all hosts | [
"Shows",
"all",
"hosts"
] | d25f169561f254bd13cc6fa5afa6b362637c1f65 | https://github.com/willfore/cp_mgmt_ruby/blob/d25f169561f254bd13cc6fa5afa6b362637c1f65/lib/cp_mgmt/host.rb#L50-L61 | train |
jarhart/rattler | lib/rattler/runtime/extended_packrat_parser.rb | Rattler::Runtime.ExtendedPackratParser.apply | def apply(match_method_name)
start_pos = @scanner.pos
if m = memo_lr(match_method_name, start_pos)
recall m, match_method_name
else
lr = LR.new(false, match_method_name, nil)
@lr_stack.push lr
m = inject_memo match_method_name, start_pos, lr, start_pos
result = eval_rule match_method_name
@lr_stack.pop
if lr.head
m.end_pos = @scanner.pos
lr.seed = result
lr_answer match_method_name, start_pos, m
else
save m, result
end
end
end | ruby | def apply(match_method_name)
start_pos = @scanner.pos
if m = memo_lr(match_method_name, start_pos)
recall m, match_method_name
else
lr = LR.new(false, match_method_name, nil)
@lr_stack.push lr
m = inject_memo match_method_name, start_pos, lr, start_pos
result = eval_rule match_method_name
@lr_stack.pop
if lr.head
m.end_pos = @scanner.pos
lr.seed = result
lr_answer match_method_name, start_pos, m
else
save m, result
end
end
end | [
"def",
"apply",
"(",
"match_method_name",
")",
"start_pos",
"=",
"@scanner",
".",
"pos",
"if",
"m",
"=",
"memo_lr",
"(",
"match_method_name",
",",
"start_pos",
")",
"recall",
"m",
",",
"match_method_name",
"else",
"lr",
"=",
"LR",
".",
"new",
"(",
"false",
",",
"match_method_name",
",",
"nil",
")",
"@lr_stack",
".",
"push",
"lr",
"m",
"=",
"inject_memo",
"match_method_name",
",",
"start_pos",
",",
"lr",
",",
"start_pos",
"result",
"=",
"eval_rule",
"match_method_name",
"@lr_stack",
".",
"pop",
"if",
"lr",
".",
"head",
"m",
".",
"end_pos",
"=",
"@scanner",
".",
"pos",
"lr",
".",
"seed",
"=",
"result",
"lr_answer",
"match_method_name",
",",
"start_pos",
",",
"m",
"else",
"save",
"m",
",",
"result",
"end",
"end",
"end"
] | Create a new extended packrat parser to parse +source+.
@param (see PackratParser#initialize)
@option (see PackratParser#initialize)
Apply a rule by dispatching to the given match method. The result of
applying the rule is memoized so that the match method is invoked at most
once at a given parse position. Left-recursion is detected and parsed
correctly.
@param (see PackratParser#apply)
@return (see PackratParser#apply) | [
"Create",
"a",
"new",
"extended",
"packrat",
"parser",
"to",
"parse",
"+",
"source",
"+",
"."
] | 8b4efde2a05e9e790955bb635d4a1a9615893719 | https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/runtime/extended_packrat_parser.rb#L29-L47 | train |
carboncalculated/calculated | lib/calculated/object_template_api_calls.rb | Calculated.ObjectTemplateApiCalls.generic_objects_for_object_template | def generic_objects_for_object_template(name, params = {})
api_call(:get, "/object_templates/#{name}/generic_objects", params) do |response|
Calculated::Models::ObjectTemplate.new(response["object_template"])
end
end | ruby | def generic_objects_for_object_template(name, params = {})
api_call(:get, "/object_templates/#{name}/generic_objects", params) do |response|
Calculated::Models::ObjectTemplate.new(response["object_template"])
end
end | [
"def",
"generic_objects_for_object_template",
"(",
"name",
",",
"params",
"=",
"{",
"}",
")",
"api_call",
"(",
":get",
",",
"\"/object_templates/#{name}/generic_objects\"",
",",
"params",
")",
"do",
"|",
"response",
"|",
"Calculated",
"::",
"Models",
"::",
"ObjectTemplate",
".",
"new",
"(",
"response",
"[",
"\"object_template\"",
"]",
")",
"end",
"end"
] | this request will have loaded generic objects for the ready basically
@param [String] name
@param [Hash] params
@return [Calculated::Models::ObjectTemplate] | [
"this",
"request",
"will",
"have",
"loaded",
"generic",
"objects",
"for",
"the",
"ready",
"basically"
] | 0234d89b515db26add000f88c594f6d3fb5edd5e | https://github.com/carboncalculated/calculated/blob/0234d89b515db26add000f88c594f6d3fb5edd5e/lib/calculated/object_template_api_calls.rb#L27-L31 | train |
carboncalculated/calculated | lib/calculated/object_template_api_calls.rb | Calculated.ObjectTemplateApiCalls.relatable_categories_for_object_template | def relatable_categories_for_object_template(name, related_attribute, params = {})
api_call(:get, "/object_templates/#{name}/relatable_categories", params.merge!(:related_attribute => related_attribute)) do |response|
Calculated::Models::ObjectTemplate.new(response["object_template"])
end
end | ruby | def relatable_categories_for_object_template(name, related_attribute, params = {})
api_call(:get, "/object_templates/#{name}/relatable_categories", params.merge!(:related_attribute => related_attribute)) do |response|
Calculated::Models::ObjectTemplate.new(response["object_template"])
end
end | [
"def",
"relatable_categories_for_object_template",
"(",
"name",
",",
"related_attribute",
",",
"params",
"=",
"{",
"}",
")",
"api_call",
"(",
":get",
",",
"\"/object_templates/#{name}/relatable_categories\"",
",",
"params",
".",
"merge!",
"(",
":related_attribute",
"=>",
"related_attribute",
")",
")",
"do",
"|",
"response",
"|",
"Calculated",
"::",
"Models",
"::",
"ObjectTemplate",
".",
"new",
"(",
"response",
"[",
"\"object_template\"",
"]",
")",
"end",
"end"
] | this request will have loaded relatable categories for the object template
@param [String] related_attribute
@param [String] name
@param [Hash] params
@return [Calculated::Models::ObjectTemplate] | [
"this",
"request",
"will",
"have",
"loaded",
"relatable",
"categories",
"for",
"the",
"object",
"template"
] | 0234d89b515db26add000f88c594f6d3fb5edd5e | https://github.com/carboncalculated/calculated/blob/0234d89b515db26add000f88c594f6d3fb5edd5e/lib/calculated/object_template_api_calls.rb#L38-L42 | train |
carboncalculated/calculated | lib/calculated/object_template_api_calls.rb | Calculated.ObjectTemplateApiCalls.generic_objects_for_object_template_with_filter | def generic_objects_for_object_template_with_filter(name, filter, params = {})
api_call(:get, "/object_templates/#{name}/generic_objects/filter", params.merge!(:filter => filter)) do |response|
Calculated::Models::ObjectTemplate.new(response["object_template"])
end
end | ruby | def generic_objects_for_object_template_with_filter(name, filter, params = {})
api_call(:get, "/object_templates/#{name}/generic_objects/filter", params.merge!(:filter => filter)) do |response|
Calculated::Models::ObjectTemplate.new(response["object_template"])
end
end | [
"def",
"generic_objects_for_object_template_with_filter",
"(",
"name",
",",
"filter",
",",
"params",
"=",
"{",
"}",
")",
"api_call",
"(",
":get",
",",
"\"/object_templates/#{name}/generic_objects/filter\"",
",",
"params",
".",
"merge!",
"(",
":filter",
"=>",
"filter",
")",
")",
"do",
"|",
"response",
"|",
"Calculated",
"::",
"Models",
"::",
"ObjectTemplate",
".",
"new",
"(",
"response",
"[",
"\"object_template\"",
"]",
")",
"end",
"end"
] | This will filter the results of the generic objects from a simple text search
note this is not an expancive text search so limit to 1 word searches for best
results
@example
generic_objects_for_object_template_with_filter('airport', 'london')
There is also the usuage of relatable_category_values with the params
this will allow further filtering on the search its an AND Filter not an OR filter
@example
searching for ford diesel cars for example
generic_objects_for_object_template_with_filter('car', 'diesel', :relatable_category_values => ["ford"])
this request will have loaded relatable categories for the object template
@param [String] name
@param [String] filter
@param [Hash] params
@return [Calculated::Models::GeneriObject] | [
"This",
"will",
"filter",
"the",
"results",
"of",
"the",
"generic",
"objects",
"from",
"a",
"simple",
"text",
"search",
"note",
"this",
"is",
"not",
"an",
"expancive",
"text",
"search",
"so",
"limit",
"to",
"1",
"word",
"searches",
"for",
"best",
"results"
] | 0234d89b515db26add000f88c594f6d3fb5edd5e | https://github.com/carboncalculated/calculated/blob/0234d89b515db26add000f88c594f6d3fb5edd5e/lib/calculated/object_template_api_calls.rb#L64-L68 | train |
postmodern/rprogram | lib/rprogram/program.rb | RProgram.Program.sudo | def sudo(*arguments)
options = case arguments.last
when Hash then arguments.pop
else {}
end
task = SudoTask.new(options.delete(:sudo) || {})
task.command = [@path] + arguments
arguments = task.arguments
arguments << options unless options.empty?
return System.sudo(*arguments)
end | ruby | def sudo(*arguments)
options = case arguments.last
when Hash then arguments.pop
else {}
end
task = SudoTask.new(options.delete(:sudo) || {})
task.command = [@path] + arguments
arguments = task.arguments
arguments << options unless options.empty?
return System.sudo(*arguments)
end | [
"def",
"sudo",
"(",
"*",
"arguments",
")",
"options",
"=",
"case",
"arguments",
".",
"last",
"when",
"Hash",
"then",
"arguments",
".",
"pop",
"else",
"{",
"}",
"end",
"task",
"=",
"SudoTask",
".",
"new",
"(",
"options",
".",
"delete",
"(",
":sudo",
")",
"||",
"{",
"}",
")",
"task",
".",
"command",
"=",
"[",
"@path",
"]",
"+",
"arguments",
"arguments",
"=",
"task",
".",
"arguments",
"arguments",
"<<",
"options",
"unless",
"options",
".",
"empty?",
"return",
"System",
".",
"sudo",
"(",
"*",
"arguments",
")",
"end"
] | Runs the program under sudo.
@overload sudo(*arguments)
Run the program under `sudo` with the given arguments.
@param [Array] arguments
Additional arguments to run the program with.
@overload sudo(*arguments,options)
Run the program under `sudo` with the given arguments
and options.
@param [Array] arguments
Additional arguments to run the program with.
@param [Hash] options
Additional options to execute the program with.
@option options [Hash{Symbol => Object}] :sudo
Additional `sudo` options.
@return [Boolean]
Specifies whether the program exited successfully.
@raise [ProgramNotFound]
Indicates that the `sudo` program could not be located.
@since 0.1.8
@see http://rubydoc.info/stdlib/core/1.9.2/Kernel#spawn-instance_method
For acceptable options.
@see SudoTask
For valid `:sudo` options. | [
"Runs",
"the",
"program",
"under",
"sudo",
"."
] | 94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be | https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/program.rb#L341-L354 | train |
postmodern/rprogram | lib/rprogram/program.rb | RProgram.Program.run_task | def run_task(task,options={})
arguments = task.arguments
arguments << options unless options.empty?
return run(*arguments)
end | ruby | def run_task(task,options={})
arguments = task.arguments
arguments << options unless options.empty?
return run(*arguments)
end | [
"def",
"run_task",
"(",
"task",
",",
"options",
"=",
"{",
"}",
")",
"arguments",
"=",
"task",
".",
"arguments",
"arguments",
"<<",
"options",
"unless",
"options",
".",
"empty?",
"return",
"run",
"(",
"*",
"arguments",
")",
"end"
] | Runs the program with the arguments from the given task.
@param [Task, #to_a] task
The task who's arguments will be used to run the program.
@param [Hash] options
Additional options to execute the program with.
@return [true, false]
Specifies the exit status of the program.
@see #run | [
"Runs",
"the",
"program",
"with",
"the",
"arguments",
"from",
"the",
"given",
"task",
"."
] | 94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be | https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/program.rb#L370-L375 | train |
postmodern/rprogram | lib/rprogram/program.rb | RProgram.Program.sudo_task | def sudo_task(task,options={},&block)
arguments = task.arguments
arguments << options unless options.empty?
return sudo(*arguments,&block)
end | ruby | def sudo_task(task,options={},&block)
arguments = task.arguments
arguments << options unless options.empty?
return sudo(*arguments,&block)
end | [
"def",
"sudo_task",
"(",
"task",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"arguments",
"=",
"task",
".",
"arguments",
"arguments",
"<<",
"options",
"unless",
"options",
".",
"empty?",
"return",
"sudo",
"(",
"*",
"arguments",
",",
"&",
"block",
")",
"end"
] | Runs the program under `sudo` with the arguments from the given task.
@param [Task, #to_a] task
The task who's arguments will be used to run the program.
@param [Hash] options
Spawn options for the program to be ran.
@yield [sudo]
If a block is given, it will be passed the sudo task.
@yieldparam [SudoTask] sudo
The sudo tasks.
@return [true, false]
Specifies the exit status of the program.
@see #sudo
@since 0.3.0 | [
"Runs",
"the",
"program",
"under",
"sudo",
"with",
"the",
"arguments",
"from",
"the",
"given",
"task",
"."
] | 94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be | https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/program.rb#L399-L404 | train |
jduckett/duck_map | lib/duck_map/mapper.rb | DuckMap.Mapper.sitemap | def sitemap(name = :sitemap, options = {}, &block)
options = name.kind_of?(Hash) ? name : options
name = name.kind_of?(String) || name.kind_of?(Symbol) ? name : :sitemap
config = {controller: :sitemap, url_limit: nil}.merge(options)
sitemap_raw_route_name = "#{name}_sitemap"
sitemap_route_name = name_for_action(sitemap_raw_route_name, nil)
begin
unless @set.routes.find {|route| route.name.eql?(sitemap_route_name)}
# create a route for the sitemap using the name that was passed to the sitemap method inside config/routes.
match %(/#{name}.:format), controller: config[:controller], action: name, via: [:get], as: sitemap_raw_route_name
# if not found here, then, there must be a real problem.
# later, i will implement an exception, etc.
sitemap_route = @set.routes.find {|route| route.name.eql?(sitemap_route_name)}
# identify the route as a "sitemap" route and build it's full name.
sitemap_route.is_sitemap = true
sitemap_route.url_limit = config[:url_limit]
sitemap_route.sitemap_route_name = sitemap_route_name
sitemap_route.sitemap_raw_route_name = sitemap_raw_route_name
# this is how I am faking to always point to the SitemapController
# regardless of namespace
sitemap_route.defaults[:controller] = "sitemap"
end
rescue ArgumentError => e
unless e.message.include?("Invalid route name")
raise e
end
end
# now, find the route again, because, we need to set the following boolean and there might be several
# calls to sitemap without a block. if we were to set this boolean in the code above when checking
# if the route already exists, then, the boolean may never be set.
sitemap_route = @set.routes.find {|route| route.is_sitemap? && route.name.eql?(sitemap_route_name) }
# once a sitemap route has been flagged as being defined with a block, then, you should never set it back to false.
# one of the features is to be able to encapsulate a set of routes within a sitemap as many times as you need.
# meaning, you might want to wrap five routes at the top of the file, three in the middle, and two at the bottom and
# have all of them included in the default sitemap.
# Since all routes within a sitemap block will be marked with the same name,
# I am not keeping track of sitemaps being defined with or without a block, so, all I need to know is about one of them.
unless sitemap_route.sitemap_with_block?
sitemap_route.sitemap_with_block = true if block_given?
end
# DuckMap::SitemapControllerHelpers is a module that is included in SitemapBaseController and contains
# methods such as sitemap_build, etc. Define a method to handle the sitemap on DuckMap::SitemapControllerHelpers
# so that method is visible to the default sitemap controller as well as any custom controllers that inherit from it.
# originally, I was simply defining the method directly on SitemapBaseController, however, it was causing problems
# during the development cycle of edit and refresh. Defining methods here seemed to cure that problem.
# for example, the default sitemap: /sitemap.xml will define a method named: sitemap
# on the DuckMap::SitemapControllerHelpers module.
unless DuckMap::SitemapControllerHelpers.public_method_defined?(name)
DuckMap::SitemapControllerHelpers.send :define_method, name do
if DuckMap::Config.attributes[:sitemap_content].eql?(:xml)
sitemap_build
end
respond_to do |format|
format.xml { render }
end
end
end
# determine if the sitemap definition included a block.
if block_given?
# the starting point would be after the current set of routes and would be length plus one.
# however, the starting point index is the length of routes, since arrays are zero based.
start_point = @set.routes.length
# push a copy of the current filter settings onto an array.
# this will allow you to specify criteria setting within a sitemap definition without affecting
# the default settings after the block is finished executing.
@set.sitemap_filters.push
# yield to the block. all standard route code should execute just fine and define namespaces, resource, matches, etc.
yield
total = run_filter(sitemap_route.sitemap_route_name, start_point)
# knock the current filter setting off of the stack
@set.sitemap_filters.pop
DuckMap.logger.debug %(total routes filtered: #{@set.routes.length - start_point} included? #{total})
@set.routes.each do |route|
DuckMap.logger.debug %( Route name: #{route.name}) if route.sitemap_route_name.eql?(sitemap_route.sitemap_route_name)
end
end
return nil
end | ruby | def sitemap(name = :sitemap, options = {}, &block)
options = name.kind_of?(Hash) ? name : options
name = name.kind_of?(String) || name.kind_of?(Symbol) ? name : :sitemap
config = {controller: :sitemap, url_limit: nil}.merge(options)
sitemap_raw_route_name = "#{name}_sitemap"
sitemap_route_name = name_for_action(sitemap_raw_route_name, nil)
begin
unless @set.routes.find {|route| route.name.eql?(sitemap_route_name)}
# create a route for the sitemap using the name that was passed to the sitemap method inside config/routes.
match %(/#{name}.:format), controller: config[:controller], action: name, via: [:get], as: sitemap_raw_route_name
# if not found here, then, there must be a real problem.
# later, i will implement an exception, etc.
sitemap_route = @set.routes.find {|route| route.name.eql?(sitemap_route_name)}
# identify the route as a "sitemap" route and build it's full name.
sitemap_route.is_sitemap = true
sitemap_route.url_limit = config[:url_limit]
sitemap_route.sitemap_route_name = sitemap_route_name
sitemap_route.sitemap_raw_route_name = sitemap_raw_route_name
# this is how I am faking to always point to the SitemapController
# regardless of namespace
sitemap_route.defaults[:controller] = "sitemap"
end
rescue ArgumentError => e
unless e.message.include?("Invalid route name")
raise e
end
end
# now, find the route again, because, we need to set the following boolean and there might be several
# calls to sitemap without a block. if we were to set this boolean in the code above when checking
# if the route already exists, then, the boolean may never be set.
sitemap_route = @set.routes.find {|route| route.is_sitemap? && route.name.eql?(sitemap_route_name) }
# once a sitemap route has been flagged as being defined with a block, then, you should never set it back to false.
# one of the features is to be able to encapsulate a set of routes within a sitemap as many times as you need.
# meaning, you might want to wrap five routes at the top of the file, three in the middle, and two at the bottom and
# have all of them included in the default sitemap.
# Since all routes within a sitemap block will be marked with the same name,
# I am not keeping track of sitemaps being defined with or without a block, so, all I need to know is about one of them.
unless sitemap_route.sitemap_with_block?
sitemap_route.sitemap_with_block = true if block_given?
end
# DuckMap::SitemapControllerHelpers is a module that is included in SitemapBaseController and contains
# methods such as sitemap_build, etc. Define a method to handle the sitemap on DuckMap::SitemapControllerHelpers
# so that method is visible to the default sitemap controller as well as any custom controllers that inherit from it.
# originally, I was simply defining the method directly on SitemapBaseController, however, it was causing problems
# during the development cycle of edit and refresh. Defining methods here seemed to cure that problem.
# for example, the default sitemap: /sitemap.xml will define a method named: sitemap
# on the DuckMap::SitemapControllerHelpers module.
unless DuckMap::SitemapControllerHelpers.public_method_defined?(name)
DuckMap::SitemapControllerHelpers.send :define_method, name do
if DuckMap::Config.attributes[:sitemap_content].eql?(:xml)
sitemap_build
end
respond_to do |format|
format.xml { render }
end
end
end
# determine if the sitemap definition included a block.
if block_given?
# the starting point would be after the current set of routes and would be length plus one.
# however, the starting point index is the length of routes, since arrays are zero based.
start_point = @set.routes.length
# push a copy of the current filter settings onto an array.
# this will allow you to specify criteria setting within a sitemap definition without affecting
# the default settings after the block is finished executing.
@set.sitemap_filters.push
# yield to the block. all standard route code should execute just fine and define namespaces, resource, matches, etc.
yield
total = run_filter(sitemap_route.sitemap_route_name, start_point)
# knock the current filter setting off of the stack
@set.sitemap_filters.pop
DuckMap.logger.debug %(total routes filtered: #{@set.routes.length - start_point} included? #{total})
@set.routes.each do |route|
DuckMap.logger.debug %( Route name: #{route.name}) if route.sitemap_route_name.eql?(sitemap_route.sitemap_route_name)
end
end
return nil
end | [
"def",
"sitemap",
"(",
"name",
"=",
":sitemap",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"options",
"=",
"name",
".",
"kind_of?",
"(",
"Hash",
")",
"?",
"name",
":",
"options",
"name",
"=",
"name",
".",
"kind_of?",
"(",
"String",
")",
"||",
"name",
".",
"kind_of?",
"(",
"Symbol",
")",
"?",
"name",
":",
":sitemap",
"config",
"=",
"{",
"controller",
":",
":sitemap",
",",
"url_limit",
":",
"nil",
"}",
".",
"merge",
"(",
"options",
")",
"sitemap_raw_route_name",
"=",
"\"#{name}_sitemap\"",
"sitemap_route_name",
"=",
"name_for_action",
"(",
"sitemap_raw_route_name",
",",
"nil",
")",
"begin",
"unless",
"@set",
".",
"routes",
".",
"find",
"{",
"|",
"route",
"|",
"route",
".",
"name",
".",
"eql?",
"(",
"sitemap_route_name",
")",
"}",
"match",
"%(/#{name}.:format)",
",",
"controller",
":",
"config",
"[",
":controller",
"]",
",",
"action",
":",
"name",
",",
"via",
":",
"[",
":get",
"]",
",",
"as",
":",
"sitemap_raw_route_name",
"sitemap_route",
"=",
"@set",
".",
"routes",
".",
"find",
"{",
"|",
"route",
"|",
"route",
".",
"name",
".",
"eql?",
"(",
"sitemap_route_name",
")",
"}",
"sitemap_route",
".",
"is_sitemap",
"=",
"true",
"sitemap_route",
".",
"url_limit",
"=",
"config",
"[",
":url_limit",
"]",
"sitemap_route",
".",
"sitemap_route_name",
"=",
"sitemap_route_name",
"sitemap_route",
".",
"sitemap_raw_route_name",
"=",
"sitemap_raw_route_name",
"sitemap_route",
".",
"defaults",
"[",
":controller",
"]",
"=",
"\"sitemap\"",
"end",
"rescue",
"ArgumentError",
"=>",
"e",
"unless",
"e",
".",
"message",
".",
"include?",
"(",
"\"Invalid route name\"",
")",
"raise",
"e",
"end",
"end",
"sitemap_route",
"=",
"@set",
".",
"routes",
".",
"find",
"{",
"|",
"route",
"|",
"route",
".",
"is_sitemap?",
"&&",
"route",
".",
"name",
".",
"eql?",
"(",
"sitemap_route_name",
")",
"}",
"unless",
"sitemap_route",
".",
"sitemap_with_block?",
"sitemap_route",
".",
"sitemap_with_block",
"=",
"true",
"if",
"block_given?",
"end",
"unless",
"DuckMap",
"::",
"SitemapControllerHelpers",
".",
"public_method_defined?",
"(",
"name",
")",
"DuckMap",
"::",
"SitemapControllerHelpers",
".",
"send",
":define_method",
",",
"name",
"do",
"if",
"DuckMap",
"::",
"Config",
".",
"attributes",
"[",
":sitemap_content",
"]",
".",
"eql?",
"(",
":xml",
")",
"sitemap_build",
"end",
"respond_to",
"do",
"|",
"format",
"|",
"format",
".",
"xml",
"{",
"render",
"}",
"end",
"end",
"end",
"if",
"block_given?",
"start_point",
"=",
"@set",
".",
"routes",
".",
"length",
"@set",
".",
"sitemap_filters",
".",
"push",
"yield",
"total",
"=",
"run_filter",
"(",
"sitemap_route",
".",
"sitemap_route_name",
",",
"start_point",
")",
"@set",
".",
"sitemap_filters",
".",
"pop",
"DuckMap",
".",
"logger",
".",
"debug",
"%(total routes filtered: #{@set.routes.length - start_point} included? #{total})",
"@set",
".",
"routes",
".",
"each",
"do",
"|",
"route",
"|",
"DuckMap",
".",
"logger",
".",
"debug",
"%( Route name: #{route.name})",
"if",
"route",
".",
"sitemap_route_name",
".",
"eql?",
"(",
"sitemap_route",
".",
"sitemap_route_name",
")",
"end",
"end",
"return",
"nil",
"end"
] | Defines a sitemap for a Rails app.
You can find a few examples and apps at:
- (http://www.jeffduckett.com/blog/11/defining-rails-3-x-sitemaps-using-duckmap.html)
- (http://www.jeffduckett.com/blog/12/multiple-sitemap-definitions.html)
@return [Nil] | [
"Defines",
"a",
"sitemap",
"for",
"a",
"Rails",
"app",
"."
] | c510acfa95e8ad4afb1501366058ae88a73704df | https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/mapper.rb#L21-L124 | train |
medcat/packed_struct | lib/packed_struct/package.rb | PackedStruct.Package.pack | def pack(data)
values = []
data.each do |k, v|
values.push([k, v])
end
mapped_directives = @directives.map(&:name)
values = values.select { |x| mapped_directives.include?(x[0]) }
values.sort! do |a, b|
mapped_directives.index(a[0]) <=> mapped_directives.index(b[0])
end
ary = values.map(&:last)
ary.pack to_s(data)
end | ruby | def pack(data)
values = []
data.each do |k, v|
values.push([k, v])
end
mapped_directives = @directives.map(&:name)
values = values.select { |x| mapped_directives.include?(x[0]) }
values.sort! do |a, b|
mapped_directives.index(a[0]) <=> mapped_directives.index(b[0])
end
ary = values.map(&:last)
ary.pack to_s(data)
end | [
"def",
"pack",
"(",
"data",
")",
"values",
"=",
"[",
"]",
"data",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"values",
".",
"push",
"(",
"[",
"k",
",",
"v",
"]",
")",
"end",
"mapped_directives",
"=",
"@directives",
".",
"map",
"(",
"&",
":name",
")",
"values",
"=",
"values",
".",
"select",
"{",
"|",
"x",
"|",
"mapped_directives",
".",
"include?",
"(",
"x",
"[",
"0",
"]",
")",
"}",
"values",
".",
"sort!",
"do",
"|",
"a",
",",
"b",
"|",
"mapped_directives",
".",
"index",
"(",
"a",
"[",
"0",
"]",
")",
"<=>",
"mapped_directives",
".",
"index",
"(",
"b",
"[",
"0",
"]",
")",
"end",
"ary",
"=",
"values",
".",
"map",
"(",
"&",
":last",
")",
"ary",
".",
"pack",
"to_s",
"(",
"data",
")",
"end"
] | Packs the given data into a string. The keys of the data
correspond to the names of the directives.
@param data [Hash<Symbol, Object>] the data.
@return [String] the packed data. | [
"Packs",
"the",
"given",
"data",
"into",
"a",
"string",
".",
"The",
"keys",
"of",
"the",
"data",
"correspond",
"to",
"the",
"names",
"of",
"the",
"directives",
"."
] | 4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f | https://github.com/medcat/packed_struct/blob/4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f/lib/packed_struct/package.rb#L37-L53 | train |
medcat/packed_struct | lib/packed_struct/package.rb | PackedStruct.Package.unpack | def unpack(string)
total = ""
parts = {}
directives.each_with_index do |directive, i|
total << directive.to_s(parts)
parts[directive.name] = string.unpack(total)[i]
end
parts.delete(:null) {}
parts
end | ruby | def unpack(string)
total = ""
parts = {}
directives.each_with_index do |directive, i|
total << directive.to_s(parts)
parts[directive.name] = string.unpack(total)[i]
end
parts.delete(:null) {}
parts
end | [
"def",
"unpack",
"(",
"string",
")",
"total",
"=",
"\"\"",
"parts",
"=",
"{",
"}",
"directives",
".",
"each_with_index",
"do",
"|",
"directive",
",",
"i",
"|",
"total",
"<<",
"directive",
".",
"to_s",
"(",
"parts",
")",
"parts",
"[",
"directive",
".",
"name",
"]",
"=",
"string",
".",
"unpack",
"(",
"total",
")",
"[",
"i",
"]",
"end",
"parts",
".",
"delete",
"(",
":null",
")",
"{",
"}",
"parts",
"end"
] | Unpacks the given string with the directives. Returns a hash
containing the values, with the keys being the names of the
directives.
@param string [String] the packed string.
@return [Hash<Symbol, Object>] the unpacked data. | [
"Unpacks",
"the",
"given",
"string",
"with",
"the",
"directives",
".",
"Returns",
"a",
"hash",
"containing",
"the",
"values",
"with",
"the",
"keys",
"being",
"the",
"names",
"of",
"the",
"directives",
"."
] | 4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f | https://github.com/medcat/packed_struct/blob/4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f/lib/packed_struct/package.rb#L61-L72 | train |
medcat/packed_struct | lib/packed_struct/package.rb | PackedStruct.Package.fast_unpack | def fast_unpack(string)
out = string.unpack(to_s)
parts = {}
directives.each_with_index do |directive, i|
parts[directive.name] = out[i]
end
parts.delete(:null) {}
parts
end | ruby | def fast_unpack(string)
out = string.unpack(to_s)
parts = {}
directives.each_with_index do |directive, i|
parts[directive.name] = out[i]
end
parts.delete(:null) {}
parts
end | [
"def",
"fast_unpack",
"(",
"string",
")",
"out",
"=",
"string",
".",
"unpack",
"(",
"to_s",
")",
"parts",
"=",
"{",
"}",
"directives",
".",
"each_with_index",
"do",
"|",
"directive",
",",
"i",
"|",
"parts",
"[",
"directive",
".",
"name",
"]",
"=",
"out",
"[",
"i",
"]",
"end",
"parts",
".",
"delete",
"(",
":null",
")",
"{",
"}",
"parts",
"end"
] | This unpacks the entire string at once. It assumes that none of
the directives will need the values of other directives. If
you're not sure what this means, don't use it.
@param string [String] the packed string.
@return [Hash<Symbol, Object>] the unpacked data. | [
"This",
"unpacks",
"the",
"entire",
"string",
"at",
"once",
".",
"It",
"assumes",
"that",
"none",
"of",
"the",
"directives",
"will",
"need",
"the",
"values",
"of",
"other",
"directives",
".",
"If",
"you",
"re",
"not",
"sure",
"what",
"this",
"means",
"don",
"t",
"use",
"it",
"."
] | 4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f | https://github.com/medcat/packed_struct/blob/4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f/lib/packed_struct/package.rb#L99-L109 | train |
medcat/packed_struct | lib/packed_struct/package.rb | PackedStruct.Package.method_missing | def method_missing(method, *arguments, &block)
super if @finalized
if arguments.length == 1 && arguments.first.is_a?(Directive)
arguments.first.add_modifier Modifier.new(method)
else
(directives.push Directive.new(method)).last
end
end | ruby | def method_missing(method, *arguments, &block)
super if @finalized
if arguments.length == 1 && arguments.first.is_a?(Directive)
arguments.first.add_modifier Modifier.new(method)
else
(directives.push Directive.new(method)).last
end
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"arguments",
",",
"&",
"block",
")",
"super",
"if",
"@finalized",
"if",
"arguments",
".",
"length",
"==",
"1",
"&&",
"arguments",
".",
"first",
".",
"is_a?",
"(",
"Directive",
")",
"arguments",
".",
"first",
".",
"add_modifier",
"Modifier",
".",
"new",
"(",
"method",
")",
"else",
"(",
"directives",
".",
"push",
"Directive",
".",
"new",
"(",
"method",
")",
")",
".",
"last",
"end",
"end"
] | Creates a new directive with the given method and arguments.
@return [Directive] the new directive. | [
"Creates",
"a",
"new",
"directive",
"with",
"the",
"given",
"method",
"and",
"arguments",
"."
] | 4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f | https://github.com/medcat/packed_struct/blob/4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f/lib/packed_struct/package.rb#L137-L144 | train |
botanicus/nake | lib/nake/file_task.rb | Nake.FileTask.invoke_dependencies | def invoke_dependencies(*args, options)
self.dependencies.each do |name|
if task = self.class[name] # first try if there is a task with given name
task.call(*args, options) # TODO: what about arguments?
elsif File.exist?(name) # if not, then fallback to file
task_will_run?(name)
else
raise TaskNotFound, "Task with name #{name} doesn't exist"
end
end
end | ruby | def invoke_dependencies(*args, options)
self.dependencies.each do |name|
if task = self.class[name] # first try if there is a task with given name
task.call(*args, options) # TODO: what about arguments?
elsif File.exist?(name) # if not, then fallback to file
task_will_run?(name)
else
raise TaskNotFound, "Task with name #{name} doesn't exist"
end
end
end | [
"def",
"invoke_dependencies",
"(",
"*",
"args",
",",
"options",
")",
"self",
".",
"dependencies",
".",
"each",
"do",
"|",
"name",
"|",
"if",
"task",
"=",
"self",
".",
"class",
"[",
"name",
"]",
"task",
".",
"call",
"(",
"*",
"args",
",",
"options",
")",
"elsif",
"File",
".",
"exist?",
"(",
"name",
")",
"task_will_run?",
"(",
"name",
")",
"else",
"raise",
"TaskNotFound",
",",
"\"Task with name #{name} doesn't exist\"",
"end",
"end",
"end"
] | return true if the task need to be executed, false otherwise | [
"return",
"true",
"if",
"the",
"task",
"need",
"to",
"be",
"executed",
"false",
"otherwise"
] | d0ca22c3ce686dc916bdbe5bbd5475a18371a41d | https://github.com/botanicus/nake/blob/d0ca22c3ce686dc916bdbe5bbd5475a18371a41d/lib/nake/file_task.rb#L50-L60 | train |
yaauie/typed-array | lib/typed-array/functions.rb | TypedArray.Functions._ensure_all_items_in_array_are_allowed | def _ensure_all_items_in_array_are_allowed(ary)
# If we're getting an instance of self, accept
return if ary.is_a? self.class
_ensure_item_is_allowed(ary, [Array])
ary.each { |item| _ensure_item_is_allowed(item) }
end | ruby | def _ensure_all_items_in_array_are_allowed(ary)
# If we're getting an instance of self, accept
return if ary.is_a? self.class
_ensure_item_is_allowed(ary, [Array])
ary.each { |item| _ensure_item_is_allowed(item) }
end | [
"def",
"_ensure_all_items_in_array_are_allowed",
"(",
"ary",
")",
"return",
"if",
"ary",
".",
"is_a?",
"self",
".",
"class",
"_ensure_item_is_allowed",
"(",
"ary",
",",
"[",
"Array",
"]",
")",
"ary",
".",
"each",
"{",
"|",
"item",
"|",
"_ensure_item_is_allowed",
"(",
"item",
")",
"}",
"end"
] | Ensure that all items in the passed Array are allowed | [
"Ensure",
"that",
"all",
"items",
"in",
"the",
"passed",
"Array",
"are",
"allowed"
] | 3b92cb3d4c0a294dcf9720f46cbbb086686d2574 | https://github.com/yaauie/typed-array/blob/3b92cb3d4c0a294dcf9720f46cbbb086686d2574/lib/typed-array/functions.rb#L96-L101 | train |
yaauie/typed-array | lib/typed-array/functions.rb | TypedArray.Functions._ensure_item_is_allowed | def _ensure_item_is_allowed(item, expected=nil)
return if item.nil? #allow nil entries
expected ||= self.class.restricted_types
return if expected.any? { |allowed| item.class <= allowed }
raise TypedArray::UnexpectedTypeException.new(expected, item.class)
end | ruby | def _ensure_item_is_allowed(item, expected=nil)
return if item.nil? #allow nil entries
expected ||= self.class.restricted_types
return if expected.any? { |allowed| item.class <= allowed }
raise TypedArray::UnexpectedTypeException.new(expected, item.class)
end | [
"def",
"_ensure_item_is_allowed",
"(",
"item",
",",
"expected",
"=",
"nil",
")",
"return",
"if",
"item",
".",
"nil?",
"expected",
"||=",
"self",
".",
"class",
".",
"restricted_types",
"return",
"if",
"expected",
".",
"any?",
"{",
"|",
"allowed",
"|",
"item",
".",
"class",
"<=",
"allowed",
"}",
"raise",
"TypedArray",
"::",
"UnexpectedTypeException",
".",
"new",
"(",
"expected",
",",
"item",
".",
"class",
")",
"end"
] | Ensure that the specific item passed is allowed | [
"Ensure",
"that",
"the",
"specific",
"item",
"passed",
"is",
"allowed"
] | 3b92cb3d4c0a294dcf9720f46cbbb086686d2574 | https://github.com/yaauie/typed-array/blob/3b92cb3d4c0a294dcf9720f46cbbb086686d2574/lib/typed-array/functions.rb#L104-L109 | train |
jarhart/rattler | lib/rattler/parsers/sequence.rb | Rattler::Parsers.Sequence.parse | def parse(scanner, rules, scope = ParserScope.empty)
backtracking(scanner) do
if scope = parse_children(scanner, rules, scope.nest)
yield scope if block_given?
parse_result(scope)
end
end
end | ruby | def parse(scanner, rules, scope = ParserScope.empty)
backtracking(scanner) do
if scope = parse_children(scanner, rules, scope.nest)
yield scope if block_given?
parse_result(scope)
end
end
end | [
"def",
"parse",
"(",
"scanner",
",",
"rules",
",",
"scope",
"=",
"ParserScope",
".",
"empty",
")",
"backtracking",
"(",
"scanner",
")",
"do",
"if",
"scope",
"=",
"parse_children",
"(",
"scanner",
",",
"rules",
",",
"scope",
".",
"nest",
")",
"yield",
"scope",
"if",
"block_given?",
"parse_result",
"(",
"scope",
")",
"end",
"end",
"end"
] | Try each parser in sequence, and if they all succeed return an array of
captured results, or return +false+ if any parser fails.
@param (see Match#parse)
@return an array of captured results of each parser in sequence, or
+false+ | [
"Try",
"each",
"parser",
"in",
"sequence",
"and",
"if",
"they",
"all",
"succeed",
"return",
"an",
"array",
"of",
"captured",
"results",
"or",
"return",
"+",
"false",
"+",
"if",
"any",
"parser",
"fails",
"."
] | 8b4efde2a05e9e790955bb635d4a1a9615893719 | https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/parsers/sequence.rb#L22-L29 | train |
jduff/herbalist | lib/herbalist/herbalist.rb | Herbalist.Token.get_tag | def get_tag(tag_type)
matches = @tags.select { |m| m.type==tag_type }
return matches.first
end | ruby | def get_tag(tag_type)
matches = @tags.select { |m| m.type==tag_type }
return matches.first
end | [
"def",
"get_tag",
"(",
"tag_type",
")",
"matches",
"=",
"@tags",
".",
"select",
"{",
"|",
"m",
"|",
"m",
".",
"type",
"==",
"tag_type",
"}",
"return",
"matches",
".",
"first",
"end"
] | Return the Tag that matches the given class | [
"Return",
"the",
"Tag",
"that",
"matches",
"the",
"given",
"class"
] | 78743a8082d78f32349049ba0ce73db41c70ad87 | https://github.com/jduff/herbalist/blob/78743a8082d78f32349049ba0ce73db41c70ad87/lib/herbalist/herbalist.rb#L89-L92 | train |
boost/safety_cone | lib/safety_cone/configuration.rb | SafetyCone.Configuration.add | def add(options = {})
self.options = options
raise(ArgumentError, 'Mandatory param :name missing') unless options[:name]
if options[:feature]
features << options
SafetyCone::ViewHelpers.add_method(options[:feature])
else
paths[make_key] = options
end
end | ruby | def add(options = {})
self.options = options
raise(ArgumentError, 'Mandatory param :name missing') unless options[:name]
if options[:feature]
features << options
SafetyCone::ViewHelpers.add_method(options[:feature])
else
paths[make_key] = options
end
end | [
"def",
"add",
"(",
"options",
"=",
"{",
"}",
")",
"self",
".",
"options",
"=",
"options",
"raise",
"(",
"ArgumentError",
",",
"'Mandatory param :name missing'",
")",
"unless",
"options",
"[",
":name",
"]",
"if",
"options",
"[",
":feature",
"]",
"features",
"<<",
"options",
"SafetyCone",
"::",
"ViewHelpers",
".",
"add_method",
"(",
"options",
"[",
":feature",
"]",
")",
"else",
"paths",
"[",
"make_key",
"]",
"=",
"options",
"end",
"end"
] | Method add a route or method to be managed by safety cone | [
"Method",
"add",
"a",
"route",
"or",
"method",
"to",
"be",
"managed",
"by",
"safety",
"cone"
] | 45dfcb0a9f9702386f8f0af8254c72cb5162b0cb | https://github.com/boost/safety_cone/blob/45dfcb0a9f9702386f8f0af8254c72cb5162b0cb/lib/safety_cone/configuration.rb#L7-L18 | train |
boost/safety_cone | lib/safety_cone/configuration.rb | SafetyCone.Configuration.make_key | def make_key
if options.key? :method
options[:method].to_sym
elsif options.include?(:controller) && options.include?(:action)
"#{options[:controller]}_#{options[:action]}".to_sym
else
raise(ArgumentError,
'Options should contain :controller and :action or :method.')
end
end | ruby | def make_key
if options.key? :method
options[:method].to_sym
elsif options.include?(:controller) && options.include?(:action)
"#{options[:controller]}_#{options[:action]}".to_sym
else
raise(ArgumentError,
'Options should contain :controller and :action or :method.')
end
end | [
"def",
"make_key",
"if",
"options",
".",
"key?",
":method",
"options",
"[",
":method",
"]",
".",
"to_sym",
"elsif",
"options",
".",
"include?",
"(",
":controller",
")",
"&&",
"options",
".",
"include?",
"(",
":action",
")",
"\"#{options[:controller]}_#{options[:action]}\"",
".",
"to_sym",
"else",
"raise",
"(",
"ArgumentError",
",",
"'Options should contain :controller and :action or :method.'",
")",
"end",
"end"
] | Method to generate a key from the options | [
"Method",
"to",
"generate",
"a",
"key",
"from",
"the",
"options"
] | 45dfcb0a9f9702386f8f0af8254c72cb5162b0cb | https://github.com/boost/safety_cone/blob/45dfcb0a9f9702386f8f0af8254c72cb5162b0cb/lib/safety_cone/configuration.rb#L21-L30 | train |
agoragames/oembedr | lib/oembedr/client.rb | Oembedr.Client.get | def get options = {}
additional_params = options.delete(:params) || {}
connection(options).get do |req|
req.url parsed_url.path
req.params = additional_params.merge({
:url => resource_url,
:format => "json"
})
end
end | ruby | def get options = {}
additional_params = options.delete(:params) || {}
connection(options).get do |req|
req.url parsed_url.path
req.params = additional_params.merge({
:url => resource_url,
:format => "json"
})
end
end | [
"def",
"get",
"options",
"=",
"{",
"}",
"additional_params",
"=",
"options",
".",
"delete",
"(",
":params",
")",
"||",
"{",
"}",
"connection",
"(",
"options",
")",
".",
"get",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"parsed_url",
".",
"path",
"req",
".",
"params",
"=",
"additional_params",
".",
"merge",
"(",
"{",
":url",
"=>",
"resource_url",
",",
":format",
"=>",
"\"json\"",
"}",
")",
"end",
"end"
] | Requests the oembeddable resource
@return Faraday::Response | [
"Requests",
"the",
"oembeddable",
"resource"
] | 9e453adceaa01c5b07db466e6429a4ebb8bcda03 | https://github.com/agoragames/oembedr/blob/9e453adceaa01c5b07db466e6429a4ebb8bcda03/lib/oembedr/client.rb#L40-L49 | train |
gnumarcelo/campaigning | lib/campaigning/list.rb | Campaigning.List.create_custom_field! | def create_custom_field!(params)
response = @@soap.createListCustomField(
:apiKey => @apiKey,
:listID => @listID,
:fieldName => params[:fieldName],
:dataType => params[:dataType],
:options => params.fetch(:options, "")
)
handle_response response.list_CreateCustomFieldResult
end | ruby | def create_custom_field!(params)
response = @@soap.createListCustomField(
:apiKey => @apiKey,
:listID => @listID,
:fieldName => params[:fieldName],
:dataType => params[:dataType],
:options => params.fetch(:options, "")
)
handle_response response.list_CreateCustomFieldResult
end | [
"def",
"create_custom_field!",
"(",
"params",
")",
"response",
"=",
"@@soap",
".",
"createListCustomField",
"(",
":apiKey",
"=>",
"@apiKey",
",",
":listID",
"=>",
"@listID",
",",
":fieldName",
"=>",
"params",
"[",
":fieldName",
"]",
",",
":dataType",
"=>",
"params",
"[",
":dataType",
"]",
",",
":options",
"=>",
"params",
".",
"fetch",
"(",
":options",
",",
"\"\"",
")",
")",
"handle_response",
"response",
".",
"list_CreateCustomFieldResult",
"end"
] | Creates a new custom field for a list
Available _params_ argument are:
* :fieldName - The Name for the new Custom Field. This will be used to generate the custom fields Key.
* :dataType - The Data Type for the new Custom Field. This must be one of Text, Number, MultiSelectOne, or MultiSelectMany
* :options - The available options for a multi-valued custom field. Options should be an Array of Strings, like: %w[Brazil Ireland England].
You can't pass this field for Text and Number custom fields
*Return*:
*Success*: Upon a successful call, this method will return a Campaigning::Result object wich consists of a +code+ and +message+ fields
containing a successful message.
*Error*: An Exception containing the cause of the error will be raised. | [
"Creates",
"a",
"new",
"custom",
"field",
"for",
"a",
"list"
] | f3d7da053b65cfa376269533183919dc890964fd | https://github.com/gnumarcelo/campaigning/blob/f3d7da053b65cfa376269533183919dc890964fd/lib/campaigning/list.rb#L61-L70 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.