repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
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 | train |
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 | train |
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",
"=",
"{",
"}",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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",
"rescue",
"=>",
"exception",
"@logger",
".",
"error",
"\"Error processing item in search result of type #{item.node_name} [#{exception}] \"",
"+",
"\"caused by #{exception.backtrace.first}\"",
"end",
"end",
"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 | train |
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",
"success",
"=",
"false",
"ensure",
"mark_auth_task_as_finished",
"(",
"channel_msg",
")",
"end",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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",
"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 | train |
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",
")",
"@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 | train |
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...\"",
"begin",
"c",
"=",
"Chimp",
".",
"new",
"c",
".",
"interactive",
"=",
"false",
"c",
".",
"quiet",
"=",
"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 | train |
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 | train |
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",
"default_values",
"=",
"{",
"}",
"self",
".",
"class",
".",
"default",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"default_values",
"[",
"k",
"]",
"=",
"v",
".",
"is_a?",
"(",
"Proc",
")",
"?",
"instance_eval",
"(",
"&",
"v",
")",
":",
"v",
"end",
"options",
"=",
"options",
".",
"reverse_merge",
"(",
"default_values",
")",
"wrap_delivery_behavior!",
"(",
"options",
".",
"delete",
"(",
":delivery_method",
")",
",",
"options",
".",
"delete",
"(",
":delivery_method_options",
")",
")",
"assignable",
"=",
"options",
".",
"except",
"(",
":body",
",",
":template_name",
",",
":template_path",
")",
"assignable",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"m",
"[",
"k",
"]",
"=",
"v",
"}",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
activenetwork/actv | lib/actv/client.rb | ACTV.Client.multi_search | def multi_search(*options)
results = []
query_index = 0
options_hash = options.inject({}) do |hash, options|
hash.merge! "query_#{query_index}" => "[#{URI.encode_www_form options}]"
query_index += 1
hash
end
if options_hash.present?
response = get("/v2/multisearch", options_hash)
response[:body].each_value do |sub_query|
sub_query[:results].each do |asset|
results << ACTV::Asset.from_response(body: asset)
end
end
end
results
end | ruby | def multi_search(*options)
results = []
query_index = 0
options_hash = options.inject({}) do |hash, options|
hash.merge! "query_#{query_index}" => "[#{URI.encode_www_form options}]"
query_index += 1
hash
end
if options_hash.present?
response = get("/v2/multisearch", options_hash)
response[:body].each_value do |sub_query|
sub_query[:results].each do |asset|
results << ACTV::Asset.from_response(body: asset)
end
end
end
results
end | [
"def",
"multi_search",
"(",
"*",
"options",
")",
"results",
"=",
"[",
"]",
"query_index",
"=",
"0",
"options_hash",
"=",
"options",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"hash",
",",
"options",
"|",
"hash",
".",
"merge!",
"\"query_#{query_index}\"",
"=>",
"\"[#{URI.encode_www_form options}]\"",
"query_index",
"+=",
"1",
"hash",
"end",
"if",
"options_hash",
".",
"present?",
"response",
"=",
"get",
"(",
"\"/v2/multisearch\"",
",",
"options_hash",
")",
"response",
"[",
":body",
"]",
".",
"each_value",
"do",
"|",
"sub_query",
"|",
"sub_query",
"[",
":results",
"]",
".",
"each",
"do",
"|",
"asset",
"|",
"results",
"<<",
"ACTV",
"::",
"Asset",
".",
"from_response",
"(",
"body",
":",
"asset",
")",
"end",
"end",
"end",
"results",
"end"
] | Returns results with multiple queries
@param options list of search options
@example ACTV.multi_search({category: 'event', per_page: 4}, {category: 'articles OR quiz', per_page: 5}) | [
"Returns",
"results",
"with",
"multiple",
"queries"
] | 861222f5eccf81628221c71af8b8681789171402 | https://github.com/activenetwork/actv/blob/861222f5eccf81628221c71af8b8681789171402/lib/actv/client.rb#L281-L301 | train |
activenetwork/actv | lib/actv/client.rb | ACTV.Client.request | def request(method, path, params, options)
uri = options[:endpoint] || @endpoint
uri = URI(uri) unless uri.respond_to?(:host)
uri += path
request_headers = {}
params[:api_key] = @api_key unless @api_key.nil?
if self.credentials?
# When posting a file, don't sign any params
signature_params = if [:post, :put].include?(method.to_sym) && params.values.any?{|value| value.is_a?(File) || (value.is_a?(Hash) && (value[:io].is_a?(IO) || value[:io].is_a?(StringIO)))}
{}
else
params
end
authorization = SimpleOAuth::Header.new(method, uri, signature_params, credentials)
request_headers[:authorization] = authorization.to_s.sub('OAuth', "Bearer")
end
connection.url_prefix = options[:endpoint] || @endpoint
connection.run_request(method.to_sym, path, nil, request_headers) do |request|
unless params.empty?
case request.method
when :post, :put
request.body = params
else
request.params.update(params)
end
end
yield request if block_given?
end.env
rescue Faraday::Error::ClientError
raise ACTV::Error::ClientError
end | ruby | def request(method, path, params, options)
uri = options[:endpoint] || @endpoint
uri = URI(uri) unless uri.respond_to?(:host)
uri += path
request_headers = {}
params[:api_key] = @api_key unless @api_key.nil?
if self.credentials?
# When posting a file, don't sign any params
signature_params = if [:post, :put].include?(method.to_sym) && params.values.any?{|value| value.is_a?(File) || (value.is_a?(Hash) && (value[:io].is_a?(IO) || value[:io].is_a?(StringIO)))}
{}
else
params
end
authorization = SimpleOAuth::Header.new(method, uri, signature_params, credentials)
request_headers[:authorization] = authorization.to_s.sub('OAuth', "Bearer")
end
connection.url_prefix = options[:endpoint] || @endpoint
connection.run_request(method.to_sym, path, nil, request_headers) do |request|
unless params.empty?
case request.method
when :post, :put
request.body = params
else
request.params.update(params)
end
end
yield request if block_given?
end.env
rescue Faraday::Error::ClientError
raise ACTV::Error::ClientError
end | [
"def",
"request",
"(",
"method",
",",
"path",
",",
"params",
",",
"options",
")",
"uri",
"=",
"options",
"[",
":endpoint",
"]",
"||",
"@endpoint",
"uri",
"=",
"URI",
"(",
"uri",
")",
"unless",
"uri",
".",
"respond_to?",
"(",
":host",
")",
"uri",
"+=",
"path",
"request_headers",
"=",
"{",
"}",
"params",
"[",
":api_key",
"]",
"=",
"@api_key",
"unless",
"@api_key",
".",
"nil?",
"if",
"self",
".",
"credentials?",
"signature_params",
"=",
"if",
"[",
":post",
",",
":put",
"]",
".",
"include?",
"(",
"method",
".",
"to_sym",
")",
"&&",
"params",
".",
"values",
".",
"any?",
"{",
"|",
"value",
"|",
"value",
".",
"is_a?",
"(",
"File",
")",
"||",
"(",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"(",
"value",
"[",
":io",
"]",
".",
"is_a?",
"(",
"IO",
")",
"||",
"value",
"[",
":io",
"]",
".",
"is_a?",
"(",
"StringIO",
")",
")",
")",
"}",
"{",
"}",
"else",
"params",
"end",
"authorization",
"=",
"SimpleOAuth",
"::",
"Header",
".",
"new",
"(",
"method",
",",
"uri",
",",
"signature_params",
",",
"credentials",
")",
"request_headers",
"[",
":authorization",
"]",
"=",
"authorization",
".",
"to_s",
".",
"sub",
"(",
"'OAuth'",
",",
"\"Bearer\"",
")",
"end",
"connection",
".",
"url_prefix",
"=",
"options",
"[",
":endpoint",
"]",
"||",
"@endpoint",
"connection",
".",
"run_request",
"(",
"method",
".",
"to_sym",
",",
"path",
",",
"nil",
",",
"request_headers",
")",
"do",
"|",
"request",
"|",
"unless",
"params",
".",
"empty?",
"case",
"request",
".",
"method",
"when",
":post",
",",
":put",
"request",
".",
"body",
"=",
"params",
"else",
"request",
".",
"params",
".",
"update",
"(",
"params",
")",
"end",
"end",
"yield",
"request",
"if",
"block_given?",
"end",
".",
"env",
"rescue",
"Faraday",
"::",
"Error",
"::",
"ClientError",
"raise",
"ACTV",
"::",
"Error",
"::",
"ClientError",
"end"
] | Perform an HTTP Request | [
"Perform",
"an",
"HTTP",
"Request"
] | 861222f5eccf81628221c71af8b8681789171402 | https://github.com/activenetwork/actv/blob/861222f5eccf81628221c71af8b8681789171402/lib/actv/client.rb#L373-L404 | train |
rberger/phaserunner | lib/phaserunner/modbus.rb | Phaserunner.Modbus.bulk_log_data | def bulk_log_data(registers = register_list)
registers.map do |reg|
read_scaled_range(reg.start, reg.count)
end.flatten
end | ruby | def bulk_log_data(registers = register_list)
registers.map do |reg|
read_scaled_range(reg.start, reg.count)
end.flatten
end | [
"def",
"bulk_log_data",
"(",
"registers",
"=",
"register_list",
")",
"registers",
".",
"map",
"do",
"|",
"reg",
"|",
"read_scaled_range",
"(",
"reg",
".",
"start",
",",
"reg",
".",
"count",
")",
"end",
".",
"flatten",
"end"
] | More optimized data fetch. Gets an array of address range structs
@param register_list [Array<RegistersRunLength] Register ranges to log. Optional, has a default
@return [Array<Integer>] List of the register values in the order requested | [
"More",
"optimized",
"data",
"fetch",
".",
"Gets",
"an",
"array",
"of",
"address",
"range",
"structs"
] | bc1d7c94381c1a3547f5badd581c2f40eefdd807 | https://github.com/rberger/phaserunner/blob/bc1d7c94381c1a3547f5badd581c2f40eefdd807/lib/phaserunner/modbus.rb#L148-L152 | train |
rberger/phaserunner | lib/phaserunner/modbus.rb | Phaserunner.Modbus.bulk_log_header | def bulk_log_header(registers = register_list)
registers.map do |reg|
range_address_header(reg.start, reg.count)
end.flatten
end | ruby | def bulk_log_header(registers = register_list)
registers.map do |reg|
range_address_header(reg.start, reg.count)
end.flatten
end | [
"def",
"bulk_log_header",
"(",
"registers",
"=",
"register_list",
")",
"registers",
".",
"map",
"do",
"|",
"reg",
"|",
"range_address_header",
"(",
"reg",
".",
"start",
",",
"reg",
".",
"count",
")",
"end",
".",
"flatten",
"end"
] | Get the headers for the bulk_log data
@param register_list [Array<RegistersRunLength] Register ranges to log. Optional, has a default
@return [Array<String>] Array of the headers | [
"Get",
"the",
"headers",
"for",
"the",
"bulk_log",
"data"
] | bc1d7c94381c1a3547f5badd581c2f40eefdd807 | https://github.com/rberger/phaserunner/blob/bc1d7c94381c1a3547f5badd581c2f40eefdd807/lib/phaserunner/modbus.rb#L157-L161 | train |
allenwq/settings_on_rails | lib/settings_on_rails/has_settings.rb | SettingsOnRails.HasSettings.key | def key(*keys)
options = keys.extract_options!
raise ArgumentError.new("has_settings: Option :defaults expected, but got #{options.keys.join(', ')}") unless options.blank? || (options.keys == [:defaults])
keys.each do |key_name|
unless key_name.is_a?(Symbol) || key_name.is_a?(String)
raise ArgumentError.new("has_settings: symbol or string expected, but got a #{key_name.class}")
end
end
options[:defaults].each do |k, v|
has_settings(*keys).attr(k, default: v)
end
end | ruby | def key(*keys)
options = keys.extract_options!
raise ArgumentError.new("has_settings: Option :defaults expected, but got #{options.keys.join(', ')}") unless options.blank? || (options.keys == [:defaults])
keys.each do |key_name|
unless key_name.is_a?(Symbol) || key_name.is_a?(String)
raise ArgumentError.new("has_settings: symbol or string expected, but got a #{key_name.class}")
end
end
options[:defaults].each do |k, v|
has_settings(*keys).attr(k, default: v)
end
end | [
"def",
"key",
"(",
"*",
"keys",
")",
"options",
"=",
"keys",
".",
"extract_options!",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"has_settings: Option :defaults expected, but got #{options.keys.join(', ')}\"",
")",
"unless",
"options",
".",
"blank?",
"||",
"(",
"options",
".",
"keys",
"==",
"[",
":defaults",
"]",
")",
"keys",
".",
"each",
"do",
"|",
"key_name",
"|",
"unless",
"key_name",
".",
"is_a?",
"(",
"Symbol",
")",
"||",
"key_name",
".",
"is_a?",
"(",
"String",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"has_settings: symbol or string expected, but got a #{key_name.class}\"",
")",
"end",
"end",
"options",
"[",
":defaults",
"]",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"has_settings",
"(",
"*",
"keys",
")",
".",
"attr",
"(",
"k",
",",
"default",
":",
"v",
")",
"end",
"end"
] | Declare a key, with default values
@param [Symbol] keys
@param [Hash] options, the last param must be an option with a defaults hash | [
"Declare",
"a",
"key",
"with",
"default",
"values"
] | b7b2580a40b674e85aa912cde27201ca245f6c41 | https://github.com/allenwq/settings_on_rails/blob/b7b2580a40b674e85aa912cde27201ca245f6c41/lib/settings_on_rails/has_settings.rb#L24-L36 | train |
allenwq/settings_on_rails | lib/settings_on_rails/has_settings.rb | SettingsOnRails.HasSettings.attr | def attr(value, options = {})
unless value.is_a?(Symbol) || value.is_a?(String)
raise ArgumentError.new("has_settings: symbol expected, but got a #{value.class}")
end
raise ArgumentError.new("has_settings: Option :default expected, but got #{options.keys.join(', ')}") unless options.blank? || (options.keys == [:default])
default_value = options[:default]
raise 'Error' unless value.to_s =~ REGEX_ATTR
_set_value(value.to_s, default_value)
end | ruby | def attr(value, options = {})
unless value.is_a?(Symbol) || value.is_a?(String)
raise ArgumentError.new("has_settings: symbol expected, but got a #{value.class}")
end
raise ArgumentError.new("has_settings: Option :default expected, but got #{options.keys.join(', ')}") unless options.blank? || (options.keys == [:default])
default_value = options[:default]
raise 'Error' unless value.to_s =~ REGEX_ATTR
_set_value(value.to_s, default_value)
end | [
"def",
"attr",
"(",
"value",
",",
"options",
"=",
"{",
"}",
")",
"unless",
"value",
".",
"is_a?",
"(",
"Symbol",
")",
"||",
"value",
".",
"is_a?",
"(",
"String",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"has_settings: symbol expected, but got a #{value.class}\"",
")",
"end",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"has_settings: Option :default expected, but got #{options.keys.join(', ')}\"",
")",
"unless",
"options",
".",
"blank?",
"||",
"(",
"options",
".",
"keys",
"==",
"[",
":default",
"]",
")",
"default_value",
"=",
"options",
"[",
":default",
"]",
"raise",
"'Error'",
"unless",
"value",
".",
"to_s",
"=~",
"REGEX_ATTR",
"_set_value",
"(",
"value",
".",
"to_s",
",",
"default_value",
")",
"end"
] | Declare an attribute with default value
@param [Symbol] value
@param [Hash] options, options with a default Hash | [
"Declare",
"an",
"attribute",
"with",
"default",
"value"
] | b7b2580a40b674e85aa912cde27201ca245f6c41 | https://github.com/allenwq/settings_on_rails/blob/b7b2580a40b674e85aa912cde27201ca245f6c41/lib/settings_on_rails/has_settings.rb#L42-L52 | train |
varvet/stomp_parser | lib/stomp_parser/frame.rb | StompParser.Frame.content_encoding | def content_encoding
if content_type = headers["content-type"]
mime_type, charset = content_type.split(SEMICOLON, 2)
charset = charset[CHARSET_OFFSET] if charset
charset ||= EMPTY
if charset.empty? and mime_type.start_with?("text/")
Encoding::UTF_8
elsif charset.empty?
Encoding::BINARY
else
ENCODINGS[charset] or raise StompParser::InvalidEncodingError, "invalid encoding #{charset.inspect}"
end
else
Encoding::BINARY
end
end | ruby | def content_encoding
if content_type = headers["content-type"]
mime_type, charset = content_type.split(SEMICOLON, 2)
charset = charset[CHARSET_OFFSET] if charset
charset ||= EMPTY
if charset.empty? and mime_type.start_with?("text/")
Encoding::UTF_8
elsif charset.empty?
Encoding::BINARY
else
ENCODINGS[charset] or raise StompParser::InvalidEncodingError, "invalid encoding #{charset.inspect}"
end
else
Encoding::BINARY
end
end | [
"def",
"content_encoding",
"if",
"content_type",
"=",
"headers",
"[",
"\"content-type\"",
"]",
"mime_type",
",",
"charset",
"=",
"content_type",
".",
"split",
"(",
"SEMICOLON",
",",
"2",
")",
"charset",
"=",
"charset",
"[",
"CHARSET_OFFSET",
"]",
"if",
"charset",
"charset",
"||=",
"EMPTY",
"if",
"charset",
".",
"empty?",
"and",
"mime_type",
".",
"start_with?",
"(",
"\"text/\"",
")",
"Encoding",
"::",
"UTF_8",
"elsif",
"charset",
".",
"empty?",
"Encoding",
"::",
"BINARY",
"else",
"ENCODINGS",
"[",
"charset",
"]",
"or",
"raise",
"StompParser",
"::",
"InvalidEncodingError",
",",
"\"invalid encoding #{charset.inspect}\"",
"end",
"else",
"Encoding",
"::",
"BINARY",
"end",
"end"
] | Determine content encoding by reviewing message headers.
@raise [InvalidEncodingError] if encoding does not exist in Ruby
@return [Encoding] | [
"Determine",
"content",
"encoding",
"by",
"reviewing",
"message",
"headers",
"."
] | 039f6fa417ac2deef7a0ba4787f9d738dfdc6549 | https://github.com/varvet/stomp_parser/blob/039f6fa417ac2deef7a0ba4787f9d738dfdc6549/lib/stomp_parser/frame.rb#L112-L128 | train |
varvet/stomp_parser | lib/stomp_parser/frame.rb | StompParser.Frame.write_header | def write_header(key, value)
# @see http://stomp.github.io/stomp-specification-1.2.html#Repeated_Header_Entries
key = decode_header(key)
@headers[key] = decode_header(value) unless @headers.has_key?(key)
end | ruby | def write_header(key, value)
# @see http://stomp.github.io/stomp-specification-1.2.html#Repeated_Header_Entries
key = decode_header(key)
@headers[key] = decode_header(value) unless @headers.has_key?(key)
end | [
"def",
"write_header",
"(",
"key",
",",
"value",
")",
"key",
"=",
"decode_header",
"(",
"key",
")",
"@headers",
"[",
"key",
"]",
"=",
"decode_header",
"(",
"value",
")",
"unless",
"@headers",
".",
"has_key?",
"(",
"key",
")",
"end"
] | Write a single header to this frame.
@param [String] key
@param [String] value | [
"Write",
"a",
"single",
"header",
"to",
"this",
"frame",
"."
] | 039f6fa417ac2deef7a0ba4787f9d738dfdc6549 | https://github.com/varvet/stomp_parser/blob/039f6fa417ac2deef7a0ba4787f9d738dfdc6549/lib/stomp_parser/frame.rb#L141-L145 | train |
ejlangev/citibike | lib/citibike/client.rb | Citibike.Client.stations | def stations
resp = self.connection.request(
:get,
Citibike::Station.path
)
return resp if @options[:unwrapped]
Citibike::Responses::Station.new(resp)
end | ruby | def stations
resp = self.connection.request(
:get,
Citibike::Station.path
)
return resp if @options[:unwrapped]
Citibike::Responses::Station.new(resp)
end | [
"def",
"stations",
"resp",
"=",
"self",
".",
"connection",
".",
"request",
"(",
":get",
",",
"Citibike",
"::",
"Station",
".",
"path",
")",
"return",
"resp",
"if",
"@options",
"[",
":unwrapped",
"]",
"Citibike",
"::",
"Responses",
"::",
"Station",
".",
"new",
"(",
"resp",
")",
"end"
] | Wrapper around a call to list all stations
@return [Response] [A response object unless] | [
"Wrapper",
"around",
"a",
"call",
"to",
"list",
"all",
"stations"
] | 40ae300dacb299468985fa9c2fdf5dba7a235c93 | https://github.com/ejlangev/citibike/blob/40ae300dacb299468985fa9c2fdf5dba7a235c93/lib/citibike/client.rb#L35-L44 | train |
message-driver/message-driver | lib/message_driver/broker.rb | MessageDriver.Broker.find_destination | def find_destination(destination_name)
destination = @destinations[destination_name]
if destination.nil?
raise MessageDriver::NoSuchDestinationError, "no destination #{destination_name} has been configured"
end
destination
end | ruby | def find_destination(destination_name)
destination = @destinations[destination_name]
if destination.nil?
raise MessageDriver::NoSuchDestinationError, "no destination #{destination_name} has been configured"
end
destination
end | [
"def",
"find_destination",
"(",
"destination_name",
")",
"destination",
"=",
"@destinations",
"[",
"destination_name",
"]",
"if",
"destination",
".",
"nil?",
"raise",
"MessageDriver",
"::",
"NoSuchDestinationError",
",",
"\"no destination #{destination_name} has been configured\"",
"end",
"destination",
"end"
] | Find a previously declared Destination
@param destination_name [Symbol] the name of the destination
@return [Destination::Base] the requested destination
@raise [MessageDriver::NoSuchDestinationError] if there is no destination with that name | [
"Find",
"a",
"previously",
"declared",
"Destination"
] | 72a2b1b889a9aaaeab9101e223020500741636e7 | https://github.com/message-driver/message-driver/blob/72a2b1b889a9aaaeab9101e223020500741636e7/lib/message_driver/broker.rb#L165-L171 | train |
hmans/slodown | lib/slodown/formatter.rb | Slodown.Formatter.extract_metadata | def extract_metadata
@metadata = {}
convert do |current|
current.each_line.drop_while do |line|
next false if line !~ /^#\+([a-z_]+): (.*)/
key, value = $1, $2
@metadata[key.to_sym] = value
end.join('')
end
end | ruby | def extract_metadata
@metadata = {}
convert do |current|
current.each_line.drop_while do |line|
next false if line !~ /^#\+([a-z_]+): (.*)/
key, value = $1, $2
@metadata[key.to_sym] = value
end.join('')
end
end | [
"def",
"extract_metadata",
"@metadata",
"=",
"{",
"}",
"convert",
"do",
"|",
"current",
"|",
"current",
".",
"each_line",
".",
"drop_while",
"do",
"|",
"line",
"|",
"next",
"false",
"if",
"line",
"!~",
"/",
"\\+",
"/",
"key",
",",
"value",
"=",
"$1",
",",
"$2",
"@metadata",
"[",
"key",
".",
"to_sym",
"]",
"=",
"value",
"end",
".",
"join",
"(",
"''",
")",
"end",
"end"
] | Extract metadata from the document. | [
"Extract",
"metadata",
"from",
"the",
"document",
"."
] | e867a8d1f079c2e039470e285d48cac5045ba4f3 | https://github.com/hmans/slodown/blob/e867a8d1f079c2e039470e285d48cac5045ba4f3/lib/slodown/formatter.rb#L48-L59 | train |
hmans/slodown | lib/slodown/formatter.rb | Slodown.Formatter.embed_transformer | def embed_transformer
lambda do |env|
node = env[:node]
node_name = env[:node_name]
# We're fine with a bunch of stuff -- but not <iframe> and <embed> tags.
return if env[:is_whitelisted] || !env[:node].element?
return unless %w[iframe embed].include? env[:node_name]
# We're dealing with an <iframe> or <embed> tag! Let's check its src attribute.
# If its host name matches our regular expression, we can whitelist it.
uri = URI(env[:node]['src'])
return unless uri.host =~ allowed_iframe_hosts
Sanitize.clean_node!(node, {
elements: %w[iframe embed],
attributes: {
all: %w[allowfullscreen frameborder height src width]
}
})
{ node_whitelist: [node] }
end
end | ruby | def embed_transformer
lambda do |env|
node = env[:node]
node_name = env[:node_name]
# We're fine with a bunch of stuff -- but not <iframe> and <embed> tags.
return if env[:is_whitelisted] || !env[:node].element?
return unless %w[iframe embed].include? env[:node_name]
# We're dealing with an <iframe> or <embed> tag! Let's check its src attribute.
# If its host name matches our regular expression, we can whitelist it.
uri = URI(env[:node]['src'])
return unless uri.host =~ allowed_iframe_hosts
Sanitize.clean_node!(node, {
elements: %w[iframe embed],
attributes: {
all: %w[allowfullscreen frameborder height src width]
}
})
{ node_whitelist: [node] }
end
end | [
"def",
"embed_transformer",
"lambda",
"do",
"|",
"env",
"|",
"node",
"=",
"env",
"[",
":node",
"]",
"node_name",
"=",
"env",
"[",
":node_name",
"]",
"return",
"if",
"env",
"[",
":is_whitelisted",
"]",
"||",
"!",
"env",
"[",
":node",
"]",
".",
"element?",
"return",
"unless",
"%w[",
"iframe",
"embed",
"]",
".",
"include?",
"env",
"[",
":node_name",
"]",
"uri",
"=",
"URI",
"(",
"env",
"[",
":node",
"]",
"[",
"'src'",
"]",
")",
"return",
"unless",
"uri",
".",
"host",
"=~",
"allowed_iframe_hosts",
"Sanitize",
".",
"clean_node!",
"(",
"node",
",",
"{",
"elements",
":",
"%w[",
"iframe",
"embed",
"]",
",",
"attributes",
":",
"{",
"all",
":",
"%w[",
"allowfullscreen",
"frameborder",
"height",
"src",
"width",
"]",
"}",
"}",
")",
"{",
"node_whitelist",
":",
"[",
"node",
"]",
"}",
"end",
"end"
] | A sanitize transformer that will check the document for IFRAME tags and
validate them against +allowed_iframe_hosts+. | [
"A",
"sanitize",
"transformer",
"that",
"will",
"check",
"the",
"document",
"for",
"IFRAME",
"tags",
"and",
"validate",
"them",
"against",
"+",
"allowed_iframe_hosts",
"+",
"."
] | e867a8d1f079c2e039470e285d48cac5045ba4f3 | https://github.com/hmans/slodown/blob/e867a8d1f079c2e039470e285d48cac5045ba4f3/lib/slodown/formatter.rb#L141-L164 | train |
tscolari/tenanfy | lib/tenanfy/helpers.rb | Tenanfy.Helpers.append_tenant_theme_to_assets | def append_tenant_theme_to_assets(*assets)
assets.map! do |asset|
if should_add_tenant_theme_to_asset?(asset) && current_tenant
"#{current_tenant.themes.first}/#{asset}"
else
asset
end
end
assets
end | ruby | def append_tenant_theme_to_assets(*assets)
assets.map! do |asset|
if should_add_tenant_theme_to_asset?(asset) && current_tenant
"#{current_tenant.themes.first}/#{asset}"
else
asset
end
end
assets
end | [
"def",
"append_tenant_theme_to_assets",
"(",
"*",
"assets",
")",
"assets",
".",
"map!",
"do",
"|",
"asset",
"|",
"if",
"should_add_tenant_theme_to_asset?",
"(",
"asset",
")",
"&&",
"current_tenant",
"\"#{current_tenant.themes.first}/#{asset}\"",
"else",
"asset",
"end",
"end",
"assets",
"end"
] | updates the asset list with tenant theme where it's
necessary | [
"updates",
"the",
"asset",
"list",
"with",
"tenant",
"theme",
"where",
"it",
"s",
"necessary"
] | 3dfe960b4569032d69a7626a631c200acf640c2f | https://github.com/tscolari/tenanfy/blob/3dfe960b4569032d69a7626a631c200acf640c2f/lib/tenanfy/helpers.rb#L24-L33 | train |
ECHOInternational/your_membership | lib/your_membership/session.rb | YourMembership.Session.authenticate | def authenticate(user_name, password)
options = {}
options[:Username] = user_name
options[:Password] = password
response = self.class.post('/', :body => self.class.build_XML_request('Auth.Authenticate', self, options))
self.class.response_valid? response
if response['YourMembership_Response']['Auth.Authenticate']
get_authenticated_user
else
false
end
end | ruby | def authenticate(user_name, password)
options = {}
options[:Username] = user_name
options[:Password] = password
response = self.class.post('/', :body => self.class.build_XML_request('Auth.Authenticate', self, options))
self.class.response_valid? response
if response['YourMembership_Response']['Auth.Authenticate']
get_authenticated_user
else
false
end
end | [
"def",
"authenticate",
"(",
"user_name",
",",
"password",
")",
"options",
"=",
"{",
"}",
"options",
"[",
":Username",
"]",
"=",
"user_name",
"options",
"[",
":Password",
"]",
"=",
"password",
"response",
"=",
"self",
".",
"class",
".",
"post",
"(",
"'/'",
",",
":body",
"=>",
"self",
".",
"class",
".",
"build_XML_request",
"(",
"'Auth.Authenticate'",
",",
"self",
",",
"options",
")",
")",
"self",
".",
"class",
".",
"response_valid?",
"response",
"if",
"response",
"[",
"'YourMembership_Response'",
"]",
"[",
"'Auth.Authenticate'",
"]",
"get_authenticated_user",
"else",
"false",
"end",
"end"
] | Authenticates a member's username and password and binds them to the current API session.
@see https://api.yourmembership.com/reference/2_00/Auth_Authenticate.htm
@param user_name [String] The username of the member that is being authenticated.
@param password [String] The clear text password of the member that is being authenticated.
@return [Hash] Returns the member's ID and WebsiteID. The returned WebsiteID represents the numeric identifier
used by the YourMembership.com application for navigation purposes. It may be used to provide direct navigation to
a member's profile, photo gallery, personal blog, etc. | [
"Authenticates",
"a",
"member",
"s",
"username",
"and",
"password",
"and",
"binds",
"them",
"to",
"the",
"current",
"API",
"session",
"."
] | b0154e668c265283b63c7986861db26426f9b700 | https://github.com/ECHOInternational/your_membership/blob/b0154e668c265283b63c7986861db26426f9b700/lib/your_membership/session.rb#L94-L107 | train |
3scale/xcflushd | lib/xcflushd/authorizer.rb | Xcflushd.Authorizer.sorted_metrics | def sorted_metrics(metrics, hierarchy)
# 'hierarchy' is a hash where the keys are metric names and the values
# are arrays with the names of the children metrics. Only metrics with
# children and with at least one usage limit appear as keys.
parent_metrics = hierarchy.keys
child_metrics = metrics - parent_metrics
parent_metrics + child_metrics
end | ruby | def sorted_metrics(metrics, hierarchy)
# 'hierarchy' is a hash where the keys are metric names and the values
# are arrays with the names of the children metrics. Only metrics with
# children and with at least one usage limit appear as keys.
parent_metrics = hierarchy.keys
child_metrics = metrics - parent_metrics
parent_metrics + child_metrics
end | [
"def",
"sorted_metrics",
"(",
"metrics",
",",
"hierarchy",
")",
"parent_metrics",
"=",
"hierarchy",
".",
"keys",
"child_metrics",
"=",
"metrics",
"-",
"parent_metrics",
"parent_metrics",
"+",
"child_metrics",
"end"
] | Returns an array of metric names. The array is guaranteed to have all the
parents first, and then the rest.
In 3scale, metric hierarchies only have 2 levels. In other words, a
metric that has a parent cannot have children. | [
"Returns",
"an",
"array",
"of",
"metric",
"names",
".",
"The",
"array",
"is",
"guaranteed",
"to",
"have",
"all",
"the",
"parents",
"first",
"and",
"then",
"the",
"rest",
".",
"In",
"3scale",
"metric",
"hierarchies",
"only",
"have",
"2",
"levels",
".",
"In",
"other",
"words",
"a",
"metric",
"that",
"has",
"a",
"parent",
"cannot",
"have",
"children",
"."
] | ca29b7674c3cd952a2a50c0604a99f04662bf27d | https://github.com/3scale/xcflushd/blob/ca29b7674c3cd952a2a50c0604a99f04662bf27d/lib/xcflushd/authorizer.rb#L79-L86 | train |
ejlangev/citibike | lib/citibike/response.rb | Citibike.Response.all_near | def all_near(obj, dist)
@data.select do |d|
if d.id == obj.id
false
else
d.distance_from(obj.latitude, obj.longitude) < dist
end
end
end | ruby | def all_near(obj, dist)
@data.select do |d|
if d.id == obj.id
false
else
d.distance_from(obj.latitude, obj.longitude) < dist
end
end
end | [
"def",
"all_near",
"(",
"obj",
",",
"dist",
")",
"@data",
".",
"select",
"do",
"|",
"d",
"|",
"if",
"d",
".",
"id",
"==",
"obj",
".",
"id",
"false",
"else",
"d",
".",
"distance_from",
"(",
"obj",
".",
"latitude",
",",
"obj",
".",
"longitude",
")",
"<",
"dist",
"end",
"end",
"end"
] | Returns every object within dist miles
of obj
@param obj [Api] [Api Object]
@param dist [Float] [Distance to consider]
@return [type] [description] | [
"Returns",
"every",
"object",
"within",
"dist",
"miles",
"of",
"obj"
] | 40ae300dacb299468985fa9c2fdf5dba7a235c93 | https://github.com/ejlangev/citibike/blob/40ae300dacb299468985fa9c2fdf5dba7a235c93/lib/citibike/response.rb#L98-L106 | train |
ejlangev/citibike | lib/citibike/response.rb | Citibike.Response.method_missing | def method_missing(sym, *args, &block)
if self.data.respond_to?(sym)
return self.data.send(sym, *args, &block)
end
super
end | ruby | def method_missing(sym, *args, &block)
if self.data.respond_to?(sym)
return self.data.send(sym, *args, &block)
end
super
end | [
"def",
"method_missing",
"(",
"sym",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"self",
".",
"data",
".",
"respond_to?",
"(",
"sym",
")",
"return",
"self",
".",
"data",
".",
"send",
"(",
"sym",
",",
"*",
"args",
",",
"&",
"block",
")",
"end",
"super",
"end"
] | Delegates any undefined methods to the underlying data | [
"Delegates",
"any",
"undefined",
"methods",
"to",
"the",
"underlying",
"data"
] | 40ae300dacb299468985fa9c2fdf5dba7a235c93 | https://github.com/ejlangev/citibike/blob/40ae300dacb299468985fa9c2fdf5dba7a235c93/lib/citibike/response.rb#L109-L115 | train |
rightscale/right_chimp | lib/right_chimp/queue/queue_worker.rb | Chimp.QueueWorker.run | def run
while @never_exit
work_item = ChimpQueue.instance.shift()
begin
if work_item != nil
job_uuid = work_item.job_uuid
group = work_item.group.group_id
work_item.retry_count = @retry_count
work_item.owner = Thread.current.object_id
ChimpDaemon.instance.semaphore.synchronize do
# only do this if we are running with chimpd
if ChimpDaemon.instance.queue.processing[group].nil?
# no op
else
# remove from the processing queue
if ChimpDaemon.instance.queue.processing[group][job_uuid.to_sym] == 0
Log.debug 'Completed processing task ' + job_uuid.to_s
Log.debug 'Deleting ' + job_uuid.to_s
ChimpDaemon.instance.queue.processing[group].delete(job_uuid.to_sym)
Log.debug ChimpDaemon.instance.queue.processing.inspect
ChimpDaemon.instance.proc_counter -= 1
else
if ChimpDaemon.instance.queue.processing[group][job_uuid.to_sym].nil?
Log.debug 'Job group was already deleted, no counter to decrease.'
else
Log.debug 'Decreasing processing counter (' + ChimpDaemon.instance.proc_counter.to_s +
') for [' + job_uuid.to_s + '] group: ' + group.to_s
ChimpDaemon.instance.queue.processing[group][job_uuid.to_sym] -= 1
Log.debug 'Processing counter now (' + ChimpDaemon.instance.proc_counter.to_s +
') for [' + job_uuid.to_s + '] group: ' + group.to_s
Log.debug ChimpDaemon.instance.queue.processing[group].inspect
Log.debug 'Still counting down for ' + job_uuid.to_s
ChimpDaemon.instance.proc_counter -= 1
end
end
end
end
work_item.run
else
sleep 1
end
rescue Exception => ex
Log.error "Exception in QueueWorker.run: #{ex}"
Log.debug ex.inspect
Log.debug ex.backtrace
work_item.status = Executor::STATUS_ERROR
work_item.error = ex
end
end
end | ruby | def run
while @never_exit
work_item = ChimpQueue.instance.shift()
begin
if work_item != nil
job_uuid = work_item.job_uuid
group = work_item.group.group_id
work_item.retry_count = @retry_count
work_item.owner = Thread.current.object_id
ChimpDaemon.instance.semaphore.synchronize do
# only do this if we are running with chimpd
if ChimpDaemon.instance.queue.processing[group].nil?
# no op
else
# remove from the processing queue
if ChimpDaemon.instance.queue.processing[group][job_uuid.to_sym] == 0
Log.debug 'Completed processing task ' + job_uuid.to_s
Log.debug 'Deleting ' + job_uuid.to_s
ChimpDaemon.instance.queue.processing[group].delete(job_uuid.to_sym)
Log.debug ChimpDaemon.instance.queue.processing.inspect
ChimpDaemon.instance.proc_counter -= 1
else
if ChimpDaemon.instance.queue.processing[group][job_uuid.to_sym].nil?
Log.debug 'Job group was already deleted, no counter to decrease.'
else
Log.debug 'Decreasing processing counter (' + ChimpDaemon.instance.proc_counter.to_s +
') for [' + job_uuid.to_s + '] group: ' + group.to_s
ChimpDaemon.instance.queue.processing[group][job_uuid.to_sym] -= 1
Log.debug 'Processing counter now (' + ChimpDaemon.instance.proc_counter.to_s +
') for [' + job_uuid.to_s + '] group: ' + group.to_s
Log.debug ChimpDaemon.instance.queue.processing[group].inspect
Log.debug 'Still counting down for ' + job_uuid.to_s
ChimpDaemon.instance.proc_counter -= 1
end
end
end
end
work_item.run
else
sleep 1
end
rescue Exception => ex
Log.error "Exception in QueueWorker.run: #{ex}"
Log.debug ex.inspect
Log.debug ex.backtrace
work_item.status = Executor::STATUS_ERROR
work_item.error = ex
end
end
end | [
"def",
"run",
"while",
"@never_exit",
"work_item",
"=",
"ChimpQueue",
".",
"instance",
".",
"shift",
"(",
")",
"begin",
"if",
"work_item",
"!=",
"nil",
"job_uuid",
"=",
"work_item",
".",
"job_uuid",
"group",
"=",
"work_item",
".",
"group",
".",
"group_id",
"work_item",
".",
"retry_count",
"=",
"@retry_count",
"work_item",
".",
"owner",
"=",
"Thread",
".",
"current",
".",
"object_id",
"ChimpDaemon",
".",
"instance",
".",
"semaphore",
".",
"synchronize",
"do",
"if",
"ChimpDaemon",
".",
"instance",
".",
"queue",
".",
"processing",
"[",
"group",
"]",
".",
"nil?",
"else",
"if",
"ChimpDaemon",
".",
"instance",
".",
"queue",
".",
"processing",
"[",
"group",
"]",
"[",
"job_uuid",
".",
"to_sym",
"]",
"==",
"0",
"Log",
".",
"debug",
"'Completed processing task '",
"+",
"job_uuid",
".",
"to_s",
"Log",
".",
"debug",
"'Deleting '",
"+",
"job_uuid",
".",
"to_s",
"ChimpDaemon",
".",
"instance",
".",
"queue",
".",
"processing",
"[",
"group",
"]",
".",
"delete",
"(",
"job_uuid",
".",
"to_sym",
")",
"Log",
".",
"debug",
"ChimpDaemon",
".",
"instance",
".",
"queue",
".",
"processing",
".",
"inspect",
"ChimpDaemon",
".",
"instance",
".",
"proc_counter",
"-=",
"1",
"else",
"if",
"ChimpDaemon",
".",
"instance",
".",
"queue",
".",
"processing",
"[",
"group",
"]",
"[",
"job_uuid",
".",
"to_sym",
"]",
".",
"nil?",
"Log",
".",
"debug",
"'Job group was already deleted, no counter to decrease.'",
"else",
"Log",
".",
"debug",
"'Decreasing processing counter ('",
"+",
"ChimpDaemon",
".",
"instance",
".",
"proc_counter",
".",
"to_s",
"+",
"') for ['",
"+",
"job_uuid",
".",
"to_s",
"+",
"'] group: '",
"+",
"group",
".",
"to_s",
"ChimpDaemon",
".",
"instance",
".",
"queue",
".",
"processing",
"[",
"group",
"]",
"[",
"job_uuid",
".",
"to_sym",
"]",
"-=",
"1",
"Log",
".",
"debug",
"'Processing counter now ('",
"+",
"ChimpDaemon",
".",
"instance",
".",
"proc_counter",
".",
"to_s",
"+",
"') for ['",
"+",
"job_uuid",
".",
"to_s",
"+",
"'] group: '",
"+",
"group",
".",
"to_s",
"Log",
".",
"debug",
"ChimpDaemon",
".",
"instance",
".",
"queue",
".",
"processing",
"[",
"group",
"]",
".",
"inspect",
"Log",
".",
"debug",
"'Still counting down for '",
"+",
"job_uuid",
".",
"to_s",
"ChimpDaemon",
".",
"instance",
".",
"proc_counter",
"-=",
"1",
"end",
"end",
"end",
"end",
"work_item",
".",
"run",
"else",
"sleep",
"1",
"end",
"rescue",
"Exception",
"=>",
"ex",
"Log",
".",
"error",
"\"Exception in QueueWorker.run: #{ex}\"",
"Log",
".",
"debug",
"ex",
".",
"inspect",
"Log",
".",
"debug",
"ex",
".",
"backtrace",
"work_item",
".",
"status",
"=",
"Executor",
"::",
"STATUS_ERROR",
"work_item",
".",
"error",
"=",
"ex",
"end",
"end",
"end"
] | Grab work items from the ChimpQueue and process them
Only stop is @ever_exit is false | [
"Grab",
"work",
"items",
"from",
"the",
"ChimpQueue",
"and",
"process",
"them",
"Only",
"stop",
"is"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/queue_worker.rb#L19-L81 | train |
arvicco/win_gui | old_code/lib/win_gui/def_api.rb | WinGui.DefApi.enforce_count | def enforce_count(args, params, diff = 0)
num_args = args.size
num_params = params == 'V' ? 0 : params.size + diff
if num_args != num_params
raise ArgumentError, "wrong number of parameters: expected #{num_params}, got #{num_args}"
end
end | ruby | def enforce_count(args, params, diff = 0)
num_args = args.size
num_params = params == 'V' ? 0 : params.size + diff
if num_args != num_params
raise ArgumentError, "wrong number of parameters: expected #{num_params}, got #{num_args}"
end
end | [
"def",
"enforce_count",
"(",
"args",
",",
"params",
",",
"diff",
"=",
"0",
")",
"num_args",
"=",
"args",
".",
"size",
"num_params",
"=",
"params",
"==",
"'V'",
"?",
"0",
":",
"params",
".",
"size",
"+",
"diff",
"if",
"num_args",
"!=",
"num_params",
"raise",
"ArgumentError",
",",
"\"wrong number of parameters: expected #{num_params}, got #{num_args}\"",
"end",
"end"
] | Ensures that args count is equal to params count plus diff | [
"Ensures",
"that",
"args",
"count",
"is",
"equal",
"to",
"params",
"count",
"plus",
"diff"
] | a3a4c18db2391144fcb535e4be2f0fb47e9dcec7 | https://github.com/arvicco/win_gui/blob/a3a4c18db2391144fcb535e4be2f0fb47e9dcec7/old_code/lib/win_gui/def_api.rb#L78-L84 | train |
arvicco/win_gui | old_code/lib/win_gui/def_api.rb | WinGui.DefApi.return_enum | def return_enum
lambda do |api, *args, &block|
WinGui.enforce_count( args, api.prototype, -1)
handles = []
cb = if block
callback('LP', 'I', &block)
else
callback('LP', 'I') do |handle, message|
handles << handle
true
end
end
args[api.prototype.find_index('K'), 0] = cb # Insert callback into appropriate place of args Array
api.call *args
handles
end
end | ruby | def return_enum
lambda do |api, *args, &block|
WinGui.enforce_count( args, api.prototype, -1)
handles = []
cb = if block
callback('LP', 'I', &block)
else
callback('LP', 'I') do |handle, message|
handles << handle
true
end
end
args[api.prototype.find_index('K'), 0] = cb # Insert callback into appropriate place of args Array
api.call *args
handles
end
end | [
"def",
"return_enum",
"lambda",
"do",
"|",
"api",
",",
"*",
"args",
",",
"&",
"block",
"|",
"WinGui",
".",
"enforce_count",
"(",
"args",
",",
"api",
".",
"prototype",
",",
"-",
"1",
")",
"handles",
"=",
"[",
"]",
"cb",
"=",
"if",
"block",
"callback",
"(",
"'LP'",
",",
"'I'",
",",
"&",
"block",
")",
"else",
"callback",
"(",
"'LP'",
",",
"'I'",
")",
"do",
"|",
"handle",
",",
"message",
"|",
"handles",
"<<",
"handle",
"true",
"end",
"end",
"args",
"[",
"api",
".",
"prototype",
".",
"find_index",
"(",
"'K'",
")",
",",
"0",
"]",
"=",
"cb",
"api",
".",
"call",
"*",
"args",
"handles",
"end",
"end"
] | Procedure that calls api function expecting a callback. If runtime block is given
it is converted into actual callback, otherwise procedure returns an array of all
handles pushed into callback by api enumeration | [
"Procedure",
"that",
"calls",
"api",
"function",
"expecting",
"a",
"callback",
".",
"If",
"runtime",
"block",
"is",
"given",
"it",
"is",
"converted",
"into",
"actual",
"callback",
"otherwise",
"procedure",
"returns",
"an",
"array",
"of",
"all",
"handles",
"pushed",
"into",
"callback",
"by",
"api",
"enumeration"
] | a3a4c18db2391144fcb535e4be2f0fb47e9dcec7 | https://github.com/arvicco/win_gui/blob/a3a4c18db2391144fcb535e4be2f0fb47e9dcec7/old_code/lib/win_gui/def_api.rb#L125-L141 | train |
Aupajo/oulipo | lib/oulipo/string_extensions.rb | Oulipo.StringExtensions.alliterativity | def alliterativity
words = self.downcase.gsub(/[^a-z\s]/, '').split
leading_letters = words.map(&:chr)
# { 'a' => 3, 'b' => 1, ... }
leading_letter_counts = leading_letters.inject({}) do |result, letter|
result[letter] ||= 0
result[letter] += 1
result
end
most_used_count = leading_letter_counts.max_by { |kv| kv.last }.pop
most_used_count.to_f / words.length
end | ruby | def alliterativity
words = self.downcase.gsub(/[^a-z\s]/, '').split
leading_letters = words.map(&:chr)
# { 'a' => 3, 'b' => 1, ... }
leading_letter_counts = leading_letters.inject({}) do |result, letter|
result[letter] ||= 0
result[letter] += 1
result
end
most_used_count = leading_letter_counts.max_by { |kv| kv.last }.pop
most_used_count.to_f / words.length
end | [
"def",
"alliterativity",
"words",
"=",
"self",
".",
"downcase",
".",
"gsub",
"(",
"/",
"\\s",
"/",
",",
"''",
")",
".",
"split",
"leading_letters",
"=",
"words",
".",
"map",
"(",
"&",
":chr",
")",
"leading_letter_counts",
"=",
"leading_letters",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"result",
",",
"letter",
"|",
"result",
"[",
"letter",
"]",
"||=",
"0",
"result",
"[",
"letter",
"]",
"+=",
"1",
"result",
"end",
"most_used_count",
"=",
"leading_letter_counts",
".",
"max_by",
"{",
"|",
"kv",
"|",
"kv",
".",
"last",
"}",
".",
"pop",
"most_used_count",
".",
"to_f",
"/",
"words",
".",
"length",
"end"
] | A score between 0 and 1 representing the level of alliteration | [
"A",
"score",
"between",
"0",
"and",
"1",
"representing",
"the",
"level",
"of",
"alliteration"
] | dff71355efe0c050cfbf79b0a2cef9855bcc4923 | https://github.com/Aupajo/oulipo/blob/dff71355efe0c050cfbf79b0a2cef9855bcc4923/lib/oulipo/string_extensions.rb#L16-L29 | train |
Aupajo/oulipo | lib/oulipo/string_extensions.rb | Oulipo.StringExtensions.n_plus | def n_plus(places, word_list)
analysis = Analysis.new(self, :nouns => word_list)
substitutor = Substitutor.new(analysis)
substitutor.replace(:nouns).increment(places)
end | ruby | def n_plus(places, word_list)
analysis = Analysis.new(self, :nouns => word_list)
substitutor = Substitutor.new(analysis)
substitutor.replace(:nouns).increment(places)
end | [
"def",
"n_plus",
"(",
"places",
",",
"word_list",
")",
"analysis",
"=",
"Analysis",
".",
"new",
"(",
"self",
",",
":nouns",
"=>",
"word_list",
")",
"substitutor",
"=",
"Substitutor",
".",
"new",
"(",
"analysis",
")",
"substitutor",
".",
"replace",
"(",
":nouns",
")",
".",
"increment",
"(",
"places",
")",
"end"
] | Replace the words in the word list with the word n places after it | [
"Replace",
"the",
"words",
"in",
"the",
"word",
"list",
"with",
"the",
"word",
"n",
"places",
"after",
"it"
] | dff71355efe0c050cfbf79b0a2cef9855bcc4923 | https://github.com/Aupajo/oulipo/blob/dff71355efe0c050cfbf79b0a2cef9855bcc4923/lib/oulipo/string_extensions.rb#L38-L42 | train |
Aupajo/oulipo | lib/oulipo/string_extensions.rb | Oulipo.StringExtensions.snowball? | def snowball?
words = self.split
self.chaterism? && words.first.length < words.last.length
end | ruby | def snowball?
words = self.split
self.chaterism? && words.first.length < words.last.length
end | [
"def",
"snowball?",
"words",
"=",
"self",
".",
"split",
"self",
".",
"chaterism?",
"&&",
"words",
".",
"first",
".",
"length",
"<",
"words",
".",
"last",
".",
"length",
"end"
] | Returns true if each word is one letter larger than the previous | [
"Returns",
"true",
"if",
"each",
"word",
"is",
"one",
"letter",
"larger",
"than",
"the",
"previous"
] | dff71355efe0c050cfbf79b0a2cef9855bcc4923 | https://github.com/Aupajo/oulipo/blob/dff71355efe0c050cfbf79b0a2cef9855bcc4923/lib/oulipo/string_extensions.rb#L45-L48 | train |
Aupajo/oulipo | lib/oulipo/string_extensions.rb | Oulipo.StringExtensions.chaterism? | def chaterism?
words = self.gsub(/[^a-z\s]/i, '').split
# Find the direction we're traveling
flen, llen = words.first.length, words.last.length
direction = flen > llen ? :downto : :upto
# Compare the pattern of word lengths against a range-turned-array of expected word lengths
words.map(&:length) == flen.send(direction, llen).to_a
end | ruby | def chaterism?
words = self.gsub(/[^a-z\s]/i, '').split
# Find the direction we're traveling
flen, llen = words.first.length, words.last.length
direction = flen > llen ? :downto : :upto
# Compare the pattern of word lengths against a range-turned-array of expected word lengths
words.map(&:length) == flen.send(direction, llen).to_a
end | [
"def",
"chaterism?",
"words",
"=",
"self",
".",
"gsub",
"(",
"/",
"\\s",
"/i",
",",
"''",
")",
".",
"split",
"flen",
",",
"llen",
"=",
"words",
".",
"first",
".",
"length",
",",
"words",
".",
"last",
".",
"length",
"direction",
"=",
"flen",
">",
"llen",
"?",
":downto",
":",
":upto",
"words",
".",
"map",
"(",
"&",
":length",
")",
"==",
"flen",
".",
"send",
"(",
"direction",
",",
"llen",
")",
".",
"to_a",
"end"
] | Returns true if the string is a sequence of words in each of which is one letter larger than the
previous, or each word in the sequence is one letter less than the previous | [
"Returns",
"true",
"if",
"the",
"string",
"is",
"a",
"sequence",
"of",
"words",
"in",
"each",
"of",
"which",
"is",
"one",
"letter",
"larger",
"than",
"the",
"previous",
"or",
"each",
"word",
"in",
"the",
"sequence",
"is",
"one",
"letter",
"less",
"than",
"the",
"previous"
] | dff71355efe0c050cfbf79b0a2cef9855bcc4923 | https://github.com/Aupajo/oulipo/blob/dff71355efe0c050cfbf79b0a2cef9855bcc4923/lib/oulipo/string_extensions.rb#L57-L66 | train |
PeterCamilleri/mini_readline | lib/mini_readline/read_line/edit/edit_window/sync_window.rb | MiniReadline.EditWindow.sync_window | def sync_window(edit_buffer, edit_posn)
unless check_margins(edit_buffer.length, edit_posn)
window_buffer.clear
@show_prompt = true
end
image = build_screen_image(edit_buffer)
update_screen(image)
@window_buffer = image
end | ruby | def sync_window(edit_buffer, edit_posn)
unless check_margins(edit_buffer.length, edit_posn)
window_buffer.clear
@show_prompt = true
end
image = build_screen_image(edit_buffer)
update_screen(image)
@window_buffer = image
end | [
"def",
"sync_window",
"(",
"edit_buffer",
",",
"edit_posn",
")",
"unless",
"check_margins",
"(",
"edit_buffer",
".",
"length",
",",
"edit_posn",
")",
"window_buffer",
".",
"clear",
"@show_prompt",
"=",
"true",
"end",
"image",
"=",
"build_screen_image",
"(",
"edit_buffer",
")",
"update_screen",
"(",
"image",
")",
"@window_buffer",
"=",
"image",
"end"
] | Keep the edit window in sync! | [
"Keep",
"the",
"edit",
"window",
"in",
"sync!"
] | 45175ee01653a184b8ba04b2e8691dce5b26a1b5 | https://github.com/PeterCamilleri/mini_readline/blob/45175ee01653a184b8ba04b2e8691dce5b26a1b5/lib/mini_readline/read_line/edit/edit_window/sync_window.rb#L10-L19 | train |
PeterCamilleri/mini_readline | lib/mini_readline/read_line/edit/edit_window/sync_window.rb | MiniReadline.EditWindow.build_screen_image | def build_screen_image(edit_buffer)
working_region = edit_buffer[left_margin..right_margin]
if (mask = @options[:secret_mask])
mask[0] * working_region.length
else
working_region
end.ljust(active_width)
end | ruby | def build_screen_image(edit_buffer)
working_region = edit_buffer[left_margin..right_margin]
if (mask = @options[:secret_mask])
mask[0] * working_region.length
else
working_region
end.ljust(active_width)
end | [
"def",
"build_screen_image",
"(",
"edit_buffer",
")",
"working_region",
"=",
"edit_buffer",
"[",
"left_margin",
"..",
"right_margin",
"]",
"if",
"(",
"mask",
"=",
"@options",
"[",
":secret_mask",
"]",
")",
"mask",
"[",
"0",
"]",
"*",
"working_region",
".",
"length",
"else",
"working_region",
"end",
".",
"ljust",
"(",
"active_width",
")",
"end"
] | Compute what should be on the screen. | [
"Compute",
"what",
"should",
"be",
"on",
"the",
"screen",
"."
] | 45175ee01653a184b8ba04b2e8691dce5b26a1b5 | https://github.com/PeterCamilleri/mini_readline/blob/45175ee01653a184b8ba04b2e8691dce5b26a1b5/lib/mini_readline/read_line/edit/edit_window/sync_window.rb#L37-L45 | train |
PeterCamilleri/mini_readline | lib/mini_readline/read_line/edit/edit_window/sync_window.rb | MiniReadline.EditWindow.update_screen | def update_screen(image)
if @show_prompt
MiniTerm.print("\r#{prompt.text}\r")
@show_prompt = false
end
(0...active_width).each do |index|
if (image_char = image[index]) != window_buffer[index]
MiniTerm.set_posn(column: prompt.length + index)
MiniTerm.print(image_char)
end
end
end | ruby | def update_screen(image)
if @show_prompt
MiniTerm.print("\r#{prompt.text}\r")
@show_prompt = false
end
(0...active_width).each do |index|
if (image_char = image[index]) != window_buffer[index]
MiniTerm.set_posn(column: prompt.length + index)
MiniTerm.print(image_char)
end
end
end | [
"def",
"update_screen",
"(",
"image",
")",
"if",
"@show_prompt",
"MiniTerm",
".",
"print",
"(",
"\"\\r#{prompt.text}\\r\"",
")",
"@show_prompt",
"=",
"false",
"end",
"(",
"0",
"...",
"active_width",
")",
".",
"each",
"do",
"|",
"index",
"|",
"if",
"(",
"image_char",
"=",
"image",
"[",
"index",
"]",
")",
"!=",
"window_buffer",
"[",
"index",
"]",
"MiniTerm",
".",
"set_posn",
"(",
"column",
":",
"prompt",
".",
"length",
"+",
"index",
")",
"MiniTerm",
".",
"print",
"(",
"image_char",
")",
"end",
"end",
"end"
] | Bring the screen into agreement with the image. | [
"Bring",
"the",
"screen",
"into",
"agreement",
"with",
"the",
"image",
"."
] | 45175ee01653a184b8ba04b2e8691dce5b26a1b5 | https://github.com/PeterCamilleri/mini_readline/blob/45175ee01653a184b8ba04b2e8691dce5b26a1b5/lib/mini_readline/read_line/edit/edit_window/sync_window.rb#L48-L60 | train |
iHiD/mandate | lib/mandate/memoize.rb | Mandate.Memoize.__mandate_memoize | def __mandate_memoize(method_name)
memoizer = Module.new do
define_method method_name do
@__mandate_memoized_results ||= {}
if @__mandate_memoized_results.include?(method_name)
@__mandate_memoized_results[method_name]
else
@__mandate_memoized_results[method_name] = super()
end
end
end
prepend memoizer
end | ruby | def __mandate_memoize(method_name)
memoizer = Module.new do
define_method method_name do
@__mandate_memoized_results ||= {}
if @__mandate_memoized_results.include?(method_name)
@__mandate_memoized_results[method_name]
else
@__mandate_memoized_results[method_name] = super()
end
end
end
prepend memoizer
end | [
"def",
"__mandate_memoize",
"(",
"method_name",
")",
"memoizer",
"=",
"Module",
".",
"new",
"do",
"define_method",
"method_name",
"do",
"@__mandate_memoized_results",
"||=",
"{",
"}",
"if",
"@__mandate_memoized_results",
".",
"include?",
"(",
"method_name",
")",
"@__mandate_memoized_results",
"[",
"method_name",
"]",
"else",
"@__mandate_memoized_results",
"[",
"method_name",
"]",
"=",
"super",
"(",
")",
"end",
"end",
"end",
"prepend",
"memoizer",
"end"
] | Create an anonymous module that defines a method
with the same name as main method being defined.
Add some memoize code to check whether the method
has been previously called or not. If it's not
been then call the underlying method and store the result.
We then prepend this module so that its method
comes first in the method-lookup chain. | [
"Create",
"an",
"anonymous",
"module",
"that",
"defines",
"a",
"method",
"with",
"the",
"same",
"name",
"as",
"main",
"method",
"being",
"defined",
".",
"Add",
"some",
"memoize",
"code",
"to",
"check",
"whether",
"the",
"method",
"has",
"been",
"previously",
"called",
"or",
"not",
".",
"If",
"it",
"s",
"not",
"been",
"then",
"call",
"the",
"underlying",
"method",
"and",
"store",
"the",
"result",
"."
] | bded81c497837d8755b81ab460033c912c9f95ab | https://github.com/iHiD/mandate/blob/bded81c497837d8755b81ab460033c912c9f95ab/lib/mandate/memoize.rb#L31-L44 | train |
fixrb/aw | lib/aw/fork.rb | Aw.Fork.call | def call(*, **, &block)
pid = fork_and_return_pid(&block)
write.close
result = read.read
Process.wait(pid)
# rubocop:disable MarshalLoad
Marshal.load(result)
# rubocop:enable MarshalLoad
end | ruby | def call(*, **, &block)
pid = fork_and_return_pid(&block)
write.close
result = read.read
Process.wait(pid)
# rubocop:disable MarshalLoad
Marshal.load(result)
# rubocop:enable MarshalLoad
end | [
"def",
"call",
"(",
"*",
",",
"**",
",",
"&",
"block",
")",
"pid",
"=",
"fork_and_return_pid",
"(",
"&",
"block",
")",
"write",
".",
"close",
"result",
"=",
"read",
".",
"read",
"Process",
".",
"wait",
"(",
"pid",
")",
"Marshal",
".",
"load",
"(",
"result",
")",
"end"
] | Run the block inside a subprocess, and return the value.
@return [#object_id] The result. | [
"Run",
"the",
"block",
"inside",
"a",
"subprocess",
"and",
"return",
"the",
"value",
"."
] | 2ca162e1744b4354eed2d374d46db8d750129f94 | https://github.com/fixrb/aw/blob/2ca162e1744b4354eed2d374d46db8d750129f94/lib/aw/fork.rb#L31-L40 | train |
cldwalker/boson-more | lib/boson/commands/web_core.rb | Boson::Commands::WebCore.Get.get_body | def get_body
uri = URI.parse(@url)
@response = get_response(uri)
(@options[:any_response] || @response.code == '200') ? @response.body : nil
rescue
@options[:raise_error] ? raise : puts("Error: GET '#{@url}' -> #{$!.class}: #{$!.message}")
end | ruby | def get_body
uri = URI.parse(@url)
@response = get_response(uri)
(@options[:any_response] || @response.code == '200') ? @response.body : nil
rescue
@options[:raise_error] ? raise : puts("Error: GET '#{@url}' -> #{$!.class}: #{$!.message}")
end | [
"def",
"get_body",
"uri",
"=",
"URI",
".",
"parse",
"(",
"@url",
")",
"@response",
"=",
"get_response",
"(",
"uri",
")",
"(",
"@options",
"[",
":any_response",
"]",
"||",
"@response",
".",
"code",
"==",
"'200'",
")",
"?",
"@response",
".",
"body",
":",
"nil",
"rescue",
"@options",
"[",
":raise_error",
"]",
"?",
"raise",
":",
"puts",
"(",
"\"Error: GET '#{@url}' -> #{$!.class}: #{$!.message}\"",
")",
"end"
] | Returns body string if successful or nil if not. | [
"Returns",
"body",
"string",
"if",
"successful",
"or",
"nil",
"if",
"not",
"."
] | f928ebc18d8641e038891f78896ae7251b97415c | https://github.com/cldwalker/boson-more/blob/f928ebc18d8641e038891f78896ae7251b97415c/lib/boson/commands/web_core.rb#L114-L120 | train |
cldwalker/boson-more | lib/boson/commands/web_core.rb | Boson::Commands::WebCore.Get.parse_body | def parse_body(body)
format = determine_format(@options[:parse])
case format
when :json
unless ::Boson::Util.safe_require 'json'
return puts("Install the json gem to parse json: sudo gem install json")
end
JSON.parse body
when :yaml
YAML::load body
else
puts "Can't parse this format."
end
rescue
@options[:raise_error] ? raise : puts("Error while parsing #{format} response of '#{@url}': #{$!.class}")
end | ruby | def parse_body(body)
format = determine_format(@options[:parse])
case format
when :json
unless ::Boson::Util.safe_require 'json'
return puts("Install the json gem to parse json: sudo gem install json")
end
JSON.parse body
when :yaml
YAML::load body
else
puts "Can't parse this format."
end
rescue
@options[:raise_error] ? raise : puts("Error while parsing #{format} response of '#{@url}': #{$!.class}")
end | [
"def",
"parse_body",
"(",
"body",
")",
"format",
"=",
"determine_format",
"(",
"@options",
"[",
":parse",
"]",
")",
"case",
"format",
"when",
":json",
"unless",
"::",
"Boson",
"::",
"Util",
".",
"safe_require",
"'json'",
"return",
"puts",
"(",
"\"Install the json gem to parse json: sudo gem install json\"",
")",
"end",
"JSON",
".",
"parse",
"body",
"when",
":yaml",
"YAML",
"::",
"load",
"body",
"else",
"puts",
"\"Can't parse this format.\"",
"end",
"rescue",
"@options",
"[",
":raise_error",
"]",
"?",
"raise",
":",
"puts",
"(",
"\"Error while parsing #{format} response of '#{@url}': #{$!.class}\"",
")",
"end"
] | Returns nil if dependencies or parsing fails | [
"Returns",
"nil",
"if",
"dependencies",
"or",
"parsing",
"fails"
] | f928ebc18d8641e038891f78896ae7251b97415c | https://github.com/cldwalker/boson-more/blob/f928ebc18d8641e038891f78896ae7251b97415c/lib/boson/commands/web_core.rb#L130-L145 | train |
angelim/rails_redshift_replicator | lib/rails_redshift_replicator/file_manager.rb | RailsRedshiftReplicator.FileManager.write_csv | def write_csv(file_name, records)
line_number = exporter.connection_adapter.write(local_file(file_name), records)
end | ruby | def write_csv(file_name, records)
line_number = exporter.connection_adapter.write(local_file(file_name), records)
end | [
"def",
"write_csv",
"(",
"file_name",
",",
"records",
")",
"line_number",
"=",
"exporter",
".",
"connection_adapter",
".",
"write",
"(",
"local_file",
"(",
"file_name",
")",
",",
"records",
")",
"end"
] | Writes all results to one file for future splitting.
@param file_name [String] name of the local export file
@return [Integer] number of records to export. | [
"Writes",
"all",
"results",
"to",
"one",
"file",
"for",
"future",
"splitting",
"."
] | 823f6da36f43a39f340a3ca7eb159df58a86766d | https://github.com/angelim/rails_redshift_replicator/blob/823f6da36f43a39f340a3ca7eb159df58a86766d/lib/rails_redshift_replicator/file_manager.rb#L49-L51 | train |
angelim/rails_redshift_replicator | lib/rails_redshift_replicator/file_manager.rb | RailsRedshiftReplicator.FileManager.file_key_in_format | def file_key_in_format(file_name, format)
if format == "gzip"
self.class.s3_file_key exporter.source_table, gzipped(file_name)
else
self.class.s3_file_key exporter.source_table, file_name
end
end | ruby | def file_key_in_format(file_name, format)
if format == "gzip"
self.class.s3_file_key exporter.source_table, gzipped(file_name)
else
self.class.s3_file_key exporter.source_table, file_name
end
end | [
"def",
"file_key_in_format",
"(",
"file_name",
",",
"format",
")",
"if",
"format",
"==",
"\"gzip\"",
"self",
".",
"class",
".",
"s3_file_key",
"exporter",
".",
"source_table",
",",
"gzipped",
"(",
"file_name",
")",
"else",
"self",
".",
"class",
".",
"s3_file_key",
"exporter",
".",
"source_table",
",",
"file_name",
"end",
"end"
] | Returns the s3 key to be used
@return [String] file key with extension | [
"Returns",
"the",
"s3",
"key",
"to",
"be",
"used"
] | 823f6da36f43a39f340a3ca7eb159df58a86766d | https://github.com/angelim/rails_redshift_replicator/blob/823f6da36f43a39f340a3ca7eb159df58a86766d/lib/rails_redshift_replicator/file_manager.rb#L80-L86 | train |
angelim/rails_redshift_replicator | lib/rails_redshift_replicator/file_manager.rb | RailsRedshiftReplicator.FileManager.upload_csv | def upload_csv(files)
files.each do |file|
basename = File.basename(file)
next if basename == File.basename(exporter.replication.key)
RailsRedshiftReplicator.logger.info I18n.t(:uploading_notice,
file: file,
key: self.class.s3_file_key(exporter.source_table, basename),
scope: :rails_redshift_replicator)
s3_client.put_object(
key: self.class.s3_file_key(exporter.source_table, basename),
body: File.open(file),
bucket: bucket
)
end
files.each { |f| FileUtils.rm f }
end | ruby | def upload_csv(files)
files.each do |file|
basename = File.basename(file)
next if basename == File.basename(exporter.replication.key)
RailsRedshiftReplicator.logger.info I18n.t(:uploading_notice,
file: file,
key: self.class.s3_file_key(exporter.source_table, basename),
scope: :rails_redshift_replicator)
s3_client.put_object(
key: self.class.s3_file_key(exporter.source_table, basename),
body: File.open(file),
bucket: bucket
)
end
files.each { |f| FileUtils.rm f }
end | [
"def",
"upload_csv",
"(",
"files",
")",
"files",
".",
"each",
"do",
"|",
"file",
"|",
"basename",
"=",
"File",
".",
"basename",
"(",
"file",
")",
"next",
"if",
"basename",
"==",
"File",
".",
"basename",
"(",
"exporter",
".",
"replication",
".",
"key",
")",
"RailsRedshiftReplicator",
".",
"logger",
".",
"info",
"I18n",
".",
"t",
"(",
":uploading_notice",
",",
"file",
":",
"file",
",",
"key",
":",
"self",
".",
"class",
".",
"s3_file_key",
"(",
"exporter",
".",
"source_table",
",",
"basename",
")",
",",
"scope",
":",
":rails_redshift_replicator",
")",
"s3_client",
".",
"put_object",
"(",
"key",
":",
"self",
".",
"class",
".",
"s3_file_key",
"(",
"exporter",
".",
"source_table",
",",
"basename",
")",
",",
"body",
":",
"File",
".",
"open",
"(",
"file",
")",
",",
"bucket",
":",
"bucket",
")",
"end",
"files",
".",
"each",
"{",
"|",
"f",
"|",
"FileUtils",
".",
"rm",
"f",
"}",
"end"
] | Uploads splitted CSVs
@param files [Array<String>] array of files paths to upload | [
"Uploads",
"splitted",
"CSVs"
] | 823f6da36f43a39f340a3ca7eb159df58a86766d | https://github.com/angelim/rails_redshift_replicator/blob/823f6da36f43a39f340a3ca7eb159df58a86766d/lib/rails_redshift_replicator/file_manager.rb#L117-L132 | train |
rightscale/right_chimp | lib/right_chimp/exec/executor.rb | Chimp.Executor.run_with_retry | def run_with_retry(&block)
Log.debug "Running job '#{@job_id}' with status '#{@status}'"
# If we are not the first job in this group, wait @delay
ChimpDaemon.instance.semaphore.synchronize do
if @group.started >= @concurrency && @delay.nonzero?
Log.info "[#{@job_uuid}] Sleeping #{@delay} seconds between tasks"
sleep @delay
end
@group.started += 1
end
@status = STATUS_RUNNING
@time_start = Time.now
Log.info self.describe_work_start unless @quiet
#
# The inner level of exception handling here tries to catch anything
# that can be easily retired or failed-- normal exceptions.
#
# The outer level of exception handling handles weird stuff; for example,
# sometimes rest_connection raises RuntimeError exceptions...
#
# This fixes acu75562.
#
begin
begin
yield if not @dry_run
if @owner != nil
@status = STATUS_DONE
@group.job_completed
else
Log.warn "[#{@job_uuid}][#{@job_id}] Ownership of job_id #{job_id} lost. User cancelled operation?"
end
rescue SystemExit, Interrupt => ex
$stderr.puts 'Exiting!'
raise ex
rescue Interrupt => ex
name = @array['name'] if @array
name = @server['name'] || @server['nickname'] if @server
Log.error self.describe_work_error
if @retry_count > 0
@status = STATUS_RETRYING
Log.error "[#{@job_uuid}][#{@job_id}] Error executing on \"#{name}\". Retrying in #{@retry_sleep} seconds..."
@retry_count -= 1
sleep @retry_sleep
retry
end
@status = STATUS_ERROR
@error = ex
Log.error "[#{@job_uuid}][#{@job_id}] Error executing on \"#{name}\": #{ex}"
ensure
@time_end = Time.now
Log.info self.describe_work_done unless @quiet
end
rescue RuntimeError => ex
err = ex.message + "IP: #{@server.params["ip_address"]}\n" if @server.params['ip_address']
err += " Group: #{@group.group_id}\n" if @group.group_id
err += " Notes: #{@job_notes}\n" if @job_notes
err += " Notes: #{@job_notes}\n" if @job_notes
Log.error "[#{@job_uuid}][#{@job_id}] Caught RuntimeError: #{err} Job failed.\n"
@status = STATUS_ERROR
@error = ex
end
end | ruby | def run_with_retry(&block)
Log.debug "Running job '#{@job_id}' with status '#{@status}'"
# If we are not the first job in this group, wait @delay
ChimpDaemon.instance.semaphore.synchronize do
if @group.started >= @concurrency && @delay.nonzero?
Log.info "[#{@job_uuid}] Sleeping #{@delay} seconds between tasks"
sleep @delay
end
@group.started += 1
end
@status = STATUS_RUNNING
@time_start = Time.now
Log.info self.describe_work_start unless @quiet
#
# The inner level of exception handling here tries to catch anything
# that can be easily retired or failed-- normal exceptions.
#
# The outer level of exception handling handles weird stuff; for example,
# sometimes rest_connection raises RuntimeError exceptions...
#
# This fixes acu75562.
#
begin
begin
yield if not @dry_run
if @owner != nil
@status = STATUS_DONE
@group.job_completed
else
Log.warn "[#{@job_uuid}][#{@job_id}] Ownership of job_id #{job_id} lost. User cancelled operation?"
end
rescue SystemExit, Interrupt => ex
$stderr.puts 'Exiting!'
raise ex
rescue Interrupt => ex
name = @array['name'] if @array
name = @server['name'] || @server['nickname'] if @server
Log.error self.describe_work_error
if @retry_count > 0
@status = STATUS_RETRYING
Log.error "[#{@job_uuid}][#{@job_id}] Error executing on \"#{name}\". Retrying in #{@retry_sleep} seconds..."
@retry_count -= 1
sleep @retry_sleep
retry
end
@status = STATUS_ERROR
@error = ex
Log.error "[#{@job_uuid}][#{@job_id}] Error executing on \"#{name}\": #{ex}"
ensure
@time_end = Time.now
Log.info self.describe_work_done unless @quiet
end
rescue RuntimeError => ex
err = ex.message + "IP: #{@server.params["ip_address"]}\n" if @server.params['ip_address']
err += " Group: #{@group.group_id}\n" if @group.group_id
err += " Notes: #{@job_notes}\n" if @job_notes
err += " Notes: #{@job_notes}\n" if @job_notes
Log.error "[#{@job_uuid}][#{@job_id}] Caught RuntimeError: #{err} Job failed.\n"
@status = STATUS_ERROR
@error = ex
end
end | [
"def",
"run_with_retry",
"(",
"&",
"block",
")",
"Log",
".",
"debug",
"\"Running job '#{@job_id}' with status '#{@status}'\"",
"ChimpDaemon",
".",
"instance",
".",
"semaphore",
".",
"synchronize",
"do",
"if",
"@group",
".",
"started",
">=",
"@concurrency",
"&&",
"@delay",
".",
"nonzero?",
"Log",
".",
"info",
"\"[#{@job_uuid}] Sleeping #{@delay} seconds between tasks\"",
"sleep",
"@delay",
"end",
"@group",
".",
"started",
"+=",
"1",
"end",
"@status",
"=",
"STATUS_RUNNING",
"@time_start",
"=",
"Time",
".",
"now",
"Log",
".",
"info",
"self",
".",
"describe_work_start",
"unless",
"@quiet",
"begin",
"begin",
"yield",
"if",
"not",
"@dry_run",
"if",
"@owner",
"!=",
"nil",
"@status",
"=",
"STATUS_DONE",
"@group",
".",
"job_completed",
"else",
"Log",
".",
"warn",
"\"[#{@job_uuid}][#{@job_id}] Ownership of job_id #{job_id} lost. User cancelled operation?\"",
"end",
"rescue",
"SystemExit",
",",
"Interrupt",
"=>",
"ex",
"$stderr",
".",
"puts",
"'Exiting!'",
"raise",
"ex",
"rescue",
"Interrupt",
"=>",
"ex",
"name",
"=",
"@array",
"[",
"'name'",
"]",
"if",
"@array",
"name",
"=",
"@server",
"[",
"'name'",
"]",
"||",
"@server",
"[",
"'nickname'",
"]",
"if",
"@server",
"Log",
".",
"error",
"self",
".",
"describe_work_error",
"if",
"@retry_count",
">",
"0",
"@status",
"=",
"STATUS_RETRYING",
"Log",
".",
"error",
"\"[#{@job_uuid}][#{@job_id}] Error executing on \\\"#{name}\\\". Retrying in #{@retry_sleep} seconds...\"",
"@retry_count",
"-=",
"1",
"sleep",
"@retry_sleep",
"retry",
"end",
"@status",
"=",
"STATUS_ERROR",
"@error",
"=",
"ex",
"Log",
".",
"error",
"\"[#{@job_uuid}][#{@job_id}] Error executing on \\\"#{name}\\\": #{ex}\"",
"ensure",
"@time_end",
"=",
"Time",
".",
"now",
"Log",
".",
"info",
"self",
".",
"describe_work_done",
"unless",
"@quiet",
"end",
"rescue",
"RuntimeError",
"=>",
"ex",
"err",
"=",
"ex",
".",
"message",
"+",
"\"IP: #{@server.params[\"ip_address\"]}\\n\"",
"if",
"@server",
".",
"params",
"[",
"'ip_address'",
"]",
"err",
"+=",
"\" Group: #{@group.group_id}\\n\"",
"if",
"@group",
".",
"group_id",
"err",
"+=",
"\" Notes: #{@job_notes}\\n\"",
"if",
"@job_notes",
"err",
"+=",
"\" Notes: #{@job_notes}\\n\"",
"if",
"@job_notes",
"Log",
".",
"error",
"\"[#{@job_uuid}][#{@job_id}] Caught RuntimeError: #{err} Job failed.\\n\"",
"@status",
"=",
"STATUS_ERROR",
"@error",
"=",
"ex",
"end",
"end"
] | Run a unit of work with retries
This is called from the subclass with a code block to yield to | [
"Run",
"a",
"unit",
"of",
"work",
"with",
"retries",
"This",
"is",
"called",
"from",
"the",
"subclass",
"with",
"a",
"code",
"block",
"to",
"yield",
"to"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/exec/executor.rb#L108-L179 | train |
catarse/catarse_pagarme | app/models/catarse_pagarme/payment_delegator.rb | CatarsePagarme.PaymentDelegator.transfer_funds | def transfer_funds
raise "payment must be paid" if !payment.paid?
bank_account = PagarMe::BankAccount.new(bank_account_attributes.delete(:bank_account))
bank_account.create
raise "unable to create an bank account" unless bank_account.id.present?
transfer = PagarMe::Transfer.new({
bank_account_id: bank_account.id,
amount: value_for_transaction
})
transfer.create
raise "unable to create a transfer" unless transfer.id.present?
#avoid sending notification
payment.update_attributes(state: 'pending_refund')
payment.payment_transfers.create!({
user: payment.user,
transfer_id: transfer.id,
transfer_data: transfer.to_json
})
end | ruby | def transfer_funds
raise "payment must be paid" if !payment.paid?
bank_account = PagarMe::BankAccount.new(bank_account_attributes.delete(:bank_account))
bank_account.create
raise "unable to create an bank account" unless bank_account.id.present?
transfer = PagarMe::Transfer.new({
bank_account_id: bank_account.id,
amount: value_for_transaction
})
transfer.create
raise "unable to create a transfer" unless transfer.id.present?
#avoid sending notification
payment.update_attributes(state: 'pending_refund')
payment.payment_transfers.create!({
user: payment.user,
transfer_id: transfer.id,
transfer_data: transfer.to_json
})
end | [
"def",
"transfer_funds",
"raise",
"\"payment must be paid\"",
"if",
"!",
"payment",
".",
"paid?",
"bank_account",
"=",
"PagarMe",
"::",
"BankAccount",
".",
"new",
"(",
"bank_account_attributes",
".",
"delete",
"(",
":bank_account",
")",
")",
"bank_account",
".",
"create",
"raise",
"\"unable to create an bank account\"",
"unless",
"bank_account",
".",
"id",
".",
"present?",
"transfer",
"=",
"PagarMe",
"::",
"Transfer",
".",
"new",
"(",
"{",
"bank_account_id",
":",
"bank_account",
".",
"id",
",",
"amount",
":",
"value_for_transaction",
"}",
")",
"transfer",
".",
"create",
"raise",
"\"unable to create a transfer\"",
"unless",
"transfer",
".",
"id",
".",
"present?",
"payment",
".",
"update_attributes",
"(",
"state",
":",
"'pending_refund'",
")",
"payment",
".",
"payment_transfers",
".",
"create!",
"(",
"{",
"user",
":",
"payment",
".",
"user",
",",
"transfer_id",
":",
"transfer",
".",
"id",
",",
"transfer_data",
":",
"transfer",
".",
"to_json",
"}",
")",
"end"
] | Transfer payment amount to payer bank account via transfers API | [
"Transfer",
"payment",
"amount",
"to",
"payer",
"bank",
"account",
"via",
"transfers",
"API"
] | 5990bdbfddb3f2309c805d3074ea4dc04140d198 | https://github.com/catarse/catarse_pagarme/blob/5990bdbfddb3f2309c805d3074ea4dc04140d198/app/models/catarse_pagarme/payment_delegator.rb#L112-L133 | train |
rightscale/right_chimp | lib/right_chimp/chimp.rb | Chimp.Chimp.run | def run
queue = ChimpQueue.instance
arguments = []
ARGV.each { |arg| arguments << arg.clone }
self.cli_args=arguments.collect {|param|
param.gsub(/(?<==).*/) do |match|
match='"'+match+'"'
end
}.join(" ")
parse_command_line if @interactive
check_option_validity if @interactive
disable_logging unless @@verbose
puts "chimp #{VERSION} executing..." if (@interactive and not @use_chimpd) and not @@quiet
#
# Wait for chimpd to complete tasks
#
if @chimpd_wait_until_done
chimpd_wait_until_done
exit
end
#
# Send the command to chimpd for execution
#
if @use_chimpd
timestamp = Time.now.to_i
length = 6
self.job_uuid = (36**(length - 1) + rand(36**length - 36**(length - 1))).to_s(36)
ChimpDaemonClient.submit(@chimpd_host, @chimpd_port, self, job_uuid)
exit
else
# Connect to the Api
Connection.instance
if @interactive
Connection.connect
else
Connection.connect_and_cache
end
end
# If we're processing the command ourselves, then go
# ahead and start making API calls to select the objects
# to operate upon
#
# Get elements if --array has been passed
get_array_info
# Get elements if we are searching by tags
get_server_info
# At this stage @servers should be populated with our findings
# Get ST info for all elements
if not @servers.empty?
get_template_info unless @servers.empty?
puts "Looking for the rightscripts (This might take some time)" if (@interactive and not @use_chimpd) and not @@quiet
get_executable_info
end
if Chimp.failure
#This is the failure point when executing standalone
Log.error "##################################################"
Log.error "[#{Chimp.get_job_uuid}] API CALL FAILED FOR:"
Log.error "[#{Chimp.get_job_uuid}] chimp #{@cli_args} "
Log.error "[#{Chimp.get_job_uuid}] Run manually!"
Log.error "##################################################"
exit 1
end
#
# Optionally display the list of objects to operate on
# and prompt the user
#
if @prompt and @interactive
list_of_objects = make_human_readable_list_of_objects
confirm = (list_of_objects.size > 0 and @action != :action_none) or @action == :action_none
if @script_to_run.nil?
verify("Your command will be executed on the following:", list_of_objects, confirm)
else
verify("Your command \""+@script_to_run.params['right_script']['name']+"\" will be executed on the following:", list_of_objects, confirm)
end
end
#
# Load the queue with work
#
if not @servers.first.nil? and ( not @executable.nil? or @action == :action_ssh or @action == :action_report)
jobs = generate_jobs(@servers, @server_template, @executable)
add_to_queue(jobs)
end
#
# Exit early if there is nothing to do
#
if @action == :action_none or ( queue.group[@group].nil? || queue.group[@group].size == 0)
puts "No actions to perform." unless self.quiet
else
do_work
end
end | ruby | def run
queue = ChimpQueue.instance
arguments = []
ARGV.each { |arg| arguments << arg.clone }
self.cli_args=arguments.collect {|param|
param.gsub(/(?<==).*/) do |match|
match='"'+match+'"'
end
}.join(" ")
parse_command_line if @interactive
check_option_validity if @interactive
disable_logging unless @@verbose
puts "chimp #{VERSION} executing..." if (@interactive and not @use_chimpd) and not @@quiet
#
# Wait for chimpd to complete tasks
#
if @chimpd_wait_until_done
chimpd_wait_until_done
exit
end
#
# Send the command to chimpd for execution
#
if @use_chimpd
timestamp = Time.now.to_i
length = 6
self.job_uuid = (36**(length - 1) + rand(36**length - 36**(length - 1))).to_s(36)
ChimpDaemonClient.submit(@chimpd_host, @chimpd_port, self, job_uuid)
exit
else
# Connect to the Api
Connection.instance
if @interactive
Connection.connect
else
Connection.connect_and_cache
end
end
# If we're processing the command ourselves, then go
# ahead and start making API calls to select the objects
# to operate upon
#
# Get elements if --array has been passed
get_array_info
# Get elements if we are searching by tags
get_server_info
# At this stage @servers should be populated with our findings
# Get ST info for all elements
if not @servers.empty?
get_template_info unless @servers.empty?
puts "Looking for the rightscripts (This might take some time)" if (@interactive and not @use_chimpd) and not @@quiet
get_executable_info
end
if Chimp.failure
#This is the failure point when executing standalone
Log.error "##################################################"
Log.error "[#{Chimp.get_job_uuid}] API CALL FAILED FOR:"
Log.error "[#{Chimp.get_job_uuid}] chimp #{@cli_args} "
Log.error "[#{Chimp.get_job_uuid}] Run manually!"
Log.error "##################################################"
exit 1
end
#
# Optionally display the list of objects to operate on
# and prompt the user
#
if @prompt and @interactive
list_of_objects = make_human_readable_list_of_objects
confirm = (list_of_objects.size > 0 and @action != :action_none) or @action == :action_none
if @script_to_run.nil?
verify("Your command will be executed on the following:", list_of_objects, confirm)
else
verify("Your command \""+@script_to_run.params['right_script']['name']+"\" will be executed on the following:", list_of_objects, confirm)
end
end
#
# Load the queue with work
#
if not @servers.first.nil? and ( not @executable.nil? or @action == :action_ssh or @action == :action_report)
jobs = generate_jobs(@servers, @server_template, @executable)
add_to_queue(jobs)
end
#
# Exit early if there is nothing to do
#
if @action == :action_none or ( queue.group[@group].nil? || queue.group[@group].size == 0)
puts "No actions to perform." unless self.quiet
else
do_work
end
end | [
"def",
"run",
"queue",
"=",
"ChimpQueue",
".",
"instance",
"arguments",
"=",
"[",
"]",
"ARGV",
".",
"each",
"{",
"|",
"arg",
"|",
"arguments",
"<<",
"arg",
".",
"clone",
"}",
"self",
".",
"cli_args",
"=",
"arguments",
".",
"collect",
"{",
"|",
"param",
"|",
"param",
".",
"gsub",
"(",
"/",
"/",
")",
"do",
"|",
"match",
"|",
"match",
"=",
"'\"'",
"+",
"match",
"+",
"'\"'",
"end",
"}",
".",
"join",
"(",
"\" \"",
")",
"parse_command_line",
"if",
"@interactive",
"check_option_validity",
"if",
"@interactive",
"disable_logging",
"unless",
"@@verbose",
"puts",
"\"chimp #{VERSION} executing...\"",
"if",
"(",
"@interactive",
"and",
"not",
"@use_chimpd",
")",
"and",
"not",
"@@quiet",
"if",
"@chimpd_wait_until_done",
"chimpd_wait_until_done",
"exit",
"end",
"if",
"@use_chimpd",
"timestamp",
"=",
"Time",
".",
"now",
".",
"to_i",
"length",
"=",
"6",
"self",
".",
"job_uuid",
"=",
"(",
"36",
"**",
"(",
"length",
"-",
"1",
")",
"+",
"rand",
"(",
"36",
"**",
"length",
"-",
"36",
"**",
"(",
"length",
"-",
"1",
")",
")",
")",
".",
"to_s",
"(",
"36",
")",
"ChimpDaemonClient",
".",
"submit",
"(",
"@chimpd_host",
",",
"@chimpd_port",
",",
"self",
",",
"job_uuid",
")",
"exit",
"else",
"Connection",
".",
"instance",
"if",
"@interactive",
"Connection",
".",
"connect",
"else",
"Connection",
".",
"connect_and_cache",
"end",
"end",
"get_array_info",
"get_server_info",
"if",
"not",
"@servers",
".",
"empty?",
"get_template_info",
"unless",
"@servers",
".",
"empty?",
"puts",
"\"Looking for the rightscripts (This might take some time)\"",
"if",
"(",
"@interactive",
"and",
"not",
"@use_chimpd",
")",
"and",
"not",
"@@quiet",
"get_executable_info",
"end",
"if",
"Chimp",
".",
"failure",
"Log",
".",
"error",
"\"##################################################\"",
"Log",
".",
"error",
"\"[#{Chimp.get_job_uuid}] API CALL FAILED FOR:\"",
"Log",
".",
"error",
"\"[#{Chimp.get_job_uuid}] chimp #{@cli_args} \"",
"Log",
".",
"error",
"\"[#{Chimp.get_job_uuid}] Run manually!\"",
"Log",
".",
"error",
"\"##################################################\"",
"exit",
"1",
"end",
"if",
"@prompt",
"and",
"@interactive",
"list_of_objects",
"=",
"make_human_readable_list_of_objects",
"confirm",
"=",
"(",
"list_of_objects",
".",
"size",
">",
"0",
"and",
"@action",
"!=",
":action_none",
")",
"or",
"@action",
"==",
":action_none",
"if",
"@script_to_run",
".",
"nil?",
"verify",
"(",
"\"Your command will be executed on the following:\"",
",",
"list_of_objects",
",",
"confirm",
")",
"else",
"verify",
"(",
"\"Your command \\\"\"",
"+",
"@script_to_run",
".",
"params",
"[",
"'right_script'",
"]",
"[",
"'name'",
"]",
"+",
"\"\\\" will be executed on the following:\"",
",",
"list_of_objects",
",",
"confirm",
")",
"end",
"end",
"if",
"not",
"@servers",
".",
"first",
".",
"nil?",
"and",
"(",
"not",
"@executable",
".",
"nil?",
"or",
"@action",
"==",
":action_ssh",
"or",
"@action",
"==",
":action_report",
")",
"jobs",
"=",
"generate_jobs",
"(",
"@servers",
",",
"@server_template",
",",
"@executable",
")",
"add_to_queue",
"(",
"jobs",
")",
"end",
"if",
"@action",
"==",
":action_none",
"or",
"(",
"queue",
".",
"group",
"[",
"@group",
"]",
".",
"nil?",
"||",
"queue",
".",
"group",
"[",
"@group",
"]",
".",
"size",
"==",
"0",
")",
"puts",
"\"No actions to perform.\"",
"unless",
"self",
".",
"quiet",
"else",
"do_work",
"end",
"end"
] | Set up reasonable defaults
Entry point for the chimp command line application | [
"Set",
"up",
"reasonable",
"defaults"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/chimp.rb#L97-L205 | train |
rightscale/right_chimp | lib/right_chimp/chimp.rb | Chimp.Chimp.check_option_validity | def check_option_validity
if @hold && !@array_names.empty?
puts "ERROR: Holding of array objects is not yet supported"
exit 1
end
if @tags.empty? and @array_names.empty? and @deployment_names.empty? and not @chimpd_wait_until_done
puts "ERROR: Please select the objects to operate upon."
help
exit 1
end
if not @array_names.empty? and ( not @tags.empty? or not @deployment_names.empty? )
puts "ERROR: You cannot mix ServerArray queries with other types of queries."
help
exit 1
end
end | ruby | def check_option_validity
if @hold && !@array_names.empty?
puts "ERROR: Holding of array objects is not yet supported"
exit 1
end
if @tags.empty? and @array_names.empty? and @deployment_names.empty? and not @chimpd_wait_until_done
puts "ERROR: Please select the objects to operate upon."
help
exit 1
end
if not @array_names.empty? and ( not @tags.empty? or not @deployment_names.empty? )
puts "ERROR: You cannot mix ServerArray queries with other types of queries."
help
exit 1
end
end | [
"def",
"check_option_validity",
"if",
"@hold",
"&&",
"!",
"@array_names",
".",
"empty?",
"puts",
"\"ERROR: Holding of array objects is not yet supported\"",
"exit",
"1",
"end",
"if",
"@tags",
".",
"empty?",
"and",
"@array_names",
".",
"empty?",
"and",
"@deployment_names",
".",
"empty?",
"and",
"not",
"@chimpd_wait_until_done",
"puts",
"\"ERROR: Please select the objects to operate upon.\"",
"help",
"exit",
"1",
"end",
"if",
"not",
"@array_names",
".",
"empty?",
"and",
"(",
"not",
"@tags",
".",
"empty?",
"or",
"not",
"@deployment_names",
".",
"empty?",
")",
"puts",
"\"ERROR: You cannot mix ServerArray queries with other types of queries.\"",
"help",
"exit",
"1",
"end",
"end"
] | Check for any invalid combinations of command line options | [
"Check",
"for",
"any",
"invalid",
"combinations",
"of",
"command",
"line",
"options"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/chimp.rb#L485-L502 | train |
rightscale/right_chimp | lib/right_chimp/chimp.rb | Chimp.Chimp.get_servers_by_tag | def get_servers_by_tag(tags)
# Take tags and collapse it,
# Default case, tag is AND
if @match_all
t = tags.join("&tag=")
filter = "tag=#{t}"
servers = Connection.instances(filter)
else
t = tags.join(",")
filter = "tag=#{t}"
servers = Connection.instances(filter)
end
if servers.nil?
if @ignore_errors
Log.warn "[#{Chimp.get_job_uuid}] Tag query returned no results: #{tags.join(" ")}"
else
raise "[#{Chimp.get_job_uuid}] Tag query returned no results: #{tags.join(" ")}\n"
end
elsif servers.empty?
if @ignore_errors
Log.warn "[#{Chimp.get_job_uuid}] Tag query returned no results: #{tags.join(" ")}"
else
raise "[#{Chimp.get_job_uuid}] Tag query returned no results: #{tags.join(" ")}\n"
end
end
servers = verify_tagged_instances(servers,tags)
return(servers)
end | ruby | def get_servers_by_tag(tags)
# Take tags and collapse it,
# Default case, tag is AND
if @match_all
t = tags.join("&tag=")
filter = "tag=#{t}"
servers = Connection.instances(filter)
else
t = tags.join(",")
filter = "tag=#{t}"
servers = Connection.instances(filter)
end
if servers.nil?
if @ignore_errors
Log.warn "[#{Chimp.get_job_uuid}] Tag query returned no results: #{tags.join(" ")}"
else
raise "[#{Chimp.get_job_uuid}] Tag query returned no results: #{tags.join(" ")}\n"
end
elsif servers.empty?
if @ignore_errors
Log.warn "[#{Chimp.get_job_uuid}] Tag query returned no results: #{tags.join(" ")}"
else
raise "[#{Chimp.get_job_uuid}] Tag query returned no results: #{tags.join(" ")}\n"
end
end
servers = verify_tagged_instances(servers,tags)
return(servers)
end | [
"def",
"get_servers_by_tag",
"(",
"tags",
")",
"if",
"@match_all",
"t",
"=",
"tags",
".",
"join",
"(",
"\"&tag=\"",
")",
"filter",
"=",
"\"tag=#{t}\"",
"servers",
"=",
"Connection",
".",
"instances",
"(",
"filter",
")",
"else",
"t",
"=",
"tags",
".",
"join",
"(",
"\",\"",
")",
"filter",
"=",
"\"tag=#{t}\"",
"servers",
"=",
"Connection",
".",
"instances",
"(",
"filter",
")",
"end",
"if",
"servers",
".",
"nil?",
"if",
"@ignore_errors",
"Log",
".",
"warn",
"\"[#{Chimp.get_job_uuid}] Tag query returned no results: #{tags.join(\" \")}\"",
"else",
"raise",
"\"[#{Chimp.get_job_uuid}] Tag query returned no results: #{tags.join(\" \")}\\n\"",
"end",
"elsif",
"servers",
".",
"empty?",
"if",
"@ignore_errors",
"Log",
".",
"warn",
"\"[#{Chimp.get_job_uuid}] Tag query returned no results: #{tags.join(\" \")}\"",
"else",
"raise",
"\"[#{Chimp.get_job_uuid}] Tag query returned no results: #{tags.join(\" \")}\\n\"",
"end",
"end",
"servers",
"=",
"verify_tagged_instances",
"(",
"servers",
",",
"tags",
")",
"return",
"(",
"servers",
")",
"end"
] | Api1.6 equivalent | [
"Api1",
".",
"6",
"equivalent"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/chimp.rb#L507-L537 | train |
rightscale/right_chimp | lib/right_chimp/chimp.rb | Chimp.Chimp.verify_tagged_instances | def verify_tagged_instances(servers,tags)
array_list = servers
# servers is an array of hashes
# verify that each object contains the tags.
if @match_all
# has to contain BOTH
matching_servers = array_list.select { |instance| (tags - instance['tags']).empty? }
else
# has to contain ANY
matching_servers = array_list.select { |instance| tags.any? {|tag| instance['tags'].include?(tag) }}
end
# Shall there be a discrepancy, we need to raise an error and end the run.
if matching_servers.size != servers.size
if @ignore_errors
Log.error "[#{Chimp.get_job_uuid}] #{servers.size - matching_servers.size} instances didnt match tag selection."
Log.error "[#{Chimp.get_job_uuid}] #{tags.join(" ")}"
Chimp.set_failure(true)
Log.error "[#{Chimp.get_job_uuid}] Set failure to true because of discrepancy"
servers = []
else
raise "[#{Chimp.get_job_uuid}] #{servers.size - matching_servers.size} instances didnt match tag selection"
end
end
return servers
end | ruby | def verify_tagged_instances(servers,tags)
array_list = servers
# servers is an array of hashes
# verify that each object contains the tags.
if @match_all
# has to contain BOTH
matching_servers = array_list.select { |instance| (tags - instance['tags']).empty? }
else
# has to contain ANY
matching_servers = array_list.select { |instance| tags.any? {|tag| instance['tags'].include?(tag) }}
end
# Shall there be a discrepancy, we need to raise an error and end the run.
if matching_servers.size != servers.size
if @ignore_errors
Log.error "[#{Chimp.get_job_uuid}] #{servers.size - matching_servers.size} instances didnt match tag selection."
Log.error "[#{Chimp.get_job_uuid}] #{tags.join(" ")}"
Chimp.set_failure(true)
Log.error "[#{Chimp.get_job_uuid}] Set failure to true because of discrepancy"
servers = []
else
raise "[#{Chimp.get_job_uuid}] #{servers.size - matching_servers.size} instances didnt match tag selection"
end
end
return servers
end | [
"def",
"verify_tagged_instances",
"(",
"servers",
",",
"tags",
")",
"array_list",
"=",
"servers",
"if",
"@match_all",
"matching_servers",
"=",
"array_list",
".",
"select",
"{",
"|",
"instance",
"|",
"(",
"tags",
"-",
"instance",
"[",
"'tags'",
"]",
")",
".",
"empty?",
"}",
"else",
"matching_servers",
"=",
"array_list",
".",
"select",
"{",
"|",
"instance",
"|",
"tags",
".",
"any?",
"{",
"|",
"tag",
"|",
"instance",
"[",
"'tags'",
"]",
".",
"include?",
"(",
"tag",
")",
"}",
"}",
"end",
"if",
"matching_servers",
".",
"size",
"!=",
"servers",
".",
"size",
"if",
"@ignore_errors",
"Log",
".",
"error",
"\"[#{Chimp.get_job_uuid}] #{servers.size - matching_servers.size} instances didnt match tag selection.\"",
"Log",
".",
"error",
"\"[#{Chimp.get_job_uuid}] #{tags.join(\" \")}\"",
"Chimp",
".",
"set_failure",
"(",
"true",
")",
"Log",
".",
"error",
"\"[#{Chimp.get_job_uuid}] Set failure to true because of discrepancy\"",
"servers",
"=",
"[",
"]",
"else",
"raise",
"\"[#{Chimp.get_job_uuid}] #{servers.size - matching_servers.size} instances didnt match tag selection\"",
"end",
"end",
"return",
"servers",
"end"
] | Verify that all returned instances from the API match our tag request | [
"Verify",
"that",
"all",
"returned",
"instances",
"from",
"the",
"API",
"match",
"our",
"tag",
"request"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/chimp.rb#L542-L570 | train |
rightscale/right_chimp | lib/right_chimp/chimp.rb | Chimp.Chimp.get_hrefs_for_arrays | def get_hrefs_for_arrays(names)
result = []
arrays_hrefs = []
if names.size > 0
names.each do |array_name|
# Find if arrays exist, if not raise warning.
# One API call per array
begin
Log.debug "[#{Chimp.get_job_uuid}] Making API 1.5 call: client.server_arrays.index(:filter => [#{array_name}])"
tries ||= 3
result = Connection.client.server_arrays.index(:filter => ["name==#{array_name}"])
rescue
Log.error "[#{Chimp.get_job_uuid}] Making API 1.5 call: client.server_arrays.index failed (retrying)."
sleep 30
retry unless (tries -= 1).zero?
Log.error "[#{Chimp.get_job_uuid}] Making API 1.5 call: client.server_arrays.index failed (giving up)."
end
# Result is an array with all the server arrays
if result.size != 0
if @exact
#remove results that do not exactly match
result.each{ |r|
if array_names.include?(r.raw['name'])
arrays_hrefs += [ r.href ]
end
}
else
arrays_hrefs += result.collect(&:href)
end
else
if @ignore_errors
Log.debug "[#{Chimp.get_job_uuid}] Could not find array \"#{array_name}\""
else
Log.error "[#{Chimp.get_job_uuid}] Could not find array \"#{array_name}\""
end
end
end
if ( arrays_hrefs.empty? )
Log.debug "[#{Chimp.get_job_uuid}] Did not find any arrays that matched!" unless names.size == 1
end
return(arrays_hrefs)
end
end | ruby | def get_hrefs_for_arrays(names)
result = []
arrays_hrefs = []
if names.size > 0
names.each do |array_name|
# Find if arrays exist, if not raise warning.
# One API call per array
begin
Log.debug "[#{Chimp.get_job_uuid}] Making API 1.5 call: client.server_arrays.index(:filter => [#{array_name}])"
tries ||= 3
result = Connection.client.server_arrays.index(:filter => ["name==#{array_name}"])
rescue
Log.error "[#{Chimp.get_job_uuid}] Making API 1.5 call: client.server_arrays.index failed (retrying)."
sleep 30
retry unless (tries -= 1).zero?
Log.error "[#{Chimp.get_job_uuid}] Making API 1.5 call: client.server_arrays.index failed (giving up)."
end
# Result is an array with all the server arrays
if result.size != 0
if @exact
#remove results that do not exactly match
result.each{ |r|
if array_names.include?(r.raw['name'])
arrays_hrefs += [ r.href ]
end
}
else
arrays_hrefs += result.collect(&:href)
end
else
if @ignore_errors
Log.debug "[#{Chimp.get_job_uuid}] Could not find array \"#{array_name}\""
else
Log.error "[#{Chimp.get_job_uuid}] Could not find array \"#{array_name}\""
end
end
end
if ( arrays_hrefs.empty? )
Log.debug "[#{Chimp.get_job_uuid}] Did not find any arrays that matched!" unless names.size == 1
end
return(arrays_hrefs)
end
end | [
"def",
"get_hrefs_for_arrays",
"(",
"names",
")",
"result",
"=",
"[",
"]",
"arrays_hrefs",
"=",
"[",
"]",
"if",
"names",
".",
"size",
">",
"0",
"names",
".",
"each",
"do",
"|",
"array_name",
"|",
"begin",
"Log",
".",
"debug",
"\"[#{Chimp.get_job_uuid}] Making API 1.5 call: client.server_arrays.index(:filter => [#{array_name}])\"",
"tries",
"||=",
"3",
"result",
"=",
"Connection",
".",
"client",
".",
"server_arrays",
".",
"index",
"(",
":filter",
"=>",
"[",
"\"name==#{array_name}\"",
"]",
")",
"rescue",
"Log",
".",
"error",
"\"[#{Chimp.get_job_uuid}] Making API 1.5 call: client.server_arrays.index failed (retrying).\"",
"sleep",
"30",
"retry",
"unless",
"(",
"tries",
"-=",
"1",
")",
".",
"zero?",
"Log",
".",
"error",
"\"[#{Chimp.get_job_uuid}] Making API 1.5 call: client.server_arrays.index failed (giving up).\"",
"end",
"if",
"result",
".",
"size",
"!=",
"0",
"if",
"@exact",
"result",
".",
"each",
"{",
"|",
"r",
"|",
"if",
"array_names",
".",
"include?",
"(",
"r",
".",
"raw",
"[",
"'name'",
"]",
")",
"arrays_hrefs",
"+=",
"[",
"r",
".",
"href",
"]",
"end",
"}",
"else",
"arrays_hrefs",
"+=",
"result",
".",
"collect",
"(",
"&",
":href",
")",
"end",
"else",
"if",
"@ignore_errors",
"Log",
".",
"debug",
"\"[#{Chimp.get_job_uuid}] Could not find array \\\"#{array_name}\\\"\"",
"else",
"Log",
".",
"error",
"\"[#{Chimp.get_job_uuid}] Could not find array \\\"#{array_name}\\\"\"",
"end",
"end",
"end",
"if",
"(",
"arrays_hrefs",
".",
"empty?",
")",
"Log",
".",
"debug",
"\"[#{Chimp.get_job_uuid}] Did not find any arrays that matched!\"",
"unless",
"names",
".",
"size",
"==",
"1",
"end",
"return",
"(",
"arrays_hrefs",
")",
"end",
"end"
] | Given some array names, return the arrays hrefs
Api1.5 | [
"Given",
"some",
"array",
"names",
"return",
"the",
"arrays",
"hrefs",
"Api1",
".",
"5"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/chimp.rb#L592-L636 | train |
rightscale/right_chimp | lib/right_chimp/chimp.rb | Chimp.Chimp.detect_server_template | def detect_server_template(servers)
Log.debug "[#{Chimp.get_job_uuid}] Looking for server template"
st = []
if servers[0].nil?
return (st)
end
st += servers.collect { |s|
[s['href'],s['server_template']]
}.uniq {|a| a[0]}
#
# We return an array of server_template resources
# of the type [ st_href, st object ]
#
Log.debug "[#{Chimp.get_job_uuid}] Found server templates"
return(st)
end | ruby | def detect_server_template(servers)
Log.debug "[#{Chimp.get_job_uuid}] Looking for server template"
st = []
if servers[0].nil?
return (st)
end
st += servers.collect { |s|
[s['href'],s['server_template']]
}.uniq {|a| a[0]}
#
# We return an array of server_template resources
# of the type [ st_href, st object ]
#
Log.debug "[#{Chimp.get_job_uuid}] Found server templates"
return(st)
end | [
"def",
"detect_server_template",
"(",
"servers",
")",
"Log",
".",
"debug",
"\"[#{Chimp.get_job_uuid}] Looking for server template\"",
"st",
"=",
"[",
"]",
"if",
"servers",
"[",
"0",
"]",
".",
"nil?",
"return",
"(",
"st",
")",
"end",
"st",
"+=",
"servers",
".",
"collect",
"{",
"|",
"s",
"|",
"[",
"s",
"[",
"'href'",
"]",
",",
"s",
"[",
"'server_template'",
"]",
"]",
"}",
".",
"uniq",
"{",
"|",
"a",
"|",
"a",
"[",
"0",
"]",
"}",
"Log",
".",
"debug",
"\"[#{Chimp.get_job_uuid}] Found server templates\"",
"return",
"(",
"st",
")",
"end"
] | Given a list of servers | [
"Given",
"a",
"list",
"of",
"servers"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/chimp.rb#L641-L660 | train |
rightscale/right_chimp | lib/right_chimp/chimp.rb | Chimp.Chimp.detect_right_script | def detect_right_script(st, script)
Log.debug "[#{Chimp.get_job_uuid}] Looking for rightscript"
executable = nil
# In the event that chimpd find @op_scripts as nil, set it as an array.
if @op_scripts.nil?
@op_scripts = []
end
if st.nil?
return executable
end
# Take the sts and extract all operational scripts
@op_scripts = extract_operational_scripts(st)
# if script is empty, we will list all common scripts
# if not empty, we will list the first matching one
if @script == "" and @script != nil
# list all operational scripts
reduce_to_common_scripts(st.size)
script_id = list_and_select_op_script
# Provide the name + href
s = Executable.new
s.params['right_script']['href'] = @op_scripts[script_id][1].right_script.href
s.params['right_script']['name'] = @op_scripts[script_id][0]
@script_to_run = s
else
# Try to find the rightscript in our list of common operational scripts
@op_scripts.each do |rb|
script_name = rb[0]
if script_name.downcase.include?(script.downcase)
# We only need the name and the href
s = Executable.new
s.params['right_script']['href'] = rb[1].right_script.href
s.params['right_script']['name'] = script_name
@script_to_run = s
Log.debug "[#{Chimp.get_job_uuid}] Found rightscript"
return @script_to_run
end
end
#
# If we reach here it means we didnt find the script in the operationals
#
if @script_to_run == nil
# Search outside common op scripts
search_for_script_in_sts(script, st)
if @script_to_run.nil?
if @interactive
puts "ERROR: Sorry, didnt find that ( "+script+" ), provide an URI instead"
puts "I searched in:"
st.each { |s|
puts " * "+s[1]['name']+" [Rev"+s[1]['version'].to_s+"]"
}
if not @ignore_errors
exit 1
end
else
Log.error "["+self.job_uuid+"] Sorry, didnt find the script: ( "+script+" )!"
return nil
end
else
if self.job_uuid.nil?
self.job_uuid = ""
end
Log.warn "["+self.job_uuid+"] \"#{@script_to_run.params['right_script']['name']}\" is not a common operational script!"
return @script_to_run
end
end
end
end | ruby | def detect_right_script(st, script)
Log.debug "[#{Chimp.get_job_uuid}] Looking for rightscript"
executable = nil
# In the event that chimpd find @op_scripts as nil, set it as an array.
if @op_scripts.nil?
@op_scripts = []
end
if st.nil?
return executable
end
# Take the sts and extract all operational scripts
@op_scripts = extract_operational_scripts(st)
# if script is empty, we will list all common scripts
# if not empty, we will list the first matching one
if @script == "" and @script != nil
# list all operational scripts
reduce_to_common_scripts(st.size)
script_id = list_and_select_op_script
# Provide the name + href
s = Executable.new
s.params['right_script']['href'] = @op_scripts[script_id][1].right_script.href
s.params['right_script']['name'] = @op_scripts[script_id][0]
@script_to_run = s
else
# Try to find the rightscript in our list of common operational scripts
@op_scripts.each do |rb|
script_name = rb[0]
if script_name.downcase.include?(script.downcase)
# We only need the name and the href
s = Executable.new
s.params['right_script']['href'] = rb[1].right_script.href
s.params['right_script']['name'] = script_name
@script_to_run = s
Log.debug "[#{Chimp.get_job_uuid}] Found rightscript"
return @script_to_run
end
end
#
# If we reach here it means we didnt find the script in the operationals
#
if @script_to_run == nil
# Search outside common op scripts
search_for_script_in_sts(script, st)
if @script_to_run.nil?
if @interactive
puts "ERROR: Sorry, didnt find that ( "+script+" ), provide an URI instead"
puts "I searched in:"
st.each { |s|
puts " * "+s[1]['name']+" [Rev"+s[1]['version'].to_s+"]"
}
if not @ignore_errors
exit 1
end
else
Log.error "["+self.job_uuid+"] Sorry, didnt find the script: ( "+script+" )!"
return nil
end
else
if self.job_uuid.nil?
self.job_uuid = ""
end
Log.warn "["+self.job_uuid+"] \"#{@script_to_run.params['right_script']['name']}\" is not a common operational script!"
return @script_to_run
end
end
end
end | [
"def",
"detect_right_script",
"(",
"st",
",",
"script",
")",
"Log",
".",
"debug",
"\"[#{Chimp.get_job_uuid}] Looking for rightscript\"",
"executable",
"=",
"nil",
"if",
"@op_scripts",
".",
"nil?",
"@op_scripts",
"=",
"[",
"]",
"end",
"if",
"st",
".",
"nil?",
"return",
"executable",
"end",
"@op_scripts",
"=",
"extract_operational_scripts",
"(",
"st",
")",
"if",
"@script",
"==",
"\"\"",
"and",
"@script",
"!=",
"nil",
"reduce_to_common_scripts",
"(",
"st",
".",
"size",
")",
"script_id",
"=",
"list_and_select_op_script",
"s",
"=",
"Executable",
".",
"new",
"s",
".",
"params",
"[",
"'right_script'",
"]",
"[",
"'href'",
"]",
"=",
"@op_scripts",
"[",
"script_id",
"]",
"[",
"1",
"]",
".",
"right_script",
".",
"href",
"s",
".",
"params",
"[",
"'right_script'",
"]",
"[",
"'name'",
"]",
"=",
"@op_scripts",
"[",
"script_id",
"]",
"[",
"0",
"]",
"@script_to_run",
"=",
"s",
"else",
"@op_scripts",
".",
"each",
"do",
"|",
"rb",
"|",
"script_name",
"=",
"rb",
"[",
"0",
"]",
"if",
"script_name",
".",
"downcase",
".",
"include?",
"(",
"script",
".",
"downcase",
")",
"s",
"=",
"Executable",
".",
"new",
"s",
".",
"params",
"[",
"'right_script'",
"]",
"[",
"'href'",
"]",
"=",
"rb",
"[",
"1",
"]",
".",
"right_script",
".",
"href",
"s",
".",
"params",
"[",
"'right_script'",
"]",
"[",
"'name'",
"]",
"=",
"script_name",
"@script_to_run",
"=",
"s",
"Log",
".",
"debug",
"\"[#{Chimp.get_job_uuid}] Found rightscript\"",
"return",
"@script_to_run",
"end",
"end",
"if",
"@script_to_run",
"==",
"nil",
"search_for_script_in_sts",
"(",
"script",
",",
"st",
")",
"if",
"@script_to_run",
".",
"nil?",
"if",
"@interactive",
"puts",
"\"ERROR: Sorry, didnt find that ( \"",
"+",
"script",
"+",
"\" ), provide an URI instead\"",
"puts",
"\"I searched in:\"",
"st",
".",
"each",
"{",
"|",
"s",
"|",
"puts",
"\" * \"",
"+",
"s",
"[",
"1",
"]",
"[",
"'name'",
"]",
"+",
"\" [Rev\"",
"+",
"s",
"[",
"1",
"]",
"[",
"'version'",
"]",
".",
"to_s",
"+",
"\"]\"",
"}",
"if",
"not",
"@ignore_errors",
"exit",
"1",
"end",
"else",
"Log",
".",
"error",
"\"[\"",
"+",
"self",
".",
"job_uuid",
"+",
"\"] Sorry, didnt find the script: ( \"",
"+",
"script",
"+",
"\" )!\"",
"return",
"nil",
"end",
"else",
"if",
"self",
".",
"job_uuid",
".",
"nil?",
"self",
".",
"job_uuid",
"=",
"\"\"",
"end",
"Log",
".",
"warn",
"\"[\"",
"+",
"self",
".",
"job_uuid",
"+",
"\"] \\\"#{@script_to_run.params['right_script']['name']}\\\" is not a common operational script!\"",
"return",
"@script_to_run",
"end",
"end",
"end",
"end"
] | This function returns @script_to_run which is extracted from matching
the desired script against all server templates or the script URL | [
"This",
"function",
"returns"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/chimp.rb#L666-L737 | train |
rightscale/right_chimp | lib/right_chimp/chimp.rb | Chimp.Chimp.reduce_to_common_scripts | def reduce_to_common_scripts(number_of_st)
counts = Hash.new 0
@op_scripts.each { |s| counts[s[0]] +=1 }
b = @op_scripts.inject({}) do |res, row|
res[row[0]] ||= []
res[row[0]] << row[1]
res
end
b.inject([]) do |res, (key, values)|
res << [key, values.first] if values.size >= number_of_st
@op_scripts = res
end
end | ruby | def reduce_to_common_scripts(number_of_st)
counts = Hash.new 0
@op_scripts.each { |s| counts[s[0]] +=1 }
b = @op_scripts.inject({}) do |res, row|
res[row[0]] ||= []
res[row[0]] << row[1]
res
end
b.inject([]) do |res, (key, values)|
res << [key, values.first] if values.size >= number_of_st
@op_scripts = res
end
end | [
"def",
"reduce_to_common_scripts",
"(",
"number_of_st",
")",
"counts",
"=",
"Hash",
".",
"new",
"0",
"@op_scripts",
".",
"each",
"{",
"|",
"s",
"|",
"counts",
"[",
"s",
"[",
"0",
"]",
"]",
"+=",
"1",
"}",
"b",
"=",
"@op_scripts",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"res",
",",
"row",
"|",
"res",
"[",
"row",
"[",
"0",
"]",
"]",
"||=",
"[",
"]",
"res",
"[",
"row",
"[",
"0",
"]",
"]",
"<<",
"row",
"[",
"1",
"]",
"res",
"end",
"b",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"res",
",",
"(",
"key",
",",
"values",
")",
"|",
"res",
"<<",
"[",
"key",
",",
"values",
".",
"first",
"]",
"if",
"values",
".",
"size",
">=",
"number_of_st",
"@op_scripts",
"=",
"res",
"end",
"end"
] | Takes the number of st's to search in,
and reduces @op_scripts to only those who are
repeated enough times. | [
"Takes",
"the",
"number",
"of",
"st",
"s",
"to",
"search",
"in",
"and",
"reduces"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/chimp.rb#L798-L812 | train |
rightscale/right_chimp | lib/right_chimp/chimp.rb | Chimp.Chimp.extract_operational_scripts | def extract_operational_scripts(st)
op_scripts = []
size = st.size
st.each do |s|
# Example of s structure
# ["/api/server_templates/351930003",
# {"id"=>351930003,
# "name"=>"RightScale Right_Site - 2015q1",
# "kind"=>"cm#server_template",
# "version"=>5,
# "href"=>"/api/server_templates/351930003"} ]
Log.debug "[#{Chimp.get_job_uuid}] Making API 1.5 call: client.resource (ST)"
begin
tries ||= 3
temp = Connection.client.resource(s[1]['href'])
Log.debug "[#{Chimp.get_job_uuid}] API 1.5 call client.resource (ST) complete"
temp.runnable_bindings.index.each do |x|
# only add the operational ones
if x.sequence == 'operational'
name = x.raw['right_script']['name']
op_scripts.push([name, x])
end
end
rescue Exception => e
Log.error "[#{Chimp.get_job_uuid}] API 1.5 call client.resource (ST) failed (retrying)"
Log.error "[#{Chimp.get_job_uuid}] #{e.message}"
sleep 30
retry unless (tries -= 1).zero?
Log.error "[#{Chimp.get_job_uuid}] API 1.5 call client.resource (ST) failed (giving up)"
end
end
#We now only have operational runnable_bindings under the script_objects array
if op_scripts.length < 1
raise "ERROR: No operational scripts found on the server(s). "
st.each {|s|
puts " (Search performed on server template '#{s[1]['name']}')"
}
end
return op_scripts
end | ruby | def extract_operational_scripts(st)
op_scripts = []
size = st.size
st.each do |s|
# Example of s structure
# ["/api/server_templates/351930003",
# {"id"=>351930003,
# "name"=>"RightScale Right_Site - 2015q1",
# "kind"=>"cm#server_template",
# "version"=>5,
# "href"=>"/api/server_templates/351930003"} ]
Log.debug "[#{Chimp.get_job_uuid}] Making API 1.5 call: client.resource (ST)"
begin
tries ||= 3
temp = Connection.client.resource(s[1]['href'])
Log.debug "[#{Chimp.get_job_uuid}] API 1.5 call client.resource (ST) complete"
temp.runnable_bindings.index.each do |x|
# only add the operational ones
if x.sequence == 'operational'
name = x.raw['right_script']['name']
op_scripts.push([name, x])
end
end
rescue Exception => e
Log.error "[#{Chimp.get_job_uuid}] API 1.5 call client.resource (ST) failed (retrying)"
Log.error "[#{Chimp.get_job_uuid}] #{e.message}"
sleep 30
retry unless (tries -= 1).zero?
Log.error "[#{Chimp.get_job_uuid}] API 1.5 call client.resource (ST) failed (giving up)"
end
end
#We now only have operational runnable_bindings under the script_objects array
if op_scripts.length < 1
raise "ERROR: No operational scripts found on the server(s). "
st.each {|s|
puts " (Search performed on server template '#{s[1]['name']}')"
}
end
return op_scripts
end | [
"def",
"extract_operational_scripts",
"(",
"st",
")",
"op_scripts",
"=",
"[",
"]",
"size",
"=",
"st",
".",
"size",
"st",
".",
"each",
"do",
"|",
"s",
"|",
"Log",
".",
"debug",
"\"[#{Chimp.get_job_uuid}] Making API 1.5 call: client.resource (ST)\"",
"begin",
"tries",
"||=",
"3",
"temp",
"=",
"Connection",
".",
"client",
".",
"resource",
"(",
"s",
"[",
"1",
"]",
"[",
"'href'",
"]",
")",
"Log",
".",
"debug",
"\"[#{Chimp.get_job_uuid}] API 1.5 call client.resource (ST) complete\"",
"temp",
".",
"runnable_bindings",
".",
"index",
".",
"each",
"do",
"|",
"x",
"|",
"if",
"x",
".",
"sequence",
"==",
"'operational'",
"name",
"=",
"x",
".",
"raw",
"[",
"'right_script'",
"]",
"[",
"'name'",
"]",
"op_scripts",
".",
"push",
"(",
"[",
"name",
",",
"x",
"]",
")",
"end",
"end",
"rescue",
"Exception",
"=>",
"e",
"Log",
".",
"error",
"\"[#{Chimp.get_job_uuid}] API 1.5 call client.resource (ST) failed (retrying)\"",
"Log",
".",
"error",
"\"[#{Chimp.get_job_uuid}] #{e.message}\"",
"sleep",
"30",
"retry",
"unless",
"(",
"tries",
"-=",
"1",
")",
".",
"zero?",
"Log",
".",
"error",
"\"[#{Chimp.get_job_uuid}] API 1.5 call client.resource (ST) failed (giving up)\"",
"end",
"end",
"if",
"op_scripts",
".",
"length",
"<",
"1",
"raise",
"\"ERROR: No operational scripts found on the server(s). \"",
"st",
".",
"each",
"{",
"|",
"s",
"|",
"puts",
"\" (Search performed on server template '#{s[1]['name']}')\"",
"}",
"end",
"return",
"op_scripts",
"end"
] | Returns all matching operational scripts in the st list passed | [
"Returns",
"all",
"matching",
"operational",
"scripts",
"in",
"the",
"st",
"list",
"passed"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/chimp.rb#L817-L857 | train |
rightscale/right_chimp | lib/right_chimp/chimp.rb | Chimp.Chimp.queue_runner | def queue_runner(concurrency, delay, retry_count, progress)
queue = ChimpQueue.instance
queue.max_threads = concurrency
queue.delay = delay
queue.retry_count = retry_count
total_queue_size = queue.size
puts "Executing..." unless progress or not quiet
pbar = ProgressBar.new("Executing", 100) if progress
queue.start
queue.wait_until_done(@group) do
pbar.set(((total_queue_size.to_f - queue.size.to_f)/total_queue_size.to_f*100).to_i) if progress
end
pbar.finish if progress
end | ruby | def queue_runner(concurrency, delay, retry_count, progress)
queue = ChimpQueue.instance
queue.max_threads = concurrency
queue.delay = delay
queue.retry_count = retry_count
total_queue_size = queue.size
puts "Executing..." unless progress or not quiet
pbar = ProgressBar.new("Executing", 100) if progress
queue.start
queue.wait_until_done(@group) do
pbar.set(((total_queue_size.to_f - queue.size.to_f)/total_queue_size.to_f*100).to_i) if progress
end
pbar.finish if progress
end | [
"def",
"queue_runner",
"(",
"concurrency",
",",
"delay",
",",
"retry_count",
",",
"progress",
")",
"queue",
"=",
"ChimpQueue",
".",
"instance",
"queue",
".",
"max_threads",
"=",
"concurrency",
"queue",
".",
"delay",
"=",
"delay",
"queue",
".",
"retry_count",
"=",
"retry_count",
"total_queue_size",
"=",
"queue",
".",
"size",
"puts",
"\"Executing...\"",
"unless",
"progress",
"or",
"not",
"quiet",
"pbar",
"=",
"ProgressBar",
".",
"new",
"(",
"\"Executing\"",
",",
"100",
")",
"if",
"progress",
"queue",
".",
"start",
"queue",
".",
"wait_until_done",
"(",
"@group",
")",
"do",
"pbar",
".",
"set",
"(",
"(",
"(",
"total_queue_size",
".",
"to_f",
"-",
"queue",
".",
"size",
".",
"to_f",
")",
"/",
"total_queue_size",
".",
"to_f",
"*",
"100",
")",
".",
"to_i",
")",
"if",
"progress",
"end",
"pbar",
".",
"finish",
"if",
"progress",
"end"
] | Execute the user's command and provide for retrys etc. | [
"Execute",
"the",
"user",
"s",
"command",
"and",
"provide",
"for",
"retrys",
"etc",
"."
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/chimp.rb#L987-L1003 | train |
rightscale/right_chimp | lib/right_chimp/chimp.rb | Chimp.Chimp.verify_results | def verify_results(group = :default)
failed_workers, results_display = get_results(group)
#
# If no workers failed, then we're done.
#
if failed_workers.empty?
@paused = false
return "continue"
end
#
# Some workers failed; offer the user a chance to retry them
#
verify("The following objects failed:", results_display, false) unless @paused
if !@prompt || @paused
@paused = true
sleep 15
return "pause"
end
while true
puts "(R)etry failed jobs"
puts "(A)bort chimp run"
puts "(I)gnore errors and continue"
command = gets()
if command.nil?
#
# if command is nil, stdin is closed or its source ended
# probably because we are in an automated environment,
# then we pause like in '--no-prompt' scenario
#
puts 'Warning! stdin empty, using pause behaviour, use --no-prompt to avoid this message'
@paused = true
return 'pause'
end
if command =~ /^a/i
puts "Aborting!"
exit 1
elsif command =~ /^i/i
puts "Ignoring errors and continuing"
exit 0
elsif command =~ /^r/i
puts "Retrying..."
ChimpQueue.instance.group[group].requeue_failed_jobs!
return 'retry'
end
end
end | ruby | def verify_results(group = :default)
failed_workers, results_display = get_results(group)
#
# If no workers failed, then we're done.
#
if failed_workers.empty?
@paused = false
return "continue"
end
#
# Some workers failed; offer the user a chance to retry them
#
verify("The following objects failed:", results_display, false) unless @paused
if !@prompt || @paused
@paused = true
sleep 15
return "pause"
end
while true
puts "(R)etry failed jobs"
puts "(A)bort chimp run"
puts "(I)gnore errors and continue"
command = gets()
if command.nil?
#
# if command is nil, stdin is closed or its source ended
# probably because we are in an automated environment,
# then we pause like in '--no-prompt' scenario
#
puts 'Warning! stdin empty, using pause behaviour, use --no-prompt to avoid this message'
@paused = true
return 'pause'
end
if command =~ /^a/i
puts "Aborting!"
exit 1
elsif command =~ /^i/i
puts "Ignoring errors and continuing"
exit 0
elsif command =~ /^r/i
puts "Retrying..."
ChimpQueue.instance.group[group].requeue_failed_jobs!
return 'retry'
end
end
end | [
"def",
"verify_results",
"(",
"group",
"=",
":default",
")",
"failed_workers",
",",
"results_display",
"=",
"get_results",
"(",
"group",
")",
"if",
"failed_workers",
".",
"empty?",
"@paused",
"=",
"false",
"return",
"\"continue\"",
"end",
"verify",
"(",
"\"The following objects failed:\"",
",",
"results_display",
",",
"false",
")",
"unless",
"@paused",
"if",
"!",
"@prompt",
"||",
"@paused",
"@paused",
"=",
"true",
"sleep",
"15",
"return",
"\"pause\"",
"end",
"while",
"true",
"puts",
"\"(R)etry failed jobs\"",
"puts",
"\"(A)bort chimp run\"",
"puts",
"\"(I)gnore errors and continue\"",
"command",
"=",
"gets",
"(",
")",
"if",
"command",
".",
"nil?",
"puts",
"'Warning! stdin empty, using pause behaviour, use --no-prompt to avoid this message'",
"@paused",
"=",
"true",
"return",
"'pause'",
"end",
"if",
"command",
"=~",
"/",
"/i",
"puts",
"\"Aborting!\"",
"exit",
"1",
"elsif",
"command",
"=~",
"/",
"/i",
"puts",
"\"Ignoring errors and continuing\"",
"exit",
"0",
"elsif",
"command",
"=~",
"/",
"/i",
"puts",
"\"Retrying...\"",
"ChimpQueue",
".",
"instance",
".",
"group",
"[",
"group",
"]",
".",
"requeue_failed_jobs!",
"return",
"'retry'",
"end",
"end",
"end"
] | Allow user to verify results and retry if necessary | [
"Allow",
"user",
"to",
"verify",
"results",
"and",
"retry",
"if",
"necessary"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/chimp.rb#L1016-L1065 | train |
rightscale/right_chimp | lib/right_chimp/chimp.rb | Chimp.Chimp.get_results | def get_results(group_name)
queue = ChimpQueue.instance
Log.debug("getting results for group #{group_name}")
results = queue.group[@group].results()
failed_workers = []
results_display = []
results.each do |result|
next if result == nil
if result[:status] == :error
name = result[:host] || "unknown"
message = result[:error].to_s || "unknown"
message.sub!("\n", "")
failed_workers << result[:worker]
results_display << "#{name[0..40]} >> #{message}"
end
end
return [failed_workers, results_display]
end | ruby | def get_results(group_name)
queue = ChimpQueue.instance
Log.debug("getting results for group #{group_name}")
results = queue.group[@group].results()
failed_workers = []
results_display = []
results.each do |result|
next if result == nil
if result[:status] == :error
name = result[:host] || "unknown"
message = result[:error].to_s || "unknown"
message.sub!("\n", "")
failed_workers << result[:worker]
results_display << "#{name[0..40]} >> #{message}"
end
end
return [failed_workers, results_display]
end | [
"def",
"get_results",
"(",
"group_name",
")",
"queue",
"=",
"ChimpQueue",
".",
"instance",
"Log",
".",
"debug",
"(",
"\"getting results for group #{group_name}\"",
")",
"results",
"=",
"queue",
".",
"group",
"[",
"@group",
"]",
".",
"results",
"(",
")",
"failed_workers",
"=",
"[",
"]",
"results_display",
"=",
"[",
"]",
"results",
".",
"each",
"do",
"|",
"result",
"|",
"next",
"if",
"result",
"==",
"nil",
"if",
"result",
"[",
":status",
"]",
"==",
":error",
"name",
"=",
"result",
"[",
":host",
"]",
"||",
"\"unknown\"",
"message",
"=",
"result",
"[",
":error",
"]",
".",
"to_s",
"||",
"\"unknown\"",
"message",
".",
"sub!",
"(",
"\"\\n\"",
",",
"\"\"",
")",
"failed_workers",
"<<",
"result",
"[",
":worker",
"]",
"results_display",
"<<",
"\"#{name[0..40]} >> #{message}\"",
"end",
"end",
"return",
"[",
"failed_workers",
",",
"results_display",
"]",
"end"
] | Get the results from the QueueRunner and format them
in a way that's easy to display to the user | [
"Get",
"the",
"results",
"from",
"the",
"QueueRunner",
"and",
"format",
"them",
"in",
"a",
"way",
"that",
"s",
"easy",
"to",
"display",
"to",
"the",
"user"
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/chimp.rb#L1071-L1091 | train |
rightscale/right_chimp | lib/right_chimp/chimp.rb | Chimp.Chimp.process | def process
Chimp.set_failure(false)
Chimp.set_job_uuid(job_uuid)
Log.debug "[#{job_uuid}] Processing task"
# Add to our "processing" counter
Log.debug "[#{job_uuid}] Trying to get array_info" unless Chimp.failure
get_array_info unless Chimp.failure
Log.debug "[#{job_uuid}] Trying to get server_info" unless Chimp.failure
get_server_info unless Chimp.failure
Log.debug "[#{job_uuid}] Trying to get template_info" unless Chimp.failure
get_template_info unless Chimp.failure
Log.debug "[#{job_uuid}] Trying to get executable_info" unless Chimp.failure
get_executable_info unless Chimp.failure
# All elements of task have been processed
if Chimp.failure
Log.error '##################################################'
Log.error '[' + job_uuid + '] API CALL FAILED FOR:'
Log.error '[' + job_uuid + "] chimp #{@cli_args} "
Log.error '[' + job_uuid + '] Run manually!'
Log.error '##################################################'
return []
elsif @servers.first.nil? || @executable.nil?
Log.warn "[#{Chimp.get_job_uuid}] Nothing to do for \"chimp #{@cli_args}\"."
# decrease our counter
ChimpDaemon.instance.queue.processing[@group].delete(job_uuid.to_sym)
ChimpDaemon.instance.proc_counter -= 1
return []
else
Log.debug "[#{Chimp.get_job_uuid}] Generating job(s)..."
# @servers might be > 1, but we might be using limit_start
number_of_servers = if @limit_start.to_i > 0 || @limit_end.to_i > 0
@limit_end.to_i - @limit_start.to_i
else
# reminder, we already are accounting for at least 1
@servers.size - 1
end
Log.debug 'Increasing processing counter (' + ChimpDaemon.instance.proc_counter.to_s + ') + ' +
number_of_servers.to_s + ' for group ' + @group.to_s
ChimpDaemon.instance.queue.processing[@group][job_uuid.to_sym] += number_of_servers
ChimpDaemon.instance.proc_counter += number_of_servers
Log.debug 'Processing counter now (' + ChimpDaemon.instance.proc_counter.to_s + ') for group ' +
@group.to_s
return generate_jobs(@servers, @server_template, @executable)
end
end | ruby | def process
Chimp.set_failure(false)
Chimp.set_job_uuid(job_uuid)
Log.debug "[#{job_uuid}] Processing task"
# Add to our "processing" counter
Log.debug "[#{job_uuid}] Trying to get array_info" unless Chimp.failure
get_array_info unless Chimp.failure
Log.debug "[#{job_uuid}] Trying to get server_info" unless Chimp.failure
get_server_info unless Chimp.failure
Log.debug "[#{job_uuid}] Trying to get template_info" unless Chimp.failure
get_template_info unless Chimp.failure
Log.debug "[#{job_uuid}] Trying to get executable_info" unless Chimp.failure
get_executable_info unless Chimp.failure
# All elements of task have been processed
if Chimp.failure
Log.error '##################################################'
Log.error '[' + job_uuid + '] API CALL FAILED FOR:'
Log.error '[' + job_uuid + "] chimp #{@cli_args} "
Log.error '[' + job_uuid + '] Run manually!'
Log.error '##################################################'
return []
elsif @servers.first.nil? || @executable.nil?
Log.warn "[#{Chimp.get_job_uuid}] Nothing to do for \"chimp #{@cli_args}\"."
# decrease our counter
ChimpDaemon.instance.queue.processing[@group].delete(job_uuid.to_sym)
ChimpDaemon.instance.proc_counter -= 1
return []
else
Log.debug "[#{Chimp.get_job_uuid}] Generating job(s)..."
# @servers might be > 1, but we might be using limit_start
number_of_servers = if @limit_start.to_i > 0 || @limit_end.to_i > 0
@limit_end.to_i - @limit_start.to_i
else
# reminder, we already are accounting for at least 1
@servers.size - 1
end
Log.debug 'Increasing processing counter (' + ChimpDaemon.instance.proc_counter.to_s + ') + ' +
number_of_servers.to_s + ' for group ' + @group.to_s
ChimpDaemon.instance.queue.processing[@group][job_uuid.to_sym] += number_of_servers
ChimpDaemon.instance.proc_counter += number_of_servers
Log.debug 'Processing counter now (' + ChimpDaemon.instance.proc_counter.to_s + ') for group ' +
@group.to_s
return generate_jobs(@servers, @server_template, @executable)
end
end | [
"def",
"process",
"Chimp",
".",
"set_failure",
"(",
"false",
")",
"Chimp",
".",
"set_job_uuid",
"(",
"job_uuid",
")",
"Log",
".",
"debug",
"\"[#{job_uuid}] Processing task\"",
"Log",
".",
"debug",
"\"[#{job_uuid}] Trying to get array_info\"",
"unless",
"Chimp",
".",
"failure",
"get_array_info",
"unless",
"Chimp",
".",
"failure",
"Log",
".",
"debug",
"\"[#{job_uuid}] Trying to get server_info\"",
"unless",
"Chimp",
".",
"failure",
"get_server_info",
"unless",
"Chimp",
".",
"failure",
"Log",
".",
"debug",
"\"[#{job_uuid}] Trying to get template_info\"",
"unless",
"Chimp",
".",
"failure",
"get_template_info",
"unless",
"Chimp",
".",
"failure",
"Log",
".",
"debug",
"\"[#{job_uuid}] Trying to get executable_info\"",
"unless",
"Chimp",
".",
"failure",
"get_executable_info",
"unless",
"Chimp",
".",
"failure",
"if",
"Chimp",
".",
"failure",
"Log",
".",
"error",
"'##################################################'",
"Log",
".",
"error",
"'['",
"+",
"job_uuid",
"+",
"'] API CALL FAILED FOR:'",
"Log",
".",
"error",
"'['",
"+",
"job_uuid",
"+",
"\"] chimp #{@cli_args} \"",
"Log",
".",
"error",
"'['",
"+",
"job_uuid",
"+",
"'] Run manually!'",
"Log",
".",
"error",
"'##################################################'",
"return",
"[",
"]",
"elsif",
"@servers",
".",
"first",
".",
"nil?",
"||",
"@executable",
".",
"nil?",
"Log",
".",
"warn",
"\"[#{Chimp.get_job_uuid}] Nothing to do for \\\"chimp #{@cli_args}\\\".\"",
"ChimpDaemon",
".",
"instance",
".",
"queue",
".",
"processing",
"[",
"@group",
"]",
".",
"delete",
"(",
"job_uuid",
".",
"to_sym",
")",
"ChimpDaemon",
".",
"instance",
".",
"proc_counter",
"-=",
"1",
"return",
"[",
"]",
"else",
"Log",
".",
"debug",
"\"[#{Chimp.get_job_uuid}] Generating job(s)...\"",
"number_of_servers",
"=",
"if",
"@limit_start",
".",
"to_i",
">",
"0",
"||",
"@limit_end",
".",
"to_i",
">",
"0",
"@limit_end",
".",
"to_i",
"-",
"@limit_start",
".",
"to_i",
"else",
"@servers",
".",
"size",
"-",
"1",
"end",
"Log",
".",
"debug",
"'Increasing processing counter ('",
"+",
"ChimpDaemon",
".",
"instance",
".",
"proc_counter",
".",
"to_s",
"+",
"') + '",
"+",
"number_of_servers",
".",
"to_s",
"+",
"' for group '",
"+",
"@group",
".",
"to_s",
"ChimpDaemon",
".",
"instance",
".",
"queue",
".",
"processing",
"[",
"@group",
"]",
"[",
"job_uuid",
".",
"to_sym",
"]",
"+=",
"number_of_servers",
"ChimpDaemon",
".",
"instance",
".",
"proc_counter",
"+=",
"number_of_servers",
"Log",
".",
"debug",
"'Processing counter now ('",
"+",
"ChimpDaemon",
".",
"instance",
".",
"proc_counter",
".",
"to_s",
"+",
"') for group '",
"+",
"@group",
".",
"to_s",
"return",
"generate_jobs",
"(",
"@servers",
",",
"@server_template",
",",
"@executable",
")",
"end",
"end"
] | Completely process a non-interactive chimp object command
This is used by chimpd, when processing a task. | [
"Completely",
"process",
"a",
"non",
"-",
"interactive",
"chimp",
"object",
"command",
"This",
"is",
"used",
"by",
"chimpd",
"when",
"processing",
"a",
"task",
"."
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/chimp.rb#L1134-L1189 | train |
rightscale/right_chimp | lib/right_chimp/chimp.rb | Chimp.Chimp.chimpd_wait_until_done | def chimpd_wait_until_done
local_queue = ChimpQueue.instance
$stdout.print "Waiting for chimpd jobs to complete for group #{@group}..."
begin
while !@dry_run
local_queue = ChimpQueue.instance
#
# load up remote chimpd jobs into the local queue
# this makes all the standard queue control methods available to us
#
sleeping_counter = 0
while true
local_queue.reset!
begin
all = ChimpDaemonClient.retrieve_group_info(@chimpd_host, @chimpd_port, @group, :all)
rescue RestClient::ResourceNotFound
sleep 5
$stdout.print "\nINFO: Waiting on group #{@group} to populate"
retry
end
ChimpQueue.instance.create_group(@group)
ChimpQueue[@group].set_jobs(all)
if ChimpQueue[@group].done?
Log.debug 'Group ' + @group.to_s + ' is completed'
jobs = ChimpQueue[@group].size
$stdout.print "\nINFO: Group #{@group} has completed (#{jobs} jobs)"
break
else
Log.debug 'Group ' + @group.to_s + ' is not done.'
end
if sleeping_counter % 240 == 0
$stdout.print "\n(Still) Waiting for group #{@group}" unless sleeping_counter == 0
end
$stdout.print "."
$stdout.flush
sleeping_counter += 5
sleep 5
end
#
# If verify_results returns false, then ask chimpd to requeue all failed jobs.
#
case verify_results(@group)
when 'continue'
break
when 'retry'
ChimpDaemonClient.retry_group(@chimpd_host, @chimpd_port, @group)
when 'pause'
@paused = true
#stuck in this loop until action is taken
end
end
ensure
#$stdout.print " done\n"
end
end | ruby | def chimpd_wait_until_done
local_queue = ChimpQueue.instance
$stdout.print "Waiting for chimpd jobs to complete for group #{@group}..."
begin
while !@dry_run
local_queue = ChimpQueue.instance
#
# load up remote chimpd jobs into the local queue
# this makes all the standard queue control methods available to us
#
sleeping_counter = 0
while true
local_queue.reset!
begin
all = ChimpDaemonClient.retrieve_group_info(@chimpd_host, @chimpd_port, @group, :all)
rescue RestClient::ResourceNotFound
sleep 5
$stdout.print "\nINFO: Waiting on group #{@group} to populate"
retry
end
ChimpQueue.instance.create_group(@group)
ChimpQueue[@group].set_jobs(all)
if ChimpQueue[@group].done?
Log.debug 'Group ' + @group.to_s + ' is completed'
jobs = ChimpQueue[@group].size
$stdout.print "\nINFO: Group #{@group} has completed (#{jobs} jobs)"
break
else
Log.debug 'Group ' + @group.to_s + ' is not done.'
end
if sleeping_counter % 240 == 0
$stdout.print "\n(Still) Waiting for group #{@group}" unless sleeping_counter == 0
end
$stdout.print "."
$stdout.flush
sleeping_counter += 5
sleep 5
end
#
# If verify_results returns false, then ask chimpd to requeue all failed jobs.
#
case verify_results(@group)
when 'continue'
break
when 'retry'
ChimpDaemonClient.retry_group(@chimpd_host, @chimpd_port, @group)
when 'pause'
@paused = true
#stuck in this loop until action is taken
end
end
ensure
#$stdout.print " done\n"
end
end | [
"def",
"chimpd_wait_until_done",
"local_queue",
"=",
"ChimpQueue",
".",
"instance",
"$stdout",
".",
"print",
"\"Waiting for chimpd jobs to complete for group #{@group}...\"",
"begin",
"while",
"!",
"@dry_run",
"local_queue",
"=",
"ChimpQueue",
".",
"instance",
"sleeping_counter",
"=",
"0",
"while",
"true",
"local_queue",
".",
"reset!",
"begin",
"all",
"=",
"ChimpDaemonClient",
".",
"retrieve_group_info",
"(",
"@chimpd_host",
",",
"@chimpd_port",
",",
"@group",
",",
":all",
")",
"rescue",
"RestClient",
"::",
"ResourceNotFound",
"sleep",
"5",
"$stdout",
".",
"print",
"\"\\nINFO: Waiting on group #{@group} to populate\"",
"retry",
"end",
"ChimpQueue",
".",
"instance",
".",
"create_group",
"(",
"@group",
")",
"ChimpQueue",
"[",
"@group",
"]",
".",
"set_jobs",
"(",
"all",
")",
"if",
"ChimpQueue",
"[",
"@group",
"]",
".",
"done?",
"Log",
".",
"debug",
"'Group '",
"+",
"@group",
".",
"to_s",
"+",
"' is completed'",
"jobs",
"=",
"ChimpQueue",
"[",
"@group",
"]",
".",
"size",
"$stdout",
".",
"print",
"\"\\nINFO: Group #{@group} has completed (#{jobs} jobs)\"",
"break",
"else",
"Log",
".",
"debug",
"'Group '",
"+",
"@group",
".",
"to_s",
"+",
"' is not done.'",
"end",
"if",
"sleeping_counter",
"%",
"240",
"==",
"0",
"$stdout",
".",
"print",
"\"\\n(Still) Waiting for group #{@group}\"",
"unless",
"sleeping_counter",
"==",
"0",
"end",
"$stdout",
".",
"print",
"\".\"",
"$stdout",
".",
"flush",
"sleeping_counter",
"+=",
"5",
"sleep",
"5",
"end",
"case",
"verify_results",
"(",
"@group",
")",
"when",
"'continue'",
"break",
"when",
"'retry'",
"ChimpDaemonClient",
".",
"retry_group",
"(",
"@chimpd_host",
",",
"@chimpd_port",
",",
"@group",
")",
"when",
"'pause'",
"@paused",
"=",
"true",
"end",
"end",
"ensure",
"end",
"end"
] | Connect to chimpd and wait for the work queue to empty, and
prompt the user if there are any errors. | [
"Connect",
"to",
"chimpd",
"and",
"wait",
"for",
"the",
"work",
"queue",
"to",
"empty",
"and",
"prompt",
"the",
"user",
"if",
"there",
"are",
"any",
"errors",
"."
] | 290d3e01f7bf4b505722a080cb0abbb0314222f8 | https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/chimp.rb#L1209-L1269 | train |
bithavoc/background_bunnies | lib/background_bunnies/bunny.rb | BackgroundBunnies.Bunny.start | def start(connection_or_group)
@connection = connection_or_group
@channel = AMQP::Channel.new(@connection)
queue_options = {}
name = queue_name
if queue_type == :broadcast
queue_options[:exclusive] = true
queue_options[:auto_delete] = true
name = "#{Socket.gethostname}-#{Process.pid}-#{self.object_id}"
@queue = @channel.queue(name, queue_options)
@exchange = @channel.fanout(BackgroundBunnies.broadcast_exchange_name(queue_name))
@queue.bind(@exchange)
else
queue_options[:durable] = true
@queue = @channel.queue(queue_name, queue_options)
end
@consumer = @queue.subscribe(:ack=>true) do |metadata, payload|
info = metadata
properties = nil
begin
job = Job.new(JSON.parse!(payload), info, properties)
err = nil
self.process(job)
metadata.ack
rescue =>err
# processing went wrong, requeing message
job = Job.new(nil, info, properties) unless job
unless on_error(job, err)
metadata.reject(:requeue=>true)
else
metadata.ack
end
end
end
end | ruby | def start(connection_or_group)
@connection = connection_or_group
@channel = AMQP::Channel.new(@connection)
queue_options = {}
name = queue_name
if queue_type == :broadcast
queue_options[:exclusive] = true
queue_options[:auto_delete] = true
name = "#{Socket.gethostname}-#{Process.pid}-#{self.object_id}"
@queue = @channel.queue(name, queue_options)
@exchange = @channel.fanout(BackgroundBunnies.broadcast_exchange_name(queue_name))
@queue.bind(@exchange)
else
queue_options[:durable] = true
@queue = @channel.queue(queue_name, queue_options)
end
@consumer = @queue.subscribe(:ack=>true) do |metadata, payload|
info = metadata
properties = nil
begin
job = Job.new(JSON.parse!(payload), info, properties)
err = nil
self.process(job)
metadata.ack
rescue =>err
# processing went wrong, requeing message
job = Job.new(nil, info, properties) unless job
unless on_error(job, err)
metadata.reject(:requeue=>true)
else
metadata.ack
end
end
end
end | [
"def",
"start",
"(",
"connection_or_group",
")",
"@connection",
"=",
"connection_or_group",
"@channel",
"=",
"AMQP",
"::",
"Channel",
".",
"new",
"(",
"@connection",
")",
"queue_options",
"=",
"{",
"}",
"name",
"=",
"queue_name",
"if",
"queue_type",
"==",
":broadcast",
"queue_options",
"[",
":exclusive",
"]",
"=",
"true",
"queue_options",
"[",
":auto_delete",
"]",
"=",
"true",
"name",
"=",
"\"#{Socket.gethostname}-#{Process.pid}-#{self.object_id}\"",
"@queue",
"=",
"@channel",
".",
"queue",
"(",
"name",
",",
"queue_options",
")",
"@exchange",
"=",
"@channel",
".",
"fanout",
"(",
"BackgroundBunnies",
".",
"broadcast_exchange_name",
"(",
"queue_name",
")",
")",
"@queue",
".",
"bind",
"(",
"@exchange",
")",
"else",
"queue_options",
"[",
":durable",
"]",
"=",
"true",
"@queue",
"=",
"@channel",
".",
"queue",
"(",
"queue_name",
",",
"queue_options",
")",
"end",
"@consumer",
"=",
"@queue",
".",
"subscribe",
"(",
":ack",
"=>",
"true",
")",
"do",
"|",
"metadata",
",",
"payload",
"|",
"info",
"=",
"metadata",
"properties",
"=",
"nil",
"begin",
"job",
"=",
"Job",
".",
"new",
"(",
"JSON",
".",
"parse!",
"(",
"payload",
")",
",",
"info",
",",
"properties",
")",
"err",
"=",
"nil",
"self",
".",
"process",
"(",
"job",
")",
"metadata",
".",
"ack",
"rescue",
"=>",
"err",
"job",
"=",
"Job",
".",
"new",
"(",
"nil",
",",
"info",
",",
"properties",
")",
"unless",
"job",
"unless",
"on_error",
"(",
"job",
",",
"err",
")",
"metadata",
".",
"reject",
"(",
":requeue",
"=>",
"true",
")",
"else",
"metadata",
".",
"ack",
"end",
"end",
"end",
"end"
] | Starts the Worker with the given connection or group name | [
"Starts",
"the",
"Worker",
"with",
"the",
"given",
"connection",
"or",
"group",
"name"
] | 7d266b73f98b4283e68d4c7e478b1791333a91ff | https://github.com/bithavoc/background_bunnies/blob/7d266b73f98b4283e68d4c7e478b1791333a91ff/lib/background_bunnies/bunny.rb#L92-L126 | train |
arvicco/win_gui | old_code/lib/win_gui/window.rb | WinGui.Window.click | def click(id)
h = child(id).handle
rectangle = [0, 0, 0, 0].pack 'LLLL'
get_window_rect h, rectangle
left, top, right, bottom = rectangle.unpack 'LLLL'
center = [(left + right) / 2, (top + bottom) / 2]
set_cursor_pos *center
mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
end | ruby | def click(id)
h = child(id).handle
rectangle = [0, 0, 0, 0].pack 'LLLL'
get_window_rect h, rectangle
left, top, right, bottom = rectangle.unpack 'LLLL'
center = [(left + right) / 2, (top + bottom) / 2]
set_cursor_pos *center
mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
end | [
"def",
"click",
"(",
"id",
")",
"h",
"=",
"child",
"(",
"id",
")",
".",
"handle",
"rectangle",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
".",
"pack",
"'LLLL'",
"get_window_rect",
"h",
",",
"rectangle",
"left",
",",
"top",
",",
"right",
",",
"bottom",
"=",
"rectangle",
".",
"unpack",
"'LLLL'",
"center",
"=",
"[",
"(",
"left",
"+",
"right",
")",
"/",
"2",
",",
"(",
"top",
"+",
"bottom",
")",
"/",
"2",
"]",
"set_cursor_pos",
"*",
"center",
"mouse_event",
"MOUSEEVENTF_LEFTDOWN",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"mouse_event",
"MOUSEEVENTF_LEFTUP",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"end"
] | emulate click of the control identified by id | [
"emulate",
"click",
"of",
"the",
"control",
"identified",
"by",
"id"
] | a3a4c18db2391144fcb535e4be2f0fb47e9dcec7 | https://github.com/arvicco/win_gui/blob/a3a4c18db2391144fcb535e4be2f0fb47e9dcec7/old_code/lib/win_gui/window.rb#L43-L52 | train |
nixme/pandora_client | lib/pandora/song.rb | Pandora.Song.load_explorer_data | def load_explorer_data
document = Nokogiri::XML(Faraday.get(@song_explorer_url).body)
@id = document.search('songExplorer').first['musicId']
end | ruby | def load_explorer_data
document = Nokogiri::XML(Faraday.get(@song_explorer_url).body)
@id = document.search('songExplorer').first['musicId']
end | [
"def",
"load_explorer_data",
"document",
"=",
"Nokogiri",
"::",
"XML",
"(",
"Faraday",
".",
"get",
"(",
"@song_explorer_url",
")",
".",
"body",
")",
"@id",
"=",
"document",
".",
"search",
"(",
"'songExplorer'",
")",
".",
"first",
"[",
"'musicId'",
"]",
"end"
] | Unfortunately the Tuner API track JSON doesn't include the musicId, a
track identifier that's constant among different user sessions. However,
we can fetch it via the Song's Explorer XML URL. | [
"Unfortunately",
"the",
"Tuner",
"API",
"track",
"JSON",
"doesn",
"t",
"include",
"the",
"musicId",
"a",
"track",
"identifier",
"that",
"s",
"constant",
"among",
"different",
"user",
"sessions",
".",
"However",
"we",
"can",
"fetch",
"it",
"via",
"the",
"Song",
"s",
"Explorer",
"XML",
"URL",
"."
] | 45510334c9f84bc9cb974af97fa93ebf2913410a | https://github.com/nixme/pandora_client/blob/45510334c9f84bc9cb974af97fa93ebf2913410a/lib/pandora/song.rb#L80-L83 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.