id
int32 0
24.9k
| 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
|
---|---|---|---|---|---|---|---|---|---|---|---|
0 | bogdanRada/celluloid_pubsub | lib/celluloid_pubsub/reactor.rb | CelluloidPubsub.Reactor.handle_parsed_websocket_message | def handle_parsed_websocket_message(json_data)
data = json_data.is_a?(Hash) ? json_data.stringify_keys : {}
if CelluloidPubsub::Reactor::AVAILABLE_ACTIONS.include?(data['client_action'].to_s)
log_debug "#{self.class} finds actions for #{json_data}"
delegate_action(data) if data['client_action'].present?
else
handle_unknown_action(data['channel'], json_data)
end
end | ruby | def handle_parsed_websocket_message(json_data)
data = json_data.is_a?(Hash) ? json_data.stringify_keys : {}
if CelluloidPubsub::Reactor::AVAILABLE_ACTIONS.include?(data['client_action'].to_s)
log_debug "#{self.class} finds actions for #{json_data}"
delegate_action(data) if data['client_action'].present?
else
handle_unknown_action(data['channel'], json_data)
end
end | [
"def",
"handle_parsed_websocket_message",
"(",
"json_data",
")",
"data",
"=",
"json_data",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"json_data",
".",
"stringify_keys",
":",
"{",
"}",
"if",
"CelluloidPubsub",
"::",
"Reactor",
"::",
"AVAILABLE_ACTIONS",
".",
"include?",
"(",
"data",
"[",
"'client_action'",
"]",
".",
"to_s",
")",
"log_debug",
"\"#{self.class} finds actions for #{json_data}\"",
"delegate_action",
"(",
"data",
")",
"if",
"data",
"[",
"'client_action'",
"]",
".",
"present?",
"else",
"handle_unknown_action",
"(",
"data",
"[",
"'channel'",
"]",
",",
"json_data",
")",
"end",
"end"
] | method that checks if the data is a Hash
if the data is a hash then will stringify the keys and will call the method {#delegate_action}
that will handle the message, otherwise will call the method {#handle_unknown_action}
@see #delegate_action
@see #handle_unknown_action
@param [Hash] json_data
@return [void]
@api public | [
"method",
"that",
"checks",
"if",
"the",
"data",
"is",
"a",
"Hash"
] | e5558257c04e553b49e08ce27c130d572ada210d | https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L149-L157 |
1 | bogdanRada/celluloid_pubsub | lib/celluloid_pubsub/reactor.rb | CelluloidPubsub.Reactor.unsubscribe | def unsubscribe(channel, _json_data)
log_debug "#{self.class} runs 'unsubscribe' method with #{channel}"
return unless channel.present?
forget_channel(channel)
delete_server_subscribers(channel)
end | ruby | def unsubscribe(channel, _json_data)
log_debug "#{self.class} runs 'unsubscribe' method with #{channel}"
return unless channel.present?
forget_channel(channel)
delete_server_subscribers(channel)
end | [
"def",
"unsubscribe",
"(",
"channel",
",",
"_json_data",
")",
"log_debug",
"\"#{self.class} runs 'unsubscribe' method with #{channel}\"",
"return",
"unless",
"channel",
".",
"present?",
"forget_channel",
"(",
"channel",
")",
"delete_server_subscribers",
"(",
"channel",
")",
"end"
] | the method will unsubscribe a client by closing the websocket connection if has unscribed from all channels
and deleting the reactor from the channel list on the server
@param [String] channel
@return [void]
@api public | [
"the",
"method",
"will",
"unsubscribe",
"a",
"client",
"by",
"closing",
"the",
"websocket",
"connection",
"if",
"has",
"unscribed",
"from",
"all",
"channels",
"and",
"deleting",
"the",
"reactor",
"from",
"the",
"channel",
"list",
"on",
"the",
"server"
] | e5558257c04e553b49e08ce27c130d572ada210d | https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L222-L227 |
2 | bogdanRada/celluloid_pubsub | lib/celluloid_pubsub/reactor.rb | CelluloidPubsub.Reactor.delete_server_subscribers | def delete_server_subscribers(channel)
@server.mutex.synchronize do
(@server.subscribers[channel] || []).delete_if do |hash|
hash[:reactor] == Actor.current
end
end
end | ruby | def delete_server_subscribers(channel)
@server.mutex.synchronize do
(@server.subscribers[channel] || []).delete_if do |hash|
hash[:reactor] == Actor.current
end
end
end | [
"def",
"delete_server_subscribers",
"(",
"channel",
")",
"@server",
".",
"mutex",
".",
"synchronize",
"do",
"(",
"@server",
".",
"subscribers",
"[",
"channel",
"]",
"||",
"[",
"]",
")",
".",
"delete_if",
"do",
"|",
"hash",
"|",
"hash",
"[",
":reactor",
"]",
"==",
"Actor",
".",
"current",
"end",
"end",
"end"
] | the method will delete the reactor from the channel list on the server
@param [String] channel
@return [void]
@api public | [
"the",
"method",
"will",
"delete",
"the",
"reactor",
"from",
"the",
"channel",
"list",
"on",
"the",
"server"
] | e5558257c04e553b49e08ce27c130d572ada210d | https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L236-L242 |
3 | bogdanRada/celluloid_pubsub | lib/celluloid_pubsub/reactor.rb | CelluloidPubsub.Reactor.unsubscribe_clients | def unsubscribe_clients(channel, _json_data)
log_debug "#{self.class} runs 'unsubscribe_clients' method with #{channel}"
return if channel.blank?
unsubscribe_from_channel(channel)
@server.subscribers[channel] = []
end | ruby | def unsubscribe_clients(channel, _json_data)
log_debug "#{self.class} runs 'unsubscribe_clients' method with #{channel}"
return if channel.blank?
unsubscribe_from_channel(channel)
@server.subscribers[channel] = []
end | [
"def",
"unsubscribe_clients",
"(",
"channel",
",",
"_json_data",
")",
"log_debug",
"\"#{self.class} runs 'unsubscribe_clients' method with #{channel}\"",
"return",
"if",
"channel",
".",
"blank?",
"unsubscribe_from_channel",
"(",
"channel",
")",
"@server",
".",
"subscribers",
"[",
"channel",
"]",
"=",
"[",
"]",
"end"
] | the method will unsubscribe all clients subscribed to a channel by closing the
@param [String] channel
@return [void]
@api public | [
"the",
"method",
"will",
"unsubscribe",
"all",
"clients",
"subscribed",
"to",
"a",
"channel",
"by",
"closing",
"the"
] | e5558257c04e553b49e08ce27c130d572ada210d | https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L251-L256 |
4 | bogdanRada/celluloid_pubsub | lib/celluloid_pubsub/reactor.rb | CelluloidPubsub.Reactor.add_subscriber_to_channel | def add_subscriber_to_channel(channel, message)
registry_channels = CelluloidPubsub::Registry.channels
@channels << channel
registry_channels << channel unless registry_channels.include?(channel)
@server.mutex.synchronize do
@server.subscribers[channel] = channel_subscribers(channel).push(reactor: Actor.current, message: message)
end
end | ruby | def add_subscriber_to_channel(channel, message)
registry_channels = CelluloidPubsub::Registry.channels
@channels << channel
registry_channels << channel unless registry_channels.include?(channel)
@server.mutex.synchronize do
@server.subscribers[channel] = channel_subscribers(channel).push(reactor: Actor.current, message: message)
end
end | [
"def",
"add_subscriber_to_channel",
"(",
"channel",
",",
"message",
")",
"registry_channels",
"=",
"CelluloidPubsub",
"::",
"Registry",
".",
"channels",
"@channels",
"<<",
"channel",
"registry_channels",
"<<",
"channel",
"unless",
"registry_channels",
".",
"include?",
"(",
"channel",
")",
"@server",
".",
"mutex",
".",
"synchronize",
"do",
"@server",
".",
"subscribers",
"[",
"channel",
"]",
"=",
"channel_subscribers",
"(",
"channel",
")",
".",
"push",
"(",
"reactor",
":",
"Actor",
".",
"current",
",",
"message",
":",
"message",
")",
"end",
"end"
] | adds the curent actor the list of the subscribers for a particular channel
and registers the new channel
@param [String] channel
@param [Object] message
@return [void]
@api public | [
"adds",
"the",
"curent",
"actor",
"the",
"list",
"of",
"the",
"subscribers",
"for",
"a",
"particular",
"channel",
"and",
"registers",
"the",
"new",
"channel"
] | e5558257c04e553b49e08ce27c130d572ada210d | https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L309-L316 |
5 | bogdanRada/celluloid_pubsub | lib/celluloid_pubsub/reactor.rb | CelluloidPubsub.Reactor.publish | def publish(current_topic, json_data)
message = json_data['data'].to_json
return if current_topic.blank? || message.blank?
server_pusblish_event(current_topic, message)
rescue => exception
log_debug("could not publish message #{message} into topic #{current_topic} because of #{exception.inspect}")
end | ruby | def publish(current_topic, json_data)
message = json_data['data'].to_json
return if current_topic.blank? || message.blank?
server_pusblish_event(current_topic, message)
rescue => exception
log_debug("could not publish message #{message} into topic #{current_topic} because of #{exception.inspect}")
end | [
"def",
"publish",
"(",
"current_topic",
",",
"json_data",
")",
"message",
"=",
"json_data",
"[",
"'data'",
"]",
".",
"to_json",
"return",
"if",
"current_topic",
".",
"blank?",
"||",
"message",
".",
"blank?",
"server_pusblish_event",
"(",
"current_topic",
",",
"message",
")",
"rescue",
"=>",
"exception",
"log_debug",
"(",
"\"could not publish message #{message} into topic #{current_topic} because of #{exception.inspect}\"",
")",
"end"
] | method for publishing data to a channel
@param [String] current_topic The Channel to which the reactor instance {CelluloidPubsub::Reactor} will publish the message to
@param [Object] json_data The additional data that contains the message that needs to be sent
@return [void]
@api public | [
"method",
"for",
"publishing",
"data",
"to",
"a",
"channel"
] | e5558257c04e553b49e08ce27c130d572ada210d | https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L326-L332 |
6 | bogdanRada/celluloid_pubsub | lib/celluloid_pubsub/reactor.rb | CelluloidPubsub.Reactor.server_pusblish_event | def server_pusblish_event(current_topic, message)
@server.mutex.synchronize do
(@server.subscribers[current_topic].dup || []).pmap do |hash|
hash[:reactor].websocket << message
end
end
end | ruby | def server_pusblish_event(current_topic, message)
@server.mutex.synchronize do
(@server.subscribers[current_topic].dup || []).pmap do |hash|
hash[:reactor].websocket << message
end
end
end | [
"def",
"server_pusblish_event",
"(",
"current_topic",
",",
"message",
")",
"@server",
".",
"mutex",
".",
"synchronize",
"do",
"(",
"@server",
".",
"subscribers",
"[",
"current_topic",
"]",
".",
"dup",
"||",
"[",
"]",
")",
".",
"pmap",
"do",
"|",
"hash",
"|",
"hash",
"[",
":reactor",
"]",
".",
"websocket",
"<<",
"message",
"end",
"end",
"end"
] | the method will publish to all subsribers of a channel a message
@param [String] current_topic
@param [#to_s] message
@return [void]
@api public | [
"the",
"method",
"will",
"publish",
"to",
"all",
"subsribers",
"of",
"a",
"channel",
"a",
"message"
] | e5558257c04e553b49e08ce27c130d572ada210d | https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L342-L348 |
7 | bogdanRada/celluloid_pubsub | lib/celluloid_pubsub/reactor.rb | CelluloidPubsub.Reactor.unsubscribe_all | def unsubscribe_all(_channel, json_data)
log_debug "#{self.class} runs 'unsubscribe_all' method"
CelluloidPubsub::Registry.channels.dup.pmap do |channel|
unsubscribe_clients(channel, json_data)
end
log_debug 'clearing connections'
shutdown
end | ruby | def unsubscribe_all(_channel, json_data)
log_debug "#{self.class} runs 'unsubscribe_all' method"
CelluloidPubsub::Registry.channels.dup.pmap do |channel|
unsubscribe_clients(channel, json_data)
end
log_debug 'clearing connections'
shutdown
end | [
"def",
"unsubscribe_all",
"(",
"_channel",
",",
"json_data",
")",
"log_debug",
"\"#{self.class} runs 'unsubscribe_all' method\"",
"CelluloidPubsub",
"::",
"Registry",
".",
"channels",
".",
"dup",
".",
"pmap",
"do",
"|",
"channel",
"|",
"unsubscribe_clients",
"(",
"channel",
",",
"json_data",
")",
"end",
"log_debug",
"'clearing connections'",
"shutdown",
"end"
] | unsubscribes all actors from all channels and terminates the curent actor
@param [String] _channel NOT USED - needed to maintain compatibility with the other methods
@param [Object] _json_data NOT USED - needed to maintain compatibility with the other methods
@return [void]
@api public | [
"unsubscribes",
"all",
"actors",
"from",
"all",
"channels",
"and",
"terminates",
"the",
"curent",
"actor"
] | e5558257c04e553b49e08ce27c130d572ada210d | https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L358-L365 |
8 | bogdanRada/celluloid_pubsub | lib/celluloid_pubsub/reactor.rb | CelluloidPubsub.Reactor.server_kill_reactors | def server_kill_reactors(channel)
@server.mutex.synchronize do
(@server.subscribers[channel].dup || []).pmap do |hash|
reactor = hash[:reactor]
reactor.websocket.close
Celluloid::Actor.kill(reactor)
end
end
end | ruby | def server_kill_reactors(channel)
@server.mutex.synchronize do
(@server.subscribers[channel].dup || []).pmap do |hash|
reactor = hash[:reactor]
reactor.websocket.close
Celluloid::Actor.kill(reactor)
end
end
end | [
"def",
"server_kill_reactors",
"(",
"channel",
")",
"@server",
".",
"mutex",
".",
"synchronize",
"do",
"(",
"@server",
".",
"subscribers",
"[",
"channel",
"]",
".",
"dup",
"||",
"[",
"]",
")",
".",
"pmap",
"do",
"|",
"hash",
"|",
"reactor",
"=",
"hash",
"[",
":reactor",
"]",
"reactor",
".",
"websocket",
".",
"close",
"Celluloid",
"::",
"Actor",
".",
"kill",
"(",
"reactor",
")",
"end",
"end",
"end"
] | kills all reactors registered on a channel and closes their websocket connection
@param [String] channel
@return [void]
@api public | [
"kills",
"all",
"reactors",
"registered",
"on",
"a",
"channel",
"and",
"closes",
"their",
"websocket",
"connection"
] | e5558257c04e553b49e08ce27c130d572ada210d | https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L384-L392 |
9 | LessonPlanet/emaildirect-ruby | lib/emaildirect/relay_send/email.rb | EmailDirect.RelaySend::Email.send | def send(options)
response = EmailDirect.post "/RelaySends/#{category_id}", :body => options.to_json
Hashie::Mash.new(response)
end | ruby | def send(options)
response = EmailDirect.post "/RelaySends/#{category_id}", :body => options.to_json
Hashie::Mash.new(response)
end | [
"def",
"send",
"(",
"options",
")",
"response",
"=",
"EmailDirect",
".",
"post",
"\"/RelaySends/#{category_id}\"",
",",
":body",
"=>",
"options",
".",
"to_json",
"Hashie",
"::",
"Mash",
".",
"new",
"(",
"response",
")",
"end"
] | Sends a custom message. See the docs for all the possible options
@see https://docs.emaildirect.com/#RelaySendCustomEmail | [
"Sends",
"a",
"custom",
"message",
".",
"See",
"the",
"docs",
"for",
"all",
"the",
"possible",
"options"
] | b785104fa867414f18c17981542edff3794d0224 | https://github.com/LessonPlanet/emaildirect-ruby/blob/b785104fa867414f18c17981542edff3794d0224/lib/emaildirect/relay_send/email.rb#L16-L19 |
10 | emmanuel/aequitas | lib/aequitas/contextual_rule_set.rb | Aequitas.ContextualRuleSet.concat | def concat(other)
other.rule_sets.each do |context_name, rule_set|
add_rules_to_context(context_name, rule_set)
end
self
end | ruby | def concat(other)
other.rule_sets.each do |context_name, rule_set|
add_rules_to_context(context_name, rule_set)
end
self
end | [
"def",
"concat",
"(",
"other",
")",
"other",
".",
"rule_sets",
".",
"each",
"do",
"|",
"context_name",
",",
"rule_set",
"|",
"add_rules_to_context",
"(",
"context_name",
",",
"rule_set",
")",
"end",
"self",
"end"
] | Assimilate all rules contained in +other+ into the receiver
@param [ContextualRuleSet] other
the ContextualRuleSet whose rules are to be assimilated
@return [self]
@api private | [
"Assimilate",
"all",
"rules",
"contained",
"in",
"+",
"other",
"+",
"into",
"the",
"receiver"
] | 984f16a1db12e88c8e9a4a3605896b295e285a6b | https://github.com/emmanuel/aequitas/blob/984f16a1db12e88c8e9a4a3605896b295e285a6b/lib/aequitas/contextual_rule_set.rb#L134-L140 |
11 | emmanuel/aequitas | lib/aequitas/contextual_rule_set.rb | Aequitas.ContextualRuleSet.define_context | def define_context(context_name)
rule_sets.fetch(context_name) do |context_name|
rule_sets[context_name] = RuleSet.new
end
self
end | ruby | def define_context(context_name)
rule_sets.fetch(context_name) do |context_name|
rule_sets[context_name] = RuleSet.new
end
self
end | [
"def",
"define_context",
"(",
"context_name",
")",
"rule_sets",
".",
"fetch",
"(",
"context_name",
")",
"do",
"|",
"context_name",
"|",
"rule_sets",
"[",
"context_name",
"]",
"=",
"RuleSet",
".",
"new",
"end",
"self",
"end"
] | Initialize and assign a RuleSet for the named context
@param [Symbol] context_name
the name of the context to be defined. noop if already defined
@return [self]
@api private | [
"Initialize",
"and",
"assign",
"a",
"RuleSet",
"for",
"the",
"named",
"context"
] | 984f16a1db12e88c8e9a4a3605896b295e285a6b | https://github.com/emmanuel/aequitas/blob/984f16a1db12e88c8e9a4a3605896b295e285a6b/lib/aequitas/contextual_rule_set.rb#L156-L162 |
12 | activenetwork/gattica | lib/gattica.rb | Gattica.Engine.do_http_get | def do_http_get(query_string)
response, data = @http.get(query_string, @headers)
# error checking
if response.code != '200'
case response.code
when '400'
raise GatticaError::AnalyticsError, response.body + " (status code: #{response.code})"
when '401'
raise GatticaError::InvalidToken, "Your authorization token is invalid or has expired (status code: #{response.code})"
else # some other unknown error
raise GatticaError::UnknownAnalyticsError, response.body + " (status code: #{response.code})"
end
end
return data
end | ruby | def do_http_get(query_string)
response, data = @http.get(query_string, @headers)
# error checking
if response.code != '200'
case response.code
when '400'
raise GatticaError::AnalyticsError, response.body + " (status code: #{response.code})"
when '401'
raise GatticaError::InvalidToken, "Your authorization token is invalid or has expired (status code: #{response.code})"
else # some other unknown error
raise GatticaError::UnknownAnalyticsError, response.body + " (status code: #{response.code})"
end
end
return data
end | [
"def",
"do_http_get",
"(",
"query_string",
")",
"response",
",",
"data",
"=",
"@http",
".",
"get",
"(",
"query_string",
",",
"@headers",
")",
"# error checking",
"if",
"response",
".",
"code",
"!=",
"'200'",
"case",
"response",
".",
"code",
"when",
"'400'",
"raise",
"GatticaError",
"::",
"AnalyticsError",
",",
"response",
".",
"body",
"+",
"\" (status code: #{response.code})\"",
"when",
"'401'",
"raise",
"GatticaError",
"::",
"InvalidToken",
",",
"\"Your authorization token is invalid or has expired (status code: #{response.code})\"",
"else",
"# some other unknown error",
"raise",
"GatticaError",
"::",
"UnknownAnalyticsError",
",",
"response",
".",
"body",
"+",
"\" (status code: #{response.code})\"",
"end",
"end",
"return",
"data",
"end"
] | Does the work of making HTTP calls and then going through a suite of tests on the response to make
sure it's valid and not an error | [
"Does",
"the",
"work",
"of",
"making",
"HTTP",
"calls",
"and",
"then",
"going",
"through",
"a",
"suite",
"of",
"tests",
"on",
"the",
"response",
"to",
"make",
"sure",
"it",
"s",
"valid",
"and",
"not",
"an",
"error"
] | 359a5a70eba67e0f9ddd6081cb4defbf14d2e74b | https://github.com/activenetwork/gattica/blob/359a5a70eba67e0f9ddd6081cb4defbf14d2e74b/lib/gattica.rb#L241-L257 |
13 | activenetwork/gattica | lib/gattica.rb | Gattica.Engine.build_query_string | def build_query_string(args,profile)
query_params = args.clone
ga_start_date = query_params.delete(:start_date)
ga_end_date = query_params.delete(:end_date)
ga_dimensions = query_params.delete(:dimensions)
ga_metrics = query_params.delete(:metrics)
ga_sort = query_params.delete(:sort)
ga_filters = query_params.delete(:filters)
output = "ids=ga:#{profile}&start-date=#{ga_start_date}&end-date=#{ga_end_date}"
unless ga_dimensions.nil? || ga_dimensions.empty?
output += '&dimensions=' + ga_dimensions.collect do |dimension|
"ga:#{dimension}"
end.join(',')
end
unless ga_metrics.nil? || ga_metrics.empty?
output += '&metrics=' + ga_metrics.collect do |metric|
"ga:#{metric}"
end.join(',')
end
unless ga_sort.nil? || ga_sort.empty?
output += '&sort=' + Array(ga_sort).collect do |sort|
sort[0..0] == '-' ? "-ga:#{sort[1..-1]}" : "ga:#{sort}" # if the first character is a dash, move it before the ga:
end.join(',')
end
# TODO: update so that in regular expression filters (=~ and !~), any initial special characters in the regular expression aren't also picked up as part of the operator (doesn't cause a problem, but just feels dirty)
unless args[:filters].empty? # filters are a little more complicated because they can have all kinds of modifiers
output += '&filters=' + args[:filters].collect do |filter|
match, name, operator, expression = *filter.match(/^(\w*)\s*([=!<>~@]*)\s*(.*)$/) # splat the resulting Match object to pull out the parts automatically
unless name.empty? || operator.empty? || expression.empty? # make sure they all contain something
"ga:#{name}#{CGI::escape(operator.gsub(/ /,''))}#{CGI::escape(expression)}" # remove any whitespace from the operator before output
else
raise GatticaError::InvalidFilter, "The filter '#{filter}' is invalid. Filters should look like 'browser == Firefox' or 'browser==Firefox'"
end
end.join(';')
end
query_params.inject(output) {|m,(key,value)| m << "&#{key}=#{value}"}
return output
end | ruby | def build_query_string(args,profile)
query_params = args.clone
ga_start_date = query_params.delete(:start_date)
ga_end_date = query_params.delete(:end_date)
ga_dimensions = query_params.delete(:dimensions)
ga_metrics = query_params.delete(:metrics)
ga_sort = query_params.delete(:sort)
ga_filters = query_params.delete(:filters)
output = "ids=ga:#{profile}&start-date=#{ga_start_date}&end-date=#{ga_end_date}"
unless ga_dimensions.nil? || ga_dimensions.empty?
output += '&dimensions=' + ga_dimensions.collect do |dimension|
"ga:#{dimension}"
end.join(',')
end
unless ga_metrics.nil? || ga_metrics.empty?
output += '&metrics=' + ga_metrics.collect do |metric|
"ga:#{metric}"
end.join(',')
end
unless ga_sort.nil? || ga_sort.empty?
output += '&sort=' + Array(ga_sort).collect do |sort|
sort[0..0] == '-' ? "-ga:#{sort[1..-1]}" : "ga:#{sort}" # if the first character is a dash, move it before the ga:
end.join(',')
end
# TODO: update so that in regular expression filters (=~ and !~), any initial special characters in the regular expression aren't also picked up as part of the operator (doesn't cause a problem, but just feels dirty)
unless args[:filters].empty? # filters are a little more complicated because they can have all kinds of modifiers
output += '&filters=' + args[:filters].collect do |filter|
match, name, operator, expression = *filter.match(/^(\w*)\s*([=!<>~@]*)\s*(.*)$/) # splat the resulting Match object to pull out the parts automatically
unless name.empty? || operator.empty? || expression.empty? # make sure they all contain something
"ga:#{name}#{CGI::escape(operator.gsub(/ /,''))}#{CGI::escape(expression)}" # remove any whitespace from the operator before output
else
raise GatticaError::InvalidFilter, "The filter '#{filter}' is invalid. Filters should look like 'browser == Firefox' or 'browser==Firefox'"
end
end.join(';')
end
query_params.inject(output) {|m,(key,value)| m << "&#{key}=#{value}"}
return output
end | [
"def",
"build_query_string",
"(",
"args",
",",
"profile",
")",
"query_params",
"=",
"args",
".",
"clone",
"ga_start_date",
"=",
"query_params",
".",
"delete",
"(",
":start_date",
")",
"ga_end_date",
"=",
"query_params",
".",
"delete",
"(",
":end_date",
")",
"ga_dimensions",
"=",
"query_params",
".",
"delete",
"(",
":dimensions",
")",
"ga_metrics",
"=",
"query_params",
".",
"delete",
"(",
":metrics",
")",
"ga_sort",
"=",
"query_params",
".",
"delete",
"(",
":sort",
")",
"ga_filters",
"=",
"query_params",
".",
"delete",
"(",
":filters",
")",
"output",
"=",
"\"ids=ga:#{profile}&start-date=#{ga_start_date}&end-date=#{ga_end_date}\"",
"unless",
"ga_dimensions",
".",
"nil?",
"||",
"ga_dimensions",
".",
"empty?",
"output",
"+=",
"'&dimensions='",
"+",
"ga_dimensions",
".",
"collect",
"do",
"|",
"dimension",
"|",
"\"ga:#{dimension}\"",
"end",
".",
"join",
"(",
"','",
")",
"end",
"unless",
"ga_metrics",
".",
"nil?",
"||",
"ga_metrics",
".",
"empty?",
"output",
"+=",
"'&metrics='",
"+",
"ga_metrics",
".",
"collect",
"do",
"|",
"metric",
"|",
"\"ga:#{metric}\"",
"end",
".",
"join",
"(",
"','",
")",
"end",
"unless",
"ga_sort",
".",
"nil?",
"||",
"ga_sort",
".",
"empty?",
"output",
"+=",
"'&sort='",
"+",
"Array",
"(",
"ga_sort",
")",
".",
"collect",
"do",
"|",
"sort",
"|",
"sort",
"[",
"0",
"..",
"0",
"]",
"==",
"'-'",
"?",
"\"-ga:#{sort[1..-1]}\"",
":",
"\"ga:#{sort}\"",
"# if the first character is a dash, move it before the ga:",
"end",
".",
"join",
"(",
"','",
")",
"end",
"# TODO: update so that in regular expression filters (=~ and !~), any initial special characters in the regular expression aren't also picked up as part of the operator (doesn't cause a problem, but just feels dirty)",
"unless",
"args",
"[",
":filters",
"]",
".",
"empty?",
"# filters are a little more complicated because they can have all kinds of modifiers",
"output",
"+=",
"'&filters='",
"+",
"args",
"[",
":filters",
"]",
".",
"collect",
"do",
"|",
"filter",
"|",
"match",
",",
"name",
",",
"operator",
",",
"expression",
"=",
"filter",
".",
"match",
"(",
"/",
"\\w",
"\\s",
"\\s",
"/",
")",
"# splat the resulting Match object to pull out the parts automatically",
"unless",
"name",
".",
"empty?",
"||",
"operator",
".",
"empty?",
"||",
"expression",
".",
"empty?",
"# make sure they all contain something",
"\"ga:#{name}#{CGI::escape(operator.gsub(/ /,''))}#{CGI::escape(expression)}\"",
"# remove any whitespace from the operator before output",
"else",
"raise",
"GatticaError",
"::",
"InvalidFilter",
",",
"\"The filter '#{filter}' is invalid. Filters should look like 'browser == Firefox' or 'browser==Firefox'\"",
"end",
"end",
".",
"join",
"(",
"';'",
")",
"end",
"query_params",
".",
"inject",
"(",
"output",
")",
"{",
"|",
"m",
",",
"(",
"key",
",",
"value",
")",
"|",
"m",
"<<",
"\"&#{key}=#{value}\"",
"}",
"return",
"output",
"end"
] | Creates a valid query string for GA | [
"Creates",
"a",
"valid",
"query",
"string",
"for",
"GA"
] | 359a5a70eba67e0f9ddd6081cb4defbf14d2e74b | https://github.com/activenetwork/gattica/blob/359a5a70eba67e0f9ddd6081cb4defbf14d2e74b/lib/gattica.rb#L269-L310 |
14 | Avhana/allscripts_api | lib/allscripts_api/client.rb | AllscriptsApi.Client.get_token | def get_token
full_path = build_request_path("/GetToken")
response = conn.post do |req|
req.url(full_path)
req.body = { Username: @username, Password: @password }.to_json
end
raise(GetTokenError, response.body) unless response.status == 200
@token = response.body
end | ruby | def get_token
full_path = build_request_path("/GetToken")
response = conn.post do |req|
req.url(full_path)
req.body = { Username: @username, Password: @password }.to_json
end
raise(GetTokenError, response.body) unless response.status == 200
@token = response.body
end | [
"def",
"get_token",
"full_path",
"=",
"build_request_path",
"(",
"\"/GetToken\"",
")",
"response",
"=",
"conn",
".",
"post",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"(",
"full_path",
")",
"req",
".",
"body",
"=",
"{",
"Username",
":",
"@username",
",",
"Password",
":",
"@password",
"}",
".",
"to_json",
"end",
"raise",
"(",
"GetTokenError",
",",
"response",
".",
"body",
")",
"unless",
"response",
".",
"status",
"==",
"200",
"@token",
"=",
"response",
".",
"body",
"end"
] | Instantiation of the Client
@param url [String] Allscripts URL to be used to make Unity API calls
@param app_name [String] app name assigned by Allscripts
@param app_username [String] the app username supplied by Allscripts
@param app_password [String] the app password supplied by Allscripts
Gets security token necessary in all workflows
@return [String] security token | [
"Instantiation",
"of",
"the",
"Client"
] | b32da6df50565f63dbdac2c861dd6793000c3634 | https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/client.rb#L35-L44 |
15 | Avhana/allscripts_api | lib/allscripts_api/client.rb | AllscriptsApi.Client.get_user_authentication | def get_user_authentication(username, password)
@allscripts_username = username
params = MagicParams.format(user_id: username, parameter1: password)
response = magic("GetUserAuthentication", magic_params: params)
response["getuserauthenticationinfo"][0]
end | ruby | def get_user_authentication(username, password)
@allscripts_username = username
params = MagicParams.format(user_id: username, parameter1: password)
response = magic("GetUserAuthentication", magic_params: params)
response["getuserauthenticationinfo"][0]
end | [
"def",
"get_user_authentication",
"(",
"username",
",",
"password",
")",
"@allscripts_username",
"=",
"username",
"params",
"=",
"MagicParams",
".",
"format",
"(",
"user_id",
":",
"username",
",",
"parameter1",
":",
"password",
")",
"response",
"=",
"magic",
"(",
"\"GetUserAuthentication\"",
",",
"magic_params",
":",
"params",
")",
"response",
"[",
"\"getuserauthenticationinfo\"",
"]",
"[",
"0",
"]",
"end"
] | Assign a security token from `get_token` to a specific Allscripts user.
This creates a link on the Allscripts server that allows that token
to be used in subsequent `magic` calls passed that user's username.
@param username [String] the Allscripts user's username (from Allscripts)
@param password [String] the Allscripts user's password (from Allscripts)
@return [Hash] user permissions, etc. | [
"Assign",
"a",
"security",
"token",
"from",
"get_token",
"to",
"a",
"specific",
"Allscripts",
"user",
".",
"This",
"creates",
"a",
"link",
"on",
"the",
"Allscripts",
"server",
"that",
"allows",
"that",
"token",
"to",
"be",
"used",
"in",
"subsequent",
"magic",
"calls",
"passed",
"that",
"user",
"s",
"username",
"."
] | b32da6df50565f63dbdac2c861dd6793000c3634 | https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/client.rb#L53-L58 |
16 | Avhana/allscripts_api | lib/allscripts_api/client.rb | AllscriptsApi.Client.validate_sso_token | def validate_sso_token(sso_token = nil)
sso_token ||= @sso_token
params = MagicParams.format(parameter1: sso_token)
response = magic("GetTokenValidation", magic_params: params)
response["Table"][0]
end | ruby | def validate_sso_token(sso_token = nil)
sso_token ||= @sso_token
params = MagicParams.format(parameter1: sso_token)
response = magic("GetTokenValidation", magic_params: params)
response["Table"][0]
end | [
"def",
"validate_sso_token",
"(",
"sso_token",
"=",
"nil",
")",
"sso_token",
"||=",
"@sso_token",
"params",
"=",
"MagicParams",
".",
"format",
"(",
"parameter1",
":",
"sso_token",
")",
"response",
"=",
"magic",
"(",
"\"GetTokenValidation\"",
",",
"magic_params",
":",
"params",
")",
"response",
"[",
"\"Table\"",
"]",
"[",
"0",
"]",
"end"
] | Validate a token generated and passed by Allscripts during SSO
Falls back and looks for sso_token on the client if not passed one
Note that sso_token is not the token from `get_token``
TODO: test and validate. Add error handling
@param sso_token [String] the Allscripts SSO token (from Allscripts) | [
"Validate",
"a",
"token",
"generated",
"and",
"passed",
"by",
"Allscripts",
"during",
"SSO",
"Falls",
"back",
"and",
"looks",
"for",
"sso_token",
"on",
"the",
"client",
"if",
"not",
"passed",
"one",
"Note",
"that",
"sso_token",
"is",
"not",
"the",
"token",
"from",
"get_token"
] | b32da6df50565f63dbdac2c861dd6793000c3634 | https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/client.rb#L67-L72 |
17 | Avhana/allscripts_api | lib/allscripts_api/client.rb | AllscriptsApi.Client.magic | def magic(action, magic_params: MagicParams.format)
full_path = build_request_path("/MagicJson")
body = build_magic_body(action, magic_params)
response =
conn.post do |req|
req.url(full_path)
req.body = body
end
read_magic_response(action, response)
end | ruby | def magic(action, magic_params: MagicParams.format)
full_path = build_request_path("/MagicJson")
body = build_magic_body(action, magic_params)
response =
conn.post do |req|
req.url(full_path)
req.body = body
end
read_magic_response(action, response)
end | [
"def",
"magic",
"(",
"action",
",",
"magic_params",
":",
"MagicParams",
".",
"format",
")",
"full_path",
"=",
"build_request_path",
"(",
"\"/MagicJson\"",
")",
"body",
"=",
"build_magic_body",
"(",
"action",
",",
"magic_params",
")",
"response",
"=",
"conn",
".",
"post",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"(",
"full_path",
")",
"req",
".",
"body",
"=",
"body",
"end",
"read_magic_response",
"(",
"action",
",",
"response",
")",
"end"
] | Main method for interacting with the Allscripts UnityAPI
@param action [String] the API action to be performed
@param magic_params [MagicParams] a params object
used to build the Magic Action request body's user_id,
patient_id, and magic parameters. The patient_id
is sometimes oprional and the numbered
params are generally optional, but must be sent
as blank strings if unused.
@return [Hash, MagicError] the parsed JSON response from Allscripts or
a `MagicError` with the API error message(hopefully) | [
"Main",
"method",
"for",
"interacting",
"with",
"the",
"Allscripts",
"UnityAPI"
] | b32da6df50565f63dbdac2c861dd6793000c3634 | https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/client.rb#L85-L94 |
18 | skoona/skn_utils | lib/skn_utils/nested_result.rb | SknUtils.NestedResult.initialize_for_speed | def initialize_for_speed(hash)
hash.each_pair do |k,v|
key = key_as_sym(k)
case v
when Array
value = v.map { |element| translate_value(element) }
container.store(key, value)
when Hash
container.store(key, NestedResult.new(v))
else
container.store(key, v)
end
end
end | ruby | def initialize_for_speed(hash)
hash.each_pair do |k,v|
key = key_as_sym(k)
case v
when Array
value = v.map { |element| translate_value(element) }
container.store(key, value)
when Hash
container.store(key, NestedResult.new(v))
else
container.store(key, v)
end
end
end | [
"def",
"initialize_for_speed",
"(",
"hash",
")",
"hash",
".",
"each_pair",
"do",
"|",
"k",
",",
"v",
"|",
"key",
"=",
"key_as_sym",
"(",
"k",
")",
"case",
"v",
"when",
"Array",
"value",
"=",
"v",
".",
"map",
"{",
"|",
"element",
"|",
"translate_value",
"(",
"element",
")",
"}",
"container",
".",
"store",
"(",
"key",
",",
"value",
")",
"when",
"Hash",
"container",
".",
"store",
"(",
"key",
",",
"NestedResult",
".",
"new",
"(",
"v",
")",
")",
"else",
"container",
".",
"store",
"(",
"key",
",",
"v",
")",
"end",
"end",
"end"
] | Don't create methods until first access | [
"Don",
"t",
"create",
"methods",
"until",
"first",
"access"
] | 6bccc5e49490c9d3eee59056d6353d0cab6e5ed3 | https://github.com/skoona/skn_utils/blob/6bccc5e49490c9d3eee59056d6353d0cab6e5ed3/lib/skn_utils/nested_result.rb#L262-L275 |
19 | jphastings/AirVideo | lib/airvideo.rb | AirVideo.Client.set_proxy | def set_proxy(proxy_server_and_port = "")
begin
@proxy = URI.parse("http://"+((proxy_server_and_port.empty?) ? ENV['HTTP_PROXY'] : string_proxy))
@http = Net::HTTP::Proxy(@proxy.host, @proxy.port)
rescue
@proxy = nil
@http = Net::HTTP
end
end | ruby | def set_proxy(proxy_server_and_port = "")
begin
@proxy = URI.parse("http://"+((proxy_server_and_port.empty?) ? ENV['HTTP_PROXY'] : string_proxy))
@http = Net::HTTP::Proxy(@proxy.host, @proxy.port)
rescue
@proxy = nil
@http = Net::HTTP
end
end | [
"def",
"set_proxy",
"(",
"proxy_server_and_port",
"=",
"\"\"",
")",
"begin",
"@proxy",
"=",
"URI",
".",
"parse",
"(",
"\"http://\"",
"+",
"(",
"(",
"proxy_server_and_port",
".",
"empty?",
")",
"?",
"ENV",
"[",
"'HTTP_PROXY'",
"]",
":",
"string_proxy",
")",
")",
"@http",
"=",
"Net",
"::",
"HTTP",
"::",
"Proxy",
"(",
"@proxy",
".",
"host",
",",
"@proxy",
".",
"port",
")",
"rescue",
"@proxy",
"=",
"nil",
"@http",
"=",
"Net",
"::",
"HTTP",
"end",
"end"
] | Specify where your AirVideo Server lives. If your HTTP_PROXY environment variable is set, it will be honoured.
At the moment I'm expecting ENV['HTTP_PROXY'] to have the form 'sub.domain.com:8080', I throw an http:// and bung it into URI.parse for convenience.
Potentially confusing:
* Sending 'server:port' will use that address as an HTTP proxy
* An empty string (or something not recognisable as a URL with http:// put infront of it) will try to use the ENV['HTTP_PROXY'] variable
* Sending nil or any object that can't be parsed to a string will remove the proxy
NB. You can access the @proxy URI object externally, but changing it will *not* automatically call set_proxy | [
"Specify",
"where",
"your",
"AirVideo",
"Server",
"lives",
".",
"If",
"your",
"HTTP_PROXY",
"environment",
"variable",
"is",
"set",
"it",
"will",
"be",
"honoured",
"."
] | be7f5f12bacf4f60936c1fc57d21cde10fc79e3e | https://github.com/jphastings/AirVideo/blob/be7f5f12bacf4f60936c1fc57d21cde10fc79e3e/lib/airvideo.rb#L48-L56 |
20 | emilsoman/cloudster | lib/cloudster/output.rb | Cloudster.Output.output_template | def output_template(outputs)
resource_name = outputs.keys[0]
outputs_array = outputs.values[0].collect
each_output_join = outputs_array.collect {|output| {"Fn::Join" => ["|", output]}}
return resource_name => {
'Value' => { "Fn::Join" => [ ",", each_output_join] }
}
end | ruby | def output_template(outputs)
resource_name = outputs.keys[0]
outputs_array = outputs.values[0].collect
each_output_join = outputs_array.collect {|output| {"Fn::Join" => ["|", output]}}
return resource_name => {
'Value' => { "Fn::Join" => [ ",", each_output_join] }
}
end | [
"def",
"output_template",
"(",
"outputs",
")",
"resource_name",
"=",
"outputs",
".",
"keys",
"[",
"0",
"]",
"outputs_array",
"=",
"outputs",
".",
"values",
"[",
"0",
"]",
".",
"collect",
"each_output_join",
"=",
"outputs_array",
".",
"collect",
"{",
"|",
"output",
"|",
"{",
"\"Fn::Join\"",
"=>",
"[",
"\"|\"",
",",
"output",
"]",
"}",
"}",
"return",
"resource_name",
"=>",
"{",
"'Value'",
"=>",
"{",
"\"Fn::Join\"",
"=>",
"[",
"\",\"",
",",
"each_output_join",
"]",
"}",
"}",
"end"
] | Returns the Output template for resources
==== Parameters
* output: Hash containing the valid outputs and their cloudformation translations | [
"Returns",
"the",
"Output",
"template",
"for",
"resources"
] | fd0e03758c2c08c1621212b9daa28e0be9a812ff | https://github.com/emilsoman/cloudster/blob/fd0e03758c2c08c1621212b9daa28e0be9a812ff/lib/cloudster/output.rb#L7-L14 |
21 | instructure/folio | lib/folio/ordinal.rb | Folio.Ordinal.configure_pagination | def configure_pagination(page, options)
page = super(page, options)
raise ::Folio::InvalidPage unless page.current_page.is_a?(Integer)
raise ::Folio::InvalidPage if page.out_of_bounds?
page
rescue ::WillPaginate::InvalidPage
raise ::Folio::InvalidPage
end | ruby | def configure_pagination(page, options)
page = super(page, options)
raise ::Folio::InvalidPage unless page.current_page.is_a?(Integer)
raise ::Folio::InvalidPage if page.out_of_bounds?
page
rescue ::WillPaginate::InvalidPage
raise ::Folio::InvalidPage
end | [
"def",
"configure_pagination",
"(",
"page",
",",
"options",
")",
"page",
"=",
"super",
"(",
"page",
",",
"options",
")",
"raise",
"::",
"Folio",
"::",
"InvalidPage",
"unless",
"page",
".",
"current_page",
".",
"is_a?",
"(",
"Integer",
")",
"raise",
"::",
"Folio",
"::",
"InvalidPage",
"if",
"page",
".",
"out_of_bounds?",
"page",
"rescue",
"::",
"WillPaginate",
"::",
"InvalidPage",
"raise",
"::",
"Folio",
"::",
"InvalidPage",
"end"
] | validate the configured page before returning it | [
"validate",
"the",
"configured",
"page",
"before",
"returning",
"it"
] | fd4dd3a9b35922b8bec234a8bed00949f4b800f9 | https://github.com/instructure/folio/blob/fd4dd3a9b35922b8bec234a8bed00949f4b800f9/lib/folio/ordinal.rb#L26-L33 |
22 | emilsoman/cloudster | lib/cloudster/elastic_ip.rb | Cloudster.ElasticIp.add_to | def add_to(ec2)
ec2_template = ec2.template
@instance_name = ec2.name
elastic_ip_template = template
ec2.template.inner_merge(elastic_ip_template)
end | ruby | def add_to(ec2)
ec2_template = ec2.template
@instance_name = ec2.name
elastic_ip_template = template
ec2.template.inner_merge(elastic_ip_template)
end | [
"def",
"add_to",
"(",
"ec2",
")",
"ec2_template",
"=",
"ec2",
".",
"template",
"@instance_name",
"=",
"ec2",
".",
"name",
"elastic_ip_template",
"=",
"template",
"ec2",
".",
"template",
".",
"inner_merge",
"(",
"elastic_ip_template",
")",
"end"
] | Initialize an ElasticIp
==== Notes
options parameter must include values for :name
==== Examples
elastic_ip = Cloudster::ElasticIp.new(:name => 'ElasticIp')
==== Parameters
* options<~Hash> -
* :name: String containing the name of ElastiCache resource
Merges the required CloudFormation template for adding an ElasticIp to an EC2 instance
==== Examples
elastic_ip = Cloudster::ElasticIp.new(:name => 'AppServerEIp')
ec2 = Cloudster::Ec2.new(
:name => 'AppServer',
:key_name => 'mykey',
:image_id => 'ami_image_id',
:instance_type => 't1.micro'
)
elastic_ip.add_to ec2
==== Parameters
* instance of EC2 | [
"Initialize",
"an",
"ElasticIp"
] | fd0e03758c2c08c1621212b9daa28e0be9a812ff | https://github.com/emilsoman/cloudster/blob/fd0e03758c2c08c1621212b9daa28e0be9a812ff/lib/cloudster/elastic_ip.rb#L39-L44 |
23 | jaymcgavren/rubyonacid | lib/rubyonacid/factories/input.rb | RubyOnAcid.InputFactory.put | def put(key, value)
value = value.to_f
@input_values[key] = value
@smallest_seen_values[key] ||= 0.0
if @largest_seen_values[key] == nil or @smallest_seen_values[key] > @largest_seen_values[key]
@largest_seen_values[key] = @smallest_seen_values[key] + 1.0
end
@smallest_seen_values[key] = value if value < @smallest_seen_values[key]
@largest_seen_values[key] = value if value > @largest_seen_values[key]
end | ruby | def put(key, value)
value = value.to_f
@input_values[key] = value
@smallest_seen_values[key] ||= 0.0
if @largest_seen_values[key] == nil or @smallest_seen_values[key] > @largest_seen_values[key]
@largest_seen_values[key] = @smallest_seen_values[key] + 1.0
end
@smallest_seen_values[key] = value if value < @smallest_seen_values[key]
@largest_seen_values[key] = value if value > @largest_seen_values[key]
end | [
"def",
"put",
"(",
"key",
",",
"value",
")",
"value",
"=",
"value",
".",
"to_f",
"@input_values",
"[",
"key",
"]",
"=",
"value",
"@smallest_seen_values",
"[",
"key",
"]",
"||=",
"0.0",
"if",
"@largest_seen_values",
"[",
"key",
"]",
"==",
"nil",
"or",
"@smallest_seen_values",
"[",
"key",
"]",
">",
"@largest_seen_values",
"[",
"key",
"]",
"@largest_seen_values",
"[",
"key",
"]",
"=",
"@smallest_seen_values",
"[",
"key",
"]",
"+",
"1.0",
"end",
"@smallest_seen_values",
"[",
"key",
"]",
"=",
"value",
"if",
"value",
"<",
"@smallest_seen_values",
"[",
"key",
"]",
"@largest_seen_values",
"[",
"key",
"]",
"=",
"value",
"if",
"value",
">",
"@largest_seen_values",
"[",
"key",
"]",
"end"
] | Store a value for the given key.
Values will be scaled to the range 0 to 1 - the largest value yet seen will be scaled to 1.0, the smallest yet seen to 0.0. | [
"Store",
"a",
"value",
"for",
"the",
"given",
"key",
".",
"Values",
"will",
"be",
"scaled",
"to",
"the",
"range",
"0",
"to",
"1",
"-",
"the",
"largest",
"value",
"yet",
"seen",
"will",
"be",
"scaled",
"to",
"1",
".",
"0",
"the",
"smallest",
"yet",
"seen",
"to",
"0",
".",
"0",
"."
] | 2ee2af3e952b7290e18a4f7012f76af4a7fe059d | https://github.com/jaymcgavren/rubyonacid/blob/2ee2af3e952b7290e18a4f7012f76af4a7fe059d/lib/rubyonacid/factories/input.rb#L31-L40 |
24 | jaymcgavren/rubyonacid | lib/rubyonacid/factories/input.rb | RubyOnAcid.InputFactory.assigned_key | def assigned_key(key)
return @key_assignments[key] if @key_assignments[key]
available_keys = @input_values.keys - @key_assignments.values
return nil if available_keys.empty?
if available_keys.include?(key)
@key_assignments[key] = key
else
@key_assignments[key] = available_keys[rand(available_keys.length)]
end
@key_assignments[key]
end | ruby | def assigned_key(key)
return @key_assignments[key] if @key_assignments[key]
available_keys = @input_values.keys - @key_assignments.values
return nil if available_keys.empty?
if available_keys.include?(key)
@key_assignments[key] = key
else
@key_assignments[key] = available_keys[rand(available_keys.length)]
end
@key_assignments[key]
end | [
"def",
"assigned_key",
"(",
"key",
")",
"return",
"@key_assignments",
"[",
"key",
"]",
"if",
"@key_assignments",
"[",
"key",
"]",
"available_keys",
"=",
"@input_values",
".",
"keys",
"-",
"@key_assignments",
".",
"values",
"return",
"nil",
"if",
"available_keys",
".",
"empty?",
"if",
"available_keys",
".",
"include?",
"(",
"key",
")",
"@key_assignments",
"[",
"key",
"]",
"=",
"key",
"else",
"@key_assignments",
"[",
"key",
"]",
"=",
"available_keys",
"[",
"rand",
"(",
"available_keys",
".",
"length",
")",
"]",
"end",
"@key_assignments",
"[",
"key",
"]",
"end"
] | Returns the input key assigned to the given get_unit key.
If none is assigned, randomly assigns one of the available input keys. | [
"Returns",
"the",
"input",
"key",
"assigned",
"to",
"the",
"given",
"get_unit",
"key",
".",
"If",
"none",
"is",
"assigned",
"randomly",
"assigns",
"one",
"of",
"the",
"available",
"input",
"keys",
"."
] | 2ee2af3e952b7290e18a4f7012f76af4a7fe059d | https://github.com/jaymcgavren/rubyonacid/blob/2ee2af3e952b7290e18a4f7012f76af4a7fe059d/lib/rubyonacid/factories/input.rb#L67-L77 |
25 | mkdynamic/vss | lib/vss/engine.rb | VSS.Engine.search | def search(query)
# get ranks
query_vector = make_query_vector(query)
ranks = @documents.map do |document|
document_vector = make_vector(document)
cosine_rank(query_vector, document_vector)
end
# now annotate records and return them
@records.each_with_index do |record, i|
# TODO: do this in a sensible way...
record.instance_eval %{def rank; #{ranks[i]}; end}
end
# exclude 0 rank (no match) and sort by rank
@records.reject { |r| r.rank == 0 }.sort { |a,b| b.rank <=> a.rank }
end | ruby | def search(query)
# get ranks
query_vector = make_query_vector(query)
ranks = @documents.map do |document|
document_vector = make_vector(document)
cosine_rank(query_vector, document_vector)
end
# now annotate records and return them
@records.each_with_index do |record, i|
# TODO: do this in a sensible way...
record.instance_eval %{def rank; #{ranks[i]}; end}
end
# exclude 0 rank (no match) and sort by rank
@records.reject { |r| r.rank == 0 }.sort { |a,b| b.rank <=> a.rank }
end | [
"def",
"search",
"(",
"query",
")",
"# get ranks",
"query_vector",
"=",
"make_query_vector",
"(",
"query",
")",
"ranks",
"=",
"@documents",
".",
"map",
"do",
"|",
"document",
"|",
"document_vector",
"=",
"make_vector",
"(",
"document",
")",
"cosine_rank",
"(",
"query_vector",
",",
"document_vector",
")",
"end",
"# now annotate records and return them",
"@records",
".",
"each_with_index",
"do",
"|",
"record",
",",
"i",
"|",
"# TODO: do this in a sensible way...",
"record",
".",
"instance_eval",
"%{def rank; #{ranks[i]}; end}",
"end",
"# exclude 0 rank (no match) and sort by rank",
"@records",
".",
"reject",
"{",
"|",
"r",
"|",
"r",
".",
"rank",
"==",
"0",
"}",
".",
"sort",
"{",
"|",
"a",
",",
"b",
"|",
"b",
".",
"rank",
"<=>",
"a",
".",
"rank",
"}",
"end"
] | `documentizer` just takes a record and converts it to a string | [
"documentizer",
"just",
"takes",
"a",
"record",
"and",
"converts",
"it",
"to",
"a",
"string"
] | f4e62e94f0381174f26debc5c31d282997591188 | https://github.com/mkdynamic/vss/blob/f4e62e94f0381174f26debc5c31d282997591188/lib/vss/engine.rb#L13-L29 |
26 | ideonetwork/evnt | lib/evnt/event.rb | Evnt.Event._init_event_data | def _init_event_data(params)
# set state
@state = {
reloaded: !params[:evnt].nil?,
saved: true
}
# set options
initial_options = {
exceptions: false,
silent: false
}
default_options = _safe_default_options || {}
params_options = params[:_options] || {}
@options = initial_options.merge(default_options)
.merge(params_options)
# set name and attributes
@name = _safe_name
@attributes = _safe_attributes
# set payload
payload = params.reject { |k, _v| k[0] == '_' }
@payload = @state[:reloaded] ? payload : _generate_payload(payload)
# set extras
@extras = {}
extras = params.select { |k, _v| k[0] == '_' }
extras.each { |k, v| @extras[k[1..-1].to_sym] = v }
end | ruby | def _init_event_data(params)
# set state
@state = {
reloaded: !params[:evnt].nil?,
saved: true
}
# set options
initial_options = {
exceptions: false,
silent: false
}
default_options = _safe_default_options || {}
params_options = params[:_options] || {}
@options = initial_options.merge(default_options)
.merge(params_options)
# set name and attributes
@name = _safe_name
@attributes = _safe_attributes
# set payload
payload = params.reject { |k, _v| k[0] == '_' }
@payload = @state[:reloaded] ? payload : _generate_payload(payload)
# set extras
@extras = {}
extras = params.select { |k, _v| k[0] == '_' }
extras.each { |k, v| @extras[k[1..-1].to_sym] = v }
end | [
"def",
"_init_event_data",
"(",
"params",
")",
"# set state",
"@state",
"=",
"{",
"reloaded",
":",
"!",
"params",
"[",
":evnt",
"]",
".",
"nil?",
",",
"saved",
":",
"true",
"}",
"# set options",
"initial_options",
"=",
"{",
"exceptions",
":",
"false",
",",
"silent",
":",
"false",
"}",
"default_options",
"=",
"_safe_default_options",
"||",
"{",
"}",
"params_options",
"=",
"params",
"[",
":_options",
"]",
"||",
"{",
"}",
"@options",
"=",
"initial_options",
".",
"merge",
"(",
"default_options",
")",
".",
"merge",
"(",
"params_options",
")",
"# set name and attributes",
"@name",
"=",
"_safe_name",
"@attributes",
"=",
"_safe_attributes",
"# set payload",
"payload",
"=",
"params",
".",
"reject",
"{",
"|",
"k",
",",
"_v",
"|",
"k",
"[",
"0",
"]",
"==",
"'_'",
"}",
"@payload",
"=",
"@state",
"[",
":reloaded",
"]",
"?",
"payload",
":",
"_generate_payload",
"(",
"payload",
")",
"# set extras",
"@extras",
"=",
"{",
"}",
"extras",
"=",
"params",
".",
"select",
"{",
"|",
"k",
",",
"_v",
"|",
"k",
"[",
"0",
"]",
"==",
"'_'",
"}",
"extras",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"@extras",
"[",
"k",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"to_sym",
"]",
"=",
"v",
"}",
"end"
] | This function initializes the event required data. | [
"This",
"function",
"initializes",
"the",
"event",
"required",
"data",
"."
] | 01331ab48f3fe92c6189b6f4db256606d397d177 | https://github.com/ideonetwork/evnt/blob/01331ab48f3fe92c6189b6f4db256606d397d177/lib/evnt/event.rb#L95-L124 |
27 | Acornsgrow/optional_logger | lib/optional_logger/logger.rb | OptionalLogger.Logger.add | def add(severity, message = nil, progname_or_message = nil, &block)
@logger.add(severity, message, progname_or_message, &block) if @logger
end | ruby | def add(severity, message = nil, progname_or_message = nil, &block)
@logger.add(severity, message, progname_or_message, &block) if @logger
end | [
"def",
"add",
"(",
"severity",
",",
"message",
"=",
"nil",
",",
"progname_or_message",
"=",
"nil",
",",
"&",
"block",
")",
"@logger",
".",
"add",
"(",
"severity",
",",
"message",
",",
"progname_or_message",
",",
"block",
")",
"if",
"@logger",
"end"
] | Log a message at the given level if the logger is present
This isn't generally a recommended method to use while logging in your
libraries. Instead see {#debug}, {#info}, {#warn}, {#error}, {#fatal}, and
{#unknown} as they simplify messaging considerably.
If you don't want to use the recommended methods and want more control for
some reason. There are a few ways to log a message depending on your usecase.
The first is probably the most generally useful, which is logging messages
that aren't costly to build. This is accomplished as follows:
add(::Logger::INFO, 'some message', nil)
The second is for use cases in which it is costly to build the log message
as it avoids executing the block until the logger knows that the message
level will be displayed. If the message level would not be displayed then
the block is not executed, saving the performance cost of building the
message.
add(::Logger::INFO) { 'some expensive message' }
The third gives you the benefits of preventing uneeded expensive messages
but also allows you to override the program name that will be prefixed on
that log message. This is accomplished as follows.
add(::Logger::INFO, nil, 'overridden progname') { 'some expensive message' }
It is important to realize that if the wrapped logger is nil then this
method will simply do nothing.
@param severity ::Logger::DEBUG, ::Logger::INFO, ::Logger::WARN,
::Logger::ERROR, ::Logger::FATAL, ::Logger::UNKNOWN
@param message the optional message to log
@param progname_or_message the optional program name or message, if
message is nil, and a block is NOT provided, then progname_or_message is
treated as a message rather than progname
@param block the block to evaluate and yield a message, generally useful
preventing building of expensive messages when message of that level
aren't allowed | [
"Log",
"a",
"message",
"at",
"the",
"given",
"level",
"if",
"the",
"logger",
"is",
"present"
] | b88df218f3da39070ff4dee1f55e2aee2c30c1a7 | https://github.com/Acornsgrow/optional_logger/blob/b88df218f3da39070ff4dee1f55e2aee2c30c1a7/lib/optional_logger/logger.rb#L67-L69 |
28 | kkaempf/ruby-wbem | lib/wbem/cimxml.rb | Wbem.CimxmlClient._identify | def _identify
begin
product = nil
{ "sfcb" => [ "root/interop", "CIM_ObjectManager" ],
"pegasus" => [ "root/PG_Internal", "PG_ConfigSetting" ]
}.each do |cimom, op|
obj = objectpath *op
@client.instances(obj).each do |inst|
product = inst.Description || cimom
break
end
break if product
end
rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace
raise "Unknown CIMOM"
end
product
end | ruby | def _identify
begin
product = nil
{ "sfcb" => [ "root/interop", "CIM_ObjectManager" ],
"pegasus" => [ "root/PG_Internal", "PG_ConfigSetting" ]
}.each do |cimom, op|
obj = objectpath *op
@client.instances(obj).each do |inst|
product = inst.Description || cimom
break
end
break if product
end
rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace
raise "Unknown CIMOM"
end
product
end | [
"def",
"_identify",
"begin",
"product",
"=",
"nil",
"{",
"\"sfcb\"",
"=>",
"[",
"\"root/interop\"",
",",
"\"CIM_ObjectManager\"",
"]",
",",
"\"pegasus\"",
"=>",
"[",
"\"root/PG_Internal\"",
",",
"\"PG_ConfigSetting\"",
"]",
"}",
".",
"each",
"do",
"|",
"cimom",
",",
"op",
"|",
"obj",
"=",
"objectpath",
"op",
"@client",
".",
"instances",
"(",
"obj",
")",
".",
"each",
"do",
"|",
"inst",
"|",
"product",
"=",
"inst",
".",
"Description",
"||",
"cimom",
"break",
"end",
"break",
"if",
"product",
"end",
"rescue",
"Sfcc",
"::",
"Cim",
"::",
"ErrorInvalidClass",
",",
"Sfcc",
"::",
"Cim",
"::",
"ErrorInvalidNamespace",
"raise",
"\"Unknown CIMOM\"",
"end",
"product",
"end"
] | identify client
return identification string
on error return nil and set @response to http response code | [
"identify",
"client",
"return",
"identification",
"string",
"on",
"error",
"return",
"nil",
"and",
"set"
] | ce813d911b8b67ef23fb6171f6910ebbca602121 | https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/cimxml.rb#L33-L50 |
29 | kkaempf/ruby-wbem | lib/wbem/cimxml.rb | Wbem.CimxmlClient.each_instance | def each_instance( namespace_or_objectpath, classname = nil )
op = if namespace_or_objectpath.is_a? Sfcc::Cim::ObjectPath
namespace_or_objectpath
else
objectpath namespace_or_objectpath, classname
end
begin
@client.instances(op).each do |inst|
yield inst
end
rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace
end
end | ruby | def each_instance( namespace_or_objectpath, classname = nil )
op = if namespace_or_objectpath.is_a? Sfcc::Cim::ObjectPath
namespace_or_objectpath
else
objectpath namespace_or_objectpath, classname
end
begin
@client.instances(op).each do |inst|
yield inst
end
rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace
end
end | [
"def",
"each_instance",
"(",
"namespace_or_objectpath",
",",
"classname",
"=",
"nil",
")",
"op",
"=",
"if",
"namespace_or_objectpath",
".",
"is_a?",
"Sfcc",
"::",
"Cim",
"::",
"ObjectPath",
"namespace_or_objectpath",
"else",
"objectpath",
"namespace_or_objectpath",
",",
"classname",
"end",
"begin",
"@client",
".",
"instances",
"(",
"op",
")",
".",
"each",
"do",
"|",
"inst",
"|",
"yield",
"inst",
"end",
"rescue",
"Sfcc",
"::",
"Cim",
"::",
"ErrorInvalidClass",
",",
"Sfcc",
"::",
"Cim",
"::",
"ErrorInvalidNamespace",
"end",
"end"
] | Return instances for namespace and classname | [
"Return",
"instances",
"for",
"namespace",
"and",
"classname"
] | ce813d911b8b67ef23fb6171f6910ebbca602121 | https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/cimxml.rb#L125-L137 |
30 | kkaempf/ruby-wbem | lib/wbem/cimxml.rb | Wbem.CimxmlClient.class_names | def class_names op, deep_inheritance = false
ret = []
unless op.is_a? Sfcc::Cim::ObjectPath
op = Sfcc::Cim::ObjectPath.new(op.to_s, nil) # assume namespace
end
flags = deep_inheritance ? Sfcc::Flags::DeepInheritance : 0
begin
@client.class_names(op, flags).each do |name|
ret << name.to_s
end
rescue Sfcc::Cim::ErrorInvalidNamespace
end
ret
end | ruby | def class_names op, deep_inheritance = false
ret = []
unless op.is_a? Sfcc::Cim::ObjectPath
op = Sfcc::Cim::ObjectPath.new(op.to_s, nil) # assume namespace
end
flags = deep_inheritance ? Sfcc::Flags::DeepInheritance : 0
begin
@client.class_names(op, flags).each do |name|
ret << name.to_s
end
rescue Sfcc::Cim::ErrorInvalidNamespace
end
ret
end | [
"def",
"class_names",
"op",
",",
"deep_inheritance",
"=",
"false",
"ret",
"=",
"[",
"]",
"unless",
"op",
".",
"is_a?",
"Sfcc",
"::",
"Cim",
"::",
"ObjectPath",
"op",
"=",
"Sfcc",
"::",
"Cim",
"::",
"ObjectPath",
".",
"new",
"(",
"op",
".",
"to_s",
",",
"nil",
")",
"# assume namespace",
"end",
"flags",
"=",
"deep_inheritance",
"?",
"Sfcc",
"::",
"Flags",
"::",
"DeepInheritance",
":",
"0",
"begin",
"@client",
".",
"class_names",
"(",
"op",
",",
"flags",
")",
".",
"each",
"do",
"|",
"name",
"|",
"ret",
"<<",
"name",
".",
"to_s",
"end",
"rescue",
"Sfcc",
"::",
"Cim",
"::",
"ErrorInvalidNamespace",
"end",
"ret",
"end"
] | Return list of classnames for given object_path | [
"Return",
"list",
"of",
"classnames",
"for",
"given",
"object_path"
] | ce813d911b8b67ef23fb6171f6910ebbca602121 | https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/cimxml.rb#L142-L155 |
31 | kkaempf/ruby-wbem | lib/wbem/cimxml.rb | Wbem.CimxmlClient.each_association | def each_association( objectpath )
begin
@client.associators(objectpath).each do |assoc|
yield assoc
end
rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace
end
end | ruby | def each_association( objectpath )
begin
@client.associators(objectpath).each do |assoc|
yield assoc
end
rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace
end
end | [
"def",
"each_association",
"(",
"objectpath",
")",
"begin",
"@client",
".",
"associators",
"(",
"objectpath",
")",
".",
"each",
"do",
"|",
"assoc",
"|",
"yield",
"assoc",
"end",
"rescue",
"Sfcc",
"::",
"Cim",
"::",
"ErrorInvalidClass",
",",
"Sfcc",
"::",
"Cim",
"::",
"ErrorInvalidNamespace",
"end",
"end"
] | Return associations for instance | [
"Return",
"associations",
"for",
"instance"
] | ce813d911b8b67ef23fb6171f6910ebbca602121 | https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/cimxml.rb#L249-L256 |
32 | acenqiu/weibo2 | lib/weibo2/client.rb | Weibo2.Client.get_token_from_hash | def get_token_from_hash(hash)
access_token = hash.delete('access_token') || hash.delete(:access_token) || hash.delete('oauth_token') || hash.delete(:oauth_token)
opts = {:expires_at => hash["expires"] || hash[:expires],
:header_format => "OAuth2 %s",
:param_name => "access_token"}
@token = OAuth2::AccessToken.new(self, access_token, opts)
end | ruby | def get_token_from_hash(hash)
access_token = hash.delete('access_token') || hash.delete(:access_token) || hash.delete('oauth_token') || hash.delete(:oauth_token)
opts = {:expires_at => hash["expires"] || hash[:expires],
:header_format => "OAuth2 %s",
:param_name => "access_token"}
@token = OAuth2::AccessToken.new(self, access_token, opts)
end | [
"def",
"get_token_from_hash",
"(",
"hash",
")",
"access_token",
"=",
"hash",
".",
"delete",
"(",
"'access_token'",
")",
"||",
"hash",
".",
"delete",
"(",
":access_token",
")",
"||",
"hash",
".",
"delete",
"(",
"'oauth_token'",
")",
"||",
"hash",
".",
"delete",
"(",
":oauth_token",
")",
"opts",
"=",
"{",
":expires_at",
"=>",
"hash",
"[",
"\"expires\"",
"]",
"||",
"hash",
"[",
":expires",
"]",
",",
":header_format",
"=>",
"\"OAuth2 %s\"",
",",
":param_name",
"=>",
"\"access_token\"",
"}",
"@token",
"=",
"OAuth2",
"::",
"AccessToken",
".",
"new",
"(",
"self",
",",
"access_token",
",",
"opts",
")",
"end"
] | Initializes an AccessToken from a hash
@param [Hash] hash a Hash contains access_token and expires
@return [AccessToken] the initalized AccessToken | [
"Initializes",
"an",
"AccessToken",
"from",
"a",
"hash"
] | 3eb07f64139a87bcfb8926a04fe054f6fa6806b2 | https://github.com/acenqiu/weibo2/blob/3eb07f64139a87bcfb8926a04fe054f6fa6806b2/lib/weibo2/client.rb#L96-L103 |
33 | kkaempf/ruby-wbem | lib/wbem/wsman.rb | Wbem.WsmanClient.epr_uri_for | def epr_uri_for(namespace,classname)
case @product
when :winrm
# winrm embeds namespace in resource URI
Openwsman::epr_uri_for(namespace,classname) rescue "http://schema.suse.com/wbem/wscim/1/cim-schema/2/#{namespace}/#{classname}"
else
(Openwsman::epr_prefix_for(classname)+"/#{classname}") rescue "http://schema.suse.com/wbem/wscim/1/cim-schema/2/#{classname}"
end
end | ruby | def epr_uri_for(namespace,classname)
case @product
when :winrm
# winrm embeds namespace in resource URI
Openwsman::epr_uri_for(namespace,classname) rescue "http://schema.suse.com/wbem/wscim/1/cim-schema/2/#{namespace}/#{classname}"
else
(Openwsman::epr_prefix_for(classname)+"/#{classname}") rescue "http://schema.suse.com/wbem/wscim/1/cim-schema/2/#{classname}"
end
end | [
"def",
"epr_uri_for",
"(",
"namespace",
",",
"classname",
")",
"case",
"@product",
"when",
":winrm",
"# winrm embeds namespace in resource URI",
"Openwsman",
"::",
"epr_uri_for",
"(",
"namespace",
",",
"classname",
")",
"rescue",
"\"http://schema.suse.com/wbem/wscim/1/cim-schema/2/#{namespace}/#{classname}\"",
"else",
"(",
"Openwsman",
"::",
"epr_prefix_for",
"(",
"classname",
")",
"+",
"\"/#{classname}\"",
")",
"rescue",
"\"http://schema.suse.com/wbem/wscim/1/cim-schema/2/#{classname}\"",
"end",
"end"
] | create end point reference URI | [
"create",
"end",
"point",
"reference",
"URI"
] | ce813d911b8b67ef23fb6171f6910ebbca602121 | https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/wsman.rb#L25-L33 |
34 | kkaempf/ruby-wbem | lib/wbem/wsman.rb | Wbem.WsmanClient._handle_fault | def _handle_fault client, result
if result.nil?
STDERR.puts "Client connection failed:\n\tResult code #{client.response_code}, Fault: #{client.fault_string}" if Wbem.debug
return true
end
if result.fault?
fault = Openwsman::Fault.new result
if Wbem.debug
STDERR.puts "Client protocol failed for (#{client})"
STDERR.puts "\tFault code #{fault.code}, subcode #{fault.subcode}"
STDERR.puts "\t\treason #{fault.reason}"
STDERR.puts "\t\tdetail #{fault.detail}"
end
return true
end
false
end | ruby | def _handle_fault client, result
if result.nil?
STDERR.puts "Client connection failed:\n\tResult code #{client.response_code}, Fault: #{client.fault_string}" if Wbem.debug
return true
end
if result.fault?
fault = Openwsman::Fault.new result
if Wbem.debug
STDERR.puts "Client protocol failed for (#{client})"
STDERR.puts "\tFault code #{fault.code}, subcode #{fault.subcode}"
STDERR.puts "\t\treason #{fault.reason}"
STDERR.puts "\t\tdetail #{fault.detail}"
end
return true
end
false
end | [
"def",
"_handle_fault",
"client",
",",
"result",
"if",
"result",
".",
"nil?",
"STDERR",
".",
"puts",
"\"Client connection failed:\\n\\tResult code #{client.response_code}, Fault: #{client.fault_string}\"",
"if",
"Wbem",
".",
"debug",
"return",
"true",
"end",
"if",
"result",
".",
"fault?",
"fault",
"=",
"Openwsman",
"::",
"Fault",
".",
"new",
"result",
"if",
"Wbem",
".",
"debug",
"STDERR",
".",
"puts",
"\"Client protocol failed for (#{client})\"",
"STDERR",
".",
"puts",
"\"\\tFault code #{fault.code}, subcode #{fault.subcode}\"",
"STDERR",
".",
"puts",
"\"\\t\\treason #{fault.reason}\"",
"STDERR",
".",
"puts",
"\"\\t\\tdetail #{fault.detail}\"",
"end",
"return",
"true",
"end",
"false",
"end"
] | Handle client connection or protocol fault
@return: true if fault | [
"Handle",
"client",
"connection",
"or",
"protocol",
"fault"
] | ce813d911b8b67ef23fb6171f6910ebbca602121 | https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/wsman.rb#L40-L56 |
35 | kkaempf/ruby-wbem | lib/wbem/wsman.rb | Wbem.WsmanClient.namespaces | def namespaces ns = "root", cn = "__Namespace"
result = []
each_instance( ns, cn ) do |inst|
name = "#{ns}/#{inst.Name}"
result << name
result.concat namespaces name, cn
end
result.uniq
end | ruby | def namespaces ns = "root", cn = "__Namespace"
result = []
each_instance( ns, cn ) do |inst|
name = "#{ns}/#{inst.Name}"
result << name
result.concat namespaces name, cn
end
result.uniq
end | [
"def",
"namespaces",
"ns",
"=",
"\"root\"",
",",
"cn",
"=",
"\"__Namespace\"",
"result",
"=",
"[",
"]",
"each_instance",
"(",
"ns",
",",
"cn",
")",
"do",
"|",
"inst",
"|",
"name",
"=",
"\"#{ns}/#{inst.Name}\"",
"result",
"<<",
"name",
"result",
".",
"concat",
"namespaces",
"name",
",",
"cn",
"end",
"result",
".",
"uniq",
"end"
] | return list of namespaces | [
"return",
"list",
"of",
"namespaces"
] | ce813d911b8b67ef23fb6171f6910ebbca602121 | https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/wsman.rb#L192-L200 |
36 | kkaempf/ruby-wbem | lib/wbem/wsman.rb | Wbem.WsmanClient.class_names | def class_names op, deep_inheritance = false
@options.flags = Openwsman::FLAG_ENUMERATION_OPTIMIZATION
@options.max_elements = 999
namespace = (op.is_a? Sfcc::Cim::ObjectPath) ? op.namespace : op
classname = (op.is_a? Sfcc::Cim::ObjectPath) ? op.classname : nil
case @product
when :openwsman
if @product_version < "2.2"
STDERR.puts "ENUMERATE_CLASS_NAMES unsupported for #{@product_vendor} #{@product_version}, please upgrade"
return []
end
method = Openwsman::CIM_ACTION_ENUMERATE_CLASS_NAMES
uri = Openwsman::XML_NS_CIM_INTRINSIC
@options.cim_namespace = namespace
@options.add_selector("DeepInheritance", "True") if deep_inheritance
result = @client.invoke( @options, uri, method )
when :winrm
# see https://github.com/kkaempf/openwsman/blob/master/bindings/ruby/tests/winenum.rb
filter = Openwsman::Filter.new
query = "select * from meta_class"
query << " where __SuperClass is #{classname?classname:'null'}" unless deep_inheritance
filter.wql query
uri = "#{@prefix}#{namespace}/*"
result = @client.enumerate( @options, filter, uri )
else
raise "Unsupported for WSMAN product #{@product}"
end
if _handle_fault @client, result
return []
end
classes = []
case @product
when :openwsman
# extract invoke result
output = result.body[method]
output.each do |c|
classes << c.to_s
end
when :winrm
# extract enumerate/pull result
loop do
output = result.Items
output.each do |node|
classes << node.name.to_s
end if output
context = result.context
break unless context
# get the next chunk
result = @client.pull( @options, nil, uri, context)
break if _handle_fault @client, result
end
end
return classes
end | ruby | def class_names op, deep_inheritance = false
@options.flags = Openwsman::FLAG_ENUMERATION_OPTIMIZATION
@options.max_elements = 999
namespace = (op.is_a? Sfcc::Cim::ObjectPath) ? op.namespace : op
classname = (op.is_a? Sfcc::Cim::ObjectPath) ? op.classname : nil
case @product
when :openwsman
if @product_version < "2.2"
STDERR.puts "ENUMERATE_CLASS_NAMES unsupported for #{@product_vendor} #{@product_version}, please upgrade"
return []
end
method = Openwsman::CIM_ACTION_ENUMERATE_CLASS_NAMES
uri = Openwsman::XML_NS_CIM_INTRINSIC
@options.cim_namespace = namespace
@options.add_selector("DeepInheritance", "True") if deep_inheritance
result = @client.invoke( @options, uri, method )
when :winrm
# see https://github.com/kkaempf/openwsman/blob/master/bindings/ruby/tests/winenum.rb
filter = Openwsman::Filter.new
query = "select * from meta_class"
query << " where __SuperClass is #{classname?classname:'null'}" unless deep_inheritance
filter.wql query
uri = "#{@prefix}#{namespace}/*"
result = @client.enumerate( @options, filter, uri )
else
raise "Unsupported for WSMAN product #{@product}"
end
if _handle_fault @client, result
return []
end
classes = []
case @product
when :openwsman
# extract invoke result
output = result.body[method]
output.each do |c|
classes << c.to_s
end
when :winrm
# extract enumerate/pull result
loop do
output = result.Items
output.each do |node|
classes << node.name.to_s
end if output
context = result.context
break unless context
# get the next chunk
result = @client.pull( @options, nil, uri, context)
break if _handle_fault @client, result
end
end
return classes
end | [
"def",
"class_names",
"op",
",",
"deep_inheritance",
"=",
"false",
"@options",
".",
"flags",
"=",
"Openwsman",
"::",
"FLAG_ENUMERATION_OPTIMIZATION",
"@options",
".",
"max_elements",
"=",
"999",
"namespace",
"=",
"(",
"op",
".",
"is_a?",
"Sfcc",
"::",
"Cim",
"::",
"ObjectPath",
")",
"?",
"op",
".",
"namespace",
":",
"op",
"classname",
"=",
"(",
"op",
".",
"is_a?",
"Sfcc",
"::",
"Cim",
"::",
"ObjectPath",
")",
"?",
"op",
".",
"classname",
":",
"nil",
"case",
"@product",
"when",
":openwsman",
"if",
"@product_version",
"<",
"\"2.2\"",
"STDERR",
".",
"puts",
"\"ENUMERATE_CLASS_NAMES unsupported for #{@product_vendor} #{@product_version}, please upgrade\"",
"return",
"[",
"]",
"end",
"method",
"=",
"Openwsman",
"::",
"CIM_ACTION_ENUMERATE_CLASS_NAMES",
"uri",
"=",
"Openwsman",
"::",
"XML_NS_CIM_INTRINSIC",
"@options",
".",
"cim_namespace",
"=",
"namespace",
"@options",
".",
"add_selector",
"(",
"\"DeepInheritance\"",
",",
"\"True\"",
")",
"if",
"deep_inheritance",
"result",
"=",
"@client",
".",
"invoke",
"(",
"@options",
",",
"uri",
",",
"method",
")",
"when",
":winrm",
"# see https://github.com/kkaempf/openwsman/blob/master/bindings/ruby/tests/winenum.rb",
"filter",
"=",
"Openwsman",
"::",
"Filter",
".",
"new",
"query",
"=",
"\"select * from meta_class\"",
"query",
"<<",
"\" where __SuperClass is #{classname?classname:'null'}\"",
"unless",
"deep_inheritance",
"filter",
".",
"wql",
"query",
"uri",
"=",
"\"#{@prefix}#{namespace}/*\"",
"result",
"=",
"@client",
".",
"enumerate",
"(",
"@options",
",",
"filter",
",",
"uri",
")",
"else",
"raise",
"\"Unsupported for WSMAN product #{@product}\"",
"end",
"if",
"_handle_fault",
"@client",
",",
"result",
"return",
"[",
"]",
"end",
"classes",
"=",
"[",
"]",
"case",
"@product",
"when",
":openwsman",
"# extract invoke result",
"output",
"=",
"result",
".",
"body",
"[",
"method",
"]",
"output",
".",
"each",
"do",
"|",
"c",
"|",
"classes",
"<<",
"c",
".",
"to_s",
"end",
"when",
":winrm",
"# extract enumerate/pull result",
"loop",
"do",
"output",
"=",
"result",
".",
"Items",
"output",
".",
"each",
"do",
"|",
"node",
"|",
"classes",
"<<",
"node",
".",
"name",
".",
"to_s",
"end",
"if",
"output",
"context",
"=",
"result",
".",
"context",
"break",
"unless",
"context",
"# get the next chunk",
"result",
"=",
"@client",
".",
"pull",
"(",
"@options",
",",
"nil",
",",
"uri",
",",
"context",
")",
"break",
"if",
"_handle_fault",
"@client",
",",
"result",
"end",
"end",
"return",
"classes",
"end"
] | Enumerate class names | [
"Enumerate",
"class",
"names"
] | ce813d911b8b67ef23fb6171f6910ebbca602121 | https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/wsman.rb#L241-L297 |
37 | ableco/heroku_s3_backups | lib/heroku_s3_backups.rb | HerokuS3Backups.Heroku.download | def download(output_filename, options = {target_backup: nil})
raise "Please specify a filename" if output_filename.length.eql?(0)
HerokuCLI.cmd("pg:backups:download #{target_backup} --output #{output_filename}", @app_name)
end | ruby | def download(output_filename, options = {target_backup: nil})
raise "Please specify a filename" if output_filename.length.eql?(0)
HerokuCLI.cmd("pg:backups:download #{target_backup} --output #{output_filename}", @app_name)
end | [
"def",
"download",
"(",
"output_filename",
",",
"options",
"=",
"{",
"target_backup",
":",
"nil",
"}",
")",
"raise",
"\"Please specify a filename\"",
"if",
"output_filename",
".",
"length",
".",
"eql?",
"(",
"0",
")",
"HerokuCLI",
".",
"cmd",
"(",
"\"pg:backups:download #{target_backup} --output #{output_filename}\"",
",",
"@app_name",
")",
"end"
] | Download the latest backup
@param {string} output_filename
@param {hash} options
Valid options:
=> {string?} target_backup - If a target is set, a backup will be pulled from there,
otherwise, we'll pull from the latest backup
@param {hash} options | [
"Download",
"the",
"latest",
"backup"
] | 0c568f6774243cb276ed2fa8546d601f2f9e21a2 | https://github.com/ableco/heroku_s3_backups/blob/0c568f6774243cb276ed2fa8546d601f2f9e21a2/lib/heroku_s3_backups.rb#L62-L65 |
38 | ableco/heroku_s3_backups | lib/heroku_s3_backups.rb | HerokuS3Backups.Heroku.store_on_s3 | def store_on_s3(backup_location, backup_filename)
prod_backup_folder = AWS_S3().buckets.find(ENV["S3_PRODUCTION_BACKUP_BUCKET"]).objects(prefix: backup_location)
backup_obj = prod_backup_folder.build("#{backup_location}/#{backup_filename}")
# Need to do this to set content length for some reason
backup_obj.content = open(@backup_filename)
backup_obj.save
end | ruby | def store_on_s3(backup_location, backup_filename)
prod_backup_folder = AWS_S3().buckets.find(ENV["S3_PRODUCTION_BACKUP_BUCKET"]).objects(prefix: backup_location)
backup_obj = prod_backup_folder.build("#{backup_location}/#{backup_filename}")
# Need to do this to set content length for some reason
backup_obj.content = open(@backup_filename)
backup_obj.save
end | [
"def",
"store_on_s3",
"(",
"backup_location",
",",
"backup_filename",
")",
"prod_backup_folder",
"=",
"AWS_S3",
"(",
")",
".",
"buckets",
".",
"find",
"(",
"ENV",
"[",
"\"S3_PRODUCTION_BACKUP_BUCKET\"",
"]",
")",
".",
"objects",
"(",
"prefix",
":",
"backup_location",
")",
"backup_obj",
"=",
"prod_backup_folder",
".",
"build",
"(",
"\"#{backup_location}/#{backup_filename}\"",
")",
"# Need to do this to set content length for some reason",
"backup_obj",
".",
"content",
"=",
"open",
"(",
"@backup_filename",
")",
"backup_obj",
".",
"save",
"end"
] | Stores the recently backed up file in a specified S3 bucket
@param {string} backup_location | [
"Stores",
"the",
"recently",
"backed",
"up",
"file",
"in",
"a",
"specified",
"S3",
"bucket"
] | 0c568f6774243cb276ed2fa8546d601f2f9e21a2 | https://github.com/ableco/heroku_s3_backups/blob/0c568f6774243cb276ed2fa8546d601f2f9e21a2/lib/heroku_s3_backups.rb#L76-L85 |
39 | kkaempf/ruby-wbem | lib/wbem/class_factory.rb | Wbem.ClassFactory.gen_method_parameters | def gen_method_parameters direction, parameters, file
return if parameters.empty?
file.print "#{direction.inspect} => ["
first = true
parameters.each do |p|
if first
first = false
else
file.print ", "
end
# [ <name>, <type>, <out>? ]
file.print "#{p.name.inspect}, #{p.type.to_sym.inspect}"
end
file.print "]"
return true
end | ruby | def gen_method_parameters direction, parameters, file
return if parameters.empty?
file.print "#{direction.inspect} => ["
first = true
parameters.each do |p|
if first
first = false
else
file.print ", "
end
# [ <name>, <type>, <out>? ]
file.print "#{p.name.inspect}, #{p.type.to_sym.inspect}"
end
file.print "]"
return true
end | [
"def",
"gen_method_parameters",
"direction",
",",
"parameters",
",",
"file",
"return",
"if",
"parameters",
".",
"empty?",
"file",
".",
"print",
"\"#{direction.inspect} => [\"",
"first",
"=",
"true",
"parameters",
".",
"each",
"do",
"|",
"p",
"|",
"if",
"first",
"first",
"=",
"false",
"else",
"file",
".",
"print",
"\", \"",
"end",
"# [ <name>, <type>, <out>? ]",
"file",
".",
"print",
"\"#{p.name.inspect}, #{p.type.to_sym.inspect}\"",
"end",
"file",
".",
"print",
"\"]\"",
"return",
"true",
"end"
] | generate method parameter information
return nil if no parameters | [
"generate",
"method",
"parameter",
"information",
"return",
"nil",
"if",
"no",
"parameters"
] | ce813d911b8b67ef23fb6171f6910ebbca602121 | https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/class_factory.rb#L68-L83 |
40 | kkaempf/ruby-wbem | lib/wbem/class_factory.rb | Wbem.ClassFactory.generate | def generate name, file
require 'erb'
template = File.read(File.join(File.dirname(__FILE__), "class_template.erb"))
erb = ERB.new(template)
code = erb.result(binding)
Dir.mkdir(@basedir) unless File.directory?(@basedir)
File.open(file, "w+") do |f|
f.puts code
end
end | ruby | def generate name, file
require 'erb'
template = File.read(File.join(File.dirname(__FILE__), "class_template.erb"))
erb = ERB.new(template)
code = erb.result(binding)
Dir.mkdir(@basedir) unless File.directory?(@basedir)
File.open(file, "w+") do |f|
f.puts code
end
end | [
"def",
"generate",
"name",
",",
"file",
"require",
"'erb'",
"template",
"=",
"File",
".",
"read",
"(",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
",",
"\"class_template.erb\"",
")",
")",
"erb",
"=",
"ERB",
".",
"new",
"(",
"template",
")",
"code",
"=",
"erb",
".",
"result",
"(",
"binding",
")",
"Dir",
".",
"mkdir",
"(",
"@basedir",
")",
"unless",
"File",
".",
"directory?",
"(",
"@basedir",
")",
"File",
".",
"open",
"(",
"file",
",",
"\"w+\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"puts",
"code",
"end",
"end"
] | generate .rb class declaration | [
"generate",
".",
"rb",
"class",
"declaration"
] | ce813d911b8b67ef23fb6171f6910ebbca602121 | https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/class_factory.rb#L87-L96 |
41 | kkaempf/ruby-wbem | lib/wbem/class_factory.rb | Wbem.ClassFactory.classmap | def classmap
return @classmap if @classmap
# read SCHEMA and build class index to find .mof files quickly
@classmap = Hash.new
@includes = [ Pathname.new(".") ]
SCHEMATA.each do |base, file|
@includes << base
allow_cim = (file =~ /^CIM_/) # allow CIM_ only for CIM_Schema.mof
File.open(File.join(base, file)) do |f|
f.each do |l|
if l =~ /^\#pragma\sinclude\s?\(\"(([\w\/_]+)\.mof)\"\).*/
# $1 Foo/Bar.mof
# $2 Foo/Bar
path = $1
names = $2.split("/")
name = names[1] || names[0]
next unless name =~ /_/ # class name must have underscore (rules out 'qualifiers.mof')
# puts "#{path}:#{name}"
next if !allow_cim && name =~ /^CIM_/ # skip CIM_ mofs unless allowed
if @classmap[name]
raise "Dup #{name} : #{@classmap[name]}"
else
@classmap[name] = { :path => path }
end
end
end
end
end
STDERR.puts "Found MOFs for #{@classmap.size} classes" if Wbem.debug
@classmap
end | ruby | def classmap
return @classmap if @classmap
# read SCHEMA and build class index to find .mof files quickly
@classmap = Hash.new
@includes = [ Pathname.new(".") ]
SCHEMATA.each do |base, file|
@includes << base
allow_cim = (file =~ /^CIM_/) # allow CIM_ only for CIM_Schema.mof
File.open(File.join(base, file)) do |f|
f.each do |l|
if l =~ /^\#pragma\sinclude\s?\(\"(([\w\/_]+)\.mof)\"\).*/
# $1 Foo/Bar.mof
# $2 Foo/Bar
path = $1
names = $2.split("/")
name = names[1] || names[0]
next unless name =~ /_/ # class name must have underscore (rules out 'qualifiers.mof')
# puts "#{path}:#{name}"
next if !allow_cim && name =~ /^CIM_/ # skip CIM_ mofs unless allowed
if @classmap[name]
raise "Dup #{name} : #{@classmap[name]}"
else
@classmap[name] = { :path => path }
end
end
end
end
end
STDERR.puts "Found MOFs for #{@classmap.size} classes" if Wbem.debug
@classmap
end | [
"def",
"classmap",
"return",
"@classmap",
"if",
"@classmap",
"# read SCHEMA and build class index to find .mof files quickly",
"@classmap",
"=",
"Hash",
".",
"new",
"@includes",
"=",
"[",
"Pathname",
".",
"new",
"(",
"\".\"",
")",
"]",
"SCHEMATA",
".",
"each",
"do",
"|",
"base",
",",
"file",
"|",
"@includes",
"<<",
"base",
"allow_cim",
"=",
"(",
"file",
"=~",
"/",
"/",
")",
"# allow CIM_ only for CIM_Schema.mof",
"File",
".",
"open",
"(",
"File",
".",
"join",
"(",
"base",
",",
"file",
")",
")",
"do",
"|",
"f",
"|",
"f",
".",
"each",
"do",
"|",
"l",
"|",
"if",
"l",
"=~",
"/",
"\\#",
"\\s",
"\\s",
"\\(",
"\\\"",
"\\w",
"\\/",
"\\.",
"\\\"",
"\\)",
"/",
"# $1 Foo/Bar.mof",
"# $2 Foo/Bar",
"path",
"=",
"$1",
"names",
"=",
"$2",
".",
"split",
"(",
"\"/\"",
")",
"name",
"=",
"names",
"[",
"1",
"]",
"||",
"names",
"[",
"0",
"]",
"next",
"unless",
"name",
"=~",
"/",
"/",
"# class name must have underscore (rules out 'qualifiers.mof')",
"# puts \"#{path}:#{name}\"",
"next",
"if",
"!",
"allow_cim",
"&&",
"name",
"=~",
"/",
"/",
"# skip CIM_ mofs unless allowed",
"if",
"@classmap",
"[",
"name",
"]",
"raise",
"\"Dup #{name} : #{@classmap[name]}\"",
"else",
"@classmap",
"[",
"name",
"]",
"=",
"{",
":path",
"=>",
"path",
"}",
"end",
"end",
"end",
"end",
"end",
"STDERR",
".",
"puts",
"\"Found MOFs for #{@classmap.size} classes\"",
"if",
"Wbem",
".",
"debug",
"@classmap",
"end"
] | classmap - generate map of classes and their .mof files | [
"classmap",
"-",
"generate",
"map",
"of",
"classes",
"and",
"their",
".",
"mof",
"files"
] | ce813d911b8b67ef23fb6171f6910ebbca602121 | https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/class_factory.rb#L101-L131 |
42 | baltavay/dawg | lib/dawg/finder.rb | Dawg.Finder.query | def query(word)
node = @the_node
results = []
word.split("").each do |letter|
next_node = node[letter]
if next_node != nil
node = next_node
next
else
return ['']
end
end
results << Word.new(word, node.final)
results += get_childs(node).map{|s| Word.new(word) + s}
results.select{|r| r.final}.map{|r| r.to_s }
end | ruby | def query(word)
node = @the_node
results = []
word.split("").each do |letter|
next_node = node[letter]
if next_node != nil
node = next_node
next
else
return ['']
end
end
results << Word.new(word, node.final)
results += get_childs(node).map{|s| Word.new(word) + s}
results.select{|r| r.final}.map{|r| r.to_s }
end | [
"def",
"query",
"(",
"word",
")",
"node",
"=",
"@the_node",
"results",
"=",
"[",
"]",
"word",
".",
"split",
"(",
"\"\"",
")",
".",
"each",
"do",
"|",
"letter",
"|",
"next_node",
"=",
"node",
"[",
"letter",
"]",
"if",
"next_node",
"!=",
"nil",
"node",
"=",
"next_node",
"next",
"else",
"return",
"[",
"''",
"]",
"end",
"end",
"results",
"<<",
"Word",
".",
"new",
"(",
"word",
",",
"node",
".",
"final",
")",
"results",
"+=",
"get_childs",
"(",
"node",
")",
".",
"map",
"{",
"|",
"s",
"|",
"Word",
".",
"new",
"(",
"word",
")",
"+",
"s",
"}",
"results",
".",
"select",
"{",
"|",
"r",
"|",
"r",
".",
"final",
"}",
".",
"map",
"{",
"|",
"r",
"|",
"r",
".",
"to_s",
"}",
"end"
] | get all words with given prefix | [
"get",
"all",
"words",
"with",
"given",
"prefix"
] | 2f08b319b1d6ba6c98d938bd0742c3c74dc6acd9 | https://github.com/baltavay/dawg/blob/2f08b319b1d6ba6c98d938bd0742c3c74dc6acd9/lib/dawg/finder.rb#L22-L37 |
43 | flajann2/deep_dive | lib/deep_dive/deep_dive.rb | DeepDive.::Enumerable._add | def _add(v: nil, dupit: nil, oc: nil, patch: {})
unless _pairs?
case
when self.kind_of?(::Set)
when self.kind_of?(::Array)
self << _ob_maybe_repl(v: v, dupit: dupit, oc: oc, patch: patch)
else
raise DeepDiveException.new("Don't know how to add new elements for class #{self.class}")
end
else
self[v.first] = _ob_maybe_repl(v: v.last, dupit: dupit, oc: oc, patch: patch)
end
end | ruby | def _add(v: nil, dupit: nil, oc: nil, patch: {})
unless _pairs?
case
when self.kind_of?(::Set)
when self.kind_of?(::Array)
self << _ob_maybe_repl(v: v, dupit: dupit, oc: oc, patch: patch)
else
raise DeepDiveException.new("Don't know how to add new elements for class #{self.class}")
end
else
self[v.first] = _ob_maybe_repl(v: v.last, dupit: dupit, oc: oc, patch: patch)
end
end | [
"def",
"_add",
"(",
"v",
":",
"nil",
",",
"dupit",
":",
"nil",
",",
"oc",
":",
"nil",
",",
"patch",
":",
"{",
"}",
")",
"unless",
"_pairs?",
"case",
"when",
"self",
".",
"kind_of?",
"(",
"::",
"Set",
")",
"when",
"self",
".",
"kind_of?",
"(",
"::",
"Array",
")",
"self",
"<<",
"_ob_maybe_repl",
"(",
"v",
":",
"v",
",",
"dupit",
":",
"dupit",
",",
"oc",
":",
"oc",
",",
"patch",
":",
"patch",
")",
"else",
"raise",
"DeepDiveException",
".",
"new",
"(",
"\"Don't know how to add new elements for class #{self.class}\"",
")",
"end",
"else",
"self",
"[",
"v",
".",
"first",
"]",
"=",
"_ob_maybe_repl",
"(",
"v",
":",
"v",
".",
"last",
",",
"dupit",
":",
"dupit",
",",
"oc",
":",
"oc",
",",
"patch",
":",
"patch",
")",
"end",
"end"
] | add a single element to the enumerable.
You may pass a single parameter, or a key, value. In any case,
all will added.
Here all the logic will be present to handle the "special case"
enumerables. Most notedly, Hash and Array will require special
treatment. | [
"add",
"a",
"single",
"element",
"to",
"the",
"enumerable",
".",
"You",
"may",
"pass",
"a",
"single",
"parameter",
"or",
"a",
"key",
"value",
".",
"In",
"any",
"case",
"all",
"will",
"added",
"."
] | dae12cefe5706d76c4c3a37735ebef2e0d3f6cb0 | https://github.com/flajann2/deep_dive/blob/dae12cefe5706d76c4c3a37735ebef2e0d3f6cb0/lib/deep_dive/deep_dive.rb#L110-L122 |
44 | rightscale/right_chimp | lib/right_chimp/queue/chimp_queue.rb | Chimp.ChimpQueue.start | def start
self.sort_queues!
for i in (1..max_threads)
@threads << Thread.new(i) do
worker = QueueWorker.new
worker.delay = @delay
worker.retry_count = @retry_count
worker.run
end
end
end | ruby | def start
self.sort_queues!
for i in (1..max_threads)
@threads << Thread.new(i) do
worker = QueueWorker.new
worker.delay = @delay
worker.retry_count = @retry_count
worker.run
end
end
end | [
"def",
"start",
"self",
".",
"sort_queues!",
"for",
"i",
"in",
"(",
"1",
"..",
"max_threads",
")",
"@threads",
"<<",
"Thread",
".",
"new",
"(",
"i",
")",
"do",
"worker",
"=",
"QueueWorker",
".",
"new",
"worker",
".",
"delay",
"=",
"@delay",
"worker",
".",
"retry_count",
"=",
"@retry_count",
"worker",
".",
"run",
"end",
"end",
"end"
] | Start up queue runners | [
"Start",
"up",
"queue",
"runners"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/chimp_queue.rb#L35-L46 |
45 | rightscale/right_chimp | lib/right_chimp/queue/chimp_queue.rb | Chimp.ChimpQueue.push | def push(g, w)
raise "no group specified" unless g
create_group(g) if not ChimpQueue[g]
ChimpQueue[g].push(w) unless ChimpQueue[g].get_job(w.job_id)
end | ruby | def push(g, w)
raise "no group specified" unless g
create_group(g) if not ChimpQueue[g]
ChimpQueue[g].push(w) unless ChimpQueue[g].get_job(w.job_id)
end | [
"def",
"push",
"(",
"g",
",",
"w",
")",
"raise",
"\"no group specified\"",
"unless",
"g",
"create_group",
"(",
"g",
")",
"if",
"not",
"ChimpQueue",
"[",
"g",
"]",
"ChimpQueue",
"[",
"g",
"]",
".",
"push",
"(",
"w",
")",
"unless",
"ChimpQueue",
"[",
"g",
"]",
".",
"get_job",
"(",
"w",
".",
"job_id",
")",
"end"
] | Push a task into the queue | [
"Push",
"a",
"task",
"into",
"the",
"queue"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/chimp_queue.rb#L51-L56 |
46 | rightscale/right_chimp | lib/right_chimp/queue/chimp_queue.rb | Chimp.ChimpQueue.shift | def shift
r = nil
@semaphore.synchronize do
@group.values.each do |group|
if group.ready?
r = group.shift
Log.debug "Shifting job '#{r.job_id}' from group '#{group.group_id}'" unless r.nil?
break
end
end
end
return(r)
end | ruby | def shift
r = nil
@semaphore.synchronize do
@group.values.each do |group|
if group.ready?
r = group.shift
Log.debug "Shifting job '#{r.job_id}' from group '#{group.group_id}'" unless r.nil?
break
end
end
end
return(r)
end | [
"def",
"shift",
"r",
"=",
"nil",
"@semaphore",
".",
"synchronize",
"do",
"@group",
".",
"values",
".",
"each",
"do",
"|",
"group",
"|",
"if",
"group",
".",
"ready?",
"r",
"=",
"group",
".",
"shift",
"Log",
".",
"debug",
"\"Shifting job '#{r.job_id}' from group '#{group.group_id}'\"",
"unless",
"r",
".",
"nil?",
"break",
"end",
"end",
"end",
"return",
"(",
"r",
")",
"end"
] | Grab the oldest work item available | [
"Grab",
"the",
"oldest",
"work",
"item",
"available"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/chimp_queue.rb#L69-L81 |
47 | rightscale/right_chimp | lib/right_chimp/queue/chimp_queue.rb | Chimp.ChimpQueue.quit | def quit
i = 0
@group.keys.each do |group|
wait_until_done(group) do
if i < 30
sleep 1
i += 1
print "."
else
break
end
end
end
@threads.each { |t| t.kill }
puts " done."
end | ruby | def quit
i = 0
@group.keys.each do |group|
wait_until_done(group) do
if i < 30
sleep 1
i += 1
print "."
else
break
end
end
end
@threads.each { |t| t.kill }
puts " done."
end | [
"def",
"quit",
"i",
"=",
"0",
"@group",
".",
"keys",
".",
"each",
"do",
"|",
"group",
"|",
"wait_until_done",
"(",
"group",
")",
"do",
"if",
"i",
"<",
"30",
"sleep",
"1",
"i",
"+=",
"1",
"print",
"\".\"",
"else",
"break",
"end",
"end",
"end",
"@threads",
".",
"each",
"{",
"|",
"t",
"|",
"t",
".",
"kill",
"}",
"puts",
"\" done.\"",
"end"
] | Quit - empty the queue and wait for remaining jobs to complete | [
"Quit",
"-",
"empty",
"the",
"queue",
"and",
"wait",
"for",
"remaining",
"jobs",
"to",
"complete"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/chimp_queue.rb#L98-L114 |
48 | rightscale/right_chimp | lib/right_chimp/queue/chimp_queue.rb | Chimp.ChimpQueue.get_jobs_by_status | def get_jobs_by_status(status)
r = []
@group.values.each do |group|
v = group.get_jobs_by_status(status)
if v != nil and v != []
r += v
end
end
return r
end | ruby | def get_jobs_by_status(status)
r = []
@group.values.each do |group|
v = group.get_jobs_by_status(status)
if v != nil and v != []
r += v
end
end
return r
end | [
"def",
"get_jobs_by_status",
"(",
"status",
")",
"r",
"=",
"[",
"]",
"@group",
".",
"values",
".",
"each",
"do",
"|",
"group",
"|",
"v",
"=",
"group",
".",
"get_jobs_by_status",
"(",
"status",
")",
"if",
"v",
"!=",
"nil",
"and",
"v",
"!=",
"[",
"]",
"r",
"+=",
"v",
"end",
"end",
"return",
"r",
"end"
] | Return an array of all jobs with the requested
status. | [
"Return",
"an",
"array",
"of",
"all",
"jobs",
"with",
"the",
"requested",
"status",
"."
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/chimp_queue.rb#L151-L161 |
49 | ECHOInternational/your_membership | lib/your_membership/profile.rb | YourMembership.Profile.clean | def clean(data_hash)
clean_hash = {}
# Remove Nils
data_hash.each do |k, v|
clean_hash[k] = v if v
end
clean_hash
end | ruby | def clean(data_hash)
clean_hash = {}
# Remove Nils
data_hash.each do |k, v|
clean_hash[k] = v if v
end
clean_hash
end | [
"def",
"clean",
"(",
"data_hash",
")",
"clean_hash",
"=",
"{",
"}",
"# Remove Nils",
"data_hash",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"clean_hash",
"[",
"k",
"]",
"=",
"v",
"if",
"v",
"end",
"clean_hash",
"end"
] | Removes nil values | [
"Removes",
"nil",
"values"
] | b0154e668c265283b63c7986861db26426f9b700 | https://github.com/ECHOInternational/your_membership/blob/b0154e668c265283b63c7986861db26426f9b700/lib/your_membership/profile.rb#L83-L90 |
50 | rightscale/right_chimp | lib/right_chimp/queue/execution_group.rb | Chimp.ExecutionGroup.push | def push(j)
raise "invalid work" if j == nil
j.job_id = IDManager.get if j.job_id == nil
j.group = self
@queue.push(j)
@jobs_by_id[j.job_id] = j
end | ruby | def push(j)
raise "invalid work" if j == nil
j.job_id = IDManager.get if j.job_id == nil
j.group = self
@queue.push(j)
@jobs_by_id[j.job_id] = j
end | [
"def",
"push",
"(",
"j",
")",
"raise",
"\"invalid work\"",
"if",
"j",
"==",
"nil",
"j",
".",
"job_id",
"=",
"IDManager",
".",
"get",
"if",
"j",
".",
"job_id",
"==",
"nil",
"j",
".",
"group",
"=",
"self",
"@queue",
".",
"push",
"(",
"j",
")",
"@jobs_by_id",
"[",
"j",
".",
"job_id",
"]",
"=",
"j",
"end"
] | Add something to the work queue | [
"Add",
"something",
"to",
"the",
"work",
"queue"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/execution_group.rb#L42-L48 |
51 | rightscale/right_chimp | lib/right_chimp/queue/execution_group.rb | Chimp.ExecutionGroup.shift | def shift
updated_queue = []
found_job = nil
@queue.each do |job|
if found_job || job.status == Executor::STATUS_HOLDING
updated_queue.push(job)
elsif job.status == Executor::STATUS_NONE
found_job = job
end
end
@queue = updated_queue
@time_start = Time.now if @time_start == nil
return found_job
end | ruby | def shift
updated_queue = []
found_job = nil
@queue.each do |job|
if found_job || job.status == Executor::STATUS_HOLDING
updated_queue.push(job)
elsif job.status == Executor::STATUS_NONE
found_job = job
end
end
@queue = updated_queue
@time_start = Time.now if @time_start == nil
return found_job
end | [
"def",
"shift",
"updated_queue",
"=",
"[",
"]",
"found_job",
"=",
"nil",
"@queue",
".",
"each",
"do",
"|",
"job",
"|",
"if",
"found_job",
"||",
"job",
".",
"status",
"==",
"Executor",
"::",
"STATUS_HOLDING",
"updated_queue",
".",
"push",
"(",
"job",
")",
"elsif",
"job",
".",
"status",
"==",
"Executor",
"::",
"STATUS_NONE",
"found_job",
"=",
"job",
"end",
"end",
"@queue",
"=",
"updated_queue",
"@time_start",
"=",
"Time",
".",
"now",
"if",
"@time_start",
"==",
"nil",
"return",
"found_job",
"end"
] | Take something from the queue | [
"Take",
"something",
"from",
"the",
"queue"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/execution_group.rb#L53-L66 |
52 | rightscale/right_chimp | lib/right_chimp/queue/execution_group.rb | Chimp.ExecutionGroup.results | def results
return self.get_jobs.map do |task|
next if task == nil
next if task.server == nil
{
:job_id => task.job_id,
:name => task.info[0],
:host => task.server.name,
:status => task.status,
:error => task.error,
:total => self.get_total_execution_time(task.status, task.time_start, task.time_end),
:start => task.time_start,
:end => task.time_end,
:worker => task
}
end
end | ruby | def results
return self.get_jobs.map do |task|
next if task == nil
next if task.server == nil
{
:job_id => task.job_id,
:name => task.info[0],
:host => task.server.name,
:status => task.status,
:error => task.error,
:total => self.get_total_execution_time(task.status, task.time_start, task.time_end),
:start => task.time_start,
:end => task.time_end,
:worker => task
}
end
end | [
"def",
"results",
"return",
"self",
".",
"get_jobs",
".",
"map",
"do",
"|",
"task",
"|",
"next",
"if",
"task",
"==",
"nil",
"next",
"if",
"task",
".",
"server",
"==",
"nil",
"{",
":job_id",
"=>",
"task",
".",
"job_id",
",",
":name",
"=>",
"task",
".",
"info",
"[",
"0",
"]",
",",
":host",
"=>",
"task",
".",
"server",
".",
"name",
",",
":status",
"=>",
"task",
".",
"status",
",",
":error",
"=>",
"task",
".",
"error",
",",
":total",
"=>",
"self",
".",
"get_total_execution_time",
"(",
"task",
".",
"status",
",",
"task",
".",
"time_start",
",",
"task",
".",
"time_end",
")",
",",
":start",
"=>",
"task",
".",
"time_start",
",",
":end",
"=>",
"task",
".",
"time_end",
",",
":worker",
"=>",
"task",
"}",
"end",
"end"
] | Return a hash of the results | [
"Return",
"a",
"hash",
"of",
"the",
"results"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/execution_group.rb#L71-L87 |
53 | rightscale/right_chimp | lib/right_chimp/queue/execution_group.rb | Chimp.ExecutionGroup.sort! | def sort!
if @queue != nil
@queue.sort! do |a,b|
a.server.nickname <=> b.server.nickname
end
end
end | ruby | def sort!
if @queue != nil
@queue.sort! do |a,b|
a.server.nickname <=> b.server.nickname
end
end
end | [
"def",
"sort!",
"if",
"@queue",
"!=",
"nil",
"@queue",
".",
"sort!",
"do",
"|",
"a",
",",
"b",
"|",
"a",
".",
"server",
".",
"nickname",
"<=>",
"b",
".",
"server",
".",
"nickname",
"end",
"end",
"end"
] | Sort queue by server nickname | [
"Sort",
"queue",
"by",
"server",
"nickname"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/execution_group.rb#L99-L105 |
54 | rightscale/right_chimp | lib/right_chimp/queue/execution_group.rb | Chimp.ExecutionGroup.get_jobs_by_status | def get_jobs_by_status(status)
r = []
@jobs_by_id.values.each do |i|
r << i if i.status == status.to_sym || status.to_sym == :all
end
return r
end | ruby | def get_jobs_by_status(status)
r = []
@jobs_by_id.values.each do |i|
r << i if i.status == status.to_sym || status.to_sym == :all
end
return r
end | [
"def",
"get_jobs_by_status",
"(",
"status",
")",
"r",
"=",
"[",
"]",
"@jobs_by_id",
".",
"values",
".",
"each",
"do",
"|",
"i",
"|",
"r",
"<<",
"i",
"if",
"i",
".",
"status",
"==",
"status",
".",
"to_sym",
"||",
"status",
".",
"to_sym",
"==",
":all",
"end",
"return",
"r",
"end"
] | Get jobs by status | [
"Get",
"jobs",
"by",
"status"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/execution_group.rb#L138-L144 |
55 | rightscale/right_chimp | lib/right_chimp/queue/execution_group.rb | Chimp.ExecutionGroup.done? | def done?
return (
get_jobs_by_status(Executor::STATUS_NONE).size == 0 &&
get_jobs_by_status(Executor::STATUS_RUNNING).size == 0 &&
get_jobs_by_status(Executor::STATUS_DONE).size > 0
)
end | ruby | def done?
return (
get_jobs_by_status(Executor::STATUS_NONE).size == 0 &&
get_jobs_by_status(Executor::STATUS_RUNNING).size == 0 &&
get_jobs_by_status(Executor::STATUS_DONE).size > 0
)
end | [
"def",
"done?",
"return",
"(",
"get_jobs_by_status",
"(",
"Executor",
"::",
"STATUS_NONE",
")",
".",
"size",
"==",
"0",
"&&",
"get_jobs_by_status",
"(",
"Executor",
"::",
"STATUS_RUNNING",
")",
".",
"size",
"==",
"0",
"&&",
"get_jobs_by_status",
"(",
"Executor",
"::",
"STATUS_DONE",
")",
".",
"size",
">",
"0",
")",
"end"
] | An execution group is "done" if nothing is queued or running
and at least one job has completed. | [
"An",
"execution",
"group",
"is",
"done",
"if",
"nothing",
"is",
"queued",
"or",
"running",
"and",
"at",
"least",
"one",
"job",
"has",
"completed",
"."
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/execution_group.rb#L172-L178 |
56 | rightscale/right_chimp | lib/right_chimp/queue/execution_group.rb | Chimp.ExecutionGroup.running? | def running?
total_jobs_running = get_jobs_by_status(Executor::STATUS_NONE).size +
get_jobs_by_status(Executor::STATUS_RUNNING).size +
get_jobs_by_status(Executor::STATUS_RETRYING).size
(total_jobs_running > 0)
end | ruby | def running?
total_jobs_running = get_jobs_by_status(Executor::STATUS_NONE).size +
get_jobs_by_status(Executor::STATUS_RUNNING).size +
get_jobs_by_status(Executor::STATUS_RETRYING).size
(total_jobs_running > 0)
end | [
"def",
"running?",
"total_jobs_running",
"=",
"get_jobs_by_status",
"(",
"Executor",
"::",
"STATUS_NONE",
")",
".",
"size",
"+",
"get_jobs_by_status",
"(",
"Executor",
"::",
"STATUS_RUNNING",
")",
".",
"size",
"+",
"get_jobs_by_status",
"(",
"Executor",
"::",
"STATUS_RETRYING",
")",
".",
"size",
"(",
"total_jobs_running",
">",
"0",
")",
"end"
] | Is this execution group running anything? | [
"Is",
"this",
"execution",
"group",
"running",
"anything?"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/execution_group.rb#L183-L188 |
57 | rightscale/right_chimp | lib/right_chimp/queue/execution_group.rb | Chimp.ExecutionGroup.queue | def queue(id)
Log.debug "Queuing held job id #{id}"
job = @jobs_by_id[id]
job.owner = nil
job.time_start = Time.now
job.time_end = nil
job.status = Executor::STATUS_NONE
self.push(job)
end | ruby | def queue(id)
Log.debug "Queuing held job id #{id}"
job = @jobs_by_id[id]
job.owner = nil
job.time_start = Time.now
job.time_end = nil
job.status = Executor::STATUS_NONE
self.push(job)
end | [
"def",
"queue",
"(",
"id",
")",
"Log",
".",
"debug",
"\"Queuing held job id #{id}\"",
"job",
"=",
"@jobs_by_id",
"[",
"id",
"]",
"job",
".",
"owner",
"=",
"nil",
"job",
".",
"time_start",
"=",
"Time",
".",
"now",
"job",
".",
"time_end",
"=",
"nil",
"job",
".",
"status",
"=",
"Executor",
"::",
"STATUS_NONE",
"self",
".",
"push",
"(",
"job",
")",
"end"
] | Queue a held job by id | [
"Queue",
"a",
"held",
"job",
"by",
"id"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/execution_group.rb#L202-L210 |
58 | rightscale/right_chimp | lib/right_chimp/queue/execution_group.rb | Chimp.ExecutionGroup.cancel | def cancel(id)
Log.warn "Cancelling job id #{id}"
job = @jobs_by_id[id]
job.status = Executor::STATUS_ERROR
job.owner = nil
job.time_end = Time.now
@queue.delete(job)
end | ruby | def cancel(id)
Log.warn "Cancelling job id #{id}"
job = @jobs_by_id[id]
job.status = Executor::STATUS_ERROR
job.owner = nil
job.time_end = Time.now
@queue.delete(job)
end | [
"def",
"cancel",
"(",
"id",
")",
"Log",
".",
"warn",
"\"Cancelling job id #{id}\"",
"job",
"=",
"@jobs_by_id",
"[",
"id",
"]",
"job",
".",
"status",
"=",
"Executor",
"::",
"STATUS_ERROR",
"job",
".",
"owner",
"=",
"nil",
"job",
".",
"time_end",
"=",
"Time",
".",
"now",
"@queue",
".",
"delete",
"(",
"job",
")",
"end"
] | Cancel a job by id | [
"Cancel",
"a",
"job",
"by",
"id"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/execution_group.rb#L228-L235 |
59 | rayyanqcri/rayyan-scrapers | lib/rayyan-scrapers/entrez_scraper.rb | RayyanScrapers.EntrezScraper.parse_search_results | def parse_search_results(string, extraction_fields = nil)
xml = Nokogiri::XML.parse(string, "file:///rawfile.xml")
items = xml/"/#{@xml_element_root}/*"
total = items.length
@logger.debug("Found #{total} articles in input pubmed file")
items.each do |item|
begin
mArticle = RayyanFormats::Target.new
failed = false
case item.node_name
when @xml_element_root_article
process_article_detail_page(item, mArticle, extraction_fields)
when @xml_element_root_book
process_book_detail_page(item, mArticle, extraction_fields)
else
@logger.warn "Unknown XML format for search result of type #{item.node_name}"
failed = true
end
unless failed
pmid = ScraperBase.node_text item, './/PMID'
mArticle.sid = pmid
mArticle.url = "#{@detail_friendly_url}#{pmid}"
yield mArticle, total if block_given?
end # unless failed
rescue => exception
@logger.error "Error processing item in search result of type #{item.node_name} [#{exception}] " +
"caused by #{exception.backtrace.first}"
end # process item rescue
end # items.each
total
end | ruby | def parse_search_results(string, extraction_fields = nil)
xml = Nokogiri::XML.parse(string, "file:///rawfile.xml")
items = xml/"/#{@xml_element_root}/*"
total = items.length
@logger.debug("Found #{total} articles in input pubmed file")
items.each do |item|
begin
mArticle = RayyanFormats::Target.new
failed = false
case item.node_name
when @xml_element_root_article
process_article_detail_page(item, mArticle, extraction_fields)
when @xml_element_root_book
process_book_detail_page(item, mArticle, extraction_fields)
else
@logger.warn "Unknown XML format for search result of type #{item.node_name}"
failed = true
end
unless failed
pmid = ScraperBase.node_text item, './/PMID'
mArticle.sid = pmid
mArticle.url = "#{@detail_friendly_url}#{pmid}"
yield mArticle, total if block_given?
end # unless failed
rescue => exception
@logger.error "Error processing item in search result of type #{item.node_name} [#{exception}] " +
"caused by #{exception.backtrace.first}"
end # process item rescue
end # items.each
total
end | [
"def",
"parse_search_results",
"(",
"string",
",",
"extraction_fields",
"=",
"nil",
")",
"xml",
"=",
"Nokogiri",
"::",
"XML",
".",
"parse",
"(",
"string",
",",
"\"file:///rawfile.xml\"",
")",
"items",
"=",
"xml",
"/",
"\"/#{@xml_element_root}/*\"",
"total",
"=",
"items",
".",
"length",
"@logger",
".",
"debug",
"(",
"\"Found #{total} articles in input pubmed file\"",
")",
"items",
".",
"each",
"do",
"|",
"item",
"|",
"begin",
"mArticle",
"=",
"RayyanFormats",
"::",
"Target",
".",
"new",
"failed",
"=",
"false",
"case",
"item",
".",
"node_name",
"when",
"@xml_element_root_article",
"process_article_detail_page",
"(",
"item",
",",
"mArticle",
",",
"extraction_fields",
")",
"when",
"@xml_element_root_book",
"process_book_detail_page",
"(",
"item",
",",
"mArticle",
",",
"extraction_fields",
")",
"else",
"@logger",
".",
"warn",
"\"Unknown XML format for search result of type #{item.node_name}\"",
"failed",
"=",
"true",
"end",
"unless",
"failed",
"pmid",
"=",
"ScraperBase",
".",
"node_text",
"item",
",",
"'.//PMID'",
"mArticle",
".",
"sid",
"=",
"pmid",
"mArticle",
".",
"url",
"=",
"\"#{@detail_friendly_url}#{pmid}\"",
"yield",
"mArticle",
",",
"total",
"if",
"block_given?",
"end",
"# unless failed",
"rescue",
"=>",
"exception",
"@logger",
".",
"error",
"\"Error processing item in search result of type #{item.node_name} [#{exception}] \"",
"+",
"\"caused by #{exception.backtrace.first}\"",
"end",
"# process item rescue",
"end",
"# items.each",
"total",
"end"
] | user upload xml | [
"user",
"upload",
"xml"
] | 63d8b02987790ca08c06121775f95c49ed52c1b4 | https://github.com/rayyanqcri/rayyan-scrapers/blob/63d8b02987790ca08c06121775f95c49ed52c1b4/lib/rayyan-scrapers/entrez_scraper.rb#L201-L232 |
60 | 3scale/xcflushd | lib/xcflushd/priority_auth_renewer.rb | Xcflushd.PriorityAuthRenewer.async_renew_and_publish_task | def async_renew_and_publish_task(channel_msg)
Concurrent::Future.new(executor: thread_pool) do
success = true
begin
combination = auth_channel_msg_2_combination(channel_msg)
app_auths = app_authorizations(combination)
renew(combination[:service_id], combination[:credentials], app_auths)
metric_auth = app_auths[combination[:metric]]
rescue StandardError
# If we do not do rescue, we would not be able to process the same
# message again.
success = false
ensure
mark_auth_task_as_finished(channel_msg)
end
# We only publish a message when there aren't any errors. When
# success is false, we could have renewed some auths, so this could
# be more fine grained and ping the subscribers that are not interested
# in the auths that failed. Also, as we do not publish anything when
# there is an error, the subscriber waits until it timeouts.
# This is good enough for now, but there is room for improvement.
publish_auth(combination, metric_auth) if success
end
end | ruby | def async_renew_and_publish_task(channel_msg)
Concurrent::Future.new(executor: thread_pool) do
success = true
begin
combination = auth_channel_msg_2_combination(channel_msg)
app_auths = app_authorizations(combination)
renew(combination[:service_id], combination[:credentials], app_auths)
metric_auth = app_auths[combination[:metric]]
rescue StandardError
# If we do not do rescue, we would not be able to process the same
# message again.
success = false
ensure
mark_auth_task_as_finished(channel_msg)
end
# We only publish a message when there aren't any errors. When
# success is false, we could have renewed some auths, so this could
# be more fine grained and ping the subscribers that are not interested
# in the auths that failed. Also, as we do not publish anything when
# there is an error, the subscriber waits until it timeouts.
# This is good enough for now, but there is room for improvement.
publish_auth(combination, metric_auth) if success
end
end | [
"def",
"async_renew_and_publish_task",
"(",
"channel_msg",
")",
"Concurrent",
"::",
"Future",
".",
"new",
"(",
"executor",
":",
"thread_pool",
")",
"do",
"success",
"=",
"true",
"begin",
"combination",
"=",
"auth_channel_msg_2_combination",
"(",
"channel_msg",
")",
"app_auths",
"=",
"app_authorizations",
"(",
"combination",
")",
"renew",
"(",
"combination",
"[",
":service_id",
"]",
",",
"combination",
"[",
":credentials",
"]",
",",
"app_auths",
")",
"metric_auth",
"=",
"app_auths",
"[",
"combination",
"[",
":metric",
"]",
"]",
"rescue",
"StandardError",
"# If we do not do rescue, we would not be able to process the same",
"# message again.",
"success",
"=",
"false",
"ensure",
"mark_auth_task_as_finished",
"(",
"channel_msg",
")",
"end",
"# We only publish a message when there aren't any errors. When",
"# success is false, we could have renewed some auths, so this could",
"# be more fine grained and ping the subscribers that are not interested",
"# in the auths that failed. Also, as we do not publish anything when",
"# there is an error, the subscriber waits until it timeouts.",
"# This is good enough for now, but there is room for improvement.",
"publish_auth",
"(",
"combination",
",",
"metric_auth",
")",
"if",
"success",
"end",
"end"
] | Apart from renewing the auth of the combination received, we also renew
all the metrics of the associated application. The reason is that to renew
a single metric we need to perform one call to 3scale, and to renew all
the limited metrics of an application we also need one. If the metric
received does not have limits defined, we need to perform two calls, but
still it is worth to renew all of them for that price.
Note: Some exceptions can be raised inside the futures that are executed
by the thread pool. For example, when 3scale is not accessible, when
renewing the cached authorizations fails, or when publishing to the
response channels fails. Trying to recover from all those cases does not
seem to be worth it. The request that published the message will wait for
a response that will not arrive and eventually, it will timeout. However,
if the request retries, it is likely to succeed, as the kind of errors
listed above are (hopefully) temporary. | [
"Apart",
"from",
"renewing",
"the",
"auth",
"of",
"the",
"combination",
"received",
"we",
"also",
"renew",
"all",
"the",
"metrics",
"of",
"the",
"associated",
"application",
".",
"The",
"reason",
"is",
"that",
"to",
"renew",
"a",
"single",
"metric",
"we",
"need",
"to",
"perform",
"one",
"call",
"to",
"3scale",
"and",
"to",
"renew",
"all",
"the",
"limited",
"metrics",
"of",
"an",
"application",
"we",
"also",
"need",
"one",
".",
"If",
"the",
"metric",
"received",
"does",
"not",
"have",
"limits",
"defined",
"we",
"need",
"to",
"perform",
"two",
"calls",
"but",
"still",
"it",
"is",
"worth",
"to",
"renew",
"all",
"of",
"them",
"for",
"that",
"price",
"."
] | ca29b7674c3cd952a2a50c0604a99f04662bf27d | https://github.com/3scale/xcflushd/blob/ca29b7674c3cd952a2a50c0604a99f04662bf27d/lib/xcflushd/priority_auth_renewer.rb#L130-L154 |
61 | leandog/gametel | lib/gametel/accessors.rb | Gametel.Accessors.text | def text(name, locator)
define_method("#{name}") do
platform.get_text(locator)
end
define_method("#{name}=") do |value|
platform.enter_text(value, locator)
end
define_method("clear_#{name}") do
platform.clear_text(locator)
end
define_method("#{name}_view") do
Gametel::Views::Text.new(platform, locator)
end
end | ruby | def text(name, locator)
define_method("#{name}") do
platform.get_text(locator)
end
define_method("#{name}=") do |value|
platform.enter_text(value, locator)
end
define_method("clear_#{name}") do
platform.clear_text(locator)
end
define_method("#{name}_view") do
Gametel::Views::Text.new(platform, locator)
end
end | [
"def",
"text",
"(",
"name",
",",
"locator",
")",
"define_method",
"(",
"\"#{name}\"",
")",
"do",
"platform",
".",
"get_text",
"(",
"locator",
")",
"end",
"define_method",
"(",
"\"#{name}=\"",
")",
"do",
"|",
"value",
"|",
"platform",
".",
"enter_text",
"(",
"value",
",",
"locator",
")",
"end",
"define_method",
"(",
"\"clear_#{name}\"",
")",
"do",
"platform",
".",
"clear_text",
"(",
"locator",
")",
"end",
"define_method",
"(",
"\"#{name}_view\"",
")",
"do",
"Gametel",
"::",
"Views",
"::",
"Text",
".",
"new",
"(",
"platform",
",",
"locator",
")",
"end",
"end"
] | Generates methods to enter text into a text field, clear the text
field, get the hint as well as the description
@example
text(:first_name, :index => 0)
# will generate 'first_name', 'first_name=', 'clear_first_name', 'first_name_hint' and 'first_name_description' methods
@param [Symbol] the name used for the generated methods
@param [Hash] locator for how the text is found The valid
keys are:
* :id
* :index | [
"Generates",
"methods",
"to",
"enter",
"text",
"into",
"a",
"text",
"field",
"clear",
"the",
"text",
"field",
"get",
"the",
"hint",
"as",
"well",
"as",
"the",
"description"
] | fc9468da9a443b5e6ac553b3e445333a0eabfc18 | https://github.com/leandog/gametel/blob/fc9468da9a443b5e6ac553b3e445333a0eabfc18/lib/gametel/accessors.rb#L31-L44 |
62 | leandog/gametel | lib/gametel/accessors.rb | Gametel.Accessors.button | def button(name, locator)
define_method(name) do
platform.press_button(locator)
end
define_method("#{name}_view") do
Gametel::Views::Button.new(platform, locator)
end
end | ruby | def button(name, locator)
define_method(name) do
platform.press_button(locator)
end
define_method("#{name}_view") do
Gametel::Views::Button.new(platform, locator)
end
end | [
"def",
"button",
"(",
"name",
",",
"locator",
")",
"define_method",
"(",
"name",
")",
"do",
"platform",
".",
"press_button",
"(",
"locator",
")",
"end",
"define_method",
"(",
"\"#{name}_view\"",
")",
"do",
"Gametel",
"::",
"Views",
"::",
"Button",
".",
"new",
"(",
"platform",
",",
"locator",
")",
"end",
"end"
] | Generates a method to click a button and determine if it is enabled.
@example
button(:save, :text => 'Save')
# will generate 'save' and 'save_enabled?' methods
@param [Symbol] the name used for the generated methods
@param [Hash] locator for how the button is found The valid
keys are:
* :text
* :index
* :id | [
"Generates",
"a",
"method",
"to",
"click",
"a",
"button",
"and",
"determine",
"if",
"it",
"is",
"enabled",
"."
] | fc9468da9a443b5e6ac553b3e445333a0eabfc18 | https://github.com/leandog/gametel/blob/fc9468da9a443b5e6ac553b3e445333a0eabfc18/lib/gametel/accessors.rb#L60-L67 |
63 | leandog/gametel | lib/gametel/accessors.rb | Gametel.Accessors.list_item | def list_item(name, locator)
define_method(name) do
platform.press_list_item(locator)
end
define_method("#{name}_view") do
Gametel::Views::ListItem.new(platform, locator)
end
end | ruby | def list_item(name, locator)
define_method(name) do
platform.press_list_item(locator)
end
define_method("#{name}_view") do
Gametel::Views::ListItem.new(platform, locator)
end
end | [
"def",
"list_item",
"(",
"name",
",",
"locator",
")",
"define_method",
"(",
"name",
")",
"do",
"platform",
".",
"press_list_item",
"(",
"locator",
")",
"end",
"define_method",
"(",
"\"#{name}_view\"",
")",
"do",
"Gametel",
"::",
"Views",
"::",
"ListItem",
".",
"new",
"(",
"platform",
",",
"locator",
")",
"end",
"end"
] | Generates one method to click a list item.
@example
list_item(:details, :text => 'Details')
# will generate 'details' method
@example
list_item(:details, :index => 1, :list => 1)
# will generate 'details' method to select second item in the
# second list
@example
list_item(:details, :index => 2)
# will generate 'details' method to select third item in the
# first list
@param [Symbol] the name used for the generated methods
@param [Hash] locator for how the list item is found The valid
keys are:
* :text
* :index
* :list - only us with :index to indicate which list to use on
the screen. Default is 0 | [
"Generates",
"one",
"method",
"to",
"click",
"a",
"list",
"item",
"."
] | fc9468da9a443b5e6ac553b3e445333a0eabfc18 | https://github.com/leandog/gametel/blob/fc9468da9a443b5e6ac553b3e445333a0eabfc18/lib/gametel/accessors.rb#L94-L101 |
64 | leandog/gametel | lib/gametel/accessors.rb | Gametel.Accessors.checkbox | def checkbox(name, locator)
define_method(name) do
platform.click_checkbox(locator)
end
define_method("#{name}_checked?") do
Gametel::Views::CheckBox.new(platform, locator).checked?
end
define_method("#{name}_view") do
Gametel::Views::CheckBox.new(platform, locator)
end
end | ruby | def checkbox(name, locator)
define_method(name) do
platform.click_checkbox(locator)
end
define_method("#{name}_checked?") do
Gametel::Views::CheckBox.new(platform, locator).checked?
end
define_method("#{name}_view") do
Gametel::Views::CheckBox.new(platform, locator)
end
end | [
"def",
"checkbox",
"(",
"name",
",",
"locator",
")",
"define_method",
"(",
"name",
")",
"do",
"platform",
".",
"click_checkbox",
"(",
"locator",
")",
"end",
"define_method",
"(",
"\"#{name}_checked?\"",
")",
"do",
"Gametel",
"::",
"Views",
"::",
"CheckBox",
".",
"new",
"(",
"platform",
",",
"locator",
")",
".",
"checked?",
"end",
"define_method",
"(",
"\"#{name}_view\"",
")",
"do",
"Gametel",
"::",
"Views",
"::",
"CheckBox",
".",
"new",
"(",
"platform",
",",
"locator",
")",
"end",
"end"
] | Generates one method to click a checkbox.
@example
checkbox(:enable, :text => 'Enable')
# will generate 'enable' method
@param [Symbol] the name used for the generated methods
@param [Hash] locator for how the checkbox is found The valid
keys are:
* :text
* :index
* :id | [
"Generates",
"one",
"method",
"to",
"click",
"a",
"checkbox",
"."
] | fc9468da9a443b5e6ac553b3e445333a0eabfc18 | https://github.com/leandog/gametel/blob/fc9468da9a443b5e6ac553b3e445333a0eabfc18/lib/gametel/accessors.rb#L117-L127 |
65 | leandog/gametel | lib/gametel/accessors.rb | Gametel.Accessors.radio_button | def radio_button(name, locator)
define_method(name) do
platform.click_radio_button(locator)
end
define_method("#{name}_view") do
Gametel::Views::RadioButton.new(platform, locator)
end
end | ruby | def radio_button(name, locator)
define_method(name) do
platform.click_radio_button(locator)
end
define_method("#{name}_view") do
Gametel::Views::RadioButton.new(platform, locator)
end
end | [
"def",
"radio_button",
"(",
"name",
",",
"locator",
")",
"define_method",
"(",
"name",
")",
"do",
"platform",
".",
"click_radio_button",
"(",
"locator",
")",
"end",
"define_method",
"(",
"\"#{name}_view\"",
")",
"do",
"Gametel",
"::",
"Views",
"::",
"RadioButton",
".",
"new",
"(",
"platform",
",",
"locator",
")",
"end",
"end"
] | Generates one method to click a radio button.
@example
radio_button(:circle, :text => 'Circle')
# will generate 'circle' method
@param [Symbol] the name used for the generated methods
@param [Hash] locator for how the checkbox is found The valid
keys are:
* :text
* :index
* :id | [
"Generates",
"one",
"method",
"to",
"click",
"a",
"radio",
"button",
"."
] | fc9468da9a443b5e6ac553b3e445333a0eabfc18 | https://github.com/leandog/gametel/blob/fc9468da9a443b5e6ac553b3e445333a0eabfc18/lib/gametel/accessors.rb#L143-L150 |
66 | leandog/gametel | lib/gametel/accessors.rb | Gametel.Accessors.image | def image(name, locator)
define_method("click_#{name}") do
platform.click_image(locator)
end
define_method("wait_for_#{name}") do
wait_until do
platform.has_drawable?(locator)
end
end
define_method("#{name}_view") do
Gametel::Views::Image.new(platform, locator)
end
end | ruby | def image(name, locator)
define_method("click_#{name}") do
platform.click_image(locator)
end
define_method("wait_for_#{name}") do
wait_until do
platform.has_drawable?(locator)
end
end
define_method("#{name}_view") do
Gametel::Views::Image.new(platform, locator)
end
end | [
"def",
"image",
"(",
"name",
",",
"locator",
")",
"define_method",
"(",
"\"click_#{name}\"",
")",
"do",
"platform",
".",
"click_image",
"(",
"locator",
")",
"end",
"define_method",
"(",
"\"wait_for_#{name}\"",
")",
"do",
"wait_until",
"do",
"platform",
".",
"has_drawable?",
"(",
"locator",
")",
"end",
"end",
"define_method",
"(",
"\"#{name}_view\"",
")",
"do",
"Gametel",
"::",
"Views",
"::",
"Image",
".",
"new",
"(",
"platform",
",",
"locator",
")",
"end",
"end"
] | Generaes method to interact with an image.
@example
image(:headshot, :id => 'headshot')
# will generate 'click_headshot' method to click the image,
# 'wait_for_headshot' which will wait until the image has
# loaded a drawable and 'headshot_view' to return the view
@param [Symbol] the name used for the generated methods
@param [Hash] locator indicating an id for how the image is found.
The only valid keys are:
* :index | [
"Generaes",
"method",
"to",
"interact",
"with",
"an",
"image",
"."
] | fc9468da9a443b5e6ac553b3e445333a0eabfc18 | https://github.com/leandog/gametel/blob/fc9468da9a443b5e6ac553b3e445333a0eabfc18/lib/gametel/accessors.rb#L249-L261 |
67 | knowledge-ruby/knowledge | lib/knowledge/learner.rb | Knowledge.Learner.gather! | def gather!
::Knowledge::Initializer.new(
adapters: enabled_adapters,
params: additionnal_params,
setter: setter,
variables: variables
).run
end | ruby | def gather!
::Knowledge::Initializer.new(
adapters: enabled_adapters,
params: additionnal_params,
setter: setter,
variables: variables
).run
end | [
"def",
"gather!",
"::",
"Knowledge",
"::",
"Initializer",
".",
"new",
"(",
"adapters",
":",
"enabled_adapters",
",",
"params",
":",
"additionnal_params",
",",
"setter",
":",
"setter",
",",
"variables",
":",
"variables",
")",
".",
"run",
"end"
] | Gathers all the knowledge and put it into your app.
=== Usage
@example:
learner = Knowledge::Learner.new
# Do some config (add adapters, define your setter, etc.)
learner.gather! | [
"Gathers",
"all",
"the",
"knowledge",
"and",
"put",
"it",
"into",
"your",
"app",
"."
] | 64dcc9f138af9af513c341d933353ff31a52e104 | https://github.com/knowledge-ruby/knowledge/blob/64dcc9f138af9af513c341d933353ff31a52e104/lib/knowledge/learner.rb#L140-L147 |
68 | knowledge-ruby/knowledge | lib/knowledge/learner.rb | Knowledge.Learner.enable_adapter | def enable_adapter(name:, variables: nil)
_key, klass = available_adapters.find { |key, _klass| key.to_sym == name.to_sym }
raise Knowledge::AdapterNotFound, "Cannot find \"#{name}\" in available adapters" if klass.nil?
@enabled_adapters[name.to_sym] = klass
set_adapter_variables(name: name, variables: variables)
end | ruby | def enable_adapter(name:, variables: nil)
_key, klass = available_adapters.find { |key, _klass| key.to_sym == name.to_sym }
raise Knowledge::AdapterNotFound, "Cannot find \"#{name}\" in available adapters" if klass.nil?
@enabled_adapters[name.to_sym] = klass
set_adapter_variables(name: name, variables: variables)
end | [
"def",
"enable_adapter",
"(",
"name",
":",
",",
"variables",
":",
"nil",
")",
"_key",
",",
"klass",
"=",
"available_adapters",
".",
"find",
"{",
"|",
"key",
",",
"_klass",
"|",
"key",
".",
"to_sym",
"==",
"name",
".",
"to_sym",
"}",
"raise",
"Knowledge",
"::",
"AdapterNotFound",
",",
"\"Cannot find \\\"#{name}\\\" in available adapters\"",
"if",
"klass",
".",
"nil?",
"@enabled_adapters",
"[",
"name",
".",
"to_sym",
"]",
"=",
"klass",
"set_adapter_variables",
"(",
"name",
":",
"name",
",",
"variables",
":",
"variables",
")",
"end"
] | Enables an adapter.
=== Usage
@example:
learner = Knowledge::Learner.new
# Register your adapter
learner.register_adapter(name: :my_adapter, klass: MyAdapter)
# Now you can enable it
learner.enable_adapter(name: :my_adapter)
=== Errors
@raises [Knowledge::AdapterNotFound] if adapter is not available
=== Parameters
@param :name [String | Symbol]
@param :variables [Hash | String | nil] | [
"Enables",
"an",
"adapter",
"."
] | 64dcc9f138af9af513c341d933353ff31a52e104 | https://github.com/knowledge-ruby/knowledge/blob/64dcc9f138af9af513c341d933353ff31a52e104/lib/knowledge/learner.rb#L235-L242 |
69 | knowledge-ruby/knowledge | lib/knowledge/learner.rb | Knowledge.Learner.register_adapter | def register_adapter(name:, klass:, enable: false, variables: nil)
@available_adapters[name.to_sym] = klass
enable_adapter(name: name) if enable
set_adapter_variables(name: name, variables: variables)
end | ruby | def register_adapter(name:, klass:, enable: false, variables: nil)
@available_adapters[name.to_sym] = klass
enable_adapter(name: name) if enable
set_adapter_variables(name: name, variables: variables)
end | [
"def",
"register_adapter",
"(",
"name",
":",
",",
"klass",
":",
",",
"enable",
":",
"false",
",",
"variables",
":",
"nil",
")",
"@available_adapters",
"[",
"name",
".",
"to_sym",
"]",
"=",
"klass",
"enable_adapter",
"(",
"name",
":",
"name",
")",
"if",
"enable",
"set_adapter_variables",
"(",
"name",
":",
"name",
",",
"variables",
":",
"variables",
")",
"end"
] | Registers an adapter and enable it if asked.
=== Usage
@example:
learner = Knowledge::Learner.new
learner.register_adapter(name: :my_adapter, klass: MyAdapter, enable: true)
=== Parameters
@param :name [String | Symbol]
@param :klass [Class]
@param :enable [Boolean]
@param :variables [Hash | String | nil] | [
"Registers",
"an",
"adapter",
"and",
"enable",
"it",
"if",
"asked",
"."
] | 64dcc9f138af9af513c341d933353ff31a52e104 | https://github.com/knowledge-ruby/knowledge/blob/64dcc9f138af9af513c341d933353ff31a52e104/lib/knowledge/learner.rb#L261-L265 |
70 | knowledge-ruby/knowledge | lib/knowledge/learner.rb | Knowledge.Learner.set_adapter_variables | def set_adapter_variables(name:, variables: nil)
return unless variables
case variables
when Hash
set_adapter_variables_by_hash(name: name, variables: variables)
when String
set_adapter_variables(name: name, variables: yaml_content(variables))
else
raise "Unknown variables type #{variables.class}"
end
rescue StandardError => e
raise ::Knowledge::LearnError, e.message
end | ruby | def set_adapter_variables(name:, variables: nil)
return unless variables
case variables
when Hash
set_adapter_variables_by_hash(name: name, variables: variables)
when String
set_adapter_variables(name: name, variables: yaml_content(variables))
else
raise "Unknown variables type #{variables.class}"
end
rescue StandardError => e
raise ::Knowledge::LearnError, e.message
end | [
"def",
"set_adapter_variables",
"(",
"name",
":",
",",
"variables",
":",
"nil",
")",
"return",
"unless",
"variables",
"case",
"variables",
"when",
"Hash",
"set_adapter_variables_by_hash",
"(",
"name",
":",
"name",
",",
"variables",
":",
"variables",
")",
"when",
"String",
"set_adapter_variables",
"(",
"name",
":",
"name",
",",
"variables",
":",
"yaml_content",
"(",
"variables",
")",
")",
"else",
"raise",
"\"Unknown variables type #{variables.class}\"",
"end",
"rescue",
"StandardError",
"=>",
"e",
"raise",
"::",
"Knowledge",
"::",
"LearnError",
",",
"e",
".",
"message",
"end"
] | Sets variables for a given adapter.
=== Usage
@example:
learner = Knowledge::Learner.new
learner.set_adapter_variables(name: :default, variables: { foo: :bar })
=== Parameters
@param :name [String | Symbol]
@param :variables [Hash | nil] | [
"Sets",
"variables",
"for",
"a",
"given",
"adapter",
"."
] | 64dcc9f138af9af513c341d933353ff31a52e104 | https://github.com/knowledge-ruby/knowledge/blob/64dcc9f138af9af513c341d933353ff31a52e104/lib/knowledge/learner.rb#L282-L295 |
71 | knowledge-ruby/knowledge | lib/knowledge/learner.rb | Knowledge.Learner.set_adapter_variables_by_hash | def set_adapter_variables_by_hash(name:, variables:)
variables = variables[name.to_s] if variables.key?(name.to_s)
variables = variables[name.to_sym] if variables.key?(name.to_sym)
@variables[name.to_sym] = variables
end | ruby | def set_adapter_variables_by_hash(name:, variables:)
variables = variables[name.to_s] if variables.key?(name.to_s)
variables = variables[name.to_sym] if variables.key?(name.to_sym)
@variables[name.to_sym] = variables
end | [
"def",
"set_adapter_variables_by_hash",
"(",
"name",
":",
",",
"variables",
":",
")",
"variables",
"=",
"variables",
"[",
"name",
".",
"to_s",
"]",
"if",
"variables",
".",
"key?",
"(",
"name",
".",
"to_s",
")",
"variables",
"=",
"variables",
"[",
"name",
".",
"to_sym",
"]",
"if",
"variables",
".",
"key?",
"(",
"name",
".",
"to_sym",
")",
"@variables",
"[",
"name",
".",
"to_sym",
"]",
"=",
"variables",
"end"
] | Sets variables as a hash for a given adapter.
=== Usage
@example
learner = Knowledge::Learner.new
learner.set_adapter_variables_by_hash(name: :default, variables: { foo: :bar })
=== Parameters
@param :name [String | Symbol]
@param :variables [Hash] | [
"Sets",
"variables",
"as",
"a",
"hash",
"for",
"a",
"given",
"adapter",
"."
] | 64dcc9f138af9af513c341d933353ff31a52e104 | https://github.com/knowledge-ruby/knowledge/blob/64dcc9f138af9af513c341d933353ff31a52e104/lib/knowledge/learner.rb#L312-L316 |
72 | knowledge-ruby/knowledge | lib/knowledge/learner.rb | Knowledge.Learner.use | def use(name:, enable: true)
adapter = self.class.adapters[name.to_sym]
raise ::Knowledge::RegisterError, "Unable to register following: #{name}" if adapter.nil?
register_adapter(name: name.to_sym, klass: adapter, enable: enable)
end | ruby | def use(name:, enable: true)
adapter = self.class.adapters[name.to_sym]
raise ::Knowledge::RegisterError, "Unable to register following: #{name}" if adapter.nil?
register_adapter(name: name.to_sym, klass: adapter, enable: enable)
end | [
"def",
"use",
"(",
"name",
":",
",",
"enable",
":",
"true",
")",
"adapter",
"=",
"self",
".",
"class",
".",
"adapters",
"[",
"name",
".",
"to_sym",
"]",
"raise",
"::",
"Knowledge",
"::",
"RegisterError",
",",
"\"Unable to register following: #{name}\"",
"if",
"adapter",
".",
"nil?",
"register_adapter",
"(",
"name",
":",
"name",
".",
"to_sym",
",",
"klass",
":",
"adapter",
",",
"enable",
":",
"enable",
")",
"end"
] | Registers & enables one of the lib's default adapters.
If you're writing a gem to add an adapter to knowledge, please have a look at
Knowledge::Learned#register_default_adapter
=== Usage
@example:
learner = Knowledge::Learner.new
learner.use(name: :ssm)
=== Parameters
@param :name [String | Symbol]
@param :enable [Boolean] | [
"Registers",
"&",
"enables",
"one",
"of",
"the",
"lib",
"s",
"default",
"adapters",
"."
] | 64dcc9f138af9af513c341d933353ff31a52e104 | https://github.com/knowledge-ruby/knowledge/blob/64dcc9f138af9af513c341d933353ff31a52e104/lib/knowledge/learner.rb#L358-L364 |
73 | knowledge-ruby/knowledge | lib/knowledge/learner.rb | Knowledge.Learner.fetch_variables_config | def fetch_variables_config(path)
descriptor = yaml_content(path)
@variables = descriptor[::Knowledge.config.environment.to_s] || descriptor
end | ruby | def fetch_variables_config(path)
descriptor = yaml_content(path)
@variables = descriptor[::Knowledge.config.environment.to_s] || descriptor
end | [
"def",
"fetch_variables_config",
"(",
"path",
")",
"descriptor",
"=",
"yaml_content",
"(",
"path",
")",
"@variables",
"=",
"descriptor",
"[",
"::",
"Knowledge",
".",
"config",
".",
"environment",
".",
"to_s",
"]",
"||",
"descriptor",
"end"
] | Opens the config file and sets the variable config.
=== Parameters
@param path [String] | [
"Opens",
"the",
"config",
"file",
"and",
"sets",
"the",
"variable",
"config",
"."
] | 64dcc9f138af9af513c341d933353ff31a52e104 | https://github.com/knowledge-ruby/knowledge/blob/64dcc9f138af9af513c341d933353ff31a52e104/lib/knowledge/learner.rb#L418-L421 |
74 | cldwalker/boson-more | lib/boson/repo_index.rb | Boson.RepoIndex.update | def update(options={})
libraries_to_update = !exists? ? repo.all_libraries : options[:libraries] || changed_libraries
read_and_transfer(libraries_to_update)
if options[:verbose]
puts !exists? ? "Generating index for all #{libraries_to_update.size} libraries. Patience ... is a bitch" :
(libraries_to_update.empty? ? "No libraries indexed" :
"Indexing the following libraries: #{libraries_to_update.join(', ')}")
end
Manager.instance.failed_libraries = []
unless libraries_to_update.empty?
Manager.load(libraries_to_update, options.merge(:index=>true))
unless Manager.instance.failed_libraries.empty?
$stderr.puts("Error: These libraries failed to load while indexing: #{Manager.instance.failed_libraries.join(', ')}")
end
end
write(Manager.instance.failed_libraries)
end | ruby | def update(options={})
libraries_to_update = !exists? ? repo.all_libraries : options[:libraries] || changed_libraries
read_and_transfer(libraries_to_update)
if options[:verbose]
puts !exists? ? "Generating index for all #{libraries_to_update.size} libraries. Patience ... is a bitch" :
(libraries_to_update.empty? ? "No libraries indexed" :
"Indexing the following libraries: #{libraries_to_update.join(', ')}")
end
Manager.instance.failed_libraries = []
unless libraries_to_update.empty?
Manager.load(libraries_to_update, options.merge(:index=>true))
unless Manager.instance.failed_libraries.empty?
$stderr.puts("Error: These libraries failed to load while indexing: #{Manager.instance.failed_libraries.join(', ')}")
end
end
write(Manager.instance.failed_libraries)
end | [
"def",
"update",
"(",
"options",
"=",
"{",
"}",
")",
"libraries_to_update",
"=",
"!",
"exists?",
"?",
"repo",
".",
"all_libraries",
":",
"options",
"[",
":libraries",
"]",
"||",
"changed_libraries",
"read_and_transfer",
"(",
"libraries_to_update",
")",
"if",
"options",
"[",
":verbose",
"]",
"puts",
"!",
"exists?",
"?",
"\"Generating index for all #{libraries_to_update.size} libraries. Patience ... is a bitch\"",
":",
"(",
"libraries_to_update",
".",
"empty?",
"?",
"\"No libraries indexed\"",
":",
"\"Indexing the following libraries: #{libraries_to_update.join(', ')}\"",
")",
"end",
"Manager",
".",
"instance",
".",
"failed_libraries",
"=",
"[",
"]",
"unless",
"libraries_to_update",
".",
"empty?",
"Manager",
".",
"load",
"(",
"libraries_to_update",
",",
"options",
".",
"merge",
"(",
":index",
"=>",
"true",
")",
")",
"unless",
"Manager",
".",
"instance",
".",
"failed_libraries",
".",
"empty?",
"$stderr",
".",
"puts",
"(",
"\"Error: These libraries failed to load while indexing: #{Manager.instance.failed_libraries.join(', ')}\"",
")",
"end",
"end",
"write",
"(",
"Manager",
".",
"instance",
".",
"failed_libraries",
")",
"end"
] | Updates the index. | [
"Updates",
"the",
"index",
"."
] | f928ebc18d8641e038891f78896ae7251b97415c | https://github.com/cldwalker/boson-more/blob/f928ebc18d8641e038891f78896ae7251b97415c/lib/boson/repo_index.rb#L16-L32 |
75 | cldwalker/boson-more | lib/boson/repo_index.rb | Boson.RepoIndex.set_command_namespaces | def set_command_namespaces
lib_commands = @commands.inject({}) {|t,e| (t[e.lib] ||= []) << e; t }
namespace_libs = @libraries.select {|e| e.namespace(e.indexed_namespace) }
namespace_libs.each {|lib|
(lib_commands[lib.name] || []).each {|e| e.namespace = lib.namespace }
}
end | ruby | def set_command_namespaces
lib_commands = @commands.inject({}) {|t,e| (t[e.lib] ||= []) << e; t }
namespace_libs = @libraries.select {|e| e.namespace(e.indexed_namespace) }
namespace_libs.each {|lib|
(lib_commands[lib.name] || []).each {|e| e.namespace = lib.namespace }
}
end | [
"def",
"set_command_namespaces",
"lib_commands",
"=",
"@commands",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"t",
",",
"e",
"|",
"(",
"t",
"[",
"e",
".",
"lib",
"]",
"||=",
"[",
"]",
")",
"<<",
"e",
";",
"t",
"}",
"namespace_libs",
"=",
"@libraries",
".",
"select",
"{",
"|",
"e",
"|",
"e",
".",
"namespace",
"(",
"e",
".",
"indexed_namespace",
")",
"}",
"namespace_libs",
".",
"each",
"{",
"|",
"lib",
"|",
"(",
"lib_commands",
"[",
"lib",
".",
"name",
"]",
"||",
"[",
"]",
")",
".",
"each",
"{",
"|",
"e",
"|",
"e",
".",
"namespace",
"=",
"lib",
".",
"namespace",
"}",
"}",
"end"
] | set namespaces for commands | [
"set",
"namespaces",
"for",
"commands"
] | f928ebc18d8641e038891f78896ae7251b97415c | https://github.com/cldwalker/boson-more/blob/f928ebc18d8641e038891f78896ae7251b97415c/lib/boson/repo_index.rb#L85-L91 |
76 | cldwalker/boson-more | lib/boson/comment_inspector.rb | Boson.CommentInspector.scrape | def scrape(file_string, line, mod, attribute=nil)
hash = scrape_file(file_string, line) || {}
options = (arr = hash.delete(:option)) ? parse_option_comments(arr, mod) : {}
hash.select {|k,v| v && (attribute.nil? || attribute == k) }.each do |k,v|
hash[k] = EVAL_ATTRIBUTES.include?(k) ? eval_comment(v.join(' '), mod, k) : v.join(' ')
end
(hash[:options] ||= {}).merge!(options) if !options.empty?
attribute ? hash[attribute] : hash
end | ruby | def scrape(file_string, line, mod, attribute=nil)
hash = scrape_file(file_string, line) || {}
options = (arr = hash.delete(:option)) ? parse_option_comments(arr, mod) : {}
hash.select {|k,v| v && (attribute.nil? || attribute == k) }.each do |k,v|
hash[k] = EVAL_ATTRIBUTES.include?(k) ? eval_comment(v.join(' '), mod, k) : v.join(' ')
end
(hash[:options] ||= {}).merge!(options) if !options.empty?
attribute ? hash[attribute] : hash
end | [
"def",
"scrape",
"(",
"file_string",
",",
"line",
",",
"mod",
",",
"attribute",
"=",
"nil",
")",
"hash",
"=",
"scrape_file",
"(",
"file_string",
",",
"line",
")",
"||",
"{",
"}",
"options",
"=",
"(",
"arr",
"=",
"hash",
".",
"delete",
"(",
":option",
")",
")",
"?",
"parse_option_comments",
"(",
"arr",
",",
"mod",
")",
":",
"{",
"}",
"hash",
".",
"select",
"{",
"|",
"k",
",",
"v",
"|",
"v",
"&&",
"(",
"attribute",
".",
"nil?",
"||",
"attribute",
"==",
"k",
")",
"}",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"hash",
"[",
"k",
"]",
"=",
"EVAL_ATTRIBUTES",
".",
"include?",
"(",
"k",
")",
"?",
"eval_comment",
"(",
"v",
".",
"join",
"(",
"' '",
")",
",",
"mod",
",",
"k",
")",
":",
"v",
".",
"join",
"(",
"' '",
")",
"end",
"(",
"hash",
"[",
":options",
"]",
"||=",
"{",
"}",
")",
".",
"merge!",
"(",
"options",
")",
"if",
"!",
"options",
".",
"empty?",
"attribute",
"?",
"hash",
"[",
"attribute",
"]",
":",
"hash",
"end"
] | Given a method's file string, line number and defining module, returns a hash
of attributes defined for that method. | [
"Given",
"a",
"method",
"s",
"file",
"string",
"line",
"number",
"and",
"defining",
"module",
"returns",
"a",
"hash",
"of",
"attributes",
"defined",
"for",
"that",
"method",
"."
] | f928ebc18d8641e038891f78896ae7251b97415c | https://github.com/cldwalker/boson-more/blob/f928ebc18d8641e038891f78896ae7251b97415c/lib/boson/comment_inspector.rb#L25-L33 |
77 | cldwalker/boson-more | lib/boson/comment_inspector.rb | Boson.CommentInspector.scrape_file | def scrape_file(file_string, line)
lines = file_string.split("\n")
saved = []
i = line -2
while lines[i] =~ /^\s*#\s*(\S+)/ && i >= 0
saved << lines[i]
i -= 1
end
saved.empty? ? {} : splitter(saved.reverse)
end | ruby | def scrape_file(file_string, line)
lines = file_string.split("\n")
saved = []
i = line -2
while lines[i] =~ /^\s*#\s*(\S+)/ && i >= 0
saved << lines[i]
i -= 1
end
saved.empty? ? {} : splitter(saved.reverse)
end | [
"def",
"scrape_file",
"(",
"file_string",
",",
"line",
")",
"lines",
"=",
"file_string",
".",
"split",
"(",
"\"\\n\"",
")",
"saved",
"=",
"[",
"]",
"i",
"=",
"line",
"-",
"2",
"while",
"lines",
"[",
"i",
"]",
"=~",
"/",
"\\s",
"\\s",
"\\S",
"/",
"&&",
"i",
">=",
"0",
"saved",
"<<",
"lines",
"[",
"i",
"]",
"i",
"-=",
"1",
"end",
"saved",
".",
"empty?",
"?",
"{",
"}",
":",
"splitter",
"(",
"saved",
".",
"reverse",
")",
"end"
] | Scrapes a given string for commented @keywords, starting with the line above the given line | [
"Scrapes",
"a",
"given",
"string",
"for",
"commented"
] | f928ebc18d8641e038891f78896ae7251b97415c | https://github.com/cldwalker/boson-more/blob/f928ebc18d8641e038891f78896ae7251b97415c/lib/boson/comment_inspector.rb#L59-L69 |
78 | allenwq/settings_on_rails | lib/settings_on_rails/key_tree_builder.rb | SettingsOnRails.KeyTreeBuilder.build_nodes | def build_nodes
value = _target_column
for key in _key_chain
value[key] = {} unless value[key]
value = value[key]
end
end | ruby | def build_nodes
value = _target_column
for key in _key_chain
value[key] = {} unless value[key]
value = value[key]
end
end | [
"def",
"build_nodes",
"value",
"=",
"_target_column",
"for",
"key",
"in",
"_key_chain",
"value",
"[",
"key",
"]",
"=",
"{",
"}",
"unless",
"value",
"[",
"key",
"]",
"value",
"=",
"value",
"[",
"key",
"]",
"end",
"end"
] | Call this method before set any values | [
"Call",
"this",
"method",
"before",
"set",
"any",
"values"
] | b7b2580a40b674e85aa912cde27201ca245f6c41 | https://github.com/allenwq/settings_on_rails/blob/b7b2580a40b674e85aa912cde27201ca245f6c41/lib/settings_on_rails/key_tree_builder.rb#L27-L34 |
79 | allenwq/settings_on_rails | lib/settings_on_rails/key_tree_builder.rb | SettingsOnRails.KeyTreeBuilder._key_chain | def _key_chain
handler = self
key_chain = []
begin
key_chain = handler.keys + key_chain
handler = handler.parent
end while handler
key_chain
end | ruby | def _key_chain
handler = self
key_chain = []
begin
key_chain = handler.keys + key_chain
handler = handler.parent
end while handler
key_chain
end | [
"def",
"_key_chain",
"handler",
"=",
"self",
"key_chain",
"=",
"[",
"]",
"begin",
"key_chain",
"=",
"handler",
".",
"keys",
"+",
"key_chain",
"handler",
"=",
"handler",
".",
"parent",
"end",
"while",
"handler",
"key_chain",
"end"
] | Returns a key chain which includes all parent's keys and self keys | [
"Returns",
"a",
"key",
"chain",
"which",
"includes",
"all",
"parent",
"s",
"keys",
"and",
"self",
"keys"
] | b7b2580a40b674e85aa912cde27201ca245f6c41 | https://github.com/allenwq/settings_on_rails/blob/b7b2580a40b674e85aa912cde27201ca245f6c41/lib/settings_on_rails/key_tree_builder.rb#L50-L60 |
80 | bvandenbos/copyscape-rb | lib/copyscape/response.rb | Copyscape.Response.result_to_hash | def result_to_hash(result)
result.children.inject({}) do |hash, node|
hash[node.name] = node.text
hash[node.name] = node.text.to_i if node.text && node.text =~ /^\d+$/
hash
end
end | ruby | def result_to_hash(result)
result.children.inject({}) do |hash, node|
hash[node.name] = node.text
hash[node.name] = node.text.to_i if node.text && node.text =~ /^\d+$/
hash
end
end | [
"def",
"result_to_hash",
"(",
"result",
")",
"result",
".",
"children",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"hash",
",",
"node",
"|",
"hash",
"[",
"node",
".",
"name",
"]",
"=",
"node",
".",
"text",
"hash",
"[",
"node",
".",
"name",
"]",
"=",
"node",
".",
"text",
".",
"to_i",
"if",
"node",
".",
"text",
"&&",
"node",
".",
"text",
"=~",
"/",
"\\d",
"/",
"hash",
"end",
"end"
] | Given a result xml element, return a hash of the values we're interested in. | [
"Given",
"a",
"result",
"xml",
"element",
"return",
"a",
"hash",
"of",
"the",
"values",
"we",
"re",
"interested",
"in",
"."
] | c724da4cf9aa2b7a146a1a351f931a42c743fd8b | https://github.com/bvandenbos/copyscape-rb/blob/c724da4cf9aa2b7a146a1a351f931a42c743fd8b/lib/copyscape/response.rb#L55-L61 |
81 | PeterCamilleri/mini_readline | lib/mini_readline/read_line/history.rb | MiniReadline.History.append_history | def append_history(str)
return if @options[:no_blanks] && str.strip.empty?
if history.include?(str)
if @options[:no_dups]
return if @options[:no_move]
history.delete(str)
end
end
history << str
end | ruby | def append_history(str)
return if @options[:no_blanks] && str.strip.empty?
if history.include?(str)
if @options[:no_dups]
return if @options[:no_move]
history.delete(str)
end
end
history << str
end | [
"def",
"append_history",
"(",
"str",
")",
"return",
"if",
"@options",
"[",
":no_blanks",
"]",
"&&",
"str",
".",
"strip",
".",
"empty?",
"if",
"history",
".",
"include?",
"(",
"str",
")",
"if",
"@options",
"[",
":no_dups",
"]",
"return",
"if",
"@options",
"[",
":no_move",
"]",
"history",
".",
"delete",
"(",
"str",
")",
"end",
"end",
"history",
"<<",
"str",
"end"
] | Append a string to the history buffer if enabled. | [
"Append",
"a",
"string",
"to",
"the",
"history",
"buffer",
"if",
"enabled",
"."
] | 45175ee01653a184b8ba04b2e8691dce5b26a1b5 | https://github.com/PeterCamilleri/mini_readline/blob/45175ee01653a184b8ba04b2e8691dce5b26a1b5/lib/mini_readline/read_line/history.rb#L47-L59 |
82 | rightscale/right_chimp | lib/right_chimp/daemon/chimp_daemon.rb | Chimp.ChimpDaemon.parse_command_line | def parse_command_line
begin
opts = GetoptLong.new(
[ '--logfile', '-l', GetoptLong::REQUIRED_ARGUMENT ],
[ '--verbose', '-v', GetoptLong::NO_ARGUMENT ],
[ '--quiet', '-q', GetoptLong::NO_ARGUMENT ],
[ '--concurrency', '-c', GetoptLong::REQUIRED_ARGUMENT ],
[ '--delay', '-d', GetoptLong::REQUIRED_ARGUMENT ],
[ '--retry', '-y', GetoptLong::REQUIRED_ARGUMENT ],
[ '--port', '-p', GetoptLong::REQUIRED_ARGUMENT ],
[ '--bind-address', '-b', GetoptLong::REQUIRED_ARGUMENT ],
[ '--help', '-h', GetoptLong::NO_ARGUMENT ],
[ '--exit', '-x', GetoptLong::NO_ARGUMENT ]
)
opts.each do |opt, arg|
case opt
when '--logfile', '-l'
@logfile = arg
Log.logger = Logger.new(@logfile)
when '--concurrency', '-c'
@concurrency = arg.to_i
when '--delay', '-d'
@delay = arg.to_i
when '--retry', '-y'
@retry_count = arg.to_i
when '--verbose', '-v'
@verbose = true
when '--quiet', '-q'
@quiet = true
when '--port', '-p'
@port = arg
when '--bind-address', '-b'
@bind_address = arg.to_s
when '--help', '-h'
help
when '--exit', '-x'
uri = "http://localhost:#{@port}/admin"
response = RestClient.post uri, { 'shutdown' => true }.to_yaml
exit 0
end
end
rescue GetoptLong::InvalidOption => ex
puts "Syntax: chimpd [--logfile=<name>] [--concurrency=<c>] [--delay=<d>] [--retry=<r>] [--port=<p>] [--bind-address=<addr> ] [--verbose]"
exit 1
end
#
# Set up logging/verbosity
#
Chimp.set_verbose(@verbose, @quiet)
if not @verbose
ENV['REST_CONNECTION_LOG'] = "/dev/null"
ENV['RESTCLIENT_LOG'] = "/dev/null"
Log.threshold= Logger::INFO
else
Log.threshold= Logger::DEBUG
end
if @quiet
Log.threshold = Logger::WARN
end
end | ruby | def parse_command_line
begin
opts = GetoptLong.new(
[ '--logfile', '-l', GetoptLong::REQUIRED_ARGUMENT ],
[ '--verbose', '-v', GetoptLong::NO_ARGUMENT ],
[ '--quiet', '-q', GetoptLong::NO_ARGUMENT ],
[ '--concurrency', '-c', GetoptLong::REQUIRED_ARGUMENT ],
[ '--delay', '-d', GetoptLong::REQUIRED_ARGUMENT ],
[ '--retry', '-y', GetoptLong::REQUIRED_ARGUMENT ],
[ '--port', '-p', GetoptLong::REQUIRED_ARGUMENT ],
[ '--bind-address', '-b', GetoptLong::REQUIRED_ARGUMENT ],
[ '--help', '-h', GetoptLong::NO_ARGUMENT ],
[ '--exit', '-x', GetoptLong::NO_ARGUMENT ]
)
opts.each do |opt, arg|
case opt
when '--logfile', '-l'
@logfile = arg
Log.logger = Logger.new(@logfile)
when '--concurrency', '-c'
@concurrency = arg.to_i
when '--delay', '-d'
@delay = arg.to_i
when '--retry', '-y'
@retry_count = arg.to_i
when '--verbose', '-v'
@verbose = true
when '--quiet', '-q'
@quiet = true
when '--port', '-p'
@port = arg
when '--bind-address', '-b'
@bind_address = arg.to_s
when '--help', '-h'
help
when '--exit', '-x'
uri = "http://localhost:#{@port}/admin"
response = RestClient.post uri, { 'shutdown' => true }.to_yaml
exit 0
end
end
rescue GetoptLong::InvalidOption => ex
puts "Syntax: chimpd [--logfile=<name>] [--concurrency=<c>] [--delay=<d>] [--retry=<r>] [--port=<p>] [--bind-address=<addr> ] [--verbose]"
exit 1
end
#
# Set up logging/verbosity
#
Chimp.set_verbose(@verbose, @quiet)
if not @verbose
ENV['REST_CONNECTION_LOG'] = "/dev/null"
ENV['RESTCLIENT_LOG'] = "/dev/null"
Log.threshold= Logger::INFO
else
Log.threshold= Logger::DEBUG
end
if @quiet
Log.threshold = Logger::WARN
end
end | [
"def",
"parse_command_line",
"begin",
"opts",
"=",
"GetoptLong",
".",
"new",
"(",
"[",
"'--logfile'",
",",
"'-l'",
",",
"GetoptLong",
"::",
"REQUIRED_ARGUMENT",
"]",
",",
"[",
"'--verbose'",
",",
"'-v'",
",",
"GetoptLong",
"::",
"NO_ARGUMENT",
"]",
",",
"[",
"'--quiet'",
",",
"'-q'",
",",
"GetoptLong",
"::",
"NO_ARGUMENT",
"]",
",",
"[",
"'--concurrency'",
",",
"'-c'",
",",
"GetoptLong",
"::",
"REQUIRED_ARGUMENT",
"]",
",",
"[",
"'--delay'",
",",
"'-d'",
",",
"GetoptLong",
"::",
"REQUIRED_ARGUMENT",
"]",
",",
"[",
"'--retry'",
",",
"'-y'",
",",
"GetoptLong",
"::",
"REQUIRED_ARGUMENT",
"]",
",",
"[",
"'--port'",
",",
"'-p'",
",",
"GetoptLong",
"::",
"REQUIRED_ARGUMENT",
"]",
",",
"[",
"'--bind-address'",
",",
"'-b'",
",",
"GetoptLong",
"::",
"REQUIRED_ARGUMENT",
"]",
",",
"[",
"'--help'",
",",
"'-h'",
",",
"GetoptLong",
"::",
"NO_ARGUMENT",
"]",
",",
"[",
"'--exit'",
",",
"'-x'",
",",
"GetoptLong",
"::",
"NO_ARGUMENT",
"]",
")",
"opts",
".",
"each",
"do",
"|",
"opt",
",",
"arg",
"|",
"case",
"opt",
"when",
"'--logfile'",
",",
"'-l'",
"@logfile",
"=",
"arg",
"Log",
".",
"logger",
"=",
"Logger",
".",
"new",
"(",
"@logfile",
")",
"when",
"'--concurrency'",
",",
"'-c'",
"@concurrency",
"=",
"arg",
".",
"to_i",
"when",
"'--delay'",
",",
"'-d'",
"@delay",
"=",
"arg",
".",
"to_i",
"when",
"'--retry'",
",",
"'-y'",
"@retry_count",
"=",
"arg",
".",
"to_i",
"when",
"'--verbose'",
",",
"'-v'",
"@verbose",
"=",
"true",
"when",
"'--quiet'",
",",
"'-q'",
"@quiet",
"=",
"true",
"when",
"'--port'",
",",
"'-p'",
"@port",
"=",
"arg",
"when",
"'--bind-address'",
",",
"'-b'",
"@bind_address",
"=",
"arg",
".",
"to_s",
"when",
"'--help'",
",",
"'-h'",
"help",
"when",
"'--exit'",
",",
"'-x'",
"uri",
"=",
"\"http://localhost:#{@port}/admin\"",
"response",
"=",
"RestClient",
".",
"post",
"uri",
",",
"{",
"'shutdown'",
"=>",
"true",
"}",
".",
"to_yaml",
"exit",
"0",
"end",
"end",
"rescue",
"GetoptLong",
"::",
"InvalidOption",
"=>",
"ex",
"puts",
"\"Syntax: chimpd [--logfile=<name>] [--concurrency=<c>] [--delay=<d>] [--retry=<r>] [--port=<p>] [--bind-address=<addr> ] [--verbose]\"",
"exit",
"1",
"end",
"#",
"# Set up logging/verbosity",
"#",
"Chimp",
".",
"set_verbose",
"(",
"@verbose",
",",
"@quiet",
")",
"if",
"not",
"@verbose",
"ENV",
"[",
"'REST_CONNECTION_LOG'",
"]",
"=",
"\"/dev/null\"",
"ENV",
"[",
"'RESTCLIENT_LOG'",
"]",
"=",
"\"/dev/null\"",
"Log",
".",
"threshold",
"=",
"Logger",
"::",
"INFO",
"else",
"Log",
".",
"threshold",
"=",
"Logger",
"::",
"DEBUG",
"end",
"if",
"@quiet",
"Log",
".",
"threshold",
"=",
"Logger",
"::",
"WARN",
"end",
"end"
] | Parse chimpd command line options | [
"Parse",
"chimpd",
"command",
"line",
"options"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/daemon/chimp_daemon.rb#L55-L118 |
83 | rightscale/right_chimp | lib/right_chimp/daemon/chimp_daemon.rb | Chimp.ChimpDaemon.spawn_webserver | def spawn_webserver
opts = {
:BindAddress => @bind_address,
:Port => @port,
:MaxClients => 500,
:RequestTimeout => 120,
:DoNotReverseLookup => true
}
if not @verbose
opts[:Logger] = WEBrick::Log.new("/dev/null")
opts[:AccessLog] = [nil, nil]
end
@server = ::WEBrick::HTTPServer.new(opts)
@server.mount('/', DisplayServlet)
@server.mount('/display', DisplayServlet)
@server.mount('/job', JobServlet)
@server.mount('/group', GroupServlet)
@server.mount('/admin', AdminServlet)
#
# WEBrick threads
#
@threads << Thread.new(1001) do
@server.start
end
end | ruby | def spawn_webserver
opts = {
:BindAddress => @bind_address,
:Port => @port,
:MaxClients => 500,
:RequestTimeout => 120,
:DoNotReverseLookup => true
}
if not @verbose
opts[:Logger] = WEBrick::Log.new("/dev/null")
opts[:AccessLog] = [nil, nil]
end
@server = ::WEBrick::HTTPServer.new(opts)
@server.mount('/', DisplayServlet)
@server.mount('/display', DisplayServlet)
@server.mount('/job', JobServlet)
@server.mount('/group', GroupServlet)
@server.mount('/admin', AdminServlet)
#
# WEBrick threads
#
@threads << Thread.new(1001) do
@server.start
end
end | [
"def",
"spawn_webserver",
"opts",
"=",
"{",
":BindAddress",
"=>",
"@bind_address",
",",
":Port",
"=>",
"@port",
",",
":MaxClients",
"=>",
"500",
",",
":RequestTimeout",
"=>",
"120",
",",
":DoNotReverseLookup",
"=>",
"true",
"}",
"if",
"not",
"@verbose",
"opts",
"[",
":Logger",
"]",
"=",
"WEBrick",
"::",
"Log",
".",
"new",
"(",
"\"/dev/null\"",
")",
"opts",
"[",
":AccessLog",
"]",
"=",
"[",
"nil",
",",
"nil",
"]",
"end",
"@server",
"=",
"::",
"WEBrick",
"::",
"HTTPServer",
".",
"new",
"(",
"opts",
")",
"@server",
".",
"mount",
"(",
"'/'",
",",
"DisplayServlet",
")",
"@server",
".",
"mount",
"(",
"'/display'",
",",
"DisplayServlet",
")",
"@server",
".",
"mount",
"(",
"'/job'",
",",
"JobServlet",
")",
"@server",
".",
"mount",
"(",
"'/group'",
",",
"GroupServlet",
")",
"@server",
".",
"mount",
"(",
"'/admin'",
",",
"AdminServlet",
")",
"#",
"# WEBrick threads",
"#",
"@threads",
"<<",
"Thread",
".",
"new",
"(",
"1001",
")",
"do",
"@server",
".",
"start",
"end",
"end"
] | Spawn a WEBrick Web server | [
"Spawn",
"a",
"WEBrick",
"Web",
"server"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/daemon/chimp_daemon.rb#L161-L188 |
84 | rightscale/right_chimp | lib/right_chimp/daemon/chimp_daemon.rb | Chimp.ChimpDaemon.spawn_chimpd_submission_processor | def spawn_chimpd_submission_processor
n = @concurrency/4
n = 10 if n < 10
Log.debug "Logging into API..."
#
# There is a race condition logging in with rest_connection.
# As a workaround, do a tag query first thing when chimpd starts.
#
begin
c = Chimp.new
c.interactive = false
c.quiet = true
#c.tags = ["bogus:tag=true"]
c.run
rescue StandardError
end
puts "chimpd #{VERSION} launched with #{@concurrency} workers"
Log.debug "Spawning #{n} submission processing threads"
(1..n).each do |n|
@threads ||=[]
@threads << Thread.new {
while true
begin
queued_request = @chimp_queue.pop
group = queued_request.group
queued_request.interactive = false
tasks = queued_request.process
tasks.each do |task|
ChimpQueue.instance.push(group, task)
end
rescue StandardError => ex
puts ex.backtrace
Log.error " submission processor: group=\"#{group}\" script=\"#{queued_request.script}\": #{ex}"
end
end
}
end
end | ruby | def spawn_chimpd_submission_processor
n = @concurrency/4
n = 10 if n < 10
Log.debug "Logging into API..."
#
# There is a race condition logging in with rest_connection.
# As a workaround, do a tag query first thing when chimpd starts.
#
begin
c = Chimp.new
c.interactive = false
c.quiet = true
#c.tags = ["bogus:tag=true"]
c.run
rescue StandardError
end
puts "chimpd #{VERSION} launched with #{@concurrency} workers"
Log.debug "Spawning #{n} submission processing threads"
(1..n).each do |n|
@threads ||=[]
@threads << Thread.new {
while true
begin
queued_request = @chimp_queue.pop
group = queued_request.group
queued_request.interactive = false
tasks = queued_request.process
tasks.each do |task|
ChimpQueue.instance.push(group, task)
end
rescue StandardError => ex
puts ex.backtrace
Log.error " submission processor: group=\"#{group}\" script=\"#{queued_request.script}\": #{ex}"
end
end
}
end
end | [
"def",
"spawn_chimpd_submission_processor",
"n",
"=",
"@concurrency",
"/",
"4",
"n",
"=",
"10",
"if",
"n",
"<",
"10",
"Log",
".",
"debug",
"\"Logging into API...\"",
"#",
"# There is a race condition logging in with rest_connection.",
"# As a workaround, do a tag query first thing when chimpd starts.",
"#",
"begin",
"c",
"=",
"Chimp",
".",
"new",
"c",
".",
"interactive",
"=",
"false",
"c",
".",
"quiet",
"=",
"true",
"#c.tags = [\"bogus:tag=true\"]",
"c",
".",
"run",
"rescue",
"StandardError",
"end",
"puts",
"\"chimpd #{VERSION} launched with #{@concurrency} workers\"",
"Log",
".",
"debug",
"\"Spawning #{n} submission processing threads\"",
"(",
"1",
"..",
"n",
")",
".",
"each",
"do",
"|",
"n",
"|",
"@threads",
"||=",
"[",
"]",
"@threads",
"<<",
"Thread",
".",
"new",
"{",
"while",
"true",
"begin",
"queued_request",
"=",
"@chimp_queue",
".",
"pop",
"group",
"=",
"queued_request",
".",
"group",
"queued_request",
".",
"interactive",
"=",
"false",
"tasks",
"=",
"queued_request",
".",
"process",
"tasks",
".",
"each",
"do",
"|",
"task",
"|",
"ChimpQueue",
".",
"instance",
".",
"push",
"(",
"group",
",",
"task",
")",
"end",
"rescue",
"StandardError",
"=>",
"ex",
"puts",
"ex",
".",
"backtrace",
"Log",
".",
"error",
"\" submission processor: group=\\\"#{group}\\\" script=\\\"#{queued_request.script}\\\": #{ex}\"",
"end",
"end",
"}",
"end",
"end"
] | Spawn threads to process submitted requests | [
"Spawn",
"threads",
"to",
"process",
"submitted",
"requests"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/daemon/chimp_daemon.rb#L228-L271 |
85 | 3scale/xcflushd | lib/xcflushd/flusher_error_handler.rb | Xcflushd.FlusherErrorHandler.log | def log(exception)
msg = error_msg(exception)
case exception
when *NON_TEMP_ERRORS
logger.error(msg)
when *TEMP_ERRORS
logger.warn(msg)
else
logger.error(msg)
end
end | ruby | def log(exception)
msg = error_msg(exception)
case exception
when *NON_TEMP_ERRORS
logger.error(msg)
when *TEMP_ERRORS
logger.warn(msg)
else
logger.error(msg)
end
end | [
"def",
"log",
"(",
"exception",
")",
"msg",
"=",
"error_msg",
"(",
"exception",
")",
"case",
"exception",
"when",
"NON_TEMP_ERRORS",
"logger",
".",
"error",
"(",
"msg",
")",
"when",
"TEMP_ERRORS",
"logger",
".",
"warn",
"(",
"msg",
")",
"else",
"logger",
".",
"error",
"(",
"msg",
")",
"end",
"end"
] | For exceptions that are likely to require the user intervention, we log
errors. For example, when the report could not be made because the 3scale
client received an invalid provider key.
On the other hand, for errors that are likely to be temporary, like when
we could not connect with 3scale, we log a warning. | [
"For",
"exceptions",
"that",
"are",
"likely",
"to",
"require",
"the",
"user",
"intervention",
"we",
"log",
"errors",
".",
"For",
"example",
"when",
"the",
"report",
"could",
"not",
"be",
"made",
"because",
"the",
"3scale",
"client",
"received",
"an",
"invalid",
"provider",
"key",
".",
"On",
"the",
"other",
"hand",
"for",
"errors",
"that",
"are",
"likely",
"to",
"be",
"temporary",
"like",
"when",
"we",
"could",
"not",
"connect",
"with",
"3scale",
"we",
"log",
"a",
"warning",
"."
] | ca29b7674c3cd952a2a50c0604a99f04662bf27d | https://github.com/3scale/xcflushd/blob/ca29b7674c3cd952a2a50c0604a99f04662bf27d/lib/xcflushd/flusher_error_handler.rb#L61-L71 |
86 | emn178/sms_carrier | lib/sms_carrier/base.rb | SmsCarrier.Base.sms | def sms(options = {})
return @_message if @_sms_was_called && options.blank?
m = @_message
# Call all the procs (if any)
default_values = {}
self.class.default.each do |k,v|
default_values[k] = v.is_a?(Proc) ? instance_eval(&v) : v
end
# Handle defaults
options = options.reverse_merge(default_values)
# Set configure delivery behavior
wrap_delivery_behavior!(options.delete(:delivery_method), options.delete(:delivery_method_options))
# Assign all options except body, template_name, and template_path
assignable = options.except(:body, :template_name, :template_path)
assignable.each { |k, v| m[k] = v }
# Render the templates and blocks
m.body = response(options)
@_sms_was_called = true
m
end | ruby | def sms(options = {})
return @_message if @_sms_was_called && options.blank?
m = @_message
# Call all the procs (if any)
default_values = {}
self.class.default.each do |k,v|
default_values[k] = v.is_a?(Proc) ? instance_eval(&v) : v
end
# Handle defaults
options = options.reverse_merge(default_values)
# Set configure delivery behavior
wrap_delivery_behavior!(options.delete(:delivery_method), options.delete(:delivery_method_options))
# Assign all options except body, template_name, and template_path
assignable = options.except(:body, :template_name, :template_path)
assignable.each { |k, v| m[k] = v }
# Render the templates and blocks
m.body = response(options)
@_sms_was_called = true
m
end | [
"def",
"sms",
"(",
"options",
"=",
"{",
"}",
")",
"return",
"@_message",
"if",
"@_sms_was_called",
"&&",
"options",
".",
"blank?",
"m",
"=",
"@_message",
"# Call all the procs (if any)\r",
"default_values",
"=",
"{",
"}",
"self",
".",
"class",
".",
"default",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"default_values",
"[",
"k",
"]",
"=",
"v",
".",
"is_a?",
"(",
"Proc",
")",
"?",
"instance_eval",
"(",
"v",
")",
":",
"v",
"end",
"# Handle defaults\r",
"options",
"=",
"options",
".",
"reverse_merge",
"(",
"default_values",
")",
"# Set configure delivery behavior\r",
"wrap_delivery_behavior!",
"(",
"options",
".",
"delete",
"(",
":delivery_method",
")",
",",
"options",
".",
"delete",
"(",
":delivery_method_options",
")",
")",
"# Assign all options except body, template_name, and template_path\r",
"assignable",
"=",
"options",
".",
"except",
"(",
":body",
",",
":template_name",
",",
":template_path",
")",
"assignable",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"m",
"[",
"k",
"]",
"=",
"v",
"}",
"# Render the templates and blocks\r",
"m",
".",
"body",
"=",
"response",
"(",
"options",
")",
"@_sms_was_called",
"=",
"true",
"m",
"end"
] | The main method that creates the message and renders the SMS templates. There are
two ways to call this method, with a block, or without a block.
It accepts a headers hash. This hash allows you to specify
the most used headers in an SMS message, these are:
* +:to+ - Who the message is destined for, can be a string of addresses, or an array
of addresses.
* +:from+ - Who the message is from
You can set default values for any of the above headers (except +:date+)
by using the ::default class method:
class Notifier < SmsCarrier::Base
default from: '+886987654321'
end
If you do not pass a block to the +sms+ method, it will find all
templates in the view paths using by default the carrier name and the
method name that it is being called from, it will then create parts for
each of these templates intelligently, making educated guesses on correct
content type and sequence, and return a fully prepared <tt>Sms</tt>
ready to call <tt>:deliver</tt> on to send.
For example:
class Notifier < SmsCarrier::Base
default from: '[email protected]'
def welcome
sms(to: '[email protected]')
end
end
Will look for all templates at "app/views/notifier" with name "welcome".
If no welcome template exists, it will raise an ActionView::MissingTemplate error.
However, those can be customized:
sms(template_path: 'notifications', template_name: 'another')
And now it will look for all templates at "app/views/notifications" with name "another".
You can even render plain text directly without using a template:
sms(to: '+886987654321', body: 'Hello Mikel!') | [
"The",
"main",
"method",
"that",
"creates",
"the",
"message",
"and",
"renders",
"the",
"SMS",
"templates",
".",
"There",
"are",
"two",
"ways",
"to",
"call",
"this",
"method",
"with",
"a",
"block",
"or",
"without",
"a",
"block",
"."
] | 6aa97b46d8fa6e92db67a8cf5c81076d5ae1f9ad | https://github.com/emn178/sms_carrier/blob/6aa97b46d8fa6e92db67a8cf5c81076d5ae1f9ad/lib/sms_carrier/base.rb#L242-L268 |
87 | activenetwork/actv | lib/actv/client.rb | ACTV.Client.assets | def assets(q, params={})
response = get("/v2/search.json", params.merge(query: q))
ACTV::SearchResults.from_response(response)
end | ruby | def assets(q, params={})
response = get("/v2/search.json", params.merge(query: q))
ACTV::SearchResults.from_response(response)
end | [
"def",
"assets",
"(",
"q",
",",
"params",
"=",
"{",
"}",
")",
"response",
"=",
"get",
"(",
"\"/v2/search.json\"",
",",
"params",
".",
"merge",
"(",
"query",
":",
"q",
")",
")",
"ACTV",
"::",
"SearchResults",
".",
"from_response",
"(",
"response",
")",
"end"
] | Initialized a new Client object
@param options [Hash]
@return[ACTV::Client]
Returns assets that match a specified query.
@authentication_required No
@param q [String] A search term.
@param options [Hash] A customizable set of options.
@return [ACTV::SearchResults] Return assets that match a specified query with search metadata
@example Returns assets related to running
ACTV.assets('running')
ACTV.search('running') | [
"Initialized",
"a",
"new",
"Client",
"object"
] | 861222f5eccf81628221c71af8b8681789171402 | https://github.com/activenetwork/actv/blob/861222f5eccf81628221c71af8b8681789171402/lib/actv/client.rb#L66-L69 |
88 | activenetwork/actv | lib/actv/client.rb | ACTV.Client.organizer | def organizer(id, params={})
response = get("/v3/organizers/#{id}.json", params)
ACTV::Organizer.from_response response
end | ruby | def organizer(id, params={})
response = get("/v3/organizers/#{id}.json", params)
ACTV::Organizer.from_response response
end | [
"def",
"organizer",
"(",
"id",
",",
"params",
"=",
"{",
"}",
")",
"response",
"=",
"get",
"(",
"\"/v3/organizers/#{id}.json\"",
",",
"params",
")",
"ACTV",
"::",
"Organizer",
".",
"from_response",
"response",
"end"
] | Returns an organizer with the specified ID
@authentication_required No
@return ACTV::Organizer The requested organizer.
@param id [String] An assset ID.
@param options [Hash] A customizable set of options.
@example Return the organizer with the id AA388860-2718-4B20-B380-8F939596B123
ACTV.organizer("AA388860-2718-4B20-B380-8F939596B123") | [
"Returns",
"an",
"organizer",
"with",
"the",
"specified",
"ID"
] | 861222f5eccf81628221c71af8b8681789171402 | https://github.com/activenetwork/actv/blob/861222f5eccf81628221c71af8b8681789171402/lib/actv/client.rb#L87-L90 |
89 | activenetwork/actv | lib/actv/client.rb | ACTV.Client.find_asset_by_url | def find_asset_by_url(url)
url_md5 = Digest::MD5.hexdigest(url)
response = get("/v2/seourls/#{url_md5}?load_asset=true")
ACTV::Asset.from_response(response)
end | ruby | def find_asset_by_url(url)
url_md5 = Digest::MD5.hexdigest(url)
response = get("/v2/seourls/#{url_md5}?load_asset=true")
ACTV::Asset.from_response(response)
end | [
"def",
"find_asset_by_url",
"(",
"url",
")",
"url_md5",
"=",
"Digest",
"::",
"MD5",
".",
"hexdigest",
"(",
"url",
")",
"response",
"=",
"get",
"(",
"\"/v2/seourls/#{url_md5}?load_asset=true\"",
")",
"ACTV",
"::",
"Asset",
".",
"from_response",
"(",
"response",
")",
"end"
] | Returns an asset with the specified url path
@authentication_required No
@return [ACTV::Asset] The requested asset
@param path [String]
@example Return an asset with the url http://www.active.com/miami-fl/running/miami-marathon-and-half-marathon-2014
ACTV.asset_by_path("http://www.active.com/miami-fl/running/miami-marathon-and-half-marathon-2014") | [
"Returns",
"an",
"asset",
"with",
"the",
"specified",
"url",
"path"
] | 861222f5eccf81628221c71af8b8681789171402 | https://github.com/activenetwork/actv/blob/861222f5eccf81628221c71af8b8681789171402/lib/actv/client.rb#L113-L118 |
90 | activenetwork/actv | lib/actv/client.rb | ACTV.Client.articles | def articles(q, params={})
response = get("/v2/search.json", params.merge({query: q, category: 'articles'}))
ACTV::ArticleSearchResults.from_response(response)
end | ruby | def articles(q, params={})
response = get("/v2/search.json", params.merge({query: q, category: 'articles'}))
ACTV::ArticleSearchResults.from_response(response)
end | [
"def",
"articles",
"(",
"q",
",",
"params",
"=",
"{",
"}",
")",
"response",
"=",
"get",
"(",
"\"/v2/search.json\"",
",",
"params",
".",
"merge",
"(",
"{",
"query",
":",
"q",
",",
"category",
":",
"'articles'",
"}",
")",
")",
"ACTV",
"::",
"ArticleSearchResults",
".",
"from_response",
"(",
"response",
")",
"end"
] | Returns articles that match a specified query.
@authentication_required No
@param q [String] A search term.
@param options [Hash] A customizable set of options.
@return [ACTV::SearchResults] Return articles that match a specified query with search metadata
@example Returns articles related to running
ACTV.articles('running')
ACTV.articles('running') | [
"Returns",
"articles",
"that",
"match",
"a",
"specified",
"query",
"."
] | 861222f5eccf81628221c71af8b8681789171402 | https://github.com/activenetwork/actv/blob/861222f5eccf81628221c71af8b8681789171402/lib/actv/client.rb#L136-L139 |
91 | activenetwork/actv | lib/actv/client.rb | ACTV.Client.article | def article id, params={}
request_string = "/v2/assets/#{id}"
is_preview, params = params_include_preview? params
request_string += '/preview' if is_preview
response = get "#{request_string}.json", params
article = ACTV::Article.new response[:body]
article.is_article? ? article : nil
end | ruby | def article id, params={}
request_string = "/v2/assets/#{id}"
is_preview, params = params_include_preview? params
request_string += '/preview' if is_preview
response = get "#{request_string}.json", params
article = ACTV::Article.new response[:body]
article.is_article? ? article : nil
end | [
"def",
"article",
"id",
",",
"params",
"=",
"{",
"}",
"request_string",
"=",
"\"/v2/assets/#{id}\"",
"is_preview",
",",
"params",
"=",
"params_include_preview?",
"params",
"request_string",
"+=",
"'/preview'",
"if",
"is_preview",
"response",
"=",
"get",
"\"#{request_string}.json\"",
",",
"params",
"article",
"=",
"ACTV",
"::",
"Article",
".",
"new",
"response",
"[",
":body",
"]",
"article",
".",
"is_article?",
"?",
"article",
":",
"nil",
"end"
] | Returns an article with the specified ID
@authentication_required No
@return [ACTV::Article] The requested article.
@param id [String] An article ID.
@param options [Hash] A customizable set of options.
@example Return the article with the id BA288960-2718-4B20-B380-8F939596B123
ACTV.article("BA288960-2718-4B20-B380-8F939596B123") | [
"Returns",
"an",
"article",
"with",
"the",
"specified",
"ID"
] | 861222f5eccf81628221c71af8b8681789171402 | https://github.com/activenetwork/actv/blob/861222f5eccf81628221c71af8b8681789171402/lib/actv/client.rb#L149-L158 |
92 | activenetwork/actv | lib/actv/client.rb | ACTV.Client.popular_interests | def popular_interests(params={}, options={})
response = get("/interest/_search", params, options)
ACTV::PopularInterestSearchResults.from_response(response)
end | ruby | def popular_interests(params={}, options={})
response = get("/interest/_search", params, options)
ACTV::PopularInterestSearchResults.from_response(response)
end | [
"def",
"popular_interests",
"(",
"params",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"get",
"(",
"\"/interest/_search\"",
",",
"params",
",",
"options",
")",
"ACTV",
"::",
"PopularInterestSearchResults",
".",
"from_response",
"(",
"response",
")",
"end"
] | Returns popular interests
@authentication_required No
@param options [Hash] A customizable set of options.
@return [ACTV::PopularInterestSearchResults] Return intersts
@example Returns most popular interests
ACTV.popular_interests()
ACTV.popular_interests({per_page: 8}) | [
"Returns",
"popular",
"interests"
] | 861222f5eccf81628221c71af8b8681789171402 | https://github.com/activenetwork/actv/blob/861222f5eccf81628221c71af8b8681789171402/lib/actv/client.rb#L242-L245 |
93 | activenetwork/actv | lib/actv/client.rb | ACTV.Client.event_results | def event_results(assetId, assetTypeId, options={})
begin
response = get("/api/v1/events/#{assetId}/#{assetTypeId}.json", {}, options)
ACTV::EventResult.from_response(response)
rescue
nil
end
end | ruby | def event_results(assetId, assetTypeId, options={})
begin
response = get("/api/v1/events/#{assetId}/#{assetTypeId}.json", {}, options)
ACTV::EventResult.from_response(response)
rescue
nil
end
end | [
"def",
"event_results",
"(",
"assetId",
",",
"assetTypeId",
",",
"options",
"=",
"{",
"}",
")",
"begin",
"response",
"=",
"get",
"(",
"\"/api/v1/events/#{assetId}/#{assetTypeId}.json\"",
",",
"{",
"}",
",",
"options",
")",
"ACTV",
"::",
"EventResult",
".",
"from_response",
"(",
"response",
")",
"rescue",
"nil",
"end",
"end"
] | Returns a result with the specified asset ID and asset type ID
@authentication_required No
@return [ACTV::EventResult] The requested event result.
@param assetId [String] An asset ID.
@param assetTypeId [String] An asset type ID.
@example Return the result with the assetId 286F5731-9800-4C6E-ADD5-0E3B72392CA7 and assetTypeId 3BF82BBE-CF88-4E8C-A56F-78F5CE87E4C6
ACTV.event_results("286F5731-9800-4C6E-ADD5-0E3B72392CA7","3BF82BBE-CF88-4E8C-A56F-78F5CE87E4C6") | [
"Returns",
"a",
"result",
"with",
"the",
"specified",
"asset",
"ID",
"and",
"asset",
"type",
"ID"
] | 861222f5eccf81628221c71af8b8681789171402 | https://github.com/activenetwork/actv/blob/861222f5eccf81628221c71af8b8681789171402/lib/actv/client.rb#L269-L276 |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 60