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 |
---|---|---|---|---|---|---|---|---|---|---|---|
rightscale/right_amqp | lib/right_amqp/ha_client/ha_broker_client.rb | RightAMQP.HABrokerClient.each | def each(status, identities = nil)
choices = if identities && !identities.empty?
identities.inject([]) { |c, i| if b = @brokers_hash[i] then c << b else c end }
else
@brokers
end
choices.select do |b|
if b.send("#{status}?".to_sym)
yield(b) if block_given?
true
end
end
end | ruby | def each(status, identities = nil)
choices = if identities && !identities.empty?
identities.inject([]) { |c, i| if b = @brokers_hash[i] then c << b else c end }
else
@brokers
end
choices.select do |b|
if b.send("#{status}?".to_sym)
yield(b) if block_given?
true
end
end
end | [
"def",
"each",
"(",
"status",
",",
"identities",
"=",
"nil",
")",
"choices",
"=",
"if",
"identities",
"&&",
"!",
"identities",
".",
"empty?",
"identities",
".",
"inject",
"(",
"[",
"]",
")",
"{",
"|",
"c",
",",
"i",
"|",
"if",
"b",
"=",
"@brokers_hash",
"[",
"i",
"]",
"then",
"c",
"<<",
"b",
"else",
"c",
"end",
"}",
"else",
"@brokers",
"end",
"choices",
".",
"select",
"do",
"|",
"b",
"|",
"if",
"b",
".",
"send",
"(",
"\"#{status}?\"",
".",
"to_sym",
")",
"yield",
"(",
"b",
")",
"if",
"block_given?",
"true",
"end",
"end",
"end"
] | Iterate over clients that have the specified status
=== Parameters
status(String):: Status for selecting: :usable, :connected, :failed
identities(Array):: Identity of brokers to be considered, nil or empty array means all brokers
=== Block
Optional block with following parameters to be called for each broker client selected
broker(BrokerClient):: Broker client
=== Return
(Array):: Selected broker clients | [
"Iterate",
"over",
"clients",
"that",
"have",
"the",
"specified",
"status"
] | 248de38141b228bdb437757155d7fd7dd6e50733 | https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L942-L954 | train |
rightscale/right_amqp | lib/right_amqp/ha_client/ha_broker_client.rb | RightAMQP.HABrokerClient.use | def use(options)
choices = []
select = options[:order]
if options[:brokers] && !options[:brokers].empty?
options[:brokers].each do |identity|
if choice = @brokers_hash[identity]
choices << choice
else
logger.exception("Invalid broker identity #{identity.inspect}, check server configuration")
end
end
else
choices = @brokers
select ||= @select
end
if select == :random
choices.sort_by { rand }
else
choices
end
end | ruby | def use(options)
choices = []
select = options[:order]
if options[:brokers] && !options[:brokers].empty?
options[:brokers].each do |identity|
if choice = @brokers_hash[identity]
choices << choice
else
logger.exception("Invalid broker identity #{identity.inspect}, check server configuration")
end
end
else
choices = @brokers
select ||= @select
end
if select == :random
choices.sort_by { rand }
else
choices
end
end | [
"def",
"use",
"(",
"options",
")",
"choices",
"=",
"[",
"]",
"select",
"=",
"options",
"[",
":order",
"]",
"if",
"options",
"[",
":brokers",
"]",
"&&",
"!",
"options",
"[",
":brokers",
"]",
".",
"empty?",
"options",
"[",
":brokers",
"]",
".",
"each",
"do",
"|",
"identity",
"|",
"if",
"choice",
"=",
"@brokers_hash",
"[",
"identity",
"]",
"choices",
"<<",
"choice",
"else",
"logger",
".",
"exception",
"(",
"\"Invalid broker identity #{identity.inspect}, check server configuration\"",
")",
"end",
"end",
"else",
"choices",
"=",
"@brokers",
"select",
"||=",
"@select",
"end",
"if",
"select",
"==",
":random",
"choices",
".",
"sort_by",
"{",
"rand",
"}",
"else",
"choices",
"end",
"end"
] | Select the broker clients to be used in the desired order
=== Parameters
options(Hash):: Selection options:
:brokers(Array):: Identity of brokers selected for use, defaults to all brokers if nil or empty
:order(Symbol):: Broker selection order: :random or :priority,
defaults to @select if :brokers is nil, otherwise defaults to :priority
=== Return
(Array):: Allowed BrokerClients in the order to be used | [
"Select",
"the",
"broker",
"clients",
"to",
"be",
"used",
"in",
"the",
"desired",
"order"
] | 248de38141b228bdb437757155d7fd7dd6e50733 | https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L966-L986 | train |
rightscale/right_amqp | lib/right_amqp/ha_client/ha_broker_client.rb | RightAMQP.HABrokerClient.handle_return | def handle_return(identity, to, reason, message)
@brokers_hash[identity].update_status(:stopping) if reason == "ACCESS_REFUSED"
if context = @published.fetch(message)
@return_stats.update("#{alias_(identity)} (#{reason.to_s.downcase})")
context.record_failure(identity)
name = context.name
options = context.options || {}
token = context.token
one_way = context.one_way
persistent = options[:persistent]
mandatory = true
remaining = (context.brokers - context.failed) & connected
logger.info("RETURN reason #{reason} token <#{token}> to #{to} from #{context.from} brokers #{context.brokers.inspect} " +
"failed #{context.failed.inspect} remaining #{remaining.inspect} connected #{connected.inspect}")
if remaining.empty?
if (persistent || one_way) &&
["ACCESS_REFUSED", "NO_CONSUMERS"].include?(reason) &&
!(remaining = context.brokers & connected).empty?
# Retry because persistent, and this time w/o mandatory so that gets queued even though no consumers
mandatory = false
else
t = token ? " <#{token}>" : ""
logger.info("NO ROUTE #{aliases(context.brokers).join(", ")} [#{name}]#{t} to #{to}")
@non_delivery.call(reason, context.type, token, context.from, to) if @non_delivery
@non_delivery_stats.update("no route")
end
end
unless remaining.empty?
t = token ? " <#{token}>" : ""
p = persistent ? ", persistent" : ""
m = mandatory ? ", mandatory" : ""
logger.info("RE-ROUTE #{aliases(remaining).join(", ")} [#{context.name}]#{t} to #{to}#{p}#{m}")
exchange = {:type => :queue, :name => to, :options => {:no_declare => true}}
publish(exchange, message, options.merge(:no_serialize => true, :brokers => remaining,
:persistent => persistent, :mandatory => mandatory))
end
else
@return_stats.update("#{alias_(identity)} (#{reason.to_s.downcase} - missing context)")
logger.info("Dropping message returned from broker #{identity} for reason #{reason} " +
"because no message context available for re-routing it to #{to}")
end
true
rescue Exception => e
logger.exception("Failed to handle #{reason} return from #{identity} for message being routed to #{to}", e, :trace)
@exception_stats.track("return", e)
end | ruby | def handle_return(identity, to, reason, message)
@brokers_hash[identity].update_status(:stopping) if reason == "ACCESS_REFUSED"
if context = @published.fetch(message)
@return_stats.update("#{alias_(identity)} (#{reason.to_s.downcase})")
context.record_failure(identity)
name = context.name
options = context.options || {}
token = context.token
one_way = context.one_way
persistent = options[:persistent]
mandatory = true
remaining = (context.brokers - context.failed) & connected
logger.info("RETURN reason #{reason} token <#{token}> to #{to} from #{context.from} brokers #{context.brokers.inspect} " +
"failed #{context.failed.inspect} remaining #{remaining.inspect} connected #{connected.inspect}")
if remaining.empty?
if (persistent || one_way) &&
["ACCESS_REFUSED", "NO_CONSUMERS"].include?(reason) &&
!(remaining = context.brokers & connected).empty?
# Retry because persistent, and this time w/o mandatory so that gets queued even though no consumers
mandatory = false
else
t = token ? " <#{token}>" : ""
logger.info("NO ROUTE #{aliases(context.brokers).join(", ")} [#{name}]#{t} to #{to}")
@non_delivery.call(reason, context.type, token, context.from, to) if @non_delivery
@non_delivery_stats.update("no route")
end
end
unless remaining.empty?
t = token ? " <#{token}>" : ""
p = persistent ? ", persistent" : ""
m = mandatory ? ", mandatory" : ""
logger.info("RE-ROUTE #{aliases(remaining).join(", ")} [#{context.name}]#{t} to #{to}#{p}#{m}")
exchange = {:type => :queue, :name => to, :options => {:no_declare => true}}
publish(exchange, message, options.merge(:no_serialize => true, :brokers => remaining,
:persistent => persistent, :mandatory => mandatory))
end
else
@return_stats.update("#{alias_(identity)} (#{reason.to_s.downcase} - missing context)")
logger.info("Dropping message returned from broker #{identity} for reason #{reason} " +
"because no message context available for re-routing it to #{to}")
end
true
rescue Exception => e
logger.exception("Failed to handle #{reason} return from #{identity} for message being routed to #{to}", e, :trace)
@exception_stats.track("return", e)
end | [
"def",
"handle_return",
"(",
"identity",
",",
"to",
",",
"reason",
",",
"message",
")",
"@brokers_hash",
"[",
"identity",
"]",
".",
"update_status",
"(",
":stopping",
")",
"if",
"reason",
"==",
"\"ACCESS_REFUSED\"",
"if",
"context",
"=",
"@published",
".",
"fetch",
"(",
"message",
")",
"@return_stats",
".",
"update",
"(",
"\"#{alias_(identity)} (#{reason.to_s.downcase})\"",
")",
"context",
".",
"record_failure",
"(",
"identity",
")",
"name",
"=",
"context",
".",
"name",
"options",
"=",
"context",
".",
"options",
"||",
"{",
"}",
"token",
"=",
"context",
".",
"token",
"one_way",
"=",
"context",
".",
"one_way",
"persistent",
"=",
"options",
"[",
":persistent",
"]",
"mandatory",
"=",
"true",
"remaining",
"=",
"(",
"context",
".",
"brokers",
"-",
"context",
".",
"failed",
")",
"&",
"connected",
"logger",
".",
"info",
"(",
"\"RETURN reason #{reason} token <#{token}> to #{to} from #{context.from} brokers #{context.brokers.inspect} \"",
"+",
"\"failed #{context.failed.inspect} remaining #{remaining.inspect} connected #{connected.inspect}\"",
")",
"if",
"remaining",
".",
"empty?",
"if",
"(",
"persistent",
"||",
"one_way",
")",
"&&",
"[",
"\"ACCESS_REFUSED\"",
",",
"\"NO_CONSUMERS\"",
"]",
".",
"include?",
"(",
"reason",
")",
"&&",
"!",
"(",
"remaining",
"=",
"context",
".",
"brokers",
"&",
"connected",
")",
".",
"empty?",
"mandatory",
"=",
"false",
"else",
"t",
"=",
"token",
"?",
"\" <#{token}>\"",
":",
"\"\"",
"logger",
".",
"info",
"(",
"\"NO ROUTE #{aliases(context.brokers).join(\", \")} [#{name}]#{t} to #{to}\"",
")",
"@non_delivery",
".",
"call",
"(",
"reason",
",",
"context",
".",
"type",
",",
"token",
",",
"context",
".",
"from",
",",
"to",
")",
"if",
"@non_delivery",
"@non_delivery_stats",
".",
"update",
"(",
"\"no route\"",
")",
"end",
"end",
"unless",
"remaining",
".",
"empty?",
"t",
"=",
"token",
"?",
"\" <#{token}>\"",
":",
"\"\"",
"p",
"=",
"persistent",
"?",
"\", persistent\"",
":",
"\"\"",
"m",
"=",
"mandatory",
"?",
"\", mandatory\"",
":",
"\"\"",
"logger",
".",
"info",
"(",
"\"RE-ROUTE #{aliases(remaining).join(\", \")} [#{context.name}]#{t} to #{to}#{p}#{m}\"",
")",
"exchange",
"=",
"{",
":type",
"=>",
":queue",
",",
":name",
"=>",
"to",
",",
":options",
"=>",
"{",
":no_declare",
"=>",
"true",
"}",
"}",
"publish",
"(",
"exchange",
",",
"message",
",",
"options",
".",
"merge",
"(",
":no_serialize",
"=>",
"true",
",",
":brokers",
"=>",
"remaining",
",",
":persistent",
"=>",
"persistent",
",",
":mandatory",
"=>",
"mandatory",
")",
")",
"end",
"else",
"@return_stats",
".",
"update",
"(",
"\"#{alias_(identity)} (#{reason.to_s.downcase} - missing context)\"",
")",
"logger",
".",
"info",
"(",
"\"Dropping message returned from broker #{identity} for reason #{reason} \"",
"+",
"\"because no message context available for re-routing it to #{to}\"",
")",
"end",
"true",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"exception",
"(",
"\"Failed to handle #{reason} return from #{identity} for message being routed to #{to}\"",
",",
"e",
",",
":trace",
")",
"@exception_stats",
".",
"track",
"(",
"\"return\"",
",",
"e",
")",
"end"
] | Handle message returned by broker because it could not deliver it
If agent still active, resend using another broker
If this is last usable broker and persistent is enabled, allow message to be queued
on next send even if the queue has no consumers so there is a chance of message
eventually being delivered
If persistent or one-way request and all usable brokers have failed, try one more time
without mandatory flag to give message opportunity to be queued
If there are no more usable broker clients, send non-delivery message to original sender
=== Parameters
identity(String):: Identity of broker that could not deliver message
to(String):: Queue to which message was published
reason(String):: Reason for return
"NO_ROUTE" - queue does not exist
"NO_CONSUMERS" - queue exists but it has no consumers, or if :immediate was specified,
all consumers are not immediately ready to consume
"ACCESS_REFUSED" - queue not usable because broker is in the process of stopping service
message(String):: Returned message in serialized packet format
=== Return
true:: Always return true | [
"Handle",
"message",
"returned",
"by",
"broker",
"because",
"it",
"could",
"not",
"deliver",
"it",
"If",
"agent",
"still",
"active",
"resend",
"using",
"another",
"broker",
"If",
"this",
"is",
"last",
"usable",
"broker",
"and",
"persistent",
"is",
"enabled",
"allow",
"message",
"to",
"be",
"queued",
"on",
"next",
"send",
"even",
"if",
"the",
"queue",
"has",
"no",
"consumers",
"so",
"there",
"is",
"a",
"chance",
"of",
"message",
"eventually",
"being",
"delivered",
"If",
"persistent",
"or",
"one",
"-",
"way",
"request",
"and",
"all",
"usable",
"brokers",
"have",
"failed",
"try",
"one",
"more",
"time",
"without",
"mandatory",
"flag",
"to",
"give",
"message",
"opportunity",
"to",
"be",
"queued",
"If",
"there",
"are",
"no",
"more",
"usable",
"broker",
"clients",
"send",
"non",
"-",
"delivery",
"message",
"to",
"original",
"sender"
] | 248de38141b228bdb437757155d7fd7dd6e50733 | https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L1066-L1113 | train |
KatanaCode/evvnt | lib/evvnt/attributes.rb | Evvnt.Attributes.method_missing | def method_missing(method_name, *args)
setter = method_name.to_s.ends_with?('=')
attr_name = method_name.to_s.gsub(/=$/, "")
if setter
attributes[attr_name] = args.first
else
attributes[attr_name]
end
end | ruby | def method_missing(method_name, *args)
setter = method_name.to_s.ends_with?('=')
attr_name = method_name.to_s.gsub(/=$/, "")
if setter
attributes[attr_name] = args.first
else
attributes[attr_name]
end
end | [
"def",
"method_missing",
"(",
"method_name",
",",
"*",
"args",
")",
"setter",
"=",
"method_name",
".",
"to_s",
".",
"ends_with?",
"(",
"'='",
")",
"attr_name",
"=",
"method_name",
".",
"to_s",
".",
"gsub",
"(",
"/",
"/",
",",
"\"\"",
")",
"if",
"setter",
"attributes",
"[",
"attr_name",
"]",
"=",
"args",
".",
"first",
"else",
"attributes",
"[",
"attr_name",
"]",
"end",
"end"
] | Overrides method missing to catch undefined methods. If +method_name+ is one
of the keys on +attributes+, returns the value of that attribute. If +method_name+
is not one of +attributes+, passes up the chain to super.
method_name - Symbol of the name of the method we're testing for.
args - Array of arguments send with the original mesage.
block - Proc of code passed with original message. | [
"Overrides",
"method",
"missing",
"to",
"catch",
"undefined",
"methods",
".",
"If",
"+",
"method_name",
"+",
"is",
"one",
"of",
"the",
"keys",
"on",
"+",
"attributes",
"+",
"returns",
"the",
"value",
"of",
"that",
"attribute",
".",
"If",
"+",
"method_name",
"+",
"is",
"not",
"one",
"of",
"+",
"attributes",
"+",
"passes",
"up",
"the",
"chain",
"to",
"super",
"."
] | e13f6d84af09a71819356620fb25685a6cd159c9 | https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/attributes.rb#L101-L109 | train |
jinx/core | lib/jinx/resource/match_visitor.rb | Jinx.MatchVisitor.visit | def visit(source, target, &block)
# clear the match hashes
@matches.clear
@id_mtchs.clear
# seed the matches with the top-level source => target
add_match(source, target)
# Visit the source reference.
super(source) { |src| visit_matched(src, &block) }
end | ruby | def visit(source, target, &block)
# clear the match hashes
@matches.clear
@id_mtchs.clear
# seed the matches with the top-level source => target
add_match(source, target)
# Visit the source reference.
super(source) { |src| visit_matched(src, &block) }
end | [
"def",
"visit",
"(",
"source",
",",
"target",
",",
"&",
"block",
")",
"@matches",
".",
"clear",
"@id_mtchs",
".",
"clear",
"add_match",
"(",
"source",
",",
"target",
")",
"super",
"(",
"source",
")",
"{",
"|",
"src",
"|",
"visit_matched",
"(",
"src",
",",
"&",
"block",
")",
"}",
"end"
] | Creates a new visitor which matches source and target domain object references.
The domain attributes to visit are determined by calling the selector block given to
this initializer. The selector arguments consist of the match source and target.
@param (see ReferenceVisitor#initialize)
@option opts [Proc] :mergeable the block which determines which attributes are merged
@option opts [Proc] :matchable the block which determines which attributes to match
(default is the visit selector)
@option opts [:match] :matcher an object which matches sources to targets
@option opts [Proc] :copier the block which copies an unmatched source
@yield (see ReferenceVisitor#initialize)
@yieldparam [Resource] source the matched source object
Visits the source and target.
If a block is given to this method, then this method returns the evaluation of the block on the visited
source reference and its matching copy, if any. The default return value is the target which matches
source.
@param [Resource] source the match visit source
@param [Resource] target the match visit target
@yield [target, source] the optional block to call on the matched source and target
@yieldparam [Resource] source the visited source domain object
@yieldparam [Resource] target the domain object which matches the visited source
@yieldparam [Resource] from the visiting domain object
@yieldparam [Property] property the visiting property | [
"Creates",
"a",
"new",
"visitor",
"which",
"matches",
"source",
"and",
"target",
"domain",
"object",
"references",
".",
"The",
"domain",
"attributes",
"to",
"visit",
"are",
"determined",
"by",
"calling",
"the",
"selector",
"block",
"given",
"to",
"this",
"initializer",
".",
"The",
"selector",
"arguments",
"consist",
"of",
"the",
"match",
"source",
"and",
"target",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource/match_visitor.rb#L63-L71 | train |
jinx/core | lib/jinx/resource/match_visitor.rb | Jinx.MatchVisitor.visit_matched | def visit_matched(source)
tgt = @matches[source] || return
# Match the unvisited matchable references, if any.
if @matchable then
mas = @matchable.call(source) - attributes_to_visit(source)
mas.each { |ma| match_reference(source, tgt, ma) }
end
block_given? ? yield(source, tgt) : tgt
end | ruby | def visit_matched(source)
tgt = @matches[source] || return
# Match the unvisited matchable references, if any.
if @matchable then
mas = @matchable.call(source) - attributes_to_visit(source)
mas.each { |ma| match_reference(source, tgt, ma) }
end
block_given? ? yield(source, tgt) : tgt
end | [
"def",
"visit_matched",
"(",
"source",
")",
"tgt",
"=",
"@matches",
"[",
"source",
"]",
"||",
"return",
"if",
"@matchable",
"then",
"mas",
"=",
"@matchable",
".",
"call",
"(",
"source",
")",
"-",
"attributes_to_visit",
"(",
"source",
")",
"mas",
".",
"each",
"{",
"|",
"ma",
"|",
"match_reference",
"(",
"source",
",",
"tgt",
",",
"ma",
")",
"}",
"end",
"block_given?",
"?",
"yield",
"(",
"source",
",",
"tgt",
")",
":",
"tgt",
"end"
] | Visits the given source domain object.
@param [Resource] source the match visit source
@yield [target, source] the optional block to call on the matched source and target
@yieldparam [Resource] source the visited source domain object
@yieldparam [Resource] target the domain object which matches the visited source
@yieldparam [Resource] from the visiting domain object
@yieldparam [Property] property the visiting property | [
"Visits",
"the",
"given",
"source",
"domain",
"object",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource/match_visitor.rb#L92-L100 | train |
jinx/core | lib/jinx/resource/match_visitor.rb | Jinx.MatchVisitor.match_reference | def match_reference(source, target, attribute)
srcs = source.send(attribute).to_enum
tgts = target.send(attribute).to_enum
# the match targets
mtchd_tgts = Set.new
# capture the matched targets and the the unmatched sources
unmtchd_srcs = srcs.reject do |src|
# the prior match, if any
tgt = match_for(src)
mtchd_tgts << tgt if tgt
end
# the unmatched targets
unmtchd_tgts = tgts.difference(mtchd_tgts)
logger.debug { "#{qp} matching #{unmtchd_tgts.qp}..." } if @verbose and not unmtchd_tgts.empty?
# match the residual targets and sources
rsd_mtchs = @matcher.match(unmtchd_srcs, unmtchd_tgts, source, attribute)
# add residual matches
rsd_mtchs.each { |src, tgt| add_match(src, tgt) }
logger.debug { "#{qp} matched #{rsd_mtchs.qp}..." } if @verbose and not rsd_mtchs.empty?
# The source => target match hash.
# If there is a copier, then copy each unmatched source.
matches = srcs.to_compact_hash { |src| match_for(src) or copy_unmatched(src) }
matches
end | ruby | def match_reference(source, target, attribute)
srcs = source.send(attribute).to_enum
tgts = target.send(attribute).to_enum
# the match targets
mtchd_tgts = Set.new
# capture the matched targets and the the unmatched sources
unmtchd_srcs = srcs.reject do |src|
# the prior match, if any
tgt = match_for(src)
mtchd_tgts << tgt if tgt
end
# the unmatched targets
unmtchd_tgts = tgts.difference(mtchd_tgts)
logger.debug { "#{qp} matching #{unmtchd_tgts.qp}..." } if @verbose and not unmtchd_tgts.empty?
# match the residual targets and sources
rsd_mtchs = @matcher.match(unmtchd_srcs, unmtchd_tgts, source, attribute)
# add residual matches
rsd_mtchs.each { |src, tgt| add_match(src, tgt) }
logger.debug { "#{qp} matched #{rsd_mtchs.qp}..." } if @verbose and not rsd_mtchs.empty?
# The source => target match hash.
# If there is a copier, then copy each unmatched source.
matches = srcs.to_compact_hash { |src| match_for(src) or copy_unmatched(src) }
matches
end | [
"def",
"match_reference",
"(",
"source",
",",
"target",
",",
"attribute",
")",
"srcs",
"=",
"source",
".",
"send",
"(",
"attribute",
")",
".",
"to_enum",
"tgts",
"=",
"target",
".",
"send",
"(",
"attribute",
")",
".",
"to_enum",
"mtchd_tgts",
"=",
"Set",
".",
"new",
"unmtchd_srcs",
"=",
"srcs",
".",
"reject",
"do",
"|",
"src",
"|",
"tgt",
"=",
"match_for",
"(",
"src",
")",
"mtchd_tgts",
"<<",
"tgt",
"if",
"tgt",
"end",
"unmtchd_tgts",
"=",
"tgts",
".",
"difference",
"(",
"mtchd_tgts",
")",
"logger",
".",
"debug",
"{",
"\"#{qp} matching #{unmtchd_tgts.qp}...\"",
"}",
"if",
"@verbose",
"and",
"not",
"unmtchd_tgts",
".",
"empty?",
"rsd_mtchs",
"=",
"@matcher",
".",
"match",
"(",
"unmtchd_srcs",
",",
"unmtchd_tgts",
",",
"source",
",",
"attribute",
")",
"rsd_mtchs",
".",
"each",
"{",
"|",
"src",
",",
"tgt",
"|",
"add_match",
"(",
"src",
",",
"tgt",
")",
"}",
"logger",
".",
"debug",
"{",
"\"#{qp} matched #{rsd_mtchs.qp}...\"",
"}",
"if",
"@verbose",
"and",
"not",
"rsd_mtchs",
".",
"empty?",
"matches",
"=",
"srcs",
".",
"to_compact_hash",
"{",
"|",
"src",
"|",
"match_for",
"(",
"src",
")",
"or",
"copy_unmatched",
"(",
"src",
")",
"}",
"matches",
"end"
] | Matches the given source and target attribute references.
The match is performed by this visitor's matcher.
@param source (see #visit)
@param target (see #visit)
@param [Symbol] attribute the parent reference attribute
@return [{Resource => Resource}] the referenced source => target matches | [
"Matches",
"the",
"given",
"source",
"and",
"target",
"attribute",
"references",
".",
"The",
"match",
"is",
"performed",
"by",
"this",
"visitor",
"s",
"matcher",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource/match_visitor.rb#L131-L157 | train |
DigitPaint/html_mockup | lib/html_mockup/extractor.rb | HtmlMockup.Extractor.extract_source_from_file | def extract_source_from_file(file_path, env = {})
source = HtmlMockup::Template.open(file_path, :partials_path => self.project.partial_path, :layouts_path => self.project.layouts_path).render(env.dup)
if @options[:url_relativize]
source = relativize_urls(source, file_path)
end
source
end | ruby | def extract_source_from_file(file_path, env = {})
source = HtmlMockup::Template.open(file_path, :partials_path => self.project.partial_path, :layouts_path => self.project.layouts_path).render(env.dup)
if @options[:url_relativize]
source = relativize_urls(source, file_path)
end
source
end | [
"def",
"extract_source_from_file",
"(",
"file_path",
",",
"env",
"=",
"{",
"}",
")",
"source",
"=",
"HtmlMockup",
"::",
"Template",
".",
"open",
"(",
"file_path",
",",
":partials_path",
"=>",
"self",
".",
"project",
".",
"partial_path",
",",
":layouts_path",
"=>",
"self",
".",
"project",
".",
"layouts_path",
")",
".",
"render",
"(",
"env",
".",
"dup",
")",
"if",
"@options",
"[",
":url_relativize",
"]",
"source",
"=",
"relativize_urls",
"(",
"source",
",",
"file_path",
")",
"end",
"source",
"end"
] | Runs the extractor on a single file and return processed source. | [
"Runs",
"the",
"extractor",
"on",
"a",
"single",
"file",
"and",
"return",
"processed",
"source",
"."
] | 976edadc01216b82a8cea177f53fb32559eaf41e | https://github.com/DigitPaint/html_mockup/blob/976edadc01216b82a8cea177f53fb32559eaf41e/lib/html_mockup/extractor.rb#L63-L71 | train |
booqable/scoped_serializer | lib/action_controller/serialization.rb | ActionController.Serialization.build_json_serializer | def build_json_serializer(object, options={})
ScopedSerializer.for(object, { :scope => serializer_scope, :super => true }.merge(options.merge(default_serializer_options)))
end | ruby | def build_json_serializer(object, options={})
ScopedSerializer.for(object, { :scope => serializer_scope, :super => true }.merge(options.merge(default_serializer_options)))
end | [
"def",
"build_json_serializer",
"(",
"object",
",",
"options",
"=",
"{",
"}",
")",
"ScopedSerializer",
".",
"for",
"(",
"object",
",",
"{",
":scope",
"=>",
"serializer_scope",
",",
":super",
"=>",
"true",
"}",
".",
"merge",
"(",
"options",
".",
"merge",
"(",
"default_serializer_options",
")",
")",
")",
"end"
] | JSON serializer to use. | [
"JSON",
"serializer",
"to",
"use",
"."
] | fb163bbf61f54a5e8684e4aba3908592bdd986ac | https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/action_controller/serialization.rb#L30-L32 | train |
terlar/formatter-number | lib/formatter/number.rb | Formatter.Number.format | def format(number)
case number
when Float then format_float(number)
when Integer then format_integer(number)
else fail ArgumentError
end
end | ruby | def format(number)
case number
when Float then format_float(number)
when Integer then format_integer(number)
else fail ArgumentError
end
end | [
"def",
"format",
"(",
"number",
")",
"case",
"number",
"when",
"Float",
"then",
"format_float",
"(",
"number",
")",
"when",
"Integer",
"then",
"format_integer",
"(",
"number",
")",
"else",
"fail",
"ArgumentError",
"end",
"end"
] | Initialize a formatter with the desired options.
@param [Hash] options the options to create a formatter with
@option options [Integer] :decimals (2) Number of decimal places
@option options [Boolean] :fixed (false) Fixed decimal places
@option options [String] :separator ('.') Decimal mark
@option options [Integer] :grouping (3) Number of digits per group
@option options [String] :delimiter (',') Delimiter between groups | [
"Initialize",
"a",
"formatter",
"with",
"the",
"desired",
"options",
"."
] | e206c92a6823f12d1019bd9ad5689d914d410ef3 | https://github.com/terlar/formatter-number/blob/e206c92a6823f12d1019bd9ad5689d914d410ef3/lib/formatter/number.rb#L26-L32 | train |
binford2k/arnold | gem/lib/arnold/node_manager.rb | Arnold.NodeManager.remove_stale_symlinks | def remove_stale_symlinks(path)
Dir.glob("#{path}/*").each { |f| File.unlink(f) if not File.exist?(f) }
end | ruby | def remove_stale_symlinks(path)
Dir.glob("#{path}/*").each { |f| File.unlink(f) if not File.exist?(f) }
end | [
"def",
"remove_stale_symlinks",
"(",
"path",
")",
"Dir",
".",
"glob",
"(",
"\"#{path}/*\"",
")",
".",
"each",
"{",
"|",
"f",
"|",
"File",
".",
"unlink",
"(",
"f",
")",
"if",
"not",
"File",
".",
"exist?",
"(",
"f",
")",
"}",
"end"
] | just loop through a directory and get rid of any stale symlinks | [
"just",
"loop",
"through",
"a",
"directory",
"and",
"get",
"rid",
"of",
"any",
"stale",
"symlinks"
] | 8bf1b3c1ae0e76cc97dff1a07b24c2fa9170b688 | https://github.com/binford2k/arnold/blob/8bf1b3c1ae0e76cc97dff1a07b24c2fa9170b688/gem/lib/arnold/node_manager.rb#L114-L116 | train |
bluevialabs/connfu-client | lib/connfu/listener.rb | Connfu.Listener.start | def start(queue = nil)
queue.nil? and queue = @queue
logger.debug "Listener starts..."
@thread = Thread.new {
# listen to connFu
@connfu_stream.start_listening
}
while continue do
logger.debug "Waiting for a message from connFu stream"
message = @connfu_stream.get
@counter = @counter + 1
logger.debug "#{self.class} got message => #{message}"
# Write in internal Queue
queue.put(message)
end
end | ruby | def start(queue = nil)
queue.nil? and queue = @queue
logger.debug "Listener starts..."
@thread = Thread.new {
# listen to connFu
@connfu_stream.start_listening
}
while continue do
logger.debug "Waiting for a message from connFu stream"
message = @connfu_stream.get
@counter = @counter + 1
logger.debug "#{self.class} got message => #{message}"
# Write in internal Queue
queue.put(message)
end
end | [
"def",
"start",
"(",
"queue",
"=",
"nil",
")",
"queue",
".",
"nil?",
"and",
"queue",
"=",
"@queue",
"logger",
".",
"debug",
"\"Listener starts...\"",
"@thread",
"=",
"Thread",
".",
"new",
"{",
"@connfu_stream",
".",
"start_listening",
"}",
"while",
"continue",
"do",
"logger",
".",
"debug",
"\"Waiting for a message from connFu stream\"",
"message",
"=",
"@connfu_stream",
".",
"get",
"@counter",
"=",
"@counter",
"+",
"1",
"logger",
".",
"debug",
"\"#{self.class} got message => #{message}\"",
"queue",
".",
"put",
"(",
"message",
")",
"end",
"end"
] | max amount of messages to receive
Listener initializer.
==== Parameters
* +queue+ Connfu::Events instance to forward incoming events to be processed by the Dispatcher class
* +app_stream+ valid HTTP stream url to connect and listen events
* +token+ valid token to get access to a connFu Stream
* +stream_endpoint+ endpoint to open a keepalive HTTP connection
start listening.
Should create a new thread and wait to new events to come
==== Parameters
* +queue+ to send incoming events to the Dispatcher class | [
"max",
"amount",
"of",
"messages",
"to",
"receive"
] | b62a0f5176afa203ba1eecccc7994d6bc61af3a7 | https://github.com/bluevialabs/connfu-client/blob/b62a0f5176afa203ba1eecccc7994d6bc61af3a7/lib/connfu/listener.rb#L40-L59 | train |
jinx/core | lib/jinx/resource.rb | Jinx.Resource.owner= | def owner=(obj)
if obj.nil? then
op, ov = effective_owner_property_value || return
else
op = self.class.owner_properties.detect { |prop| prop.type === obj }
end
if op.nil? then raise NoMethodError.new("#{self.class.qp} does not have an owner attribute for #{obj}") end
set_property_value(op.attribute, obj)
end | ruby | def owner=(obj)
if obj.nil? then
op, ov = effective_owner_property_value || return
else
op = self.class.owner_properties.detect { |prop| prop.type === obj }
end
if op.nil? then raise NoMethodError.new("#{self.class.qp} does not have an owner attribute for #{obj}") end
set_property_value(op.attribute, obj)
end | [
"def",
"owner",
"=",
"(",
"obj",
")",
"if",
"obj",
".",
"nil?",
"then",
"op",
",",
"ov",
"=",
"effective_owner_property_value",
"||",
"return",
"else",
"op",
"=",
"self",
".",
"class",
".",
"owner_properties",
".",
"detect",
"{",
"|",
"prop",
"|",
"prop",
".",
"type",
"===",
"obj",
"}",
"end",
"if",
"op",
".",
"nil?",
"then",
"raise",
"NoMethodError",
".",
"new",
"(",
"\"#{self.class.qp} does not have an owner attribute for #{obj}\"",
")",
"end",
"set_property_value",
"(",
"op",
".",
"attribute",
",",
"obj",
")",
"end"
] | Sets this dependent's owner attribute to the given domain object.
@param [Resource] obj the owner domain object
@raise [NoMethodError] if this Resource's class does not have an owner property
which accepts the given domain object | [
"Sets",
"this",
"dependent",
"s",
"owner",
"attribute",
"to",
"the",
"given",
"domain",
"object",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L226-L234 | train |
jinx/core | lib/jinx/resource.rb | Jinx.Resource.references | def references(attributes=nil)
attributes ||= self.class.domain_attributes
attributes.map { |pa| send(pa) }.flatten.compact
end | ruby | def references(attributes=nil)
attributes ||= self.class.domain_attributes
attributes.map { |pa| send(pa) }.flatten.compact
end | [
"def",
"references",
"(",
"attributes",
"=",
"nil",
")",
"attributes",
"||=",
"self",
".",
"class",
".",
"domain_attributes",
"attributes",
".",
"map",
"{",
"|",
"pa",
"|",
"send",
"(",
"pa",
")",
"}",
".",
"flatten",
".",
"compact",
"end"
] | Returns the domain object references for the given attributes.
@param [<Symbol>, nil] the domain attributes to include, or nil to include all domain attributes
@return [<Resource>] the referenced attribute domain object values | [
"Returns",
"the",
"domain",
"object",
"references",
"for",
"the",
"given",
"attributes",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L277-L280 | train |
jinx/core | lib/jinx/resource.rb | Jinx.Resource.direct_dependents | def direct_dependents(attribute)
deps = send(attribute)
case deps
when Enumerable then deps
when nil then Array::EMPTY_ARRAY
else [deps]
end
end | ruby | def direct_dependents(attribute)
deps = send(attribute)
case deps
when Enumerable then deps
when nil then Array::EMPTY_ARRAY
else [deps]
end
end | [
"def",
"direct_dependents",
"(",
"attribute",
")",
"deps",
"=",
"send",
"(",
"attribute",
")",
"case",
"deps",
"when",
"Enumerable",
"then",
"deps",
"when",
"nil",
"then",
"Array",
"::",
"EMPTY_ARRAY",
"else",
"[",
"deps",
"]",
"end",
"end"
] | Returns the attribute references which directly depend on this owner.
The default is the attribute value.
Returns an Enumerable. If the value is not already an Enumerable, then this method
returns an empty array if value is nil, or a singelton array with value otherwise.
If there is more than one owner of a dependent, then subclasses should override this
method to select dependents whose dependency path is shorter than an alternative
dependency path, e.g. if a Node is owned by both a Graph and a parent
Node. In that case, the Graph direct dependents consist of the top-level nodes
owned by the Graph but not referenced by another Node.
@param [Symbol] attribute the dependent attribute
@return [<Resource>] the attribute value, wrapped in an array if necessary | [
"Returns",
"the",
"attribute",
"references",
"which",
"directly",
"depend",
"on",
"this",
"owner",
".",
"The",
"default",
"is",
"the",
"attribute",
"value",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L335-L342 | train |
jinx/core | lib/jinx/resource.rb | Jinx.Resource.match_in | def match_in(others)
# trivial case: self is in others
return self if others.include?(self)
# filter for the same type
unless others.all? { |other| self.class === other } then
others = others.filter { |other| self.class === other }
end
# match on primary, secondary or alternate key
match_unique_object_with_attributes(others, self.class.primary_key_attributes) or
match_unique_object_with_attributes(others, self.class.secondary_key_attributes) or
match_unique_object_with_attributes(others, self.class.alternate_key_attributes)
end | ruby | def match_in(others)
# trivial case: self is in others
return self if others.include?(self)
# filter for the same type
unless others.all? { |other| self.class === other } then
others = others.filter { |other| self.class === other }
end
# match on primary, secondary or alternate key
match_unique_object_with_attributes(others, self.class.primary_key_attributes) or
match_unique_object_with_attributes(others, self.class.secondary_key_attributes) or
match_unique_object_with_attributes(others, self.class.alternate_key_attributes)
end | [
"def",
"match_in",
"(",
"others",
")",
"return",
"self",
"if",
"others",
".",
"include?",
"(",
"self",
")",
"unless",
"others",
".",
"all?",
"{",
"|",
"other",
"|",
"self",
".",
"class",
"===",
"other",
"}",
"then",
"others",
"=",
"others",
".",
"filter",
"{",
"|",
"other",
"|",
"self",
".",
"class",
"===",
"other",
"}",
"end",
"match_unique_object_with_attributes",
"(",
"others",
",",
"self",
".",
"class",
".",
"primary_key_attributes",
")",
"or",
"match_unique_object_with_attributes",
"(",
"others",
",",
"self",
".",
"class",
".",
"secondary_key_attributes",
")",
"or",
"match_unique_object_with_attributes",
"(",
"others",
",",
"self",
".",
"class",
".",
"alternate_key_attributes",
")",
"end"
] | Matches this dependent domain object with the others on type and key attributes
in the scope of a parent object.
Returns the object in others which matches this domain object, or nil if none.
The match attributes are, in order:
* the primary key
* the secondary key
* the alternate key
This domain object is matched against the others on the above attributes in succession
until a unique match is found. The key attribute matches are strict, i.e. each
key attribute value must be non-nil and match the other value.
@param [<Resource>] the candidate domain object matches
@return [Resource, nil] the matching domain object, or nil if no match | [
"Matches",
"this",
"dependent",
"domain",
"object",
"with",
"the",
"others",
"on",
"type",
"and",
"key",
"attributes",
"in",
"the",
"scope",
"of",
"a",
"parent",
"object",
".",
"Returns",
"the",
"object",
"in",
"others",
"which",
"matches",
"this",
"domain",
"object",
"or",
"nil",
"if",
"none",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L393-L404 | train |
jinx/core | lib/jinx/resource.rb | Jinx.Resource.visit_path | def visit_path(*path, &operator)
visitor = ReferencePathVisitor.new(self.class, path)
visitor.visit(self, &operator)
end | ruby | def visit_path(*path, &operator)
visitor = ReferencePathVisitor.new(self.class, path)
visitor.visit(self, &operator)
end | [
"def",
"visit_path",
"(",
"*",
"path",
",",
"&",
"operator",
")",
"visitor",
"=",
"ReferencePathVisitor",
".",
"new",
"(",
"self",
".",
"class",
",",
"path",
")",
"visitor",
".",
"visit",
"(",
"self",
",",
"&",
"operator",
")",
"end"
] | Applies the operator block to this object and each domain object in the reference path.
This method visits the transitive closure of each recursive path attribute.
@param [<Symbol>] path the attributes to visit
@yieldparam [Symbol] attribute the attribute to visit
@return the visit result
@see ReferencePathVisitor | [
"Applies",
"the",
"operator",
"block",
"to",
"this",
"object",
"and",
"each",
"domain",
"object",
"in",
"the",
"reference",
"path",
".",
"This",
"method",
"visits",
"the",
"transitive",
"closure",
"of",
"each",
"recursive",
"path",
"attribute",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L494-L497 | train |
jinx/core | lib/jinx/resource.rb | Jinx.Resource.printable_content | def printable_content(attributes=nil, &reference_printer)
attributes ||= printworthy_attributes
vh = value_hash(attributes)
vh.transform_value { |value| printable_value(value, &reference_printer) }
end | ruby | def printable_content(attributes=nil, &reference_printer)
attributes ||= printworthy_attributes
vh = value_hash(attributes)
vh.transform_value { |value| printable_value(value, &reference_printer) }
end | [
"def",
"printable_content",
"(",
"attributes",
"=",
"nil",
",",
"&",
"reference_printer",
")",
"attributes",
"||=",
"printworthy_attributes",
"vh",
"=",
"value_hash",
"(",
"attributes",
")",
"vh",
".",
"transform_value",
"{",
"|",
"value",
"|",
"printable_value",
"(",
"value",
",",
"&",
"reference_printer",
")",
"}",
"end"
] | Returns this domain object's attributes content as an attribute => value hash
suitable for printing.
The default attributes are this object's saved attributes. The optional
reference_printer is used to print a referenced domain object.
@param [<Symbol>, nil] attributes the attributes to print
@yield [ref] the reference print formatter
@yieldparam [Resource] ref the referenced domain object to print
@return [{Symbol => String}] the attribute => content hash | [
"Returns",
"this",
"domain",
"object",
"s",
"attributes",
"content",
"as",
"an",
"attribute",
"=",
">",
"value",
"hash",
"suitable",
"for",
"printing",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L560-L564 | train |
jinx/core | lib/jinx/resource.rb | Jinx.Resource.validate_mandatory_attributes | def validate_mandatory_attributes
invalid = missing_mandatory_attributes
unless invalid.empty? then
logger.error("Validation of #{qp} unsuccessful - missing #{invalid.join(', ')}:\n#{dump}")
raise ValidationError.new("Required attribute value missing for #{self}: #{invalid.join(', ')}")
end
validate_owner
end | ruby | def validate_mandatory_attributes
invalid = missing_mandatory_attributes
unless invalid.empty? then
logger.error("Validation of #{qp} unsuccessful - missing #{invalid.join(', ')}:\n#{dump}")
raise ValidationError.new("Required attribute value missing for #{self}: #{invalid.join(', ')}")
end
validate_owner
end | [
"def",
"validate_mandatory_attributes",
"invalid",
"=",
"missing_mandatory_attributes",
"unless",
"invalid",
".",
"empty?",
"then",
"logger",
".",
"error",
"(",
"\"Validation of #{qp} unsuccessful - missing #{invalid.join(', ')}:\\n#{dump}\"",
")",
"raise",
"ValidationError",
".",
"new",
"(",
"\"Required attribute value missing for #{self}: #{invalid.join(', ')}\"",
")",
"end",
"validate_owner",
"end"
] | Validates that this domain object contains a non-nil value for each mandatory attribute.
@raise [ValidationError] if a mandatory attribute value is missing | [
"Validates",
"that",
"this",
"domain",
"object",
"contains",
"a",
"non",
"-",
"nil",
"value",
"for",
"each",
"mandatory",
"attribute",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L703-L710 | train |
jinx/core | lib/jinx/resource.rb | Jinx.Resource.validate_owner | def validate_owner
# If there is an unambigous owner, then we are done.
return unless owner.nil?
# If there is more than one owner attribute, then check that there is at most one
# unambiguous owner reference. The owner method returns nil if the owner is ambiguous.
if self.class.owner_attributes.size > 1 then
vh = value_hash(self.class.owner_attributes)
if vh.size > 1 then
raise ValidationError.new("Dependent #{self} references multiple owners #{vh.pp_s}:\n#{dump}")
end
end
# If there is an owner reference attribute, then there must be an owner.
if self.class.bidirectional_java_dependent? then
raise ValidationError.new("Dependent #{self} does not reference an owner")
end
end | ruby | def validate_owner
# If there is an unambigous owner, then we are done.
return unless owner.nil?
# If there is more than one owner attribute, then check that there is at most one
# unambiguous owner reference. The owner method returns nil if the owner is ambiguous.
if self.class.owner_attributes.size > 1 then
vh = value_hash(self.class.owner_attributes)
if vh.size > 1 then
raise ValidationError.new("Dependent #{self} references multiple owners #{vh.pp_s}:\n#{dump}")
end
end
# If there is an owner reference attribute, then there must be an owner.
if self.class.bidirectional_java_dependent? then
raise ValidationError.new("Dependent #{self} does not reference an owner")
end
end | [
"def",
"validate_owner",
"return",
"unless",
"owner",
".",
"nil?",
"if",
"self",
".",
"class",
".",
"owner_attributes",
".",
"size",
">",
"1",
"then",
"vh",
"=",
"value_hash",
"(",
"self",
".",
"class",
".",
"owner_attributes",
")",
"if",
"vh",
".",
"size",
">",
"1",
"then",
"raise",
"ValidationError",
".",
"new",
"(",
"\"Dependent #{self} references multiple owners #{vh.pp_s}:\\n#{dump}\"",
")",
"end",
"end",
"if",
"self",
".",
"class",
".",
"bidirectional_java_dependent?",
"then",
"raise",
"ValidationError",
".",
"new",
"(",
"\"Dependent #{self} does not reference an owner\"",
")",
"end",
"end"
] | Validates that this domain object either doesn't have an owner attribute or has a unique
effective owner.
@raise [ValidationError] if there is an owner reference attribute that is not set
@raise [ValidationError] if there is more than effective owner | [
"Validates",
"that",
"this",
"domain",
"object",
"either",
"doesn",
"t",
"have",
"an",
"owner",
"attribute",
"or",
"has",
"a",
"unique",
"effective",
"owner",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L717-L732 | train |
jinx/core | lib/jinx/resource.rb | Jinx.Resource.printable_value | def printable_value(value, &reference_printer)
Jinx::Collector.on(value) do |item|
if Resource === item then
block_given? ? yield(item) : printable_value(item) { |ref| ReferencePrinter.new(ref) }
else
item
end
end
end | ruby | def printable_value(value, &reference_printer)
Jinx::Collector.on(value) do |item|
if Resource === item then
block_given? ? yield(item) : printable_value(item) { |ref| ReferencePrinter.new(ref) }
else
item
end
end
end | [
"def",
"printable_value",
"(",
"value",
",",
"&",
"reference_printer",
")",
"Jinx",
"::",
"Collector",
".",
"on",
"(",
"value",
")",
"do",
"|",
"item",
"|",
"if",
"Resource",
"===",
"item",
"then",
"block_given?",
"?",
"yield",
"(",
"item",
")",
":",
"printable_value",
"(",
"item",
")",
"{",
"|",
"ref",
"|",
"ReferencePrinter",
".",
"new",
"(",
"ref",
")",
"}",
"else",
"item",
"end",
"end",
"end"
] | Returns a value suitable for printing. If value is a domain object, then the block provided to this method is called.
The default block creates a new ReferencePrinter on the value. | [
"Returns",
"a",
"value",
"suitable",
"for",
"printing",
".",
"If",
"value",
"is",
"a",
"domain",
"object",
"then",
"the",
"block",
"provided",
"to",
"this",
"method",
"is",
"called",
".",
"The",
"default",
"block",
"creates",
"a",
"new",
"ReferencePrinter",
"on",
"the",
"value",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L807-L815 | train |
jinx/core | lib/jinx/resource.rb | Jinx.Resource.printworthy_attributes | def printworthy_attributes
if self.class.primary_key_attributes.all? { |pa| !!send(pa) } then
self.class.primary_key_attributes
elsif not self.class.secondary_key_attributes.empty? then
self.class.secondary_key_attributes
elsif not self.class.nondomain_java_attributes.empty? then
self.class.nondomain_java_attributes
else
self.class.fetched_attributes
end
end | ruby | def printworthy_attributes
if self.class.primary_key_attributes.all? { |pa| !!send(pa) } then
self.class.primary_key_attributes
elsif not self.class.secondary_key_attributes.empty? then
self.class.secondary_key_attributes
elsif not self.class.nondomain_java_attributes.empty? then
self.class.nondomain_java_attributes
else
self.class.fetched_attributes
end
end | [
"def",
"printworthy_attributes",
"if",
"self",
".",
"class",
".",
"primary_key_attributes",
".",
"all?",
"{",
"|",
"pa",
"|",
"!",
"!",
"send",
"(",
"pa",
")",
"}",
"then",
"self",
".",
"class",
".",
"primary_key_attributes",
"elsif",
"not",
"self",
".",
"class",
".",
"secondary_key_attributes",
".",
"empty?",
"then",
"self",
".",
"class",
".",
"secondary_key_attributes",
"elsif",
"not",
"self",
".",
"class",
".",
"nondomain_java_attributes",
".",
"empty?",
"then",
"self",
".",
"class",
".",
"nondomain_java_attributes",
"else",
"self",
".",
"class",
".",
"fetched_attributes",
"end",
"end"
] | Returns an attribute => value hash which identifies the object.
If this object has a complete primary key, than the primary key attributes are returned.
Otherwise, if there are secondary key attributes, then they are returned.
Otherwise, if there are nondomain attributes, then they are returned.
Otherwise, if there are fetched attributes, then they are returned.
@return [<Symbol] the attributes to print | [
"Returns",
"an",
"attribute",
"=",
">",
"value",
"hash",
"which",
"identifies",
"the",
"object",
".",
"If",
"this",
"object",
"has",
"a",
"complete",
"primary",
"key",
"than",
"the",
"primary",
"key",
"attributes",
"are",
"returned",
".",
"Otherwise",
"if",
"there",
"are",
"secondary",
"key",
"attributes",
"then",
"they",
"are",
"returned",
".",
"Otherwise",
"if",
"there",
"are",
"nondomain",
"attributes",
"then",
"they",
"are",
"returned",
".",
"Otherwise",
"if",
"there",
"are",
"fetched",
"attributes",
"then",
"they",
"are",
"returned",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L824-L834 | train |
jinx/core | lib/jinx/resource.rb | Jinx.Resource.empty_value | def empty_value(attribute)
type = java_type(attribute) || return
if type.primitive? then
type.name == 'boolean' ? false : 0
else
self.class.empty_value(attribute)
end
end | ruby | def empty_value(attribute)
type = java_type(attribute) || return
if type.primitive? then
type.name == 'boolean' ? false : 0
else
self.class.empty_value(attribute)
end
end | [
"def",
"empty_value",
"(",
"attribute",
")",
"type",
"=",
"java_type",
"(",
"attribute",
")",
"||",
"return",
"if",
"type",
".",
"primitive?",
"then",
"type",
".",
"name",
"==",
"'boolean'",
"?",
"false",
":",
"0",
"else",
"self",
".",
"class",
".",
"empty_value",
"(",
"attribute",
")",
"end",
"end"
] | Returns 0 if attribute is a Java primitive number,
+false+ if attribute is a Java primitive boolean,
an empty collectin if the Java attribute is a collection,
nil otherwise. | [
"Returns",
"0",
"if",
"attribute",
"is",
"a",
"Java",
"primitive",
"number",
"+",
"false",
"+",
"if",
"attribute",
"is",
"a",
"Java",
"primitive",
"boolean",
"an",
"empty",
"collectin",
"if",
"the",
"Java",
"attribute",
"is",
"a",
"collection",
"nil",
"otherwise",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L872-L879 | train |
jinx/core | lib/jinx/resource.rb | Jinx.Resource.java_type | def java_type(attribute)
prop = self.class.property(attribute)
prop.property_descriptor.attribute_type if JavaProperty === prop
end | ruby | def java_type(attribute)
prop = self.class.property(attribute)
prop.property_descriptor.attribute_type if JavaProperty === prop
end | [
"def",
"java_type",
"(",
"attribute",
")",
"prop",
"=",
"self",
".",
"class",
".",
"property",
"(",
"attribute",
")",
"prop",
".",
"property_descriptor",
".",
"attribute_type",
"if",
"JavaProperty",
"===",
"prop",
"end"
] | Returns the Java type of the given attribute, or nil if attribute is not a Java property attribute. | [
"Returns",
"the",
"Java",
"type",
"of",
"the",
"given",
"attribute",
"or",
"nil",
"if",
"attribute",
"is",
"not",
"a",
"Java",
"property",
"attribute",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L882-L885 | train |
jinx/core | lib/jinx/resource.rb | Jinx.Resource.match_unique_object_with_attributes | def match_unique_object_with_attributes(others, attributes)
vh = value_hash(attributes)
return if vh.empty? or vh.size < attributes.size
matches = others.select do |other|
self.class == other.class and
vh.all? { |pa, v| other.matches_attribute_value?(pa, v) }
end
matches.first if matches.size == 1
end | ruby | def match_unique_object_with_attributes(others, attributes)
vh = value_hash(attributes)
return if vh.empty? or vh.size < attributes.size
matches = others.select do |other|
self.class == other.class and
vh.all? { |pa, v| other.matches_attribute_value?(pa, v) }
end
matches.first if matches.size == 1
end | [
"def",
"match_unique_object_with_attributes",
"(",
"others",
",",
"attributes",
")",
"vh",
"=",
"value_hash",
"(",
"attributes",
")",
"return",
"if",
"vh",
".",
"empty?",
"or",
"vh",
".",
"size",
"<",
"attributes",
".",
"size",
"matches",
"=",
"others",
".",
"select",
"do",
"|",
"other",
"|",
"self",
".",
"class",
"==",
"other",
".",
"class",
"and",
"vh",
".",
"all?",
"{",
"|",
"pa",
",",
"v",
"|",
"other",
".",
"matches_attribute_value?",
"(",
"pa",
",",
"v",
")",
"}",
"end",
"matches",
".",
"first",
"if",
"matches",
".",
"size",
"==",
"1",
"end"
] | Returns the object in others which uniquely matches this domain object on the given attributes,
or nil if there is no unique match. This method returns nil if any attributes value is nil. | [
"Returns",
"the",
"object",
"in",
"others",
"which",
"uniquely",
"matches",
"this",
"domain",
"object",
"on",
"the",
"given",
"attributes",
"or",
"nil",
"if",
"there",
"is",
"no",
"unique",
"match",
".",
"This",
"method",
"returns",
"nil",
"if",
"any",
"attributes",
"value",
"is",
"nil",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L930-L938 | train |
jinx/core | lib/jinx/resource.rb | Jinx.Resource.non_id_search_attribute_values | def non_id_search_attribute_values
# if there is a secondary key, then search on those attributes.
# otherwise, search on all attributes.
key_props = self.class.secondary_key_attributes
pas = key_props.empty? ? self.class.nondomain_java_attributes : key_props
# associate the values
attr_values = pas.to_compact_hash { |pa| send(pa) }
# if there is no secondary key, then cull empty values
key_props.empty? ? attr_values.delete_if { |pa, value| value.nil? } : attr_values
end | ruby | def non_id_search_attribute_values
# if there is a secondary key, then search on those attributes.
# otherwise, search on all attributes.
key_props = self.class.secondary_key_attributes
pas = key_props.empty? ? self.class.nondomain_java_attributes : key_props
# associate the values
attr_values = pas.to_compact_hash { |pa| send(pa) }
# if there is no secondary key, then cull empty values
key_props.empty? ? attr_values.delete_if { |pa, value| value.nil? } : attr_values
end | [
"def",
"non_id_search_attribute_values",
"key_props",
"=",
"self",
".",
"class",
".",
"secondary_key_attributes",
"pas",
"=",
"key_props",
".",
"empty?",
"?",
"self",
".",
"class",
".",
"nondomain_java_attributes",
":",
"key_props",
"attr_values",
"=",
"pas",
".",
"to_compact_hash",
"{",
"|",
"pa",
"|",
"send",
"(",
"pa",
")",
"}",
"key_props",
".",
"empty?",
"?",
"attr_values",
".",
"delete_if",
"{",
"|",
"pa",
",",
"value",
"|",
"value",
".",
"nil?",
"}",
":",
"attr_values",
"end"
] | Returns the attribute => value hash to use for matching this domain object.
@see #search_attribute_values the method specification | [
"Returns",
"the",
"attribute",
"=",
">",
"value",
"hash",
"to",
"use",
"for",
"matching",
"this",
"domain",
"object",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L953-L962 | train |
barkerest/incline | lib/incline/extensions/action_controller_base.rb | Incline::Extensions.ActionControllerBase.render_csv | def render_csv(filename = nil, view_name = nil)
filename ||= params[:action]
view_name ||= params[:action]
filename.downcase!
filename += '.csv' unless filename[-4..-1] == '.csv'
headers['Content-Type'] = 'text/csv'
headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
render view_name, layout: false
end | ruby | def render_csv(filename = nil, view_name = nil)
filename ||= params[:action]
view_name ||= params[:action]
filename.downcase!
filename += '.csv' unless filename[-4..-1] == '.csv'
headers['Content-Type'] = 'text/csv'
headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
render view_name, layout: false
end | [
"def",
"render_csv",
"(",
"filename",
"=",
"nil",
",",
"view_name",
"=",
"nil",
")",
"filename",
"||=",
"params",
"[",
":action",
"]",
"view_name",
"||=",
"params",
"[",
":action",
"]",
"filename",
".",
"downcase!",
"filename",
"+=",
"'.csv'",
"unless",
"filename",
"[",
"-",
"4",
"..",
"-",
"1",
"]",
"==",
"'.csv'",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'text/csv'",
"headers",
"[",
"'Content-Disposition'",
"]",
"=",
"\"attachment; filename=\\\"#{filename}\\\"\"",
"render",
"view_name",
",",
"layout",
":",
"false",
"end"
] | Renders the view as a CSV file.
Set the +filename+ you would like to provide to the client, or leave it nil to use the action name.
Set the +view_name+ you would like to render, or leave it nil to use the action name. | [
"Renders",
"the",
"view",
"as",
"a",
"CSV",
"file",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/action_controller_base.rb#L213-L224 | train |
barkerest/incline | lib/incline/extensions/action_controller_base.rb | Incline::Extensions.ActionControllerBase.authorize! | def authorize!(*accepted_groups) #:doc:
begin
# an authenticated user must exist.
unless logged_in?
store_location
if (auth_url = ::Incline::UserManager.begin_external_authentication(request))
::Incline::Log.debug 'Redirecting for external authentication.'
redirect_to auth_url
return false
end
raise_not_logged_in "You need to login to access '#{request.fullpath}'.",
'nobody is logged in'
end
if system_admin?
log_authorize_success 'user is system admin'
else
# clean up the group list.
accepted_groups ||= []
accepted_groups.flatten!
accepted_groups.delete false
accepted_groups.delete ''
if accepted_groups.include?(true)
# group_list contains "true" so only a system admin may continue.
raise_authorize_failure "Your are not authorized to access '#{request.fullpath}'.",
'requires system administrator'
elsif accepted_groups.blank?
# group_list is empty or contained nothing but empty strings and boolean false.
# everyone can continue.
log_authorize_success 'only requires authenticated user'
else
# the group list contains one or more authorized groups.
# we want them to all be uppercase strings.
accepted_groups = accepted_groups.map{|v| v.to_s.upcase}.sort
result = current_user.has_any_group?(*accepted_groups)
unless result
raise_authorize_failure "You are not authorized to access '#{request.fullpath}'.",
"requires one of: #{accepted_groups.inspect}"
end
log_authorize_success "user has #{result.inspect}"
end
end
rescue ::Incline::NotAuthorized => err
flash[:danger] = err.message
redirect_to main_app.root_url
return false
end
true
end | ruby | def authorize!(*accepted_groups) #:doc:
begin
# an authenticated user must exist.
unless logged_in?
store_location
if (auth_url = ::Incline::UserManager.begin_external_authentication(request))
::Incline::Log.debug 'Redirecting for external authentication.'
redirect_to auth_url
return false
end
raise_not_logged_in "You need to login to access '#{request.fullpath}'.",
'nobody is logged in'
end
if system_admin?
log_authorize_success 'user is system admin'
else
# clean up the group list.
accepted_groups ||= []
accepted_groups.flatten!
accepted_groups.delete false
accepted_groups.delete ''
if accepted_groups.include?(true)
# group_list contains "true" so only a system admin may continue.
raise_authorize_failure "Your are not authorized to access '#{request.fullpath}'.",
'requires system administrator'
elsif accepted_groups.blank?
# group_list is empty or contained nothing but empty strings and boolean false.
# everyone can continue.
log_authorize_success 'only requires authenticated user'
else
# the group list contains one or more authorized groups.
# we want them to all be uppercase strings.
accepted_groups = accepted_groups.map{|v| v.to_s.upcase}.sort
result = current_user.has_any_group?(*accepted_groups)
unless result
raise_authorize_failure "You are not authorized to access '#{request.fullpath}'.",
"requires one of: #{accepted_groups.inspect}"
end
log_authorize_success "user has #{result.inspect}"
end
end
rescue ::Incline::NotAuthorized => err
flash[:danger] = err.message
redirect_to main_app.root_url
return false
end
true
end | [
"def",
"authorize!",
"(",
"*",
"accepted_groups",
")",
"begin",
"unless",
"logged_in?",
"store_location",
"if",
"(",
"auth_url",
"=",
"::",
"Incline",
"::",
"UserManager",
".",
"begin_external_authentication",
"(",
"request",
")",
")",
"::",
"Incline",
"::",
"Log",
".",
"debug",
"'Redirecting for external authentication.'",
"redirect_to",
"auth_url",
"return",
"false",
"end",
"raise_not_logged_in",
"\"You need to login to access '#{request.fullpath}'.\"",
",",
"'nobody is logged in'",
"end",
"if",
"system_admin?",
"log_authorize_success",
"'user is system admin'",
"else",
"accepted_groups",
"||=",
"[",
"]",
"accepted_groups",
".",
"flatten!",
"accepted_groups",
".",
"delete",
"false",
"accepted_groups",
".",
"delete",
"''",
"if",
"accepted_groups",
".",
"include?",
"(",
"true",
")",
"raise_authorize_failure",
"\"Your are not authorized to access '#{request.fullpath}'.\"",
",",
"'requires system administrator'",
"elsif",
"accepted_groups",
".",
"blank?",
"log_authorize_success",
"'only requires authenticated user'",
"else",
"accepted_groups",
"=",
"accepted_groups",
".",
"map",
"{",
"|",
"v",
"|",
"v",
".",
"to_s",
".",
"upcase",
"}",
".",
"sort",
"result",
"=",
"current_user",
".",
"has_any_group?",
"(",
"*",
"accepted_groups",
")",
"unless",
"result",
"raise_authorize_failure",
"\"You are not authorized to access '#{request.fullpath}'.\"",
",",
"\"requires one of: #{accepted_groups.inspect}\"",
"end",
"log_authorize_success",
"\"user has #{result.inspect}\"",
"end",
"end",
"rescue",
"::",
"Incline",
"::",
"NotAuthorized",
"=>",
"err",
"flash",
"[",
":danger",
"]",
"=",
"err",
".",
"message",
"redirect_to",
"main_app",
".",
"root_url",
"return",
"false",
"end",
"true",
"end"
] | Authorizes access for the action.
* With no arguments, this will validate that a user is currently logged in, but does not check their permission.
* With an argument of true, this will validate that the user currently logged in is an administrator.
* With one or more strings, this will validate that the user currently logged in has at least one or more
of the named permissions.
authorize!
authorize! true
authorize! "Safety Manager", "HR Manager"
If no user is logged in, then the user will be redirected to the login page and the method will return false.
If a user is logged in, but is not authorized, then the user will be redirected to the home page and the method
will return false.
If the user is authorized, the method will return true. | [
"Authorizes",
"access",
"for",
"the",
"action",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/action_controller_base.rb#L282-L339 | train |
barkerest/incline | lib/incline/extensions/action_controller_base.rb | Incline::Extensions.ActionControllerBase.valid_user? | def valid_user? #:doc:
if require_admin_for_request?
authorize! true
elsif require_anon_for_request?
if logged_in?
flash[:warning] = 'The specified action cannot be performed while logged in.'
redirect_to incline.user_path(current_user)
end
elsif allow_anon_for_request?
true
else
action = Incline::ActionSecurity.valid_items[self.class.controller_path, params[:action]]
if action && action.groups.count > 0
authorize! action.groups.pluck(:name)
else
authorize!
end
end
end | ruby | def valid_user? #:doc:
if require_admin_for_request?
authorize! true
elsif require_anon_for_request?
if logged_in?
flash[:warning] = 'The specified action cannot be performed while logged in.'
redirect_to incline.user_path(current_user)
end
elsif allow_anon_for_request?
true
else
action = Incline::ActionSecurity.valid_items[self.class.controller_path, params[:action]]
if action && action.groups.count > 0
authorize! action.groups.pluck(:name)
else
authorize!
end
end
end | [
"def",
"valid_user?",
"if",
"require_admin_for_request?",
"authorize!",
"true",
"elsif",
"require_anon_for_request?",
"if",
"logged_in?",
"flash",
"[",
":warning",
"]",
"=",
"'The specified action cannot be performed while logged in.'",
"redirect_to",
"incline",
".",
"user_path",
"(",
"current_user",
")",
"end",
"elsif",
"allow_anon_for_request?",
"true",
"else",
"action",
"=",
"Incline",
"::",
"ActionSecurity",
".",
"valid_items",
"[",
"self",
".",
"class",
".",
"controller_path",
",",
"params",
"[",
":action",
"]",
"]",
"if",
"action",
"&&",
"action",
".",
"groups",
".",
"count",
">",
"0",
"authorize!",
"action",
".",
"groups",
".",
"pluck",
"(",
":name",
")",
"else",
"authorize!",
"end",
"end",
"end"
] | Validates that the current user is authorized for the current request.
This method is called for every action except the :api action.
For the :api action, this method will not be called until the actual requested action is performed.
One of four scenarios are possible:
1. If the +require_admin+ method applies to the current action, then a system administrator must be logged in.
1. If a nobody is logged in, then the user will be redirected to the login url.
2. If a system administrator is logged in, then access is granted.
3. Non-system administrators will be redirected to the root url.
2. If the +require_anon+ method applies to the current action, then a user cannot be logged in.
1. If a user is logged in, a warning message is set and the user is redirected to their account.
2. If no user is logged in, then access is granted.
3. If the +allow_anon+ method applies to the current action, then access is granted.
4. The action doesn't require a system administrator, but does require a valid user to be logged in.
1. If nobody is logged in, then the user will be redirected to the login url.
2. If a system administrator is logged in, then access is granted.
3. If the action doesn't have any required permissions, then access is granted to any logged in user.
4. If the action has required permissions and the logged in user shares at least one, then access is granted.
5. Users without at least one required permission are redirected to the root url.
Two of the scenarios are configured at design time. If you use +require_admin+ or +allow_anon+,
they cannot be changed at runtime. The idea is that anything that allows anonymous access will always allow
anonymous access during runtime and anything that requires admin access will always require admin access during
runtime.
The third scenario is what would be used by most actions. Using the +admin+ controller, which requires admin
access, you can customize the permissions required for each available route. Using the +users+ controller,
admins can assign permissions to other users. | [
"Validates",
"that",
"the",
"current",
"user",
"is",
"authorized",
"for",
"the",
"current",
"request",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/action_controller_base.rb#L426-L444 | train |
masaomoc/aws-profile_parser | lib/aws/profile_parser.rb | AWS.ProfileParser.get | def get(profile='default')
raise 'Config File does not exist' unless File.exists?(@file)
@credentials = parse if @credentials.nil?
raise 'The profile is not specified in the config file' unless @credentials.has_key?(profile)
@credentials[profile]
end | ruby | def get(profile='default')
raise 'Config File does not exist' unless File.exists?(@file)
@credentials = parse if @credentials.nil?
raise 'The profile is not specified in the config file' unless @credentials.has_key?(profile)
@credentials[profile]
end | [
"def",
"get",
"(",
"profile",
"=",
"'default'",
")",
"raise",
"'Config File does not exist'",
"unless",
"File",
".",
"exists?",
"(",
"@file",
")",
"@credentials",
"=",
"parse",
"if",
"@credentials",
".",
"nil?",
"raise",
"'The profile is not specified in the config file'",
"unless",
"@credentials",
".",
"has_key?",
"(",
"profile",
")",
"@credentials",
"[",
"profile",
"]",
"end"
] | returns hash of AWS credential | [
"returns",
"hash",
"of",
"AWS",
"credential"
] | b45725b5497864e2f5de2457ae6b7ed0dabe94fa | https://github.com/masaomoc/aws-profile_parser/blob/b45725b5497864e2f5de2457ae6b7ed0dabe94fa/lib/aws/profile_parser.rb#L12-L19 | train |
detroit/detroit-gem | lib/detroit-gem.rb | Detroit.Gem.build | def build
trace "gem build #{gemspec}"
spec = load_gemspec
package = ::Gem::Package.build(spec)
mkdir_p(pkgdir) unless File.directory?(pkgdir)
mv(package, pkgdir)
end | ruby | def build
trace "gem build #{gemspec}"
spec = load_gemspec
package = ::Gem::Package.build(spec)
mkdir_p(pkgdir) unless File.directory?(pkgdir)
mv(package, pkgdir)
end | [
"def",
"build",
"trace",
"\"gem build #{gemspec}\"",
"spec",
"=",
"load_gemspec",
"package",
"=",
"::",
"Gem",
"::",
"Package",
".",
"build",
"(",
"spec",
")",
"mkdir_p",
"(",
"pkgdir",
")",
"unless",
"File",
".",
"directory?",
"(",
"pkgdir",
")",
"mv",
"(",
"package",
",",
"pkgdir",
")",
"end"
] | Create a gem package. | [
"Create",
"a",
"gem",
"package",
"."
] | 3a018942038c430f3fdc73ed5c40783c8f0a7c8b | https://github.com/detroit/detroit-gem/blob/3a018942038c430f3fdc73ed5c40783c8f0a7c8b/lib/detroit-gem.rb#L72-L78 | train |
detroit/detroit-gem | lib/detroit-gem.rb | Detroit.Gem.create_gemspec | def create_gemspec(file=nil)
file = gemspec if !file
#require 'gemdo/gemspec'
yaml = project.to_gemspec.to_yaml
File.open(file, 'w') do |f|
f << yaml
end
status File.basename(file) + " updated."
return file
end | ruby | def create_gemspec(file=nil)
file = gemspec if !file
#require 'gemdo/gemspec'
yaml = project.to_gemspec.to_yaml
File.open(file, 'w') do |f|
f << yaml
end
status File.basename(file) + " updated."
return file
end | [
"def",
"create_gemspec",
"(",
"file",
"=",
"nil",
")",
"file",
"=",
"gemspec",
"if",
"!",
"file",
"yaml",
"=",
"project",
".",
"to_gemspec",
".",
"to_yaml",
"File",
".",
"open",
"(",
"file",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"f",
"<<",
"yaml",
"end",
"status",
"File",
".",
"basename",
"(",
"file",
")",
"+",
"\" updated.\"",
"return",
"file",
"end"
] | Create a gemspec file from project metadata. | [
"Create",
"a",
"gemspec",
"file",
"from",
"project",
"metadata",
"."
] | 3a018942038c430f3fdc73ed5c40783c8f0a7c8b | https://github.com/detroit/detroit-gem/blob/3a018942038c430f3fdc73ed5c40783c8f0a7c8b/lib/detroit-gem.rb#L171-L180 | train |
detroit/detroit-gem | lib/detroit-gem.rb | Detroit.Gem.lookup_gemspec | def lookup_gemspec
dot_gemspec = (project.root + '.gemspec').to_s
if File.exist?(dot_gemspec)
dot_gemspec.to_s
else
project.metadata.name + '.gemspec'
end
end | ruby | def lookup_gemspec
dot_gemspec = (project.root + '.gemspec').to_s
if File.exist?(dot_gemspec)
dot_gemspec.to_s
else
project.metadata.name + '.gemspec'
end
end | [
"def",
"lookup_gemspec",
"dot_gemspec",
"=",
"(",
"project",
".",
"root",
"+",
"'.gemspec'",
")",
".",
"to_s",
"if",
"File",
".",
"exist?",
"(",
"dot_gemspec",
")",
"dot_gemspec",
".",
"to_s",
"else",
"project",
".",
"metadata",
".",
"name",
"+",
"'.gemspec'",
"end",
"end"
] | Lookup gemspec file. If not found returns default path.
Returns String of file path. | [
"Lookup",
"gemspec",
"file",
".",
"If",
"not",
"found",
"returns",
"default",
"path",
"."
] | 3a018942038c430f3fdc73ed5c40783c8f0a7c8b | https://github.com/detroit/detroit-gem/blob/3a018942038c430f3fdc73ed5c40783c8f0a7c8b/lib/detroit-gem.rb#L185-L192 | train |
detroit/detroit-gem | lib/detroit-gem.rb | Detroit.Gem.load_gemspec | def load_gemspec
file = gemspec
if yaml?(file)
::Gem::Specification.from_yaml(File.new(file))
else
::Gem::Specification.load(file)
end
end | ruby | def load_gemspec
file = gemspec
if yaml?(file)
::Gem::Specification.from_yaml(File.new(file))
else
::Gem::Specification.load(file)
end
end | [
"def",
"load_gemspec",
"file",
"=",
"gemspec",
"if",
"yaml?",
"(",
"file",
")",
"::",
"Gem",
"::",
"Specification",
".",
"from_yaml",
"(",
"File",
".",
"new",
"(",
"file",
")",
")",
"else",
"::",
"Gem",
"::",
"Specification",
".",
"load",
"(",
"file",
")",
"end",
"end"
] | Load gemspec file.
Returns a ::Gem::Specification. | [
"Load",
"gemspec",
"file",
"."
] | 3a018942038c430f3fdc73ed5c40783c8f0a7c8b | https://github.com/detroit/detroit-gem/blob/3a018942038c430f3fdc73ed5c40783c8f0a7c8b/lib/detroit-gem.rb#L197-L204 | train |
detroit/detroit-gem | lib/detroit-gem.rb | Detroit.Gem.yaml? | def yaml?(file)
line = open(file) { |f| line = f.gets }
line.index "!ruby/object:Gem::Specification"
end | ruby | def yaml?(file)
line = open(file) { |f| line = f.gets }
line.index "!ruby/object:Gem::Specification"
end | [
"def",
"yaml?",
"(",
"file",
")",
"line",
"=",
"open",
"(",
"file",
")",
"{",
"|",
"f",
"|",
"line",
"=",
"f",
".",
"gets",
"}",
"line",
".",
"index",
"\"!ruby/object:Gem::Specification\"",
"end"
] | If the gemspec a YAML gemspec? | [
"If",
"the",
"gemspec",
"a",
"YAML",
"gemspec?"
] | 3a018942038c430f3fdc73ed5c40783c8f0a7c8b | https://github.com/detroit/detroit-gem/blob/3a018942038c430f3fdc73ed5c40783c8f0a7c8b/lib/detroit-gem.rb#L207-L210 | train |
Thermatix/ruta | lib/ruta/handler.rb | Ruta.Handlers.default | def default
handler_name = @handler_name
proc {
comp = @context.elements[handler_name][:content]
if comp.kind_of?(Proc)
comp.call
else
Context.wipe handler_name
Context.render comp, handler_name
end
}
end | ruby | def default
handler_name = @handler_name
proc {
comp = @context.elements[handler_name][:content]
if comp.kind_of?(Proc)
comp.call
else
Context.wipe handler_name
Context.render comp, handler_name
end
}
end | [
"def",
"default",
"handler_name",
"=",
"@handler_name",
"proc",
"{",
"comp",
"=",
"@context",
".",
"elements",
"[",
"handler_name",
"]",
"[",
":content",
"]",
"if",
"comp",
".",
"kind_of?",
"(",
"Proc",
")",
"comp",
".",
"call",
"else",
"Context",
".",
"wipe",
"handler_name",
"Context",
".",
"render",
"comp",
",",
"handler_name",
"end",
"}",
"end"
] | Render the default content for this component as it is defined in the context. | [
"Render",
"the",
"default",
"content",
"for",
"this",
"component",
"as",
"it",
"is",
"defined",
"in",
"the",
"context",
"."
] | b4a6e3bc7c0c4b66c804023d638b173e3f61e157 | https://github.com/Thermatix/ruta/blob/b4a6e3bc7c0c4b66c804023d638b173e3f61e157/lib/ruta/handler.rb#L35-L46 | train |
lulibrary/aspire | lib/retry.rb | Retry.Engine.do | def do(delay: nil, exceptions: nil, handlers: nil, tries: nil, &block)
Retry.do(delay: delay || self.delay,
exceptions: exceptions || self.exceptions,
handlers: handlers || self.handlers,
tries: tries || self.tries,
&block)
end | ruby | def do(delay: nil, exceptions: nil, handlers: nil, tries: nil, &block)
Retry.do(delay: delay || self.delay,
exceptions: exceptions || self.exceptions,
handlers: handlers || self.handlers,
tries: tries || self.tries,
&block)
end | [
"def",
"do",
"(",
"delay",
":",
"nil",
",",
"exceptions",
":",
"nil",
",",
"handlers",
":",
"nil",
",",
"tries",
":",
"nil",
",",
"&",
"block",
")",
"Retry",
".",
"do",
"(",
"delay",
":",
"delay",
"||",
"self",
".",
"delay",
",",
"exceptions",
":",
"exceptions",
"||",
"self",
".",
"exceptions",
",",
"handlers",
":",
"handlers",
"||",
"self",
".",
"handlers",
",",
"tries",
":",
"tries",
"||",
"self",
".",
"tries",
",",
"&",
"block",
")",
"end"
] | Initialises a new Engine instance
@param delay [Float] the default delay before retrying
@param exceptions [Hash<Exception, Boolean>] the default retriable
exceptions
@param handlers [Hash<Exception|Symbol, Proc>] the default exception
handlers
@param tries [Integer, Proc] the default maximum number of tries or
a proc which accepts an Exception and returns true if a retry is allowed
or false if not
@return [void]
Executes the class method do using instance default values | [
"Initialises",
"a",
"new",
"Engine",
"instance"
] | 623f481a2e79b9cb0b5feb923da438eb1ed2abfe | https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/retry.rb#L53-L59 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.fmod_with_float | def fmod_with_float( other )
other = Node.match( other, typecode ).new other unless other.matched?
if typecode < FLOAT_ or other.typecode < FLOAT_
fmod other
else
fmod_without_float other
end
end | ruby | def fmod_with_float( other )
other = Node.match( other, typecode ).new other unless other.matched?
if typecode < FLOAT_ or other.typecode < FLOAT_
fmod other
else
fmod_without_float other
end
end | [
"def",
"fmod_with_float",
"(",
"other",
")",
"other",
"=",
"Node",
".",
"match",
"(",
"other",
",",
"typecode",
")",
".",
"new",
"other",
"unless",
"other",
".",
"matched?",
"if",
"typecode",
"<",
"FLOAT_",
"or",
"other",
".",
"typecode",
"<",
"FLOAT_",
"fmod",
"other",
"else",
"fmod_without_float",
"other",
"end",
"end"
] | Modulo operation for floating point numbers
This operation takes account of the problem that '%' does not work with
floating-point numbers in C.
@return [Node] Array with result of operation. | [
"Modulo",
"operation",
"for",
"floating",
"point",
"numbers"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L122-L129 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.to_type | def to_type(dest)
if dimension == 0 and variables.empty?
target = typecode.to_type dest
target.new(simplify.get).simplify
else
key = "to_#{dest.to_s.downcase}"
Hornetseye::ElementWise( proc { |x| x.to_type dest }, key,
proc { |t| t.to_type dest } ).new(self).force
end
end | ruby | def to_type(dest)
if dimension == 0 and variables.empty?
target = typecode.to_type dest
target.new(simplify.get).simplify
else
key = "to_#{dest.to_s.downcase}"
Hornetseye::ElementWise( proc { |x| x.to_type dest }, key,
proc { |t| t.to_type dest } ).new(self).force
end
end | [
"def",
"to_type",
"(",
"dest",
")",
"if",
"dimension",
"==",
"0",
"and",
"variables",
".",
"empty?",
"target",
"=",
"typecode",
".",
"to_type",
"dest",
"target",
".",
"new",
"(",
"simplify",
".",
"get",
")",
".",
"simplify",
"else",
"key",
"=",
"\"to_#{dest.to_s.downcase}\"",
"Hornetseye",
"::",
"ElementWise",
"(",
"proc",
"{",
"|",
"x",
"|",
"x",
".",
"to_type",
"dest",
"}",
",",
"key",
",",
"proc",
"{",
"|",
"t",
"|",
"t",
".",
"to_type",
"dest",
"}",
")",
".",
"new",
"(",
"self",
")",
".",
"force",
"end",
"end"
] | Convert array elements to different element type
@param [Class] dest Element type to convert to.
@return [Node] Array based on the different element type. | [
"Convert",
"array",
"elements",
"to",
"different",
"element",
"type"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L138-L147 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.to_type_with_rgb | def to_type_with_rgb(dest)
if typecode < RGB_
if dest < FLOAT_
lazy { r * 0.299 + g * 0.587 + b * 0.114 }.to_type dest
elsif dest < INT_
lazy { (r * 0.299 + g * 0.587 + b * 0.114).round }.to_type dest
else
to_type_without_rgb dest
end
else
to_type_without_rgb dest
end
end | ruby | def to_type_with_rgb(dest)
if typecode < RGB_
if dest < FLOAT_
lazy { r * 0.299 + g * 0.587 + b * 0.114 }.to_type dest
elsif dest < INT_
lazy { (r * 0.299 + g * 0.587 + b * 0.114).round }.to_type dest
else
to_type_without_rgb dest
end
else
to_type_without_rgb dest
end
end | [
"def",
"to_type_with_rgb",
"(",
"dest",
")",
"if",
"typecode",
"<",
"RGB_",
"if",
"dest",
"<",
"FLOAT_",
"lazy",
"{",
"r",
"*",
"0.299",
"+",
"g",
"*",
"0.587",
"+",
"b",
"*",
"0.114",
"}",
".",
"to_type",
"dest",
"elsif",
"dest",
"<",
"INT_",
"lazy",
"{",
"(",
"r",
"*",
"0.299",
"+",
"g",
"*",
"0.587",
"+",
"b",
"*",
"0.114",
")",
".",
"round",
"}",
".",
"to_type",
"dest",
"else",
"to_type_without_rgb",
"dest",
"end",
"else",
"to_type_without_rgb",
"dest",
"end",
"end"
] | Convert RGB array to scalar array
This operation is a special case handling colour to greyscale conversion.
@param [Class] dest Element type to convert to.
@return [Node] Array based on the different element type. | [
"Convert",
"RGB",
"array",
"to",
"scalar",
"array"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L156-L168 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.reshape | def reshape(*ret_shape)
target_size = ret_shape.inject 1, :*
if target_size != size
raise "Target is of size #{target_size} but should be of size #{size}"
end
Hornetseye::MultiArray(typecode, ret_shape.size).
new *(ret_shape + [:memory => memorise.memory])
end | ruby | def reshape(*ret_shape)
target_size = ret_shape.inject 1, :*
if target_size != size
raise "Target is of size #{target_size} but should be of size #{size}"
end
Hornetseye::MultiArray(typecode, ret_shape.size).
new *(ret_shape + [:memory => memorise.memory])
end | [
"def",
"reshape",
"(",
"*",
"ret_shape",
")",
"target_size",
"=",
"ret_shape",
".",
"inject",
"1",
",",
":*",
"if",
"target_size",
"!=",
"size",
"raise",
"\"Target is of size #{target_size} but should be of size #{size}\"",
"end",
"Hornetseye",
"::",
"MultiArray",
"(",
"typecode",
",",
"ret_shape",
".",
"size",
")",
".",
"new",
"*",
"(",
"ret_shape",
"+",
"[",
":memory",
"=>",
"memorise",
".",
"memory",
"]",
")",
"end"
] | Get array with same elements but different shape
The method returns an array with the same elements but with a different shape.
The desired shape must have the same number of elements.
@param [Array<Integer>] ret_shape Desired shape of return value
@return [Node] Array with desired shape. | [
"Get",
"array",
"with",
"same",
"elements",
"but",
"different",
"shape"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L197-L204 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.conditional | def conditional(a, b)
a = Node.match(a, b.matched? ? b : nil).new a unless a.matched?
b = Node.match(b, a.matched? ? a : nil).new b unless b.matched?
if dimension == 0 and variables.empty? and
a.dimension == 0 and a.variables.empty? and
b.dimension == 0 and b.variables.empty?
target = typecode.cond a.typecode, b.typecode
target.new simplify.get.conditional(proc { a.simplify.get },
proc { b.simplify.get })
else
Hornetseye::ElementWise(proc { |x,y,z| x.conditional y, z }, :conditional,
proc { |t,u,v| t.cond u, v }).
new(self, a, b).force
end
end | ruby | def conditional(a, b)
a = Node.match(a, b.matched? ? b : nil).new a unless a.matched?
b = Node.match(b, a.matched? ? a : nil).new b unless b.matched?
if dimension == 0 and variables.empty? and
a.dimension == 0 and a.variables.empty? and
b.dimension == 0 and b.variables.empty?
target = typecode.cond a.typecode, b.typecode
target.new simplify.get.conditional(proc { a.simplify.get },
proc { b.simplify.get })
else
Hornetseye::ElementWise(proc { |x,y,z| x.conditional y, z }, :conditional,
proc { |t,u,v| t.cond u, v }).
new(self, a, b).force
end
end | [
"def",
"conditional",
"(",
"a",
",",
"b",
")",
"a",
"=",
"Node",
".",
"match",
"(",
"a",
",",
"b",
".",
"matched?",
"?",
"b",
":",
"nil",
")",
".",
"new",
"a",
"unless",
"a",
".",
"matched?",
"b",
"=",
"Node",
".",
"match",
"(",
"b",
",",
"a",
".",
"matched?",
"?",
"a",
":",
"nil",
")",
".",
"new",
"b",
"unless",
"b",
".",
"matched?",
"if",
"dimension",
"==",
"0",
"and",
"variables",
".",
"empty?",
"and",
"a",
".",
"dimension",
"==",
"0",
"and",
"a",
".",
"variables",
".",
"empty?",
"and",
"b",
".",
"dimension",
"==",
"0",
"and",
"b",
".",
"variables",
".",
"empty?",
"target",
"=",
"typecode",
".",
"cond",
"a",
".",
"typecode",
",",
"b",
".",
"typecode",
"target",
".",
"new",
"simplify",
".",
"get",
".",
"conditional",
"(",
"proc",
"{",
"a",
".",
"simplify",
".",
"get",
"}",
",",
"proc",
"{",
"b",
".",
"simplify",
".",
"get",
"}",
")",
"else",
"Hornetseye",
"::",
"ElementWise",
"(",
"proc",
"{",
"|",
"x",
",",
"y",
",",
"z",
"|",
"x",
".",
"conditional",
"y",
",",
"z",
"}",
",",
":conditional",
",",
"proc",
"{",
"|",
"t",
",",
"u",
",",
"v",
"|",
"t",
".",
"cond",
"u",
",",
"v",
"}",
")",
".",
"new",
"(",
"self",
",",
"a",
",",
"b",
")",
".",
"force",
"end",
"end"
] | Element-wise conditional selection of values
@param [Node] a First array of values.
@param [Node] b Second array of values.
@return [Node] Array with selected values. | [
"Element",
"-",
"wise",
"conditional",
"selection",
"of",
"values"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L212-L226 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.transpose | def transpose(*order)
if (0 ... dimension).to_a != order.sort
raise 'Each array index must be specified exactly once!'
end
term = self
variables = shape.reverse.collect do |i|
var = Variable.new Hornetseye::INDEX( i )
term = term.element var
var
end.reverse
order.collect { |o| variables[o] }.
inject(term) { |retval,var| Lambda.new var, retval }
end | ruby | def transpose(*order)
if (0 ... dimension).to_a != order.sort
raise 'Each array index must be specified exactly once!'
end
term = self
variables = shape.reverse.collect do |i|
var = Variable.new Hornetseye::INDEX( i )
term = term.element var
var
end.reverse
order.collect { |o| variables[o] }.
inject(term) { |retval,var| Lambda.new var, retval }
end | [
"def",
"transpose",
"(",
"*",
"order",
")",
"if",
"(",
"0",
"...",
"dimension",
")",
".",
"to_a",
"!=",
"order",
".",
"sort",
"raise",
"'Each array index must be specified exactly once!'",
"end",
"term",
"=",
"self",
"variables",
"=",
"shape",
".",
"reverse",
".",
"collect",
"do",
"|",
"i",
"|",
"var",
"=",
"Variable",
".",
"new",
"Hornetseye",
"::",
"INDEX",
"(",
"i",
")",
"term",
"=",
"term",
".",
"element",
"var",
"var",
"end",
".",
"reverse",
"order",
".",
"collect",
"{",
"|",
"o",
"|",
"variables",
"[",
"o",
"]",
"}",
".",
"inject",
"(",
"term",
")",
"{",
"|",
"retval",
",",
"var",
"|",
"Lambda",
".",
"new",
"var",
",",
"retval",
"}",
"end"
] | Element-wise comparison of values
@param [Node] other Array with values to compare with.
@return [Node] Array with results.
Lazy transpose of array
Lazily compute transpose by swapping indices according to the specified
order.
@param [Array<Integer>] order New order of indices.
@return [Node] Returns the transposed array. | [
"Element",
"-",
"wise",
"comparison",
"of",
"values"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L275-L287 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.unroll | def unroll( n = 1 )
if n < 0
roll -n
else
order = ( 0 ... dimension ).to_a
n.times { order = [ order.last ] + order[ 0 ... -1 ] }
transpose *order
end
end | ruby | def unroll( n = 1 )
if n < 0
roll -n
else
order = ( 0 ... dimension ).to_a
n.times { order = [ order.last ] + order[ 0 ... -1 ] }
transpose *order
end
end | [
"def",
"unroll",
"(",
"n",
"=",
"1",
")",
"if",
"n",
"<",
"0",
"roll",
"-",
"n",
"else",
"order",
"=",
"(",
"0",
"...",
"dimension",
")",
".",
"to_a",
"n",
".",
"times",
"{",
"order",
"=",
"[",
"order",
".",
"last",
"]",
"+",
"order",
"[",
"0",
"...",
"-",
"1",
"]",
"}",
"transpose",
"*",
"order",
"end",
"end"
] | Reverse-cycle indices of array
@param [Integer] n Number of times to cycle back indices of array.
@return [Node] Resulting array expression with different order of indices. | [
"Reverse",
"-",
"cycle",
"indices",
"of",
"array"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L309-L317 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.collect | def collect(&action)
var = Variable.new typecode
block = action.call var
conversion = proc { |t| t.to_type action.call(Variable.new(t.typecode)).typecode }
Hornetseye::ElementWise( action, block.to_s, conversion ).new( self ).force
end | ruby | def collect(&action)
var = Variable.new typecode
block = action.call var
conversion = proc { |t| t.to_type action.call(Variable.new(t.typecode)).typecode }
Hornetseye::ElementWise( action, block.to_s, conversion ).new( self ).force
end | [
"def",
"collect",
"(",
"&",
"action",
")",
"var",
"=",
"Variable",
".",
"new",
"typecode",
"block",
"=",
"action",
".",
"call",
"var",
"conversion",
"=",
"proc",
"{",
"|",
"t",
"|",
"t",
".",
"to_type",
"action",
".",
"call",
"(",
"Variable",
".",
"new",
"(",
"t",
".",
"typecode",
")",
")",
".",
"typecode",
"}",
"Hornetseye",
"::",
"ElementWise",
"(",
"action",
",",
"block",
".",
"to_s",
",",
"conversion",
")",
".",
"new",
"(",
"self",
")",
".",
"force",
"end"
] | Perform element-wise operation on array
@param [Proc] action Operation(s) to perform on elements.
@return [Node] The resulting array. | [
"Perform",
"element",
"-",
"wise",
"operation",
"on",
"array"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L324-L329 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.inject | def inject(*args, &action)
options = args.last.is_a?(Hash) ? args.pop : {}
unless action or options[:block]
unless [1, 2].member? args.size
raise "Inject expected 1 or 2 arguments but got #{args.size}"
end
initial, symbol = args[-2], args[-1]
action = proc { |a,b| a.send symbol, b }
else
raise "Inject expected 0 or 1 arguments but got #{args.size}" if args.size > 1
initial = args.empty? ? nil : args.first
end
unless initial.nil?
initial = Node.match( initial ).new initial unless initial.matched?
initial_typecode = initial.typecode
else
initial_typecode = typecode
end
var1 = options[ :var1 ] || Variable.new( initial_typecode )
var2 = options[ :var2 ] || Variable.new( typecode )
block = options[ :block ] || action.call( var1, var2 )
if dimension == 0
if initial
block.subst(var1 => initial, var2 => self).simplify
else
demand
end
else
index = Variable.new Hornetseye::INDEX( nil )
value = element( index ).inject nil, :block => block,
:var1 => var1, :var2 => var2
value = typecode.new value unless value.matched?
if initial.nil? and index.size.get == 0
raise "Array was empty and no initial value for injection was given"
end
Inject.new( value, index, initial, block, var1, var2 ).force
end
end | ruby | def inject(*args, &action)
options = args.last.is_a?(Hash) ? args.pop : {}
unless action or options[:block]
unless [1, 2].member? args.size
raise "Inject expected 1 or 2 arguments but got #{args.size}"
end
initial, symbol = args[-2], args[-1]
action = proc { |a,b| a.send symbol, b }
else
raise "Inject expected 0 or 1 arguments but got #{args.size}" if args.size > 1
initial = args.empty? ? nil : args.first
end
unless initial.nil?
initial = Node.match( initial ).new initial unless initial.matched?
initial_typecode = initial.typecode
else
initial_typecode = typecode
end
var1 = options[ :var1 ] || Variable.new( initial_typecode )
var2 = options[ :var2 ] || Variable.new( typecode )
block = options[ :block ] || action.call( var1, var2 )
if dimension == 0
if initial
block.subst(var1 => initial, var2 => self).simplify
else
demand
end
else
index = Variable.new Hornetseye::INDEX( nil )
value = element( index ).inject nil, :block => block,
:var1 => var1, :var2 => var2
value = typecode.new value unless value.matched?
if initial.nil? and index.size.get == 0
raise "Array was empty and no initial value for injection was given"
end
Inject.new( value, index, initial, block, var1, var2 ).force
end
end | [
"def",
"inject",
"(",
"*",
"args",
",",
"&",
"action",
")",
"options",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"unless",
"action",
"or",
"options",
"[",
":block",
"]",
"unless",
"[",
"1",
",",
"2",
"]",
".",
"member?",
"args",
".",
"size",
"raise",
"\"Inject expected 1 or 2 arguments but got #{args.size}\"",
"end",
"initial",
",",
"symbol",
"=",
"args",
"[",
"-",
"2",
"]",
",",
"args",
"[",
"-",
"1",
"]",
"action",
"=",
"proc",
"{",
"|",
"a",
",",
"b",
"|",
"a",
".",
"send",
"symbol",
",",
"b",
"}",
"else",
"raise",
"\"Inject expected 0 or 1 arguments but got #{args.size}\"",
"if",
"args",
".",
"size",
">",
"1",
"initial",
"=",
"args",
".",
"empty?",
"?",
"nil",
":",
"args",
".",
"first",
"end",
"unless",
"initial",
".",
"nil?",
"initial",
"=",
"Node",
".",
"match",
"(",
"initial",
")",
".",
"new",
"initial",
"unless",
"initial",
".",
"matched?",
"initial_typecode",
"=",
"initial",
".",
"typecode",
"else",
"initial_typecode",
"=",
"typecode",
"end",
"var1",
"=",
"options",
"[",
":var1",
"]",
"||",
"Variable",
".",
"new",
"(",
"initial_typecode",
")",
"var2",
"=",
"options",
"[",
":var2",
"]",
"||",
"Variable",
".",
"new",
"(",
"typecode",
")",
"block",
"=",
"options",
"[",
":block",
"]",
"||",
"action",
".",
"call",
"(",
"var1",
",",
"var2",
")",
"if",
"dimension",
"==",
"0",
"if",
"initial",
"block",
".",
"subst",
"(",
"var1",
"=>",
"initial",
",",
"var2",
"=>",
"self",
")",
".",
"simplify",
"else",
"demand",
"end",
"else",
"index",
"=",
"Variable",
".",
"new",
"Hornetseye",
"::",
"INDEX",
"(",
"nil",
")",
"value",
"=",
"element",
"(",
"index",
")",
".",
"inject",
"nil",
",",
":block",
"=>",
"block",
",",
":var1",
"=>",
"var1",
",",
":var2",
"=>",
"var2",
"value",
"=",
"typecode",
".",
"new",
"value",
"unless",
"value",
".",
"matched?",
"if",
"initial",
".",
"nil?",
"and",
"index",
".",
"size",
".",
"get",
"==",
"0",
"raise",
"\"Array was empty and no initial value for injection was given\"",
"end",
"Inject",
".",
"new",
"(",
"value",
",",
"index",
",",
"initial",
",",
"block",
",",
"var1",
",",
"var2",
")",
".",
"force",
"end",
"end"
] | Perform cummulative operation on array
@overload inject(initial = nil, options = {}, &action)
@param [Object] initial Initial value for cummulative operation.
@option options [Variable] :var1 First variable defining operation.
@option options [Variable] :var1 Second variable defining operation.
@option options [Variable] :block (action.call(var1, var2)) The operation to apply.
@overload inject(initial = nil, symbol)
@param [Object] initial Initial value for cummulative operation.
@param [Symbol,String] symbol The operation to apply.
@return [Object] Result of injection. | [
"Perform",
"cummulative",
"operation",
"on",
"array"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L351-L388 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.range | def range( initial = nil )
min( initial ? initial.min : nil ) .. max( initial ? initial.max : nil )
end | ruby | def range( initial = nil )
min( initial ? initial.min : nil ) .. max( initial ? initial.max : nil )
end | [
"def",
"range",
"(",
"initial",
"=",
"nil",
")",
"min",
"(",
"initial",
"?",
"initial",
".",
"min",
":",
"nil",
")",
"..",
"max",
"(",
"initial",
"?",
"initial",
".",
"max",
":",
"nil",
")",
"end"
] | Find range of values of array
@return [Object] Range of values of array. | [
"Find",
"range",
"of",
"values",
"of",
"array"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L461-L463 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.normalise | def normalise( range = 0 .. 0xFF )
if range.exclude_end?
raise "Normalisation does not support ranges with end value " +
"excluded (such as #{range})"
end
lower, upper = min, max
if lower.is_a? RGB or upper.is_a? RGB
current = [ lower.r, lower.g, lower.b ].min ..
[ upper.r, upper.g, upper.b ].max
else
current = min .. max
end
if current.last != current.first
factor =
( range.last - range.first ).to_f / ( current.last - current.first )
collect { |x| x * factor + ( range.first - current.first * factor ) }
else
self + ( range.first - current.first )
end
end | ruby | def normalise( range = 0 .. 0xFF )
if range.exclude_end?
raise "Normalisation does not support ranges with end value " +
"excluded (such as #{range})"
end
lower, upper = min, max
if lower.is_a? RGB or upper.is_a? RGB
current = [ lower.r, lower.g, lower.b ].min ..
[ upper.r, upper.g, upper.b ].max
else
current = min .. max
end
if current.last != current.first
factor =
( range.last - range.first ).to_f / ( current.last - current.first )
collect { |x| x * factor + ( range.first - current.first * factor ) }
else
self + ( range.first - current.first )
end
end | [
"def",
"normalise",
"(",
"range",
"=",
"0",
"..",
"0xFF",
")",
"if",
"range",
".",
"exclude_end?",
"raise",
"\"Normalisation does not support ranges with end value \"",
"+",
"\"excluded (such as #{range})\"",
"end",
"lower",
",",
"upper",
"=",
"min",
",",
"max",
"if",
"lower",
".",
"is_a?",
"RGB",
"or",
"upper",
".",
"is_a?",
"RGB",
"current",
"=",
"[",
"lower",
".",
"r",
",",
"lower",
".",
"g",
",",
"lower",
".",
"b",
"]",
".",
"min",
"..",
"[",
"upper",
".",
"r",
",",
"upper",
".",
"g",
",",
"upper",
".",
"b",
"]",
".",
"max",
"else",
"current",
"=",
"min",
"..",
"max",
"end",
"if",
"current",
".",
"last",
"!=",
"current",
".",
"first",
"factor",
"=",
"(",
"range",
".",
"last",
"-",
"range",
".",
"first",
")",
".",
"to_f",
"/",
"(",
"current",
".",
"last",
"-",
"current",
".",
"first",
")",
"collect",
"{",
"|",
"x",
"|",
"x",
"*",
"factor",
"+",
"(",
"range",
".",
"first",
"-",
"current",
".",
"first",
"*",
"factor",
")",
"}",
"else",
"self",
"+",
"(",
"range",
".",
"first",
"-",
"current",
".",
"first",
")",
"end",
"end"
] | Check values against boundaries
@return [Node] Boolean array with result.
Normalise values of array
@param [Range] range Target range of normalisation.
@return [Node] Array with normalised values. | [
"Check",
"values",
"against",
"boundaries"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L477-L496 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.clip | def clip( range = 0 .. 0xFF )
if range.exclude_end?
raise "Clipping does not support ranges with end value " +
"excluded (such as #{range})"
end
collect { |x| x.major( range.begin ).minor range.end }
end | ruby | def clip( range = 0 .. 0xFF )
if range.exclude_end?
raise "Clipping does not support ranges with end value " +
"excluded (such as #{range})"
end
collect { |x| x.major( range.begin ).minor range.end }
end | [
"def",
"clip",
"(",
"range",
"=",
"0",
"..",
"0xFF",
")",
"if",
"range",
".",
"exclude_end?",
"raise",
"\"Clipping does not support ranges with end value \"",
"+",
"\"excluded (such as #{range})\"",
"end",
"collect",
"{",
"|",
"x",
"|",
"x",
".",
"major",
"(",
"range",
".",
"begin",
")",
".",
"minor",
"range",
".",
"end",
"}",
"end"
] | Clip values to specified range
@param [Range] range Allowed range of values.
@return [Node] Array with clipped values. | [
"Clip",
"values",
"to",
"specified",
"range"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L503-L509 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.stretch | def stretch(from = 0 .. 0xFF, to = 0 .. 0xFF)
if from.exclude_end?
raise "Stretching does not support ranges with end value " +
"excluded (such as #{from})"
end
if to.exclude_end?
raise "Stretching does not support ranges with end value " +
"excluded (such as #{to})"
end
if from.last != from.first
factor = (to.last - to.first).to_f / (from.last - from.first)
collect { |x| ((x - from.first) * factor).major(to.first).minor to.last }
else
(self <= from.first).conditional to.first, to.last
end
end | ruby | def stretch(from = 0 .. 0xFF, to = 0 .. 0xFF)
if from.exclude_end?
raise "Stretching does not support ranges with end value " +
"excluded (such as #{from})"
end
if to.exclude_end?
raise "Stretching does not support ranges with end value " +
"excluded (such as #{to})"
end
if from.last != from.first
factor = (to.last - to.first).to_f / (from.last - from.first)
collect { |x| ((x - from.first) * factor).major(to.first).minor to.last }
else
(self <= from.first).conditional to.first, to.last
end
end | [
"def",
"stretch",
"(",
"from",
"=",
"0",
"..",
"0xFF",
",",
"to",
"=",
"0",
"..",
"0xFF",
")",
"if",
"from",
".",
"exclude_end?",
"raise",
"\"Stretching does not support ranges with end value \"",
"+",
"\"excluded (such as #{from})\"",
"end",
"if",
"to",
".",
"exclude_end?",
"raise",
"\"Stretching does not support ranges with end value \"",
"+",
"\"excluded (such as #{to})\"",
"end",
"if",
"from",
".",
"last",
"!=",
"from",
".",
"first",
"factor",
"=",
"(",
"to",
".",
"last",
"-",
"to",
".",
"first",
")",
".",
"to_f",
"/",
"(",
"from",
".",
"last",
"-",
"from",
".",
"first",
")",
"collect",
"{",
"|",
"x",
"|",
"(",
"(",
"x",
"-",
"from",
".",
"first",
")",
"*",
"factor",
")",
".",
"major",
"(",
"to",
".",
"first",
")",
".",
"minor",
"to",
".",
"last",
"}",
"else",
"(",
"self",
"<=",
"from",
".",
"first",
")",
".",
"conditional",
"to",
".",
"first",
",",
"to",
".",
"last",
"end",
"end"
] | Stretch values from one range to another
@param [Range] from Target range of values.
@param [Range] to Source range of values.
@return [Node] Array with stretched values. | [
"Stretch",
"values",
"from",
"one",
"range",
"to",
"another"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L517-L532 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.diagonal | def diagonal( initial = nil, options = {} )
if dimension == 0
demand
else
if initial
initial = Node.match( initial ).new initial unless initial.matched?
initial_typecode = initial.typecode
else
initial_typecode = typecode
end
index0 = Variable.new Hornetseye::INDEX( nil )
index1 = Variable.new Hornetseye::INDEX( nil )
index2 = Variable.new Hornetseye::INDEX( nil )
var1 = options[ :var1 ] || Variable.new( initial_typecode )
var2 = options[ :var2 ] || Variable.new( typecode )
block = options[ :block ] || yield( var1, var2 )
value = element( index1 ).element( index2 ).
diagonal initial, :block => block, :var1 => var1, :var2 => var2
term = Diagonal.new( value, index0, index1, index2, initial,
block, var1, var2 )
index0.size = index1.size
Lambda.new( index0, term ).force
end
end | ruby | def diagonal( initial = nil, options = {} )
if dimension == 0
demand
else
if initial
initial = Node.match( initial ).new initial unless initial.matched?
initial_typecode = initial.typecode
else
initial_typecode = typecode
end
index0 = Variable.new Hornetseye::INDEX( nil )
index1 = Variable.new Hornetseye::INDEX( nil )
index2 = Variable.new Hornetseye::INDEX( nil )
var1 = options[ :var1 ] || Variable.new( initial_typecode )
var2 = options[ :var2 ] || Variable.new( typecode )
block = options[ :block ] || yield( var1, var2 )
value = element( index1 ).element( index2 ).
diagonal initial, :block => block, :var1 => var1, :var2 => var2
term = Diagonal.new( value, index0, index1, index2, initial,
block, var1, var2 )
index0.size = index1.size
Lambda.new( index0, term ).force
end
end | [
"def",
"diagonal",
"(",
"initial",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"if",
"dimension",
"==",
"0",
"demand",
"else",
"if",
"initial",
"initial",
"=",
"Node",
".",
"match",
"(",
"initial",
")",
".",
"new",
"initial",
"unless",
"initial",
".",
"matched?",
"initial_typecode",
"=",
"initial",
".",
"typecode",
"else",
"initial_typecode",
"=",
"typecode",
"end",
"index0",
"=",
"Variable",
".",
"new",
"Hornetseye",
"::",
"INDEX",
"(",
"nil",
")",
"index1",
"=",
"Variable",
".",
"new",
"Hornetseye",
"::",
"INDEX",
"(",
"nil",
")",
"index2",
"=",
"Variable",
".",
"new",
"Hornetseye",
"::",
"INDEX",
"(",
"nil",
")",
"var1",
"=",
"options",
"[",
":var1",
"]",
"||",
"Variable",
".",
"new",
"(",
"initial_typecode",
")",
"var2",
"=",
"options",
"[",
":var2",
"]",
"||",
"Variable",
".",
"new",
"(",
"typecode",
")",
"block",
"=",
"options",
"[",
":block",
"]",
"||",
"yield",
"(",
"var1",
",",
"var2",
")",
"value",
"=",
"element",
"(",
"index1",
")",
".",
"element",
"(",
"index2",
")",
".",
"diagonal",
"initial",
",",
":block",
"=>",
"block",
",",
":var1",
"=>",
"var1",
",",
":var2",
"=>",
"var2",
"term",
"=",
"Diagonal",
".",
"new",
"(",
"value",
",",
"index0",
",",
"index1",
",",
"index2",
",",
"initial",
",",
"block",
",",
"var1",
",",
"var2",
")",
"index0",
".",
"size",
"=",
"index1",
".",
"size",
"Lambda",
".",
"new",
"(",
"index0",
",",
"term",
")",
".",
"force",
"end",
"end"
] | Apply accumulative operation over elements diagonally
This method is used internally to implement convolutions.
@param [Object,Node] initial Initial value.
@option options [Variable] :var1 First variable defining operation.
@option options [Variable] :var2 Second variable defining operation.
@option options [Variable] :block (yield( var1, var2 )) The operation to
apply diagonally.
@yield Optional operation to apply diagonally.
@return [Node] Result of operation.
@see #convolve
@private | [
"Apply",
"accumulative",
"operation",
"over",
"elements",
"diagonally"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L560-L583 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.table | def table( filter, &action )
filter = Node.match( filter, typecode ).new filter unless filter.matched?
if filter.dimension > dimension
raise "Filter has #{filter.dimension} dimension(s) but should " +
"not have more than #{dimension}"
end
filter = Hornetseye::lazy( 1 ) { filter } while filter.dimension < dimension
if filter.dimension == 0
action.call self, filter
else
Hornetseye::lazy { |i,j| self[j].table filter[i], &action }
end
end | ruby | def table( filter, &action )
filter = Node.match( filter, typecode ).new filter unless filter.matched?
if filter.dimension > dimension
raise "Filter has #{filter.dimension} dimension(s) but should " +
"not have more than #{dimension}"
end
filter = Hornetseye::lazy( 1 ) { filter } while filter.dimension < dimension
if filter.dimension == 0
action.call self, filter
else
Hornetseye::lazy { |i,j| self[j].table filter[i], &action }
end
end | [
"def",
"table",
"(",
"filter",
",",
"&",
"action",
")",
"filter",
"=",
"Node",
".",
"match",
"(",
"filter",
",",
"typecode",
")",
".",
"new",
"filter",
"unless",
"filter",
".",
"matched?",
"if",
"filter",
".",
"dimension",
">",
"dimension",
"raise",
"\"Filter has #{filter.dimension} dimension(s) but should \"",
"+",
"\"not have more than #{dimension}\"",
"end",
"filter",
"=",
"Hornetseye",
"::",
"lazy",
"(",
"1",
")",
"{",
"filter",
"}",
"while",
"filter",
".",
"dimension",
"<",
"dimension",
"if",
"filter",
".",
"dimension",
"==",
"0",
"action",
".",
"call",
"self",
",",
"filter",
"else",
"Hornetseye",
"::",
"lazy",
"{",
"|",
"i",
",",
"j",
"|",
"self",
"[",
"j",
"]",
".",
"table",
"filter",
"[",
"i",
"]",
",",
"&",
"action",
"}",
"end",
"end"
] | Compute table from two arrays
Used internally to implement convolutions and other operations.
@param [Node] filter Filter to form table with.
@param [Proc] action Operation to make table for.
@return [Node] Result of operation.
@see #convolve
@private | [
"Compute",
"table",
"from",
"two",
"arrays"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L597-L609 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.convolve | def convolve( filter )
filter = Node.match( filter, typecode ).new filter unless filter.matched?
array = self
(dimension - filter.dimension).times { array = array.roll }
array.table(filter) { |a,b| a * b }.diagonal { |s,x| s + x }
end | ruby | def convolve( filter )
filter = Node.match( filter, typecode ).new filter unless filter.matched?
array = self
(dimension - filter.dimension).times { array = array.roll }
array.table(filter) { |a,b| a * b }.diagonal { |s,x| s + x }
end | [
"def",
"convolve",
"(",
"filter",
")",
"filter",
"=",
"Node",
".",
"match",
"(",
"filter",
",",
"typecode",
")",
".",
"new",
"filter",
"unless",
"filter",
".",
"matched?",
"array",
"=",
"self",
"(",
"dimension",
"-",
"filter",
".",
"dimension",
")",
".",
"times",
"{",
"array",
"=",
"array",
".",
"roll",
"}",
"array",
".",
"table",
"(",
"filter",
")",
"{",
"|",
"a",
",",
"b",
"|",
"a",
"*",
"b",
"}",
".",
"diagonal",
"{",
"|",
"s",
",",
"x",
"|",
"s",
"+",
"x",
"}",
"end"
] | Convolution with other array of same dimension
@param [Node] filter Filter to convolve with.
@return [Node] Result of convolution. | [
"Convolution",
"with",
"other",
"array",
"of",
"same",
"dimension"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L616-L621 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.histogram | def histogram( *ret_shape )
options = ret_shape.last.is_a?( Hash ) ? ret_shape.pop : {}
options = { :weight => UINT.new( 1 ), :safe => true }.merge options
unless options[:weight].matched?
options[:weight] = Node.match(options[:weight]).maxint.new options[:weight]
end
if ( shape.first != 1 or dimension == 1 ) and ret_shape.size == 1
[ self ].histogram *( ret_shape + [ options ] )
else
( 0 ... shape.first ).collect { |i| unroll[i] }.
histogram *( ret_shape + [ options ] )
end
end | ruby | def histogram( *ret_shape )
options = ret_shape.last.is_a?( Hash ) ? ret_shape.pop : {}
options = { :weight => UINT.new( 1 ), :safe => true }.merge options
unless options[:weight].matched?
options[:weight] = Node.match(options[:weight]).maxint.new options[:weight]
end
if ( shape.first != 1 or dimension == 1 ) and ret_shape.size == 1
[ self ].histogram *( ret_shape + [ options ] )
else
( 0 ... shape.first ).collect { |i| unroll[i] }.
histogram *( ret_shape + [ options ] )
end
end | [
"def",
"histogram",
"(",
"*",
"ret_shape",
")",
"options",
"=",
"ret_shape",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"ret_shape",
".",
"pop",
":",
"{",
"}",
"options",
"=",
"{",
":weight",
"=>",
"UINT",
".",
"new",
"(",
"1",
")",
",",
":safe",
"=>",
"true",
"}",
".",
"merge",
"options",
"unless",
"options",
"[",
":weight",
"]",
".",
"matched?",
"options",
"[",
":weight",
"]",
"=",
"Node",
".",
"match",
"(",
"options",
"[",
":weight",
"]",
")",
".",
"maxint",
".",
"new",
"options",
"[",
":weight",
"]",
"end",
"if",
"(",
"shape",
".",
"first",
"!=",
"1",
"or",
"dimension",
"==",
"1",
")",
"and",
"ret_shape",
".",
"size",
"==",
"1",
"[",
"self",
"]",
".",
"histogram",
"*",
"(",
"ret_shape",
"+",
"[",
"options",
"]",
")",
"else",
"(",
"0",
"...",
"shape",
".",
"first",
")",
".",
"collect",
"{",
"|",
"i",
"|",
"unroll",
"[",
"i",
"]",
"}",
".",
"histogram",
"*",
"(",
"ret_shape",
"+",
"[",
"options",
"]",
")",
"end",
"end"
] | Compute histogram of this array
@overload histogram( *ret_shape, options = {} )
@param [Array<Integer>] ret_shape Dimensions of resulting histogram.
@option options [Node] :weight (UINT(1)) Weights for computing the histogram.
@option options [Boolean] :safe (true) Do a boundary check before creating the
histogram.
@return [Node] The histogram. | [
"Compute",
"histogram",
"of",
"this",
"array"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L705-L717 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.lut | def lut( table, options = {} )
if ( shape.first != 1 or dimension == 1 ) and table.dimension == 1
[ self ].lut table, options
else
( 0 ... shape.first ).collect { |i| unroll[i] }.lut table, options
end
end | ruby | def lut( table, options = {} )
if ( shape.first != 1 or dimension == 1 ) and table.dimension == 1
[ self ].lut table, options
else
( 0 ... shape.first ).collect { |i| unroll[i] }.lut table, options
end
end | [
"def",
"lut",
"(",
"table",
",",
"options",
"=",
"{",
"}",
")",
"if",
"(",
"shape",
".",
"first",
"!=",
"1",
"or",
"dimension",
"==",
"1",
")",
"and",
"table",
".",
"dimension",
"==",
"1",
"[",
"self",
"]",
".",
"lut",
"table",
",",
"options",
"else",
"(",
"0",
"...",
"shape",
".",
"first",
")",
".",
"collect",
"{",
"|",
"i",
"|",
"unroll",
"[",
"i",
"]",
"}",
".",
"lut",
"table",
",",
"options",
"end",
"end"
] | Perform element-wise lookup
@param [Node] table The lookup table (LUT).
@option options [Boolean] :safe (true) Do a boundary check before creating the
element-wise lookup.
@return [Node] The result of the lookup operation. | [
"Perform",
"element",
"-",
"wise",
"lookup"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L726-L732 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.warp | def warp( *field )
options = field.last.is_a?( Hash ) ? field.pop : {}
options = { :safe => true, :default => typecode.default }.merge options
if options[ :safe ]
if field.size > dimension
raise "Number of arrays for warp (#{field.size}) is greater than the " +
"number of dimensions of source (#{dimension})"
end
Hornetseye::lazy do
( 0 ... field.size ).
collect { |i| ( field[i] >= 0 ).and( field[i] < shape[i] ) }.
inject :and
end.conditional Lut.new( *( field + [ self ] ) ), options[ :default ]
else
field.lut self, :safe => false
end
end | ruby | def warp( *field )
options = field.last.is_a?( Hash ) ? field.pop : {}
options = { :safe => true, :default => typecode.default }.merge options
if options[ :safe ]
if field.size > dimension
raise "Number of arrays for warp (#{field.size}) is greater than the " +
"number of dimensions of source (#{dimension})"
end
Hornetseye::lazy do
( 0 ... field.size ).
collect { |i| ( field[i] >= 0 ).and( field[i] < shape[i] ) }.
inject :and
end.conditional Lut.new( *( field + [ self ] ) ), options[ :default ]
else
field.lut self, :safe => false
end
end | [
"def",
"warp",
"(",
"*",
"field",
")",
"options",
"=",
"field",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"field",
".",
"pop",
":",
"{",
"}",
"options",
"=",
"{",
":safe",
"=>",
"true",
",",
":default",
"=>",
"typecode",
".",
"default",
"}",
".",
"merge",
"options",
"if",
"options",
"[",
":safe",
"]",
"if",
"field",
".",
"size",
">",
"dimension",
"raise",
"\"Number of arrays for warp (#{field.size}) is greater than the \"",
"+",
"\"number of dimensions of source (#{dimension})\"",
"end",
"Hornetseye",
"::",
"lazy",
"do",
"(",
"0",
"...",
"field",
".",
"size",
")",
".",
"collect",
"{",
"|",
"i",
"|",
"(",
"field",
"[",
"i",
"]",
">=",
"0",
")",
".",
"and",
"(",
"field",
"[",
"i",
"]",
"<",
"shape",
"[",
"i",
"]",
")",
"}",
".",
"inject",
":and",
"end",
".",
"conditional",
"Lut",
".",
"new",
"(",
"*",
"(",
"field",
"+",
"[",
"self",
"]",
")",
")",
",",
"options",
"[",
":default",
"]",
"else",
"field",
".",
"lut",
"self",
",",
":safe",
"=>",
"false",
"end",
"end"
] | Warp an array
@overload warp( *field, options = {} )
@param [Array<Integer>] ret_shape Dimensions of resulting histogram.
@option options [Object] :default (typecode.default) Default value for out of
range warp vectors.
@option options [Boolean] :safe (true) Apply clip to warp vectors.
@return [Node] The result of the lookup operation. | [
"Warp",
"an",
"array"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L743-L759 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.integral | def integral
left = allocate
block = Integral.new left, self
if block.compilable?
GCCFunction.run block
else
block.demand
end
left
end | ruby | def integral
left = allocate
block = Integral.new left, self
if block.compilable?
GCCFunction.run block
else
block.demand
end
left
end | [
"def",
"integral",
"left",
"=",
"allocate",
"block",
"=",
"Integral",
".",
"new",
"left",
",",
"self",
"if",
"block",
".",
"compilable?",
"GCCFunction",
".",
"run",
"block",
"else",
"block",
".",
"demand",
"end",
"left",
"end"
] | Compute integral image
@return [Node] The integral image of this array. | [
"Compute",
"integral",
"image"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L764-L773 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.components | def components( options = {} )
if shape.any? { |x| x <= 1 }
raise "Every dimension must be greater than 1 (shape was #{shape})"
end
options = { :target => UINT, :default => typecode.default }.merge options
target = options[ :target ]
default = options[ :default ]
default = typecode.new default unless default.matched?
left = Hornetseye::MultiArray(target, dimension).new *shape
labels = Sequence.new target, size; labels[0] = 0
rank = Sequence.uint size; rank[0] = 0
n = Hornetseye::Pointer( INT ).new; n.store INT.new( 0 )
block = Components.new left, self, default, target.new(0),
labels, rank, n
if block.compilable?
Hornetseye::GCCFunction.run block
else
block.demand
end
labels = labels[0 .. n.demand.get]
left.lut labels.lut(labels.histogram(labels.size, :weight => target.new(1)).
minor(1).integral - 1)
end | ruby | def components( options = {} )
if shape.any? { |x| x <= 1 }
raise "Every dimension must be greater than 1 (shape was #{shape})"
end
options = { :target => UINT, :default => typecode.default }.merge options
target = options[ :target ]
default = options[ :default ]
default = typecode.new default unless default.matched?
left = Hornetseye::MultiArray(target, dimension).new *shape
labels = Sequence.new target, size; labels[0] = 0
rank = Sequence.uint size; rank[0] = 0
n = Hornetseye::Pointer( INT ).new; n.store INT.new( 0 )
block = Components.new left, self, default, target.new(0),
labels, rank, n
if block.compilable?
Hornetseye::GCCFunction.run block
else
block.demand
end
labels = labels[0 .. n.demand.get]
left.lut labels.lut(labels.histogram(labels.size, :weight => target.new(1)).
minor(1).integral - 1)
end | [
"def",
"components",
"(",
"options",
"=",
"{",
"}",
")",
"if",
"shape",
".",
"any?",
"{",
"|",
"x",
"|",
"x",
"<=",
"1",
"}",
"raise",
"\"Every dimension must be greater than 1 (shape was #{shape})\"",
"end",
"options",
"=",
"{",
":target",
"=>",
"UINT",
",",
":default",
"=>",
"typecode",
".",
"default",
"}",
".",
"merge",
"options",
"target",
"=",
"options",
"[",
":target",
"]",
"default",
"=",
"options",
"[",
":default",
"]",
"default",
"=",
"typecode",
".",
"new",
"default",
"unless",
"default",
".",
"matched?",
"left",
"=",
"Hornetseye",
"::",
"MultiArray",
"(",
"target",
",",
"dimension",
")",
".",
"new",
"*",
"shape",
"labels",
"=",
"Sequence",
".",
"new",
"target",
",",
"size",
";",
"labels",
"[",
"0",
"]",
"=",
"0",
"rank",
"=",
"Sequence",
".",
"uint",
"size",
";",
"rank",
"[",
"0",
"]",
"=",
"0",
"n",
"=",
"Hornetseye",
"::",
"Pointer",
"(",
"INT",
")",
".",
"new",
";",
"n",
".",
"store",
"INT",
".",
"new",
"(",
"0",
")",
"block",
"=",
"Components",
".",
"new",
"left",
",",
"self",
",",
"default",
",",
"target",
".",
"new",
"(",
"0",
")",
",",
"labels",
",",
"rank",
",",
"n",
"if",
"block",
".",
"compilable?",
"Hornetseye",
"::",
"GCCFunction",
".",
"run",
"block",
"else",
"block",
".",
"demand",
"end",
"labels",
"=",
"labels",
"[",
"0",
"..",
"n",
".",
"demand",
".",
"get",
"]",
"left",
".",
"lut",
"labels",
".",
"lut",
"(",
"labels",
".",
"histogram",
"(",
"labels",
".",
"size",
",",
":weight",
"=>",
"target",
".",
"new",
"(",
"1",
")",
")",
".",
"minor",
"(",
"1",
")",
".",
"integral",
"-",
"1",
")",
"end"
] | Perform connected component labeling
@option options [Object] :default (typecode.default) Value of background elements.
@option options [Class] :target (UINT) Typecode of labels.
@return [Node] Array with labels of connected components. | [
"Perform",
"connected",
"component",
"labeling"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L781-L803 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.mask | def mask( m )
check_shape m
left = MultiArray.new typecode, *( shape.first( dimension - m.dimension ) +
[ m.size ] )
index = Hornetseye::Pointer( INT ).new
index.store INT.new( 0 )
block = Mask.new left, self, m, index
if block.compilable?
GCCFunction.run block
else
block.demand
end
left[0 ... index[]].roll
end | ruby | def mask( m )
check_shape m
left = MultiArray.new typecode, *( shape.first( dimension - m.dimension ) +
[ m.size ] )
index = Hornetseye::Pointer( INT ).new
index.store INT.new( 0 )
block = Mask.new left, self, m, index
if block.compilable?
GCCFunction.run block
else
block.demand
end
left[0 ... index[]].roll
end | [
"def",
"mask",
"(",
"m",
")",
"check_shape",
"m",
"left",
"=",
"MultiArray",
".",
"new",
"typecode",
",",
"*",
"(",
"shape",
".",
"first",
"(",
"dimension",
"-",
"m",
".",
"dimension",
")",
"+",
"[",
"m",
".",
"size",
"]",
")",
"index",
"=",
"Hornetseye",
"::",
"Pointer",
"(",
"INT",
")",
".",
"new",
"index",
".",
"store",
"INT",
".",
"new",
"(",
"0",
")",
"block",
"=",
"Mask",
".",
"new",
"left",
",",
"self",
",",
"m",
",",
"index",
"if",
"block",
".",
"compilable?",
"GCCFunction",
".",
"run",
"block",
"else",
"block",
".",
"demand",
"end",
"left",
"[",
"0",
"...",
"index",
"[",
"]",
"]",
".",
"roll",
"end"
] | Select values from array using a mask
@param [Node] m Mask to apply to this array.
@return [Node] The masked array. | [
"Select",
"values",
"from",
"array",
"using",
"a",
"mask"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L810-L823 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.unmask | def unmask( m, options = {} )
options = { :safe => true, :default => typecode.default }.merge options
default = options[:default]
default = typecode.new default unless default.matched?
m.check_shape default
if options[ :safe ]
if m.to_ubyte.sum > shape.last
raise "#{m.to_ubyte.sum} value(s) of the mask are true but the last " +
"dimension of the array for unmasking only has #{shape.last} value(s)"
end
end
left = Hornetseye::MultiArray(typecode, dimension - 1 + m.dimension).
coercion(default.typecode).new *(shape[1 .. -1] + m.shape)
index = Hornetseye::Pointer(INT).new
index.store INT.new(0)
block = Unmask.new left, self, m, index, default
if block.compilable?
GCCFunction.run block
else
block.demand
end
left
end | ruby | def unmask( m, options = {} )
options = { :safe => true, :default => typecode.default }.merge options
default = options[:default]
default = typecode.new default unless default.matched?
m.check_shape default
if options[ :safe ]
if m.to_ubyte.sum > shape.last
raise "#{m.to_ubyte.sum} value(s) of the mask are true but the last " +
"dimension of the array for unmasking only has #{shape.last} value(s)"
end
end
left = Hornetseye::MultiArray(typecode, dimension - 1 + m.dimension).
coercion(default.typecode).new *(shape[1 .. -1] + m.shape)
index = Hornetseye::Pointer(INT).new
index.store INT.new(0)
block = Unmask.new left, self, m, index, default
if block.compilable?
GCCFunction.run block
else
block.demand
end
left
end | [
"def",
"unmask",
"(",
"m",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":safe",
"=>",
"true",
",",
":default",
"=>",
"typecode",
".",
"default",
"}",
".",
"merge",
"options",
"default",
"=",
"options",
"[",
":default",
"]",
"default",
"=",
"typecode",
".",
"new",
"default",
"unless",
"default",
".",
"matched?",
"m",
".",
"check_shape",
"default",
"if",
"options",
"[",
":safe",
"]",
"if",
"m",
".",
"to_ubyte",
".",
"sum",
">",
"shape",
".",
"last",
"raise",
"\"#{m.to_ubyte.sum} value(s) of the mask are true but the last \"",
"+",
"\"dimension of the array for unmasking only has #{shape.last} value(s)\"",
"end",
"end",
"left",
"=",
"Hornetseye",
"::",
"MultiArray",
"(",
"typecode",
",",
"dimension",
"-",
"1",
"+",
"m",
".",
"dimension",
")",
".",
"coercion",
"(",
"default",
".",
"typecode",
")",
".",
"new",
"*",
"(",
"shape",
"[",
"1",
"..",
"-",
"1",
"]",
"+",
"m",
".",
"shape",
")",
"index",
"=",
"Hornetseye",
"::",
"Pointer",
"(",
"INT",
")",
".",
"new",
"index",
".",
"store",
"INT",
".",
"new",
"(",
"0",
")",
"block",
"=",
"Unmask",
".",
"new",
"left",
",",
"self",
",",
"m",
",",
"index",
",",
"default",
"if",
"block",
".",
"compilable?",
"GCCFunction",
".",
"run",
"block",
"else",
"block",
".",
"demand",
"end",
"left",
"end"
] | Distribute values in a new array using a mask
@param [Node] m Mask for inverse masking operation.
@option options [Object] :default (typecode.default) Default value for elements
where mask is +false+.
@option options [Boolean] :safe (true) Ensure that the size of this size is
sufficient.
@return [Node] The result of the inverse masking operation. | [
"Distribute",
"values",
"in",
"a",
"new",
"array",
"using",
"a",
"mask"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L834-L856 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.flip | def flip( *dimensions )
field = ( 0 ... dimension ).collect do |i|
if dimensions.member? i
Hornetseye::lazy( *shape ) { |*args| shape[i] - 1 - args[i] }
else
Hornetseye::lazy( *shape ) { |*args| args[i] }
end
end
warp *( field + [ :safe => false ] )
end | ruby | def flip( *dimensions )
field = ( 0 ... dimension ).collect do |i|
if dimensions.member? i
Hornetseye::lazy( *shape ) { |*args| shape[i] - 1 - args[i] }
else
Hornetseye::lazy( *shape ) { |*args| args[i] }
end
end
warp *( field + [ :safe => false ] )
end | [
"def",
"flip",
"(",
"*",
"dimensions",
")",
"field",
"=",
"(",
"0",
"...",
"dimension",
")",
".",
"collect",
"do",
"|",
"i",
"|",
"if",
"dimensions",
".",
"member?",
"i",
"Hornetseye",
"::",
"lazy",
"(",
"*",
"shape",
")",
"{",
"|",
"*",
"args",
"|",
"shape",
"[",
"i",
"]",
"-",
"1",
"-",
"args",
"[",
"i",
"]",
"}",
"else",
"Hornetseye",
"::",
"lazy",
"(",
"*",
"shape",
")",
"{",
"|",
"*",
"args",
"|",
"args",
"[",
"i",
"]",
"}",
"end",
"end",
"warp",
"*",
"(",
"field",
"+",
"[",
":safe",
"=>",
"false",
"]",
")",
"end"
] | Mirror the array
@param [Array<Integer>] dimensions The dimensions which should be flipped.
@return [Node] The result of flipping the dimensions. | [
"Mirror",
"the",
"array"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L863-L872 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.shift | def shift( *offset )
if offset.size != dimension
raise "#{offset.size} offset(s) were given but array has " +
"#{dimension} dimension(s)"
end
retval = Hornetseye::MultiArray(typecode, dimension).new *shape
target, source, open, close = [], [], [], []
( shape.size - 1 ).step( 0, -1 ) do |i|
callcc do |pass|
delta = offset[i] % shape[i]
source[i] = 0 ... shape[i] - delta
target[i] = delta ... shape[i]
callcc do |c|
open[i] = c
pass.call
end
source[i] = shape[i] - delta ... shape[i]
target[i] = 0 ... delta
callcc do |c|
open[i] = c
pass.call
end
close[i].call
end
end
retval[ *target ] = self[ *source ] unless target.any? { |t| t.size == 0 }
for i in 0 ... shape.size
callcc do |c|
close[i] = c
open[i].call
end
end
retval
end | ruby | def shift( *offset )
if offset.size != dimension
raise "#{offset.size} offset(s) were given but array has " +
"#{dimension} dimension(s)"
end
retval = Hornetseye::MultiArray(typecode, dimension).new *shape
target, source, open, close = [], [], [], []
( shape.size - 1 ).step( 0, -1 ) do |i|
callcc do |pass|
delta = offset[i] % shape[i]
source[i] = 0 ... shape[i] - delta
target[i] = delta ... shape[i]
callcc do |c|
open[i] = c
pass.call
end
source[i] = shape[i] - delta ... shape[i]
target[i] = 0 ... delta
callcc do |c|
open[i] = c
pass.call
end
close[i].call
end
end
retval[ *target ] = self[ *source ] unless target.any? { |t| t.size == 0 }
for i in 0 ... shape.size
callcc do |c|
close[i] = c
open[i].call
end
end
retval
end | [
"def",
"shift",
"(",
"*",
"offset",
")",
"if",
"offset",
".",
"size",
"!=",
"dimension",
"raise",
"\"#{offset.size} offset(s) were given but array has \"",
"+",
"\"#{dimension} dimension(s)\"",
"end",
"retval",
"=",
"Hornetseye",
"::",
"MultiArray",
"(",
"typecode",
",",
"dimension",
")",
".",
"new",
"*",
"shape",
"target",
",",
"source",
",",
"open",
",",
"close",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"(",
"shape",
".",
"size",
"-",
"1",
")",
".",
"step",
"(",
"0",
",",
"-",
"1",
")",
"do",
"|",
"i",
"|",
"callcc",
"do",
"|",
"pass",
"|",
"delta",
"=",
"offset",
"[",
"i",
"]",
"%",
"shape",
"[",
"i",
"]",
"source",
"[",
"i",
"]",
"=",
"0",
"...",
"shape",
"[",
"i",
"]",
"-",
"delta",
"target",
"[",
"i",
"]",
"=",
"delta",
"...",
"shape",
"[",
"i",
"]",
"callcc",
"do",
"|",
"c",
"|",
"open",
"[",
"i",
"]",
"=",
"c",
"pass",
".",
"call",
"end",
"source",
"[",
"i",
"]",
"=",
"shape",
"[",
"i",
"]",
"-",
"delta",
"...",
"shape",
"[",
"i",
"]",
"target",
"[",
"i",
"]",
"=",
"0",
"...",
"delta",
"callcc",
"do",
"|",
"c",
"|",
"open",
"[",
"i",
"]",
"=",
"c",
"pass",
".",
"call",
"end",
"close",
"[",
"i",
"]",
".",
"call",
"end",
"end",
"retval",
"[",
"*",
"target",
"]",
"=",
"self",
"[",
"*",
"source",
"]",
"unless",
"target",
".",
"any?",
"{",
"|",
"t",
"|",
"t",
".",
"size",
"==",
"0",
"}",
"for",
"i",
"in",
"0",
"...",
"shape",
".",
"size",
"callcc",
"do",
"|",
"c",
"|",
"close",
"[",
"i",
"]",
"=",
"c",
"open",
"[",
"i",
"]",
".",
"call",
"end",
"end",
"retval",
"end"
] | Create array with shifted elements
@param [Array<Integer>] offset Array with amount of shift for each dimension.
@return [Node] The result of the shifting operation. | [
"Create",
"array",
"with",
"shifted",
"elements"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L879-L912 | train |
wedesoft/multiarray | lib/multiarray/operations.rb | Hornetseye.Node.downsample | def downsample( *rate )
options = rate.last.is_a?( Hash ) ? rate.pop : {}
options = { :offset => rate.collect { |r| r - 1 } }.merge options
offset = options[ :offset ]
if rate.size != dimension
raise "#{rate.size} sampling rate(s) given but array has " +
"#{dimension} dimension(s)"
end
if offset.size != dimension
raise "#{offset.size} sampling offset(s) given but array has " +
"#{dimension} dimension(s)"
end
ret_shape = ( 0 ... dimension ).collect do |i|
( shape[i] + rate[i] - 1 - offset[i] ).div rate[i]
end
field = ( 0 ... dimension ).collect do |i|
Hornetseye::lazy( *ret_shape ) { |*args| args[i] * rate[i] + offset[i] }
end
warp *( field + [ :safe => false ] )
end | ruby | def downsample( *rate )
options = rate.last.is_a?( Hash ) ? rate.pop : {}
options = { :offset => rate.collect { |r| r - 1 } }.merge options
offset = options[ :offset ]
if rate.size != dimension
raise "#{rate.size} sampling rate(s) given but array has " +
"#{dimension} dimension(s)"
end
if offset.size != dimension
raise "#{offset.size} sampling offset(s) given but array has " +
"#{dimension} dimension(s)"
end
ret_shape = ( 0 ... dimension ).collect do |i|
( shape[i] + rate[i] - 1 - offset[i] ).div rate[i]
end
field = ( 0 ... dimension ).collect do |i|
Hornetseye::lazy( *ret_shape ) { |*args| args[i] * rate[i] + offset[i] }
end
warp *( field + [ :safe => false ] )
end | [
"def",
"downsample",
"(",
"*",
"rate",
")",
"options",
"=",
"rate",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"rate",
".",
"pop",
":",
"{",
"}",
"options",
"=",
"{",
":offset",
"=>",
"rate",
".",
"collect",
"{",
"|",
"r",
"|",
"r",
"-",
"1",
"}",
"}",
".",
"merge",
"options",
"offset",
"=",
"options",
"[",
":offset",
"]",
"if",
"rate",
".",
"size",
"!=",
"dimension",
"raise",
"\"#{rate.size} sampling rate(s) given but array has \"",
"+",
"\"#{dimension} dimension(s)\"",
"end",
"if",
"offset",
".",
"size",
"!=",
"dimension",
"raise",
"\"#{offset.size} sampling offset(s) given but array has \"",
"+",
"\"#{dimension} dimension(s)\"",
"end",
"ret_shape",
"=",
"(",
"0",
"...",
"dimension",
")",
".",
"collect",
"do",
"|",
"i",
"|",
"(",
"shape",
"[",
"i",
"]",
"+",
"rate",
"[",
"i",
"]",
"-",
"1",
"-",
"offset",
"[",
"i",
"]",
")",
".",
"div",
"rate",
"[",
"i",
"]",
"end",
"field",
"=",
"(",
"0",
"...",
"dimension",
")",
".",
"collect",
"do",
"|",
"i",
"|",
"Hornetseye",
"::",
"lazy",
"(",
"*",
"ret_shape",
")",
"{",
"|",
"*",
"args",
"|",
"args",
"[",
"i",
"]",
"*",
"rate",
"[",
"i",
"]",
"+",
"offset",
"[",
"i",
"]",
"}",
"end",
"warp",
"*",
"(",
"field",
"+",
"[",
":safe",
"=>",
"false",
"]",
")",
"end"
] | Downsampling of arrays
@overload downsample( *rate, options = {} )
@param [Array<Integer>] rate The sampling rates for each dimension.
@option options [Array<Integer>] :offset Sampling offsets for each dimension.
@return [Node] The downsampled data. | [
"Downsampling",
"of",
"arrays"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L921-L940 | train |
GemHQ/coin-op | lib/coin-op/bit/multi_wallet.rb | CoinOp::Bit.MultiWallet.signatures | def signatures(transaction, names: [:primary])
transaction.inputs.map do |input|
path = input.output.metadata[:wallet_path]
node = self.path(path)
sig_hash = transaction.sig_hash(input, node.script)
node.signatures(sig_hash, names: names)
end
end | ruby | def signatures(transaction, names: [:primary])
transaction.inputs.map do |input|
path = input.output.metadata[:wallet_path]
node = self.path(path)
sig_hash = transaction.sig_hash(input, node.script)
node.signatures(sig_hash, names: names)
end
end | [
"def",
"signatures",
"(",
"transaction",
",",
"names",
":",
"[",
":primary",
"]",
")",
"transaction",
".",
"inputs",
".",
"map",
"do",
"|",
"input",
"|",
"path",
"=",
"input",
".",
"output",
".",
"metadata",
"[",
":wallet_path",
"]",
"node",
"=",
"self",
".",
"path",
"(",
"path",
")",
"sig_hash",
"=",
"transaction",
".",
"sig_hash",
"(",
"input",
",",
"node",
".",
"script",
")",
"node",
".",
"signatures",
"(",
"sig_hash",
",",
"names",
":",
"names",
")",
"end",
"end"
] | Takes a Transaction ready to be signed.
Returns an Array of signature dictionaries. | [
"Takes",
"a",
"Transaction",
"ready",
"to",
"be",
"signed",
"."
] | 0b704b52d9826405cffb1606e914bf21b8dcc681 | https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/multi_wallet.rb#L157-L164 | train |
GemHQ/coin-op | lib/coin-op/bit/multi_wallet.rb | CoinOp::Bit.MultiWallet.authorize | def authorize(transaction, *signers)
transaction.set_script_sigs *signers do |input, *sig_dicts|
node = self.path(input.output.metadata[:wallet_path])
signatures = combine_signatures(*sig_dicts)
node.script_sig(signatures)
end
transaction
end | ruby | def authorize(transaction, *signers)
transaction.set_script_sigs *signers do |input, *sig_dicts|
node = self.path(input.output.metadata[:wallet_path])
signatures = combine_signatures(*sig_dicts)
node.script_sig(signatures)
end
transaction
end | [
"def",
"authorize",
"(",
"transaction",
",",
"*",
"signers",
")",
"transaction",
".",
"set_script_sigs",
"*",
"signers",
"do",
"|",
"input",
",",
"*",
"sig_dicts",
"|",
"node",
"=",
"self",
".",
"path",
"(",
"input",
".",
"output",
".",
"metadata",
"[",
":wallet_path",
"]",
")",
"signatures",
"=",
"combine_signatures",
"(",
"*",
"sig_dicts",
")",
"node",
".",
"script_sig",
"(",
"signatures",
")",
"end",
"transaction",
"end"
] | Takes a Transaction and any number of Arrays of signature dictionaries.
Each sig_dict in an Array corresponds to the Input with the same index.
Uses the combined signatures from all the signers to generate and set
the script_sig for each Input.
Returns the transaction. | [
"Takes",
"a",
"Transaction",
"and",
"any",
"number",
"of",
"Arrays",
"of",
"signature",
"dictionaries",
".",
"Each",
"sig_dict",
"in",
"an",
"Array",
"corresponds",
"to",
"the",
"Input",
"with",
"the",
"same",
"index",
"."
] | 0b704b52d9826405cffb1606e914bf21b8dcc681 | https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/multi_wallet.rb#L181-L188 | train |
GemHQ/coin-op | lib/coin-op/bit/multi_wallet.rb | CoinOp::Bit.MultiWallet.combine_signatures | def combine_signatures(*sig_dicts)
combined = {}
sig_dicts.each do |sig_dict|
sig_dict.each do |tree, signature|
decoded_sig = decode_base58(signature)
low_s_der_sig = Bitcoin::Script.is_low_der_signature?(decoded_sig) ?
decoded_sig : Bitcoin::OpenSSL_EC.signature_to_low_s(decoded_sig)
combined[tree] = Bitcoin::OpenSSL_EC.repack_der_signature(low_s_der_sig)
end
end
# Order of signatures is important for validation, so we always
# sort public keys and signatures by the name of the tree
# they belong to.
combined.sort_by { |tree, value| tree }.map { |tree, sig| sig }
end | ruby | def combine_signatures(*sig_dicts)
combined = {}
sig_dicts.each do |sig_dict|
sig_dict.each do |tree, signature|
decoded_sig = decode_base58(signature)
low_s_der_sig = Bitcoin::Script.is_low_der_signature?(decoded_sig) ?
decoded_sig : Bitcoin::OpenSSL_EC.signature_to_low_s(decoded_sig)
combined[tree] = Bitcoin::OpenSSL_EC.repack_der_signature(low_s_der_sig)
end
end
# Order of signatures is important for validation, so we always
# sort public keys and signatures by the name of the tree
# they belong to.
combined.sort_by { |tree, value| tree }.map { |tree, sig| sig }
end | [
"def",
"combine_signatures",
"(",
"*",
"sig_dicts",
")",
"combined",
"=",
"{",
"}",
"sig_dicts",
".",
"each",
"do",
"|",
"sig_dict",
"|",
"sig_dict",
".",
"each",
"do",
"|",
"tree",
",",
"signature",
"|",
"decoded_sig",
"=",
"decode_base58",
"(",
"signature",
")",
"low_s_der_sig",
"=",
"Bitcoin",
"::",
"Script",
".",
"is_low_der_signature?",
"(",
"decoded_sig",
")",
"?",
"decoded_sig",
":",
"Bitcoin",
"::",
"OpenSSL_EC",
".",
"signature_to_low_s",
"(",
"decoded_sig",
")",
"combined",
"[",
"tree",
"]",
"=",
"Bitcoin",
"::",
"OpenSSL_EC",
".",
"repack_der_signature",
"(",
"low_s_der_sig",
")",
"end",
"end",
"combined",
".",
"sort_by",
"{",
"|",
"tree",
",",
"value",
"|",
"tree",
"}",
".",
"map",
"{",
"|",
"tree",
",",
"sig",
"|",
"sig",
"}",
"end"
] | Takes any number of "signature dictionaries", which are Hashes where
the keys are tree names, and the values are base58-encoded signatures
for a single input.
Returns an Array of the signatures in binary, sorted by their tree names. | [
"Takes",
"any",
"number",
"of",
"signature",
"dictionaries",
"which",
"are",
"Hashes",
"where",
"the",
"keys",
"are",
"tree",
"names",
"and",
"the",
"values",
"are",
"base58",
"-",
"encoded",
"signatures",
"for",
"a",
"single",
"input",
"."
] | 0b704b52d9826405cffb1606e914bf21b8dcc681 | https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/multi_wallet.rb#L195-L210 | train |
RobertDober/Forwarder19 | lib/forwarder/arguments.rb | Forwarder.Arguments.evaluable? | def evaluable?
!lambda? &&
!aop? &&
( !args || args.all?{|a| Evaller.evaluable? a } ) &&
( !custom_target? || Evaller.evaluable?( custom_target? ) )
end | ruby | def evaluable?
!lambda? &&
!aop? &&
( !args || args.all?{|a| Evaller.evaluable? a } ) &&
( !custom_target? || Evaller.evaluable?( custom_target? ) )
end | [
"def",
"evaluable?",
"!",
"lambda?",
"&&",
"!",
"aop?",
"&&",
"(",
"!",
"args",
"||",
"args",
".",
"all?",
"{",
"|",
"a",
"|",
"Evaller",
".",
"evaluable?",
"a",
"}",
")",
"&&",
"(",
"!",
"custom_target?",
"||",
"Evaller",
".",
"evaluable?",
"(",
"custom_target?",
")",
")",
"end"
] | def delegatable?
!aop? && !custom_target? && !all? && !chain? && !args && !lambda?
end | [
"def",
"delegatable?",
"!aop?",
"&&",
"!custom_target?",
"&&",
"!all?",
"&&",
"!chain?",
"&&",
"!args",
"&&",
"!lambda?",
"end"
] | b8d0a0b568f14b157fea078ed5b4102c55701c99 | https://github.com/RobertDober/Forwarder19/blob/b8d0a0b568f14b157fea078ed5b4102c55701c99/lib/forwarder/arguments.rb#L51-L56 | train |
rolandasb/gogcom | lib/gogcom/sale.rb | Gogcom.Sale.fetch | def fetch()
url = "http://www.gog.com/"
page = Net::HTTP.get(URI(url))
@data = JSON.parse(page[/(?<=var gogData = )(.*)(?=;)/,1])
end | ruby | def fetch()
url = "http://www.gog.com/"
page = Net::HTTP.get(URI(url))
@data = JSON.parse(page[/(?<=var gogData = )(.*)(?=;)/,1])
end | [
"def",
"fetch",
"(",
")",
"url",
"=",
"\"http://www.gog.com/\"",
"page",
"=",
"Net",
"::",
"HTTP",
".",
"get",
"(",
"URI",
"(",
"url",
")",
")",
"@data",
"=",
"JSON",
".",
"parse",
"(",
"page",
"[",
"/",
"/",
",",
"1",
"]",
")",
"end"
] | Fetches raw data from source.
@return [Object] | [
"Fetches",
"raw",
"data",
"from",
"source",
"."
] | 015de453bb214c9ccb51665ecadce1367e6d987d | https://github.com/rolandasb/gogcom/blob/015de453bb214c9ccb51665ecadce1367e6d987d/lib/gogcom/sale.rb#L19-L23 | train |
rolandasb/gogcom | lib/gogcom/sale.rb | Gogcom.Sale.parse | def parse(data)
items = []
data["on_sale"].each do |item|
sale_item = SaleItem.new(get_title(item), get_current_price(item),
get_original_price(item), get_discount_percentage(item),
get_discount_amount(item))
if @type.nil?
items.push(sale_item)
else
if (@type == "games" && is_game?(item))
items.push(sale_item)
end
if (@type == "movies" && is_movie?(item))
items.push(sale_item)
end
end
end
unless @limit.nil?
items.take(@limit)
else
items
end
end | ruby | def parse(data)
items = []
data["on_sale"].each do |item|
sale_item = SaleItem.new(get_title(item), get_current_price(item),
get_original_price(item), get_discount_percentage(item),
get_discount_amount(item))
if @type.nil?
items.push(sale_item)
else
if (@type == "games" && is_game?(item))
items.push(sale_item)
end
if (@type == "movies" && is_movie?(item))
items.push(sale_item)
end
end
end
unless @limit.nil?
items.take(@limit)
else
items
end
end | [
"def",
"parse",
"(",
"data",
")",
"items",
"=",
"[",
"]",
"data",
"[",
"\"on_sale\"",
"]",
".",
"each",
"do",
"|",
"item",
"|",
"sale_item",
"=",
"SaleItem",
".",
"new",
"(",
"get_title",
"(",
"item",
")",
",",
"get_current_price",
"(",
"item",
")",
",",
"get_original_price",
"(",
"item",
")",
",",
"get_discount_percentage",
"(",
"item",
")",
",",
"get_discount_amount",
"(",
"item",
")",
")",
"if",
"@type",
".",
"nil?",
"items",
".",
"push",
"(",
"sale_item",
")",
"else",
"if",
"(",
"@type",
"==",
"\"games\"",
"&&",
"is_game?",
"(",
"item",
")",
")",
"items",
".",
"push",
"(",
"sale_item",
")",
"end",
"if",
"(",
"@type",
"==",
"\"movies\"",
"&&",
"is_movie?",
"(",
"item",
")",
")",
"items",
".",
"push",
"(",
"sale_item",
")",
"end",
"end",
"end",
"unless",
"@limit",
".",
"nil?",
"items",
".",
"take",
"(",
"@limit",
")",
"else",
"items",
"end",
"end"
] | Parses raw data and returns sale items.
@return [Array] | [
"Parses",
"raw",
"data",
"and",
"returns",
"sale",
"items",
"."
] | 015de453bb214c9ccb51665ecadce1367e6d987d | https://github.com/rolandasb/gogcom/blob/015de453bb214c9ccb51665ecadce1367e6d987d/lib/gogcom/sale.rb#L28-L54 | train |
schrodingersbox/split_cat | app/models/split_cat/experiment.rb | SplitCat.Experiment.choose_hypothesis | def choose_hypothesis
total = 0
roll = Kernel.rand( total_weight ) + 1
hypothesis = nil
hypotheses.each do |h|
if roll <= ( total += h.weight )
hypothesis ||= h
end
end
hypothesis ||= hypotheses.first
return hypothesis
end | ruby | def choose_hypothesis
total = 0
roll = Kernel.rand( total_weight ) + 1
hypothesis = nil
hypotheses.each do |h|
if roll <= ( total += h.weight )
hypothesis ||= h
end
end
hypothesis ||= hypotheses.first
return hypothesis
end | [
"def",
"choose_hypothesis",
"total",
"=",
"0",
"roll",
"=",
"Kernel",
".",
"rand",
"(",
"total_weight",
")",
"+",
"1",
"hypothesis",
"=",
"nil",
"hypotheses",
".",
"each",
"do",
"|",
"h",
"|",
"if",
"roll",
"<=",
"(",
"total",
"+=",
"h",
".",
"weight",
")",
"hypothesis",
"||=",
"h",
"end",
"end",
"hypothesis",
"||=",
"hypotheses",
".",
"first",
"return",
"hypothesis",
"end"
] | Returns a random hypothesis with weighted probability | [
"Returns",
"a",
"random",
"hypothesis",
"with",
"weighted",
"probability"
] | afe9c55e8d9be992ca601c0742b7512035e037a4 | https://github.com/schrodingersbox/split_cat/blob/afe9c55e8d9be992ca601c0742b7512035e037a4/app/models/split_cat/experiment.rb#L81-L92 | train |
schrodingersbox/split_cat | app/models/split_cat/experiment.rb | SplitCat.Experiment.same_structure? | def same_structure?( experiment )
return nil if name.to_sym != experiment.name.to_sym
return nil if goal_hash.keys != experiment.goal_hash.keys
return nil if hypothesis_hash.keys != experiment.hypothesis_hash.keys
return experiment
end | ruby | def same_structure?( experiment )
return nil if name.to_sym != experiment.name.to_sym
return nil if goal_hash.keys != experiment.goal_hash.keys
return nil if hypothesis_hash.keys != experiment.hypothesis_hash.keys
return experiment
end | [
"def",
"same_structure?",
"(",
"experiment",
")",
"return",
"nil",
"if",
"name",
".",
"to_sym",
"!=",
"experiment",
".",
"name",
".",
"to_sym",
"return",
"nil",
"if",
"goal_hash",
".",
"keys",
"!=",
"experiment",
".",
"goal_hash",
".",
"keys",
"return",
"nil",
"if",
"hypothesis_hash",
".",
"keys",
"!=",
"experiment",
".",
"hypothesis_hash",
".",
"keys",
"return",
"experiment",
"end"
] | Returns true if the experiment has the same name, goals, and hypotheses as this one | [
"Returns",
"true",
"if",
"the",
"experiment",
"has",
"the",
"same",
"name",
"goals",
"and",
"hypotheses",
"as",
"this",
"one"
] | afe9c55e8d9be992ca601c0742b7512035e037a4 | https://github.com/schrodingersbox/split_cat/blob/afe9c55e8d9be992ca601c0742b7512035e037a4/app/models/split_cat/experiment.rb#L117-L122 | train |
detroit/detroit-dnote | lib/detroit-dnote.rb | Detroit.DNote.current? | def current?
output_mapping.each do |file, format|
return false if outofdate?(file, *dnote_session.files)
end
"DNotes are current (#{output})"
end | ruby | def current?
output_mapping.each do |file, format|
return false if outofdate?(file, *dnote_session.files)
end
"DNotes are current (#{output})"
end | [
"def",
"current?",
"output_mapping",
".",
"each",
"do",
"|",
"file",
",",
"format",
"|",
"return",
"false",
"if",
"outofdate?",
"(",
"file",
",",
"*",
"dnote_session",
".",
"files",
")",
"end",
"\"DNotes are current (#{output})\"",
"end"
] | Check the output file and see if they are older than
the input files.
@return [Boolean] whether output is up-to-date | [
"Check",
"the",
"output",
"file",
"and",
"see",
"if",
"they",
"are",
"older",
"than",
"the",
"input",
"files",
"."
] | 2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef | https://github.com/detroit/detroit-dnote/blob/2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef/lib/detroit-dnote.rb#L84-L89 | train |
detroit/detroit-dnote | lib/detroit-dnote.rb | Detroit.DNote.document | def document
session = dnote_session
output_mapping.each do |file, format|
#next unless verify_format(format)
dir = File.dirname(file)
mkdir_p(dir) unless File.directory?(dir)
session.output = file
session.format = format
session.run
report "Updated #{file.sub(Dir.pwd+'/','')}"
end
end | ruby | def document
session = dnote_session
output_mapping.each do |file, format|
#next unless verify_format(format)
dir = File.dirname(file)
mkdir_p(dir) unless File.directory?(dir)
session.output = file
session.format = format
session.run
report "Updated #{file.sub(Dir.pwd+'/','')}"
end
end | [
"def",
"document",
"session",
"=",
"dnote_session",
"output_mapping",
".",
"each",
"do",
"|",
"file",
",",
"format",
"|",
"dir",
"=",
"File",
".",
"dirname",
"(",
"file",
")",
"mkdir_p",
"(",
"dir",
")",
"unless",
"File",
".",
"directory?",
"(",
"dir",
")",
"session",
".",
"output",
"=",
"file",
"session",
".",
"format",
"=",
"format",
"session",
".",
"run",
"report",
"\"Updated #{file.sub(Dir.pwd+'/','')}\"",
"end",
"end"
] | Generate notes documents.
@return [void] | [
"Generate",
"notes",
"documents",
"."
] | 2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef | https://github.com/detroit/detroit-dnote/blob/2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef/lib/detroit-dnote.rb#L94-L109 | train |
detroit/detroit-dnote | lib/detroit-dnote.rb | Detroit.DNote.reset | def reset
output.each do |file, format|
if File.exist?(file)
utime(0,0,file)
report "Marked #{file} as out-of-date."
end
end
end | ruby | def reset
output.each do |file, format|
if File.exist?(file)
utime(0,0,file)
report "Marked #{file} as out-of-date."
end
end
end | [
"def",
"reset",
"output",
".",
"each",
"do",
"|",
"file",
",",
"format",
"|",
"if",
"File",
".",
"exist?",
"(",
"file",
")",
"utime",
"(",
"0",
",",
"0",
",",
"file",
")",
"report",
"\"Marked #{file} as out-of-date.\"",
"end",
"end",
"end"
] | Reset output files, marking them as out-of-date.
@return [void] | [
"Reset",
"output",
"files",
"marking",
"them",
"as",
"out",
"-",
"of",
"-",
"date",
"."
] | 2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef | https://github.com/detroit/detroit-dnote/blob/2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef/lib/detroit-dnote.rb#L114-L121 | train |
detroit/detroit-dnote | lib/detroit-dnote.rb | Detroit.DNote.purge | def purge
output.each do |file, format|
if File.exist?(file)
rm(file)
report "Removed #{file}"
end
end
end | ruby | def purge
output.each do |file, format|
if File.exist?(file)
rm(file)
report "Removed #{file}"
end
end
end | [
"def",
"purge",
"output",
".",
"each",
"do",
"|",
"file",
",",
"format",
"|",
"if",
"File",
".",
"exist?",
"(",
"file",
")",
"rm",
"(",
"file",
")",
"report",
"\"Removed #{file}\"",
"end",
"end",
"end"
] | Remove output files.
@return [void] | [
"Remove",
"output",
"files",
"."
] | 2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef | https://github.com/detroit/detroit-dnote/blob/2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef/lib/detroit-dnote.rb#L126-L133 | train |
detroit/detroit-dnote | lib/detroit-dnote.rb | Detroit.DNote.output_mapping | def output_mapping
@output_mapping ||= (
hash = {}
case output
when Array
output.each do |path|
hash[path] = format(path)
end
when String
hash[output] = format(output)
when Hash
hash = output
end
hash
)
end | ruby | def output_mapping
@output_mapping ||= (
hash = {}
case output
when Array
output.each do |path|
hash[path] = format(path)
end
when String
hash[output] = format(output)
when Hash
hash = output
end
hash
)
end | [
"def",
"output_mapping",
"@output_mapping",
"||=",
"(",
"hash",
"=",
"{",
"}",
"case",
"output",
"when",
"Array",
"output",
".",
"each",
"do",
"|",
"path",
"|",
"hash",
"[",
"path",
"]",
"=",
"format",
"(",
"path",
")",
"end",
"when",
"String",
"hash",
"[",
"output",
"]",
"=",
"format",
"(",
"output",
")",
"when",
"Hash",
"hash",
"=",
"output",
"end",
"hash",
")",
"end"
] | Convert output into a hash of `file => format`.
@todo Should we use #apply_naming_policy ?
@return [Hash] | [
"Convert",
"output",
"into",
"a",
"hash",
"of",
"file",
"=",
">",
"format",
"."
] | 2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef | https://github.com/detroit/detroit-dnote/blob/2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef/lib/detroit-dnote.rb#L150-L165 | train |
detroit/detroit-dnote | lib/detroit-dnote.rb | Detroit.DNote.format | def format(file)
type = File.extname(file).sub('.','')
type = DEFAULT_FORMAT if type.empty?
type
end | ruby | def format(file)
type = File.extname(file).sub('.','')
type = DEFAULT_FORMAT if type.empty?
type
end | [
"def",
"format",
"(",
"file",
")",
"type",
"=",
"File",
".",
"extname",
"(",
"file",
")",
".",
"sub",
"(",
"'.'",
",",
"''",
")",
"type",
"=",
"DEFAULT_FORMAT",
"if",
"type",
".",
"empty?",
"type",
"end"
] | The format of the file based on the extension.
If the file has no extension then the value of
`DEFAULT_FORMAT` is returned.
@return [String] | [
"The",
"format",
"of",
"the",
"file",
"based",
"on",
"the",
"extension",
".",
"If",
"the",
"file",
"has",
"no",
"extension",
"then",
"the",
"value",
"of",
"DEFAULT_FORMAT",
"is",
"returned",
"."
] | 2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef | https://github.com/detroit/detroit-dnote/blob/2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef/lib/detroit-dnote.rb#L172-L176 | train |
detroit/detroit-dnote | lib/detroit-dnote.rb | Detroit.DNote.dnote_session | def dnote_session
::DNote::Session.new do |s|
s.paths = files
s.exclude = exclude
s.ignore = ignore
s.labels = labels
s.title = title
s.context = lines
s.dryrun = trial?
end
end | ruby | def dnote_session
::DNote::Session.new do |s|
s.paths = files
s.exclude = exclude
s.ignore = ignore
s.labels = labels
s.title = title
s.context = lines
s.dryrun = trial?
end
end | [
"def",
"dnote_session",
"::",
"DNote",
"::",
"Session",
".",
"new",
"do",
"|",
"s",
"|",
"s",
".",
"paths",
"=",
"files",
"s",
".",
"exclude",
"=",
"exclude",
"s",
".",
"ignore",
"=",
"ignore",
"s",
".",
"labels",
"=",
"labels",
"s",
".",
"title",
"=",
"title",
"s",
".",
"context",
"=",
"lines",
"s",
".",
"dryrun",
"=",
"trial?",
"end",
"end"
] | DNote Session instance.
@return [DNote::Session] | [
"DNote",
"Session",
"instance",
"."
] | 2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef | https://github.com/detroit/detroit-dnote/blob/2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef/lib/detroit-dnote.rb#L181-L191 | train |
aaronpk/jawbone-up-ruby | lib/jawbone-up/session.rb | JawboneUP.Session.get | def get(path, query=nil, headers={})
response = execute :get, path, query, headers
hash = JSON.parse response.body
end | ruby | def get(path, query=nil, headers={})
response = execute :get, path, query, headers
hash = JSON.parse response.body
end | [
"def",
"get",
"(",
"path",
",",
"query",
"=",
"nil",
",",
"headers",
"=",
"{",
"}",
")",
"response",
"=",
"execute",
":get",
",",
"path",
",",
"query",
",",
"headers",
"hash",
"=",
"JSON",
".",
"parse",
"response",
".",
"body",
"end"
] | Raw HTTP methods | [
"Raw",
"HTTP",
"methods"
] | 6fec67a72d7f3df5aa040fa4d5341d0c434f72ca | https://github.com/aaronpk/jawbone-up-ruby/blob/6fec67a72d7f3df5aa040fa4d5341d0c434f72ca/lib/jawbone-up/session.rb#L90-L93 | train |
seoaqua/baidumap | lib/baidumap/request.rb | Baidumap.Request.request | def request
http_segments = @segments.clone
@params.each do |key,value|
http_segments[key] = value
end
uri = URI::HTTP.build(
:host => HOST,
:path => @action_path,
:query => URI.encode_www_form(http_segments)
).to_s
result = JSON.parse(HTTParty.get(uri).parsed_response)
Baidumap::Response.new(result,self)
end | ruby | def request
http_segments = @segments.clone
@params.each do |key,value|
http_segments[key] = value
end
uri = URI::HTTP.build(
:host => HOST,
:path => @action_path,
:query => URI.encode_www_form(http_segments)
).to_s
result = JSON.parse(HTTParty.get(uri).parsed_response)
Baidumap::Response.new(result,self)
end | [
"def",
"request",
"http_segments",
"=",
"@segments",
".",
"clone",
"@params",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"http_segments",
"[",
"key",
"]",
"=",
"value",
"end",
"uri",
"=",
"URI",
"::",
"HTTP",
".",
"build",
"(",
":host",
"=>",
"HOST",
",",
":path",
"=>",
"@action_path",
",",
":query",
"=>",
"URI",
".",
"encode_www_form",
"(",
"http_segments",
")",
")",
".",
"to_s",
"result",
"=",
"JSON",
".",
"parse",
"(",
"HTTParty",
".",
"get",
"(",
"uri",
")",
".",
"parsed_response",
")",
"Baidumap",
"::",
"Response",
".",
"new",
"(",
"result",
",",
"self",
")",
"end"
] | send http request | [
"send",
"http",
"request"
] | da6c0fd4ff61eb5b89ff8acea8389b2894a2661a | https://github.com/seoaqua/baidumap/blob/da6c0fd4ff61eb5b89ff8acea8389b2894a2661a/lib/baidumap/request.rb#L36-L48 | train |
midi-visualizer/vissen-parameterized | lib/vissen/parameterized.rb | Vissen.Parameterized.bind | def bind(param, target)
raise ScopeError unless scope.include? target
@_params.fetch(param).bind target
end | ruby | def bind(param, target)
raise ScopeError unless scope.include? target
@_params.fetch(param).bind target
end | [
"def",
"bind",
"(",
"param",
",",
"target",
")",
"raise",
"ScopeError",
"unless",
"scope",
".",
"include?",
"target",
"@_params",
".",
"fetch",
"(",
"param",
")",
".",
"bind",
"target",
"end"
] | Binds a parameter to a target value.
@see Parameter#bind
@raise [KeyError] if the parameter is not found.
@raise [ScopeError] if the parameter is out of scope.
@param param [Symbol] the parameter to bind.
@param target [#value] the value object to bind to.
@return [Parameter] the parameter that was bound. | [
"Binds",
"a",
"parameter",
"to",
"a",
"target",
"value",
"."
] | 20cfb1cbaf6c7af5f5907b41c5439c39eed06420 | https://github.com/midi-visualizer/vissen-parameterized/blob/20cfb1cbaf6c7af5f5907b41c5439c39eed06420/lib/vissen/parameterized.rb#L133-L136 | train |
midi-visualizer/vissen-parameterized | lib/vissen/parameterized.rb | Vissen.Parameterized.inspect | def inspect
format INSPECT_FORMAT, name: self.class.name,
object_id: object_id,
params: params_with_types,
type: Value.canonicalize(@_value.class)
end | ruby | def inspect
format INSPECT_FORMAT, name: self.class.name,
object_id: object_id,
params: params_with_types,
type: Value.canonicalize(@_value.class)
end | [
"def",
"inspect",
"format",
"INSPECT_FORMAT",
",",
"name",
":",
"self",
".",
"class",
".",
"name",
",",
"object_id",
":",
"object_id",
",",
"params",
":",
"params_with_types",
",",
"type",
":",
"Value",
".",
"canonicalize",
"(",
"@_value",
".",
"class",
")",
"end"
] | Produces a readable string representation of the parameterized object.
@return [String] a string representation. | [
"Produces",
"a",
"readable",
"string",
"representation",
"of",
"the",
"parameterized",
"object",
"."
] | 20cfb1cbaf6c7af5f5907b41c5439c39eed06420 | https://github.com/midi-visualizer/vissen-parameterized/blob/20cfb1cbaf6c7af5f5907b41c5439c39eed06420/lib/vissen/parameterized.rb#L166-L171 | train |
midi-visualizer/vissen-parameterized | lib/vissen/parameterized.rb | Vissen.Parameterized.each_parameterized | def each_parameterized
return to_enum(__callee__) unless block_given?
@_params.each do |_, param|
next if param.constant?
target = param.target
yield target if target.is_a? Parameterized
end
end | ruby | def each_parameterized
return to_enum(__callee__) unless block_given?
@_params.each do |_, param|
next if param.constant?
target = param.target
yield target if target.is_a? Parameterized
end
end | [
"def",
"each_parameterized",
"return",
"to_enum",
"(",
"__callee__",
")",
"unless",
"block_given?",
"@_params",
".",
"each",
"do",
"|",
"_",
",",
"param",
"|",
"next",
"if",
"param",
".",
"constant?",
"target",
"=",
"param",
".",
"target",
"yield",
"target",
"if",
"target",
".",
"is_a?",
"Parameterized",
"end",
"end"
] | Iterates over the parameterized objects currently bound to the parameters.
@return [Enumerable] if no block is given. | [
"Iterates",
"over",
"the",
"parameterized",
"objects",
"currently",
"bound",
"to",
"the",
"parameters",
"."
] | 20cfb1cbaf6c7af5f5907b41c5439c39eed06420 | https://github.com/midi-visualizer/vissen-parameterized/blob/20cfb1cbaf6c7af5f5907b41c5439c39eed06420/lib/vissen/parameterized.rb#L176-L183 | train |
triglav-dataflow/triglav-client-ruby | lib/triglav_client/api/auth_api.rb | TriglavClient.AuthApi.create_token | def create_token(credential, opts = {})
data, _status_code, _headers = create_token_with_http_info(credential, opts)
return data
end | ruby | def create_token(credential, opts = {})
data, _status_code, _headers = create_token_with_http_info(credential, opts)
return data
end | [
"def",
"create_token",
"(",
"credential",
",",
"opts",
"=",
"{",
"}",
")",
"data",
",",
"_status_code",
",",
"_headers",
"=",
"create_token_with_http_info",
"(",
"credential",
",",
"opts",
")",
"return",
"data",
"end"
] | Creates a new token
@param credential
@param [Hash] opts the optional parameters
@return [TokenResponse] | [
"Creates",
"a",
"new",
"token"
] | b2f3781d65ee032ba96eb703fbd789c713a5e0bd | https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/auth_api.rb#L39-L42 | train |
barkerest/barkest_core | app/models/barkest_core/auth_config.rb | BarkestCore.AuthConfig.to_h | def to_h
{
enable_db_auth: enable_db_auth?,
enable_ldap_auth: enable_ldap_auth?,
ldap_host: ldap_host.to_s,
ldap_port: ldap_port.to_s.to_i,
ldap_ssl: ldap_ssl?,
ldap_base_dn: ldap_base_dn.to_s,
ldap_browse_user: ldap_browse_user.to_s,
ldap_browse_password: ldap_browse_password.to_s,
ldap_auto_activate: ldap_auto_activate?,
ldap_system_admin_groups: ldap_system_admin_groups.to_s,
}
end | ruby | def to_h
{
enable_db_auth: enable_db_auth?,
enable_ldap_auth: enable_ldap_auth?,
ldap_host: ldap_host.to_s,
ldap_port: ldap_port.to_s.to_i,
ldap_ssl: ldap_ssl?,
ldap_base_dn: ldap_base_dn.to_s,
ldap_browse_user: ldap_browse_user.to_s,
ldap_browse_password: ldap_browse_password.to_s,
ldap_auto_activate: ldap_auto_activate?,
ldap_system_admin_groups: ldap_system_admin_groups.to_s,
}
end | [
"def",
"to_h",
"{",
"enable_db_auth",
":",
"enable_db_auth?",
",",
"enable_ldap_auth",
":",
"enable_ldap_auth?",
",",
"ldap_host",
":",
"ldap_host",
".",
"to_s",
",",
"ldap_port",
":",
"ldap_port",
".",
"to_s",
".",
"to_i",
",",
"ldap_ssl",
":",
"ldap_ssl?",
",",
"ldap_base_dn",
":",
"ldap_base_dn",
".",
"to_s",
",",
"ldap_browse_user",
":",
"ldap_browse_user",
".",
"to_s",
",",
"ldap_browse_password",
":",
"ldap_browse_password",
".",
"to_s",
",",
"ldap_auto_activate",
":",
"ldap_auto_activate?",
",",
"ldap_system_admin_groups",
":",
"ldap_system_admin_groups",
".",
"to_s",
",",
"}",
"end"
] | Converts the configuration to a hash. | [
"Converts",
"the",
"configuration",
"to",
"a",
"hash",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/auth_config.rb#L67-L80 | train |
nrser/nrser.rb | lib/nrser/message.rb | NRSER.Message.send_to | def send_to receiver, publicly: true
if publicly
receiver.public_send symbol, *args, &block
else
receiver.send symbol, *args, &block
end
end | ruby | def send_to receiver, publicly: true
if publicly
receiver.public_send symbol, *args, &block
else
receiver.send symbol, *args, &block
end
end | [
"def",
"send_to",
"receiver",
",",
"publicly",
":",
"true",
"if",
"publicly",
"receiver",
".",
"public_send",
"symbol",
",",
"*",
"args",
",",
"&",
"block",
"else",
"receiver",
".",
"send",
"symbol",
",",
"*",
"args",
",",
"&",
"block",
"end",
"end"
] | Send this instance to a receiver object.
@example
msg.send_to obj
@param [Object] receiver
Object that the message will be sent to.
@param [Boolean] publicly
When `true`, the message will be sent via {Object#public_send}. This is
the default behavior.
When `false`, the message will be sent via {Object#send}, allowing it
to invoke private and protected methods on the receiver.
@return [Object]
Result of the method call. | [
"Send",
"this",
"instance",
"to",
"a",
"receiver",
"object",
"."
] | 7db9a729ec65894dfac13fd50851beae8b809738 | https://github.com/nrser/nrser.rb/blob/7db9a729ec65894dfac13fd50851beae8b809738/lib/nrser/message.rb#L159-L165 | train |
coralnexus/nucleon | lib/core/core.rb | Nucleon.Core.logger= | def logger=logger
Util::Logger.loggers.delete(self.logger.resource) if self.logger
if logger.is_a?(Util::Logger)
@logger = logger
else
@logger = Util::Logger.new(logger)
end
end | ruby | def logger=logger
Util::Logger.loggers.delete(self.logger.resource) if self.logger
if logger.is_a?(Util::Logger)
@logger = logger
else
@logger = Util::Logger.new(logger)
end
end | [
"def",
"logger",
"=",
"logger",
"Util",
"::",
"Logger",
".",
"loggers",
".",
"delete",
"(",
"self",
".",
"logger",
".",
"resource",
")",
"if",
"self",
".",
"logger",
"if",
"logger",
".",
"is_a?",
"(",
"Util",
"::",
"Logger",
")",
"@logger",
"=",
"logger",
"else",
"@logger",
"=",
"Util",
"::",
"Logger",
".",
"new",
"(",
"logger",
")",
"end",
"end"
] | Set current object logger instance
* *Parameters*
- [String, Nucleon::Util::Logger] *logger* Logger instance or resource name for new logger
* *Returns*
- [Void] This method does not return a value
* *Errors*
See also:
- Nucleon::Util::Logger::loggers
- Nucleon::Util::Logger::new | [
"Set",
"current",
"object",
"logger",
"instance"
] | 3a3c489251139c184e0884feaa55269cf64cad44 | https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/core.rb#L153-L161 | train |
coralnexus/nucleon | lib/core/core.rb | Nucleon.Core.ui= | def ui=ui
if ui.is_a?(Util::Console)
@ui = ui
else
@ui = Util::Console.new(ui)
end
end | ruby | def ui=ui
if ui.is_a?(Util::Console)
@ui = ui
else
@ui = Util::Console.new(ui)
end
end | [
"def",
"ui",
"=",
"ui",
"if",
"ui",
".",
"is_a?",
"(",
"Util",
"::",
"Console",
")",
"@ui",
"=",
"ui",
"else",
"@ui",
"=",
"Util",
"::",
"Console",
".",
"new",
"(",
"ui",
")",
"end",
"end"
] | Set current object console instance
* *Parameters*
- [String, Nucleon::Util::Console] *ui* Console instance or resource name for new console
* *Returns*
- [Void] This method does not return a value
* *Errors*
See also:
- Nucleon::Util::Console::new | [
"Set",
"current",
"object",
"console",
"instance"
] | 3a3c489251139c184e0884feaa55269cf64cad44 | https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/core.rb#L192-L198 | train |
coralnexus/nucleon | lib/core/core.rb | Nucleon.Core.ui_group | def ui_group(resource, color = :cyan) # :yields: ui
ui_resource = ui.resource
ui.resource = Util::Console.colorize(resource, color)
yield(ui)
ensure
ui.resource = ui_resource
end | ruby | def ui_group(resource, color = :cyan) # :yields: ui
ui_resource = ui.resource
ui.resource = Util::Console.colorize(resource, color)
yield(ui)
ensure
ui.resource = ui_resource
end | [
"def",
"ui_group",
"(",
"resource",
",",
"color",
"=",
":cyan",
")",
"ui_resource",
"=",
"ui",
".",
"resource",
"ui",
".",
"resource",
"=",
"Util",
"::",
"Console",
".",
"colorize",
"(",
"resource",
",",
"color",
")",
"yield",
"(",
"ui",
")",
"ensure",
"ui",
".",
"resource",
"=",
"ui_resource",
"end"
] | Contextualize console operations in a code block with a given resource name.
* *Parameters*
- [String, Symbol] *resource* Console resource identifier (prefix)
- [Symbol] *color* Color to use; *:black*, *:red*, *:green*, *:yellow*, *:blue*, *:purple*, *:cyan*, *:grey*
* *Returns*
- [Void] This method does not return a value
* *Errors*
* *Yields*
- [Nucleon::Util::Console] *ui* Current object console instance
See also:
- Nucleon::Util::Console::colorize | [
"Contextualize",
"console",
"operations",
"in",
"a",
"code",
"block",
"with",
"a",
"given",
"resource",
"name",
"."
] | 3a3c489251139c184e0884feaa55269cf64cad44 | https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/core.rb#L252-L259 | train |
DigitPaint/html_mockup | lib/html_mockup/release.rb | HtmlMockup.Release.log | def log(part, msg, verbose = false, &block)
if !verbose || verbose && self.project.options[:verbose]
self.project.shell.say "\033[37m#{part.class.to_s}\033[0m" + " : " + msg.to_s, nil, true
end
if block_given?
begin
self.project.shell.padding = self.project.shell.padding + 1
yield
ensure
self.project.shell.padding = self.project.shell.padding - 1
end
end
end | ruby | def log(part, msg, verbose = false, &block)
if !verbose || verbose && self.project.options[:verbose]
self.project.shell.say "\033[37m#{part.class.to_s}\033[0m" + " : " + msg.to_s, nil, true
end
if block_given?
begin
self.project.shell.padding = self.project.shell.padding + 1
yield
ensure
self.project.shell.padding = self.project.shell.padding - 1
end
end
end | [
"def",
"log",
"(",
"part",
",",
"msg",
",",
"verbose",
"=",
"false",
",",
"&",
"block",
")",
"if",
"!",
"verbose",
"||",
"verbose",
"&&",
"self",
".",
"project",
".",
"options",
"[",
":verbose",
"]",
"self",
".",
"project",
".",
"shell",
".",
"say",
"\"\\033[37m#{part.class.to_s}\\033[0m\"",
"+",
"\" : \"",
"+",
"msg",
".",
"to_s",
",",
"nil",
",",
"true",
"end",
"if",
"block_given?",
"begin",
"self",
".",
"project",
".",
"shell",
".",
"padding",
"=",
"self",
".",
"project",
".",
"shell",
".",
"padding",
"+",
"1",
"yield",
"ensure",
"self",
".",
"project",
".",
"shell",
".",
"padding",
"=",
"self",
".",
"project",
".",
"shell",
".",
"padding",
"-",
"1",
"end",
"end",
"end"
] | Write out a log message | [
"Write",
"out",
"a",
"log",
"message"
] | 976edadc01216b82a8cea177f53fb32559eaf41e | https://github.com/DigitPaint/html_mockup/blob/976edadc01216b82a8cea177f53fb32559eaf41e/lib/html_mockup/release.rb#L223-L235 | train |
DigitPaint/html_mockup | lib/html_mockup/release.rb | HtmlMockup.Release.validate_stack! | def validate_stack!
mockup_options = {}
relativizer_options = {}
run_relativizer = true
if @extractor_options
mockup_options = {:env => @extractor_options[:env]}
relativizer_options = {:url_attributes => @extractor_options[:url_attributes]}
run_relativizer = @extractor_options[:url_relativize]
end
unless @stack.find{|(processor, options)| processor.class == HtmlMockup::Release::Processors::Mockup }
@stack.unshift([HtmlMockup::Release::Processors::UrlRelativizer.new, relativizer_options])
@stack.unshift([HtmlMockup::Release::Processors::Mockup.new, mockup_options])
end
end | ruby | def validate_stack!
mockup_options = {}
relativizer_options = {}
run_relativizer = true
if @extractor_options
mockup_options = {:env => @extractor_options[:env]}
relativizer_options = {:url_attributes => @extractor_options[:url_attributes]}
run_relativizer = @extractor_options[:url_relativize]
end
unless @stack.find{|(processor, options)| processor.class == HtmlMockup::Release::Processors::Mockup }
@stack.unshift([HtmlMockup::Release::Processors::UrlRelativizer.new, relativizer_options])
@stack.unshift([HtmlMockup::Release::Processors::Mockup.new, mockup_options])
end
end | [
"def",
"validate_stack!",
"mockup_options",
"=",
"{",
"}",
"relativizer_options",
"=",
"{",
"}",
"run_relativizer",
"=",
"true",
"if",
"@extractor_options",
"mockup_options",
"=",
"{",
":env",
"=>",
"@extractor_options",
"[",
":env",
"]",
"}",
"relativizer_options",
"=",
"{",
":url_attributes",
"=>",
"@extractor_options",
"[",
":url_attributes",
"]",
"}",
"run_relativizer",
"=",
"@extractor_options",
"[",
":url_relativize",
"]",
"end",
"unless",
"@stack",
".",
"find",
"{",
"|",
"(",
"processor",
",",
"options",
")",
"|",
"processor",
".",
"class",
"==",
"HtmlMockup",
"::",
"Release",
"::",
"Processors",
"::",
"Mockup",
"}",
"@stack",
".",
"unshift",
"(",
"[",
"HtmlMockup",
"::",
"Release",
"::",
"Processors",
"::",
"UrlRelativizer",
".",
"new",
",",
"relativizer_options",
"]",
")",
"@stack",
".",
"unshift",
"(",
"[",
"HtmlMockup",
"::",
"Release",
"::",
"Processors",
"::",
"Mockup",
".",
"new",
",",
"mockup_options",
"]",
")",
"end",
"end"
] | Checks if deprecated extractor options have been set
Checks if the mockup will be runned | [
"Checks",
"if",
"deprecated",
"extractor",
"options",
"have",
"been",
"set",
"Checks",
"if",
"the",
"mockup",
"will",
"be",
"runned"
] | 976edadc01216b82a8cea177f53fb32559eaf41e | https://github.com/DigitPaint/html_mockup/blob/976edadc01216b82a8cea177f53fb32559eaf41e/lib/html_mockup/release.rb#L280-L295 | train |
riddopic/garcun | lib/garcon/task/priority_queue.rb | Garcon.MutexPriorityQueue.delete | def delete(item)
original_length = @length
k = 1
while k <= @length
if @queue[k] == item
swap(k, @length)
@length -= 1
sink(k)
@queue.pop
else
k += 1
end
end
@length != original_length
end | ruby | def delete(item)
original_length = @length
k = 1
while k <= @length
if @queue[k] == item
swap(k, @length)
@length -= 1
sink(k)
@queue.pop
else
k += 1
end
end
@length != original_length
end | [
"def",
"delete",
"(",
"item",
")",
"original_length",
"=",
"@length",
"k",
"=",
"1",
"while",
"k",
"<=",
"@length",
"if",
"@queue",
"[",
"k",
"]",
"==",
"item",
"swap",
"(",
"k",
",",
"@length",
")",
"@length",
"-=",
"1",
"sink",
"(",
"k",
")",
"@queue",
".",
"pop",
"else",
"k",
"+=",
"1",
"end",
"end",
"@length",
"!=",
"original_length",
"end"
] | Deletes all items from `self` that are equal to `item`.
@param [Object] item
The item to be removed from the queue.
@return [Object]
True if the item is found else false. | [
"Deletes",
"all",
"items",
"from",
"self",
"that",
"are",
"equal",
"to",
"item",
"."
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/priority_queue.rb#L63-L77 | train |
riddopic/garcun | lib/garcon/task/priority_queue.rb | Garcon.MutexPriorityQueue.sink | def sink(k)
while (j = (2 * k)) <= @length do
j += 1 if j < @length && ! ordered?(j, j+1)
break if ordered?(k, j)
swap(k, j)
k = j
end
end | ruby | def sink(k)
while (j = (2 * k)) <= @length do
j += 1 if j < @length && ! ordered?(j, j+1)
break if ordered?(k, j)
swap(k, j)
k = j
end
end | [
"def",
"sink",
"(",
"k",
")",
"while",
"(",
"j",
"=",
"(",
"2",
"*",
"k",
")",
")",
"<=",
"@length",
"do",
"j",
"+=",
"1",
"if",
"j",
"<",
"@length",
"&&",
"!",
"ordered?",
"(",
"j",
",",
"j",
"+",
"1",
")",
"break",
"if",
"ordered?",
"(",
"k",
",",
"j",
")",
"swap",
"(",
"k",
",",
"j",
")",
"k",
"=",
"j",
"end",
"end"
] | Percolate down to maintain heap invariant.
@param [Integer] k
The index at which to start the percolation.
@!visibility private | [
"Percolate",
"down",
"to",
"maintain",
"heap",
"invariant",
"."
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/priority_queue.rb#L210-L217 | train |
riddopic/garcun | lib/garcon/task/priority_queue.rb | Garcon.MutexPriorityQueue.swim | def swim(k)
while k > 1 && ! ordered?(k/2, k) do
swap(k, k/2)
k = k/2
end
end | ruby | def swim(k)
while k > 1 && ! ordered?(k/2, k) do
swap(k, k/2)
k = k/2
end
end | [
"def",
"swim",
"(",
"k",
")",
"while",
"k",
">",
"1",
"&&",
"!",
"ordered?",
"(",
"k",
"/",
"2",
",",
"k",
")",
"do",
"swap",
"(",
"k",
",",
"k",
"/",
"2",
")",
"k",
"=",
"k",
"/",
"2",
"end",
"end"
] | Percolate up to maintain heap invariant.
@param [Integer] k
The index at which to start the percolation.
@!visibility private | [
"Percolate",
"up",
"to",
"maintain",
"heap",
"invariant",
"."
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/priority_queue.rb#L225-L230 | train |
devnull-tools/yummi | lib/yummi/text_box.rb | Yummi.TextBox.add | def add (obj, params = {})
text = obj.to_s
params = {
:width => style.width,
:align => style.align
}.merge! params
if params[:width]
width = params[:width]
words = text.gsub($/, ' ').split(' ') unless params[:raw]
words ||= [text]
buff = ''
words.each do |word|
# go to next line if the current word blows up the width limit
if buff.size + word.size >= width and not buff.empty?
_add_ buff, params
buff = ''
end
buff << ' ' unless buff.empty?
buff << word
end
unless buff.empty?
_add_ buff, params
end
else
text.each_line do |line|
_add_ line, params
end
end
end | ruby | def add (obj, params = {})
text = obj.to_s
params = {
:width => style.width,
:align => style.align
}.merge! params
if params[:width]
width = params[:width]
words = text.gsub($/, ' ').split(' ') unless params[:raw]
words ||= [text]
buff = ''
words.each do |word|
# go to next line if the current word blows up the width limit
if buff.size + word.size >= width and not buff.empty?
_add_ buff, params
buff = ''
end
buff << ' ' unless buff.empty?
buff << word
end
unless buff.empty?
_add_ buff, params
end
else
text.each_line do |line|
_add_ line, params
end
end
end | [
"def",
"add",
"(",
"obj",
",",
"params",
"=",
"{",
"}",
")",
"text",
"=",
"obj",
".",
"to_s",
"params",
"=",
"{",
":width",
"=>",
"style",
".",
"width",
",",
":align",
"=>",
"style",
".",
"align",
"}",
".",
"merge!",
"params",
"if",
"params",
"[",
":width",
"]",
"width",
"=",
"params",
"[",
":width",
"]",
"words",
"=",
"text",
".",
"gsub",
"(",
"$/",
",",
"' '",
")",
".",
"split",
"(",
"' '",
")",
"unless",
"params",
"[",
":raw",
"]",
"words",
"||=",
"[",
"text",
"]",
"buff",
"=",
"''",
"words",
".",
"each",
"do",
"|",
"word",
"|",
"if",
"buff",
".",
"size",
"+",
"word",
".",
"size",
">=",
"width",
"and",
"not",
"buff",
".",
"empty?",
"_add_",
"buff",
",",
"params",
"buff",
"=",
"''",
"end",
"buff",
"<<",
"' '",
"unless",
"buff",
".",
"empty?",
"buff",
"<<",
"word",
"end",
"unless",
"buff",
".",
"empty?",
"_add_",
"buff",
",",
"params",
"end",
"else",
"text",
".",
"each_line",
"do",
"|",
"line",
"|",
"_add_",
"line",
",",
"params",
"end",
"end",
"end"
] | Adds a line text to this box
=== Args
+obj+::
The obj to add (will be converted to string).
+params+::
A hash of parameters. Currently supported are:
color: the text color (see #Yummi#COLORS)
width: the text maximum width. Set this to break the lines automatically.
If the #width is set, this will override the box width for this lines.
raw: if true, the entire text will be used as one word to align the text.
align: the text alignment (see #Yummi#Aligner) | [
"Adds",
"a",
"line",
"text",
"to",
"this",
"box"
] | b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df | https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/text_box.rb#L97-L125 | train |
devnull-tools/yummi | lib/yummi/text_box.rb | Yummi.TextBox.separator | def separator (params = {})
params = style.separator.merge params
params[:width] ||= style.width
raise Exception::new('Define a width for using separators') unless params[:width]
line = fill(params[:pattern], params[:width])
#replace the width with the box width to align the separator
params[:width] = style.width
add line, params
end | ruby | def separator (params = {})
params = style.separator.merge params
params[:width] ||= style.width
raise Exception::new('Define a width for using separators') unless params[:width]
line = fill(params[:pattern], params[:width])
#replace the width with the box width to align the separator
params[:width] = style.width
add line, params
end | [
"def",
"separator",
"(",
"params",
"=",
"{",
"}",
")",
"params",
"=",
"style",
".",
"separator",
".",
"merge",
"params",
"params",
"[",
":width",
"]",
"||=",
"style",
".",
"width",
"raise",
"Exception",
"::",
"new",
"(",
"'Define a width for using separators'",
")",
"unless",
"params",
"[",
":width",
"]",
"line",
"=",
"fill",
"(",
"params",
"[",
":pattern",
"]",
",",
"params",
"[",
":width",
"]",
")",
"params",
"[",
":width",
"]",
"=",
"style",
".",
"width",
"add",
"line",
",",
"params",
"end"
] | Adds a line separator.
=== Args
+params+::
A hash of parameters. Currently supported are:
pattern: the pattern to build the line
color: the separator color (see #Yummi#COLORS)
width: the separator width (#self#width will be used if unset)
align: the separator alignment (see #Yummi#Aligner) | [
"Adds",
"a",
"line",
"separator",
"."
] | b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df | https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/text_box.rb#L147-L155 | train |
kukushkin/aerogel-core | lib/aerogel/core/render/block_helper.rb | Aerogel::Render.BlockHelper.render | def render
content = output_capture(@block) do
instance_exec( *@args, &@block )
end
content_wrapped = output_capture() { wrap( content ) }
output_concat content_wrapped
end | ruby | def render
content = output_capture(@block) do
instance_exec( *@args, &@block )
end
content_wrapped = output_capture() { wrap( content ) }
output_concat content_wrapped
end | [
"def",
"render",
"content",
"=",
"output_capture",
"(",
"@block",
")",
"do",
"instance_exec",
"(",
"*",
"@args",
",",
"&",
"@block",
")",
"end",
"content_wrapped",
"=",
"output_capture",
"(",
")",
"{",
"wrap",
"(",
"content",
")",
"}",
"output_concat",
"content_wrapped",
"end"
] | Renders output to the template or returns it as a string. | [
"Renders",
"output",
"to",
"the",
"template",
"or",
"returns",
"it",
"as",
"a",
"string",
"."
] | e156af6b237c410c1ee75e5cdf1b10075e7fbb8b | https://github.com/kukushkin/aerogel-core/blob/e156af6b237c410c1ee75e5cdf1b10075e7fbb8b/lib/aerogel/core/render/block_helper.rb#L32-L38 | train |
barkerest/incline | lib/incline/extensions/application.rb | Incline::Extensions.Application.app_instance_name | def app_instance_name
@app_instance_name ||=
begin
yaml = Rails.root.join('config','instance.yml')
if File.exist?(yaml)
yaml = (YAML.load(ERB.new(File.read(yaml)).result) || {}).symbolize_keys
yaml[:name].blank? ? 'default' : yaml[:name]
else
'default'
end
end
end | ruby | def app_instance_name
@app_instance_name ||=
begin
yaml = Rails.root.join('config','instance.yml')
if File.exist?(yaml)
yaml = (YAML.load(ERB.new(File.read(yaml)).result) || {}).symbolize_keys
yaml[:name].blank? ? 'default' : yaml[:name]
else
'default'
end
end
end | [
"def",
"app_instance_name",
"@app_instance_name",
"||=",
"begin",
"yaml",
"=",
"Rails",
".",
"root",
".",
"join",
"(",
"'config'",
",",
"'instance.yml'",
")",
"if",
"File",
".",
"exist?",
"(",
"yaml",
")",
"yaml",
"=",
"(",
"YAML",
".",
"load",
"(",
"ERB",
".",
"new",
"(",
"File",
".",
"read",
"(",
"yaml",
")",
")",
".",
"result",
")",
"||",
"{",
"}",
")",
".",
"symbolize_keys",
"yaml",
"[",
":name",
"]",
".",
"blank?",
"?",
"'default'",
":",
"yaml",
"[",
":name",
"]",
"else",
"'default'",
"end",
"end",
"end"
] | Gets the application instance name.
This can be set by creating a +config/instance.yml+ configuration file and setting the 'name' property.
The instance name is used to create unique cookies for each instance of an application.
The default instance name is 'default'. | [
"Gets",
"the",
"application",
"instance",
"name",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/application.rb#L46-L57 | train |
barkerest/incline | lib/incline/extensions/application.rb | Incline::Extensions.Application.restart_pending? | def restart_pending?
return false unless File.exist?(restart_file)
request_time = File.mtime(restart_file)
request_time > Incline.start_time
end | ruby | def restart_pending?
return false unless File.exist?(restart_file)
request_time = File.mtime(restart_file)
request_time > Incline.start_time
end | [
"def",
"restart_pending?",
"return",
"false",
"unless",
"File",
".",
"exist?",
"(",
"restart_file",
")",
"request_time",
"=",
"File",
".",
"mtime",
"(",
"restart_file",
")",
"request_time",
">",
"Incline",
".",
"start_time",
"end"
] | Is a restart currently pending. | [
"Is",
"a",
"restart",
"currently",
"pending",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/application.rb#L103-L107 | train |
barkerest/incline | lib/incline/extensions/application.rb | Incline::Extensions.Application.request_restart! | def request_restart!
Incline::Log::info 'Requesting an application restart.'
FileUtils.touch restart_file
File.mtime restart_file
end | ruby | def request_restart!
Incline::Log::info 'Requesting an application restart.'
FileUtils.touch restart_file
File.mtime restart_file
end | [
"def",
"request_restart!",
"Incline",
"::",
"Log",
"::",
"info",
"'Requesting an application restart.'",
"FileUtils",
".",
"touch",
"restart_file",
"File",
".",
"mtime",
"restart_file",
"end"
] | Updates the restart file to indicate we want to restart the web app. | [
"Updates",
"the",
"restart",
"file",
"to",
"indicate",
"we",
"want",
"to",
"restart",
"the",
"web",
"app",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/application.rb#L111-L115 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.