repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
thriventures/storage_room_gem | lib/storage_room/array.rb | StorageRoom.Array.each_page_each_resource | def each_page_each_resource(args={})
self.each_page(args) do |page|
page.resources.each do |item|
yield(item)
end
end
end | ruby | def each_page_each_resource(args={})
self.each_page(args) do |page|
page.resources.each do |item|
yield(item)
end
end
end | [
"def",
"each_page_each_resource",
"(",
"args",
"=",
"{",
"}",
")",
"self",
".",
"each_page",
"(",
"args",
")",
"do",
"|",
"page",
"|",
"page",
".",
"resources",
".",
"each",
"do",
"|",
"item",
"|",
"yield",
"(",
"item",
")",
"end",
"end",
"end"
] | Iterate over all resources with pagination | [
"Iterate",
"over",
"all",
"resources",
"with",
"pagination"
] | cadf132b865ff82f7b09fadfec1d294a714c6728 | https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/array.rb#L35-L41 | train |
orendon/diffbot.rb | lib/diffbot_api/article.rb | Diffbot.Article.extract_article | def extract_article
api_response = request.get article_endpoint, token: Diffbot.token, url: @url
@response = JSON.parse(api_response.body)
end | ruby | def extract_article
api_response = request.get article_endpoint, token: Diffbot.token, url: @url
@response = JSON.parse(api_response.body)
end | [
"def",
"extract_article",
"api_response",
"=",
"request",
".",
"get",
"article_endpoint",
",",
"token",
":",
"Diffbot",
".",
"token",
",",
"url",
":",
"@url",
"@response",
"=",
"JSON",
".",
"parse",
"(",
"api_response",
".",
"body",
")",
"end"
] | Extracts article data through Diffbot API | [
"Extracts",
"article",
"data",
"through",
"Diffbot",
"API"
] | 7f292988b36304ea15e1e74a5ee9f955d82b637e | https://github.com/orendon/diffbot.rb/blob/7f292988b36304ea15e1e74a5ee9f955d82b637e/lib/diffbot_api/article.rb#L35-L38 | train |
jtzero/vigilem-assembly | lib/vigilem/assembly.rb | Vigilem.Assembly.find_stat | def find_stat(opts={}, &block)
stats = Core::Stat.all_available
# @fixme just grabs first
stat = if stats.size > 1
[*opts[:platform_defaults]].map do |os_pattern, gem_name|
if System.check[:os][os_pattern]
stats.select {|stat| stat.gem_name == gem_name }
if stats.size > 1
raise ArgumentError, "multiple handlers match :platform_defaults"\
"#{os_pattern} => #{gem_name} matches #{stats}"
else
stats.first
end
end
end.flatten.compact.first
else
stats.first
end
end | ruby | def find_stat(opts={}, &block)
stats = Core::Stat.all_available
# @fixme just grabs first
stat = if stats.size > 1
[*opts[:platform_defaults]].map do |os_pattern, gem_name|
if System.check[:os][os_pattern]
stats.select {|stat| stat.gem_name == gem_name }
if stats.size > 1
raise ArgumentError, "multiple handlers match :platform_defaults"\
"#{os_pattern} => #{gem_name} matches #{stats}"
else
stats.first
end
end
end.flatten.compact.first
else
stats.first
end
end | [
"def",
"find_stat",
"(",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"stats",
"=",
"Core",
"::",
"Stat",
".",
"all_available",
"# @fixme just grabs first",
"stat",
"=",
"if",
"stats",
".",
"size",
">",
"1",
"[",
"opts",
"[",
":platform_defaults",
"]",
"]",
".",
"map",
"do",
"|",
"os_pattern",
",",
"gem_name",
"|",
"if",
"System",
".",
"check",
"[",
":os",
"]",
"[",
"os_pattern",
"]",
"stats",
".",
"select",
"{",
"|",
"stat",
"|",
"stat",
".",
"gem_name",
"==",
"gem_name",
"}",
"if",
"stats",
".",
"size",
">",
"1",
"raise",
"ArgumentError",
",",
"\"multiple handlers match :platform_defaults\"",
"\"#{os_pattern} => #{gem_name} matches #{stats}\"",
"else",
"stats",
".",
"first",
"end",
"end",
"end",
".",
"flatten",
".",
"compact",
".",
"first",
"else",
"stats",
".",
"first",
"end",
"end"
] | find's an available handler
@param [Hash] opts
@option opts [Array<Regexp || String, Array<String> || String>] :platform_defaults [os_pattern, gem_name],
the default gem for os_pattern, if os_pattern matches this os
and there are mulitple handlers available, install this gem_name
and raises ArgumentError when the default matches more than one Stat
@param [Proc] block
@raise ArgumentError, when the platform default matches more than one Stat
@return [Stat || NilClass] | [
"find",
"s",
"an",
"available",
"handler"
] | 732af25099a5c6947e9b4770ba9d8a3f15759446 | https://github.com/jtzero/vigilem-assembly/blob/732af25099a5c6947e9b4770ba9d8a3f15759446/lib/vigilem/assembly.rb#L49-L67 | train |
lenn4rd/chores_kit | lib/chores_kit/chore.rb | ChoresKit.Chore.task | def task(options, &block)
name, params = *options
raise "Couldn't create task without a name" if name.nil?
raise "Couldn't create task without a block" unless block_given?
task = Task.new(name, params)
task.instance_eval(&block)
@dag.add_vertex(name: name, task: task)
end | ruby | def task(options, &block)
name, params = *options
raise "Couldn't create task without a name" if name.nil?
raise "Couldn't create task without a block" unless block_given?
task = Task.new(name, params)
task.instance_eval(&block)
@dag.add_vertex(name: name, task: task)
end | [
"def",
"task",
"(",
"options",
",",
"&",
"block",
")",
"name",
",",
"params",
"=",
"options",
"raise",
"\"Couldn't create task without a name\"",
"if",
"name",
".",
"nil?",
"raise",
"\"Couldn't create task without a block\"",
"unless",
"block_given?",
"task",
"=",
"Task",
".",
"new",
"(",
"name",
",",
"params",
")",
"task",
".",
"instance_eval",
"(",
"block",
")",
"@dag",
".",
"add_vertex",
"(",
"name",
":",
"name",
",",
"task",
":",
"task",
")",
"end"
] | Tasks and dependencies | [
"Tasks",
"and",
"dependencies"
] | 3349c5c62d77507f30388d2a71e10b8c40361379 | https://github.com/lenn4rd/chores_kit/blob/3349c5c62d77507f30388d2a71e10b8c40361379/lib/chores_kit/chore.rb#L55-L65 | train |
filipjakubowski/jira_issues | lib/jira_issues/jira_query.rb | JiraIssues.JiraQuery.jql_query | def jql_query(query)
result = adapter.jql(query, fields:[:description, :summary, :created, :status, :issuetype, :priority, :resolutiondate], max_results: @query_max_results)
JiraIssuesNavigator.new(result.map{|i| JiraIssueMapper.new.call(i) })
end | ruby | def jql_query(query)
result = adapter.jql(query, fields:[:description, :summary, :created, :status, :issuetype, :priority, :resolutiondate], max_results: @query_max_results)
JiraIssuesNavigator.new(result.map{|i| JiraIssueMapper.new.call(i) })
end | [
"def",
"jql_query",
"(",
"query",
")",
"result",
"=",
"adapter",
".",
"jql",
"(",
"query",
",",
"fields",
":",
"[",
":description",
",",
":summary",
",",
":created",
",",
":status",
",",
":issuetype",
",",
":priority",
",",
":resolutiondate",
"]",
",",
"max_results",
":",
"@query_max_results",
")",
"JiraIssuesNavigator",
".",
"new",
"(",
"result",
".",
"map",
"{",
"|",
"i",
"|",
"JiraIssueMapper",
".",
"new",
".",
"call",
"(",
"i",
")",
"}",
")",
"end"
] | Creates new Query object
and sets the maximum number of issues returned by Query
@param max_results [Integer] maximum number of issues returned by query
Handles a JQL Request and returns JiraIssueavigator for that query
@param query [String]
@return [JiraIssueNavigator] with those requests | [
"Creates",
"new",
"Query",
"object",
"and",
"sets",
"the",
"maximum",
"number",
"of",
"issues",
"returned",
"by",
"Query"
] | 6545c1c2b3a72226ad309386d74ca86d35ff8bb1 | https://github.com/filipjakubowski/jira_issues/blob/6545c1c2b3a72226ad309386d74ca86d35ff8bb1/lib/jira_issues/jira_query.rb#L14-L17 | train |
marcboeker/mongolicious | lib/mongolicious/filesystem.rb | Mongolicious.Filesystem.compress | def compress(path, compress_tar_file)
Mongolicious.logger.info("Compressing database #{path}")
system("cd #{path} && tar -cpf#{compress_tar_file ? 'j' : ''} #{path}.tar.bz2 .")
raise "Error while compressing #{path}" if $?.to_i != 0
# Remove mongo dump now that we have the bzip
FileUtils.rm_rf(path)
return "#{path}.tar.bz2"
end | ruby | def compress(path, compress_tar_file)
Mongolicious.logger.info("Compressing database #{path}")
system("cd #{path} && tar -cpf#{compress_tar_file ? 'j' : ''} #{path}.tar.bz2 .")
raise "Error while compressing #{path}" if $?.to_i != 0
# Remove mongo dump now that we have the bzip
FileUtils.rm_rf(path)
return "#{path}.tar.bz2"
end | [
"def",
"compress",
"(",
"path",
",",
"compress_tar_file",
")",
"Mongolicious",
".",
"logger",
".",
"info",
"(",
"\"Compressing database #{path}\"",
")",
"system",
"(",
"\"cd #{path} && tar -cpf#{compress_tar_file ? 'j' : ''} #{path}.tar.bz2 .\"",
")",
"raise",
"\"Error while compressing #{path}\"",
"if",
"$?",
".",
"to_i",
"!=",
"0",
"# Remove mongo dump now that we have the bzip",
"FileUtils",
".",
"rm_rf",
"(",
"path",
")",
"return",
"\"#{path}.tar.bz2\"",
"end"
] | Initialize a ne Filesystem object.
@return [Filesytem]
Compress the dump to an tar.bz2 archive.
@param [String] path the path, where the dump is located.
@return [String] | [
"Initialize",
"a",
"ne",
"Filesystem",
"object",
"."
] | bc1553188df97d3df825de6d826b34ab7185a431 | https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/filesystem.rb#L16-L26 | train |
marcboeker/mongolicious | lib/mongolicious/filesystem.rb | Mongolicious.Filesystem.cleanup_tar_file | def cleanup_tar_file(path)
Mongolicious.logger.info("Cleaning up local path #{path}")
begin
File.delete(path)
rescue => exception
Mongolicious.logger.error("Error trying to delete: #{path}")
Mongolicious.logger.info(exception.message)
end
end | ruby | def cleanup_tar_file(path)
Mongolicious.logger.info("Cleaning up local path #{path}")
begin
File.delete(path)
rescue => exception
Mongolicious.logger.error("Error trying to delete: #{path}")
Mongolicious.logger.info(exception.message)
end
end | [
"def",
"cleanup_tar_file",
"(",
"path",
")",
"Mongolicious",
".",
"logger",
".",
"info",
"(",
"\"Cleaning up local path #{path}\"",
")",
"begin",
"File",
".",
"delete",
"(",
"path",
")",
"rescue",
"=>",
"exception",
"Mongolicious",
".",
"logger",
".",
"error",
"(",
"\"Error trying to delete: #{path}\"",
")",
"Mongolicious",
".",
"logger",
".",
"info",
"(",
"exception",
".",
"message",
")",
"end",
"end"
] | Remove dump from tmp path.
@param [String] path the path, where the dump/archive is located.
@return [nil] | [
"Remove",
"dump",
"from",
"tmp",
"path",
"."
] | bc1553188df97d3df825de6d826b34ab7185a431 | https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/filesystem.rb#L45-L53 | train |
marcboeker/mongolicious | lib/mongolicious/filesystem.rb | Mongolicious.Filesystem.cleanup_parts | def cleanup_parts(file_parts)
Mongolicious.logger.info("Cleaning up file parts.")
if file_parts
file_parts.each do |part|
Mongolicious.logger.info("Deleting part: #{part}")
begin
File.delete(part)
rescue => exception
Mongolicious.logger.error("Error trying to delete part: #{part}")
Mongolicious.logger.error(exception.message)
Mongolicious.logger.error(exception.backtrace)
end
end
end
end | ruby | def cleanup_parts(file_parts)
Mongolicious.logger.info("Cleaning up file parts.")
if file_parts
file_parts.each do |part|
Mongolicious.logger.info("Deleting part: #{part}")
begin
File.delete(part)
rescue => exception
Mongolicious.logger.error("Error trying to delete part: #{part}")
Mongolicious.logger.error(exception.message)
Mongolicious.logger.error(exception.backtrace)
end
end
end
end | [
"def",
"cleanup_parts",
"(",
"file_parts",
")",
"Mongolicious",
".",
"logger",
".",
"info",
"(",
"\"Cleaning up file parts.\"",
")",
"if",
"file_parts",
"file_parts",
".",
"each",
"do",
"|",
"part",
"|",
"Mongolicious",
".",
"logger",
".",
"info",
"(",
"\"Deleting part: #{part}\"",
")",
"begin",
"File",
".",
"delete",
"(",
"part",
")",
"rescue",
"=>",
"exception",
"Mongolicious",
".",
"logger",
".",
"error",
"(",
"\"Error trying to delete part: #{part}\"",
")",
"Mongolicious",
".",
"logger",
".",
"error",
"(",
"exception",
".",
"message",
")",
"Mongolicious",
".",
"logger",
".",
"error",
"(",
"exception",
".",
"backtrace",
")",
"end",
"end",
"end",
"end"
] | Remove all the bzip parts
@param [Array] file_parts an array of paths
@return [nill] | [
"Remove",
"all",
"the",
"bzip",
"parts"
] | bc1553188df97d3df825de6d826b34ab7185a431 | https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/filesystem.rb#L60-L75 | train |
iamcutler/deal-redemptions | app/controllers/deal_redemptions/redeem_controller.rb | DealRedemptions.RedeemController.validate_code | def validate_code
redeem_code = DealRedemptions::RedeemCode.find_by_code(params[:code])
if redeem_code
@redeem = redeem_code.validate_code(params)
else
@redeem = false
end
end | ruby | def validate_code
redeem_code = DealRedemptions::RedeemCode.find_by_code(params[:code])
if redeem_code
@redeem = redeem_code.validate_code(params)
else
@redeem = false
end
end | [
"def",
"validate_code",
"redeem_code",
"=",
"DealRedemptions",
"::",
"RedeemCode",
".",
"find_by_code",
"(",
"params",
"[",
":code",
"]",
")",
"if",
"redeem_code",
"@redeem",
"=",
"redeem_code",
".",
"validate_code",
"(",
"params",
")",
"else",
"@redeem",
"=",
"false",
"end",
"end"
] | Validate valid redemption codes | [
"Validate",
"valid",
"redemption",
"codes"
] | b9b06df288c84a5bb0c0588ad0beca80b14edd31 | https://github.com/iamcutler/deal-redemptions/blob/b9b06df288c84a5bb0c0588ad0beca80b14edd31/app/controllers/deal_redemptions/redeem_controller.rb#L69-L76 | train |
seejohnrun/flexible_api | lib/flexible_api.rb | FlexibleApi.ClassMethods.define_request_level | def define_request_level(name, &block)
level = RequestLevel.new(name, self)
level.instance_eval &block
@levels ||= {}
@levels[name] = level
end | ruby | def define_request_level(name, &block)
level = RequestLevel.new(name, self)
level.instance_eval &block
@levels ||= {}
@levels[name] = level
end | [
"def",
"define_request_level",
"(",
"name",
",",
"&",
"block",
")",
"level",
"=",
"RequestLevel",
".",
"new",
"(",
"name",
",",
"self",
")",
"level",
".",
"instance_eval",
"block",
"@levels",
"||=",
"{",
"}",
"@levels",
"[",
"name",
"]",
"=",
"level",
"end"
] | Define a request level for this class
Takes a name, and a block which defined the request level | [
"Define",
"a",
"request",
"level",
"for",
"this",
"class",
"Takes",
"a",
"name",
"and",
"a",
"block",
"which",
"defined",
"the",
"request",
"level"
] | 5c09ca580f96f9ecea1c00b2ea15dc65d6d1c66c | https://github.com/seejohnrun/flexible_api/blob/5c09ca580f96f9ecea1c00b2ea15dc65d6d1c66c/lib/flexible_api.rb#L27-L32 | train |
seejohnrun/flexible_api | lib/flexible_api.rb | FlexibleApi.ClassMethods.find_hash | def find_hash(id, options = {})
options.assert_valid_keys(:request_level)
level = find_level(options[:request_level])
record = self.find(id, :select => level.select_field.join(', '), :include => level.include_field)
level.receive record
end | ruby | def find_hash(id, options = {})
options.assert_valid_keys(:request_level)
level = find_level(options[:request_level])
record = self.find(id, :select => level.select_field.join(', '), :include => level.include_field)
level.receive record
end | [
"def",
"find_hash",
"(",
"id",
",",
"options",
"=",
"{",
"}",
")",
"options",
".",
"assert_valid_keys",
"(",
":request_level",
")",
"level",
"=",
"find_level",
"(",
"options",
"[",
":request_level",
"]",
")",
"record",
"=",
"self",
".",
"find",
"(",
"id",
",",
":select",
"=>",
"level",
".",
"select_field",
".",
"join",
"(",
"', '",
")",
",",
":include",
"=>",
"level",
".",
"include_field",
")",
"level",
".",
"receive",
"record",
"end"
] | Find a single element and load it at the given request level | [
"Find",
"a",
"single",
"element",
"and",
"load",
"it",
"at",
"the",
"given",
"request",
"level"
] | 5c09ca580f96f9ecea1c00b2ea15dc65d6d1c66c | https://github.com/seejohnrun/flexible_api/blob/5c09ca580f96f9ecea1c00b2ea15dc65d6d1c66c/lib/flexible_api.rb#L35-L40 | train |
seejohnrun/flexible_api | lib/flexible_api.rb | FlexibleApi.ClassMethods.find_level | def find_level(name = nil)
@levels ||= {}
level = name.nil? ? load_default_request_level : @levels[name.to_sym]
level = superclass.find_level(name) and @levels[name.to_sym] = level if level.nil? && superclass.present?
raise NoSuchRequestLevelError.new(name, self.name) if level.nil?
level
end | ruby | def find_level(name = nil)
@levels ||= {}
level = name.nil? ? load_default_request_level : @levels[name.to_sym]
level = superclass.find_level(name) and @levels[name.to_sym] = level if level.nil? && superclass.present?
raise NoSuchRequestLevelError.new(name, self.name) if level.nil?
level
end | [
"def",
"find_level",
"(",
"name",
"=",
"nil",
")",
"@levels",
"||=",
"{",
"}",
"level",
"=",
"name",
".",
"nil?",
"?",
"load_default_request_level",
":",
"@levels",
"[",
"name",
".",
"to_sym",
"]",
"level",
"=",
"superclass",
".",
"find_level",
"(",
"name",
")",
"and",
"@levels",
"[",
"name",
".",
"to_sym",
"]",
"=",
"level",
"if",
"level",
".",
"nil?",
"&&",
"superclass",
".",
"present?",
"raise",
"NoSuchRequestLevelError",
".",
"new",
"(",
"name",
",",
"self",
".",
"name",
")",
"if",
"level",
".",
"nil?",
"level",
"end"
] | Find a given level by name and return the request level | [
"Find",
"a",
"given",
"level",
"by",
"name",
"and",
"return",
"the",
"request",
"level"
] | 5c09ca580f96f9ecea1c00b2ea15dc65d6d1c66c | https://github.com/seejohnrun/flexible_api/blob/5c09ca580f96f9ecea1c00b2ea15dc65d6d1c66c/lib/flexible_api.rb#L61-L67 | train |
jimjh/reaction | lib/reaction/rails/mapper.rb | ActionDispatch::Routing.Mapper.use_reaction | def use_reaction(opts = {})
raise RuntimeError, 'Already using Reaction.' if Reaction.client
opts = use_reaction_defaults opts
EM.next_tick {
faye = Faye::Client.new(opts[:at] + '/bayeux')
signer = Reaction::Client::Signer.new opts[:key]
faye.add_extension signer
Reaction.client = Reaction::Client.new faye, opts[:key]
}
end | ruby | def use_reaction(opts = {})
raise RuntimeError, 'Already using Reaction.' if Reaction.client
opts = use_reaction_defaults opts
EM.next_tick {
faye = Faye::Client.new(opts[:at] + '/bayeux')
signer = Reaction::Client::Signer.new opts[:key]
faye.add_extension signer
Reaction.client = Reaction::Client.new faye, opts[:key]
}
end | [
"def",
"use_reaction",
"(",
"opts",
"=",
"{",
"}",
")",
"raise",
"RuntimeError",
",",
"'Already using Reaction.'",
"if",
"Reaction",
".",
"client",
"opts",
"=",
"use_reaction_defaults",
"opts",
"EM",
".",
"next_tick",
"{",
"faye",
"=",
"Faye",
"::",
"Client",
".",
"new",
"(",
"opts",
"[",
":at",
"]",
"+",
"'/bayeux'",
")",
"signer",
"=",
"Reaction",
"::",
"Client",
"::",
"Signer",
".",
"new",
"opts",
"[",
":key",
"]",
"faye",
".",
"add_extension",
"signer",
"Reaction",
".",
"client",
"=",
"Reaction",
"::",
"Client",
".",
"new",
"faye",
",",
"opts",
"[",
":key",
"]",
"}",
"end"
] | Uses an external reaction server.
@example Using an external reaction server at +localhost:9292/reaction+.
use_reaction :at => 'http://localhost:9292/reaction'
@option opts [String] :at URL of external reaction server.
@option opts [String] :key secret token, used for signing messages
published from app server; defaults to
+Rails.application.config.secret_token+
@raise [RuntimeError] if the reaction client has already been initialized.
@return [Reaction::Client] client | [
"Uses",
"an",
"external",
"reaction",
"server",
"."
] | 8aff9633dbd177ea536b79f59115a2825b5adf0a | https://github.com/jimjh/reaction/blob/8aff9633dbd177ea536b79f59115a2825b5adf0a/lib/reaction/rails/mapper.rb#L23-L36 | train |
bambery/cloud_crooner | lib/cloud_crooner/storage.rb | CloudCrooner.Storage.upload_files | def upload_files
files_to_upload = local_compiled_assets.reject { |f| exists_on_remote?(f) }
files_to_upload.each do |asset|
upload_file(asset)
end
end | ruby | def upload_files
files_to_upload = local_compiled_assets.reject { |f| exists_on_remote?(f) }
files_to_upload.each do |asset|
upload_file(asset)
end
end | [
"def",
"upload_files",
"files_to_upload",
"=",
"local_compiled_assets",
".",
"reject",
"{",
"|",
"f",
"|",
"exists_on_remote?",
"(",
"f",
")",
"}",
"files_to_upload",
".",
"each",
"do",
"|",
"asset",
"|",
"upload_file",
"(",
"asset",
")",
"end",
"end"
] | Upload all new files to the bucket | [
"Upload",
"all",
"new",
"files",
"to",
"the",
"bucket"
] | 223cd525b8b83656201a645f43af1b1181555703 | https://github.com/bambery/cloud_crooner/blob/223cd525b8b83656201a645f43af1b1181555703/lib/cloud_crooner/storage.rb#L42-L47 | train |
bambery/cloud_crooner | lib/cloud_crooner/storage.rb | CloudCrooner.Storage.upload_file | def upload_file(f)
# grabs the compiled asset from public_path
full_file_path = File.join(File.dirname(@manifest.dir), f)
one_year = 31557600
mime = Rack::Mime.mime_type(File.extname(f))
file = {
:key => f,
:public => true,
:content_type => mime,
:cache_control => "public, max-age=#{one_year}",
:expires => CGI.rfc1123_date(Time.now + one_year)
}
gzipped = "#{full_file_path}.gz"
if File.exists?(gzipped)
original_size = File.size(full_file_path)
gzipped_size = File.size(gzipped)
if gzipped_size < original_size
file.merge!({
:body => File.open(gzipped),
:content_encoding => 'gzip'
})
log "Uploading #{gzipped} in place of #{f}"
else
file.merge!({
:body => File.open(full_file_path)
})
log "Gzip exists but has larger file size, uploading #{f}"
end
else
file.merge!({
:body => File.open(full_file_path)
})
log "Uploading #{f}"
end
# put in reduced redundancy option here later if desired
file = bucket.files.create( file )
end | ruby | def upload_file(f)
# grabs the compiled asset from public_path
full_file_path = File.join(File.dirname(@manifest.dir), f)
one_year = 31557600
mime = Rack::Mime.mime_type(File.extname(f))
file = {
:key => f,
:public => true,
:content_type => mime,
:cache_control => "public, max-age=#{one_year}",
:expires => CGI.rfc1123_date(Time.now + one_year)
}
gzipped = "#{full_file_path}.gz"
if File.exists?(gzipped)
original_size = File.size(full_file_path)
gzipped_size = File.size(gzipped)
if gzipped_size < original_size
file.merge!({
:body => File.open(gzipped),
:content_encoding => 'gzip'
})
log "Uploading #{gzipped} in place of #{f}"
else
file.merge!({
:body => File.open(full_file_path)
})
log "Gzip exists but has larger file size, uploading #{f}"
end
else
file.merge!({
:body => File.open(full_file_path)
})
log "Uploading #{f}"
end
# put in reduced redundancy option here later if desired
file = bucket.files.create( file )
end | [
"def",
"upload_file",
"(",
"f",
")",
"# grabs the compiled asset from public_path",
"full_file_path",
"=",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"@manifest",
".",
"dir",
")",
",",
"f",
")",
"one_year",
"=",
"31557600",
"mime",
"=",
"Rack",
"::",
"Mime",
".",
"mime_type",
"(",
"File",
".",
"extname",
"(",
"f",
")",
")",
"file",
"=",
"{",
":key",
"=>",
"f",
",",
":public",
"=>",
"true",
",",
":content_type",
"=>",
"mime",
",",
":cache_control",
"=>",
"\"public, max-age=#{one_year}\"",
",",
":expires",
"=>",
"CGI",
".",
"rfc1123_date",
"(",
"Time",
".",
"now",
"+",
"one_year",
")",
"}",
"gzipped",
"=",
"\"#{full_file_path}.gz\"",
"if",
"File",
".",
"exists?",
"(",
"gzipped",
")",
"original_size",
"=",
"File",
".",
"size",
"(",
"full_file_path",
")",
"gzipped_size",
"=",
"File",
".",
"size",
"(",
"gzipped",
")",
"if",
"gzipped_size",
"<",
"original_size",
"file",
".",
"merge!",
"(",
"{",
":body",
"=>",
"File",
".",
"open",
"(",
"gzipped",
")",
",",
":content_encoding",
"=>",
"'gzip'",
"}",
")",
"log",
"\"Uploading #{gzipped} in place of #{f}\"",
"else",
"file",
".",
"merge!",
"(",
"{",
":body",
"=>",
"File",
".",
"open",
"(",
"full_file_path",
")",
"}",
")",
"log",
"\"Gzip exists but has larger file size, uploading #{f}\"",
"end",
"else",
"file",
".",
"merge!",
"(",
"{",
":body",
"=>",
"File",
".",
"open",
"(",
"full_file_path",
")",
"}",
")",
"log",
"\"Uploading #{f}\"",
"end",
"# put in reduced redundancy option here later if desired",
"file",
"=",
"bucket",
".",
"files",
".",
"create",
"(",
"file",
")",
"end"
] | Uploads a file to the bucket. Sets expires header to one year. If a
gzipped version of the file exists and is a smaller file size | [
"Uploads",
"a",
"file",
"to",
"the",
"bucket",
".",
"Sets",
"expires",
"header",
"to",
"one",
"year",
".",
"If",
"a",
"gzipped",
"version",
"of",
"the",
"file",
"exists",
"and",
"is",
"a",
"smaller",
"file",
"size"
] | 223cd525b8b83656201a645f43af1b1181555703 | https://github.com/bambery/cloud_crooner/blob/223cd525b8b83656201a645f43af1b1181555703/lib/cloud_crooner/storage.rb#L57-L97 | train |
redding/undies | lib/undies/api.rb | Undies.API.__yield | def __yield
return if (source = @_undies_source_stack.pop).nil?
if source.file?
instance_eval(source.data, source.source, 1)
else
instance_eval(&source.data)
end
end | ruby | def __yield
return if (source = @_undies_source_stack.pop).nil?
if source.file?
instance_eval(source.data, source.source, 1)
else
instance_eval(&source.data)
end
end | [
"def",
"__yield",
"return",
"if",
"(",
"source",
"=",
"@_undies_source_stack",
".",
"pop",
")",
".",
"nil?",
"if",
"source",
".",
"file?",
"instance_eval",
"(",
"source",
".",
"data",
",",
"source",
".",
"source",
",",
"1",
")",
"else",
"instance_eval",
"(",
"source",
".",
"data",
")",
"end",
"end"
] | Source handling methods
call this to render template source
use this method in layouts to insert a layout's content source | [
"Source",
"handling",
"methods",
"call",
"this",
"to",
"render",
"template",
"source",
"use",
"this",
"method",
"in",
"layouts",
"to",
"insert",
"a",
"layout",
"s",
"content",
"source"
] | 13555df0a49fa5638cc85d16eb144443ae4ead27 | https://github.com/redding/undies/blob/13555df0a49fa5638cc85d16eb144443ae4ead27/lib/undies/api.rb#L143-L150 | train |
sinisterchipmunk/rink | lib/rink/console.rb | Rink.Console.apply_options | def apply_options(options)
return unless options
options.each do |key, value|
options[key] = value.call if value.kind_of?(Proc)
end
@_options ||= {}
@_options.merge! options
@input = setup_input_method(options[:input] || @input)
@output = setup_output_method(options[:output] || @output)
@output.silenced = options.key?(:silent) ? options[:silent] : !@output || @output.silenced?
@line_processor = options[:processor] || options[:line_processor] || @line_processor
@allow_ruby = options.key?(:allow_ruby) ? options[:allow_ruby] : @allow_ruby
if options[:namespace]
ns = options[:namespace] == :self ? self : options[:namespace]
@namespace.replace(ns)
end
if @input
@input.output = @output
@input.prompt = prompt
if @input.respond_to?(:completion_proc)
@input.completion_proc = proc { |line| autocomplete(line) }
end
end
end | ruby | def apply_options(options)
return unless options
options.each do |key, value|
options[key] = value.call if value.kind_of?(Proc)
end
@_options ||= {}
@_options.merge! options
@input = setup_input_method(options[:input] || @input)
@output = setup_output_method(options[:output] || @output)
@output.silenced = options.key?(:silent) ? options[:silent] : !@output || @output.silenced?
@line_processor = options[:processor] || options[:line_processor] || @line_processor
@allow_ruby = options.key?(:allow_ruby) ? options[:allow_ruby] : @allow_ruby
if options[:namespace]
ns = options[:namespace] == :self ? self : options[:namespace]
@namespace.replace(ns)
end
if @input
@input.output = @output
@input.prompt = prompt
if @input.respond_to?(:completion_proc)
@input.completion_proc = proc { |line| autocomplete(line) }
end
end
end | [
"def",
"apply_options",
"(",
"options",
")",
"return",
"unless",
"options",
"options",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"options",
"[",
"key",
"]",
"=",
"value",
".",
"call",
"if",
"value",
".",
"kind_of?",
"(",
"Proc",
")",
"end",
"@_options",
"||=",
"{",
"}",
"@_options",
".",
"merge!",
"options",
"@input",
"=",
"setup_input_method",
"(",
"options",
"[",
":input",
"]",
"||",
"@input",
")",
"@output",
"=",
"setup_output_method",
"(",
"options",
"[",
":output",
"]",
"||",
"@output",
")",
"@output",
".",
"silenced",
"=",
"options",
".",
"key?",
"(",
":silent",
")",
"?",
"options",
"[",
":silent",
"]",
":",
"!",
"@output",
"||",
"@output",
".",
"silenced?",
"@line_processor",
"=",
"options",
"[",
":processor",
"]",
"||",
"options",
"[",
":line_processor",
"]",
"||",
"@line_processor",
"@allow_ruby",
"=",
"options",
".",
"key?",
"(",
":allow_ruby",
")",
"?",
"options",
"[",
":allow_ruby",
"]",
":",
"@allow_ruby",
"if",
"options",
"[",
":namespace",
"]",
"ns",
"=",
"options",
"[",
":namespace",
"]",
"==",
":self",
"?",
"self",
":",
"options",
"[",
":namespace",
"]",
"@namespace",
".",
"replace",
"(",
"ns",
")",
"end",
"if",
"@input",
"@input",
".",
"output",
"=",
"@output",
"@input",
".",
"prompt",
"=",
"prompt",
"if",
"@input",
".",
"respond_to?",
"(",
":completion_proc",
")",
"@input",
".",
"completion_proc",
"=",
"proc",
"{",
"|",
"line",
"|",
"autocomplete",
"(",
"line",
")",
"}",
"end",
"end",
"end"
] | Applies a new set of options. Options that are currently unset or nil will not be modified. | [
"Applies",
"a",
"new",
"set",
"of",
"options",
".",
"Options",
"that",
"are",
"currently",
"unset",
"or",
"nil",
"will",
"not",
"be",
"modified",
"."
] | cea8c602623da75fcbec7efef4e3454cd7649a43 | https://github.com/sinisterchipmunk/rink/blob/cea8c602623da75fcbec7efef4e3454cd7649a43/lib/rink/console.rb#L86-L112 | train |
sinisterchipmunk/rink | lib/rink/console.rb | Rink.Console.autocomplete | def autocomplete(line)
return [] unless @line_processor
result = @line_processor.autocomplete(line, namespace)
case result
when String
[result]
when nil
[]
when Array
result
else
result.to_a
end
end | ruby | def autocomplete(line)
return [] unless @line_processor
result = @line_processor.autocomplete(line, namespace)
case result
when String
[result]
when nil
[]
when Array
result
else
result.to_a
end
end | [
"def",
"autocomplete",
"(",
"line",
")",
"return",
"[",
"]",
"unless",
"@line_processor",
"result",
"=",
"@line_processor",
".",
"autocomplete",
"(",
"line",
",",
"namespace",
")",
"case",
"result",
"when",
"String",
"[",
"result",
"]",
"when",
"nil",
"[",
"]",
"when",
"Array",
"result",
"else",
"result",
".",
"to_a",
"end",
"end"
] | Runs the autocomplete method from the line processor, then reformats its result to be an array. | [
"Runs",
"the",
"autocomplete",
"method",
"from",
"the",
"line",
"processor",
"then",
"reformats",
"its",
"result",
"to",
"be",
"an",
"array",
"."
] | cea8c602623da75fcbec7efef4e3454cd7649a43 | https://github.com/sinisterchipmunk/rink/blob/cea8c602623da75fcbec7efef4e3454cd7649a43/lib/rink/console.rb#L314-L327 | train |
maestrodev/maestro-ruby-plugin | lib/maestro_plugin/maestro_worker.rb | Maestro.MaestroWorker.perform | def perform(action, workitem)
@action, @workitem = action, workitem
send(action)
write_output('') # Triggers any remaining buffered output to be sent
run_callbacks
rescue MaestroDev::Plugin::PluginError => e
write_output('') # Triggers any remaining buffered output to be sent
set_error(e.message)
rescue Exception => e
write_output('') # Triggers any remaining buffered output to be sent
lowerstack = e.backtrace.find_index(caller[0])
stack = lowerstack ? e.backtrace[0..lowerstack - 1] : e.backtrace
msg = "Unexpected error executing task: #{e.class} #{e} at\n" + stack.join("\n")
Maestro.log.warn("#{msg}\nFull stack:\n" + e.backtrace.join("\n"))
# Let user-supplied exception handler do its thing
handle_exception(e)
set_error(msg)
ensure
# Older agents expected this method to *maybe* return something
# .. something that no longer exists, but if we return anything
# it will be *wrong* :P
return nil
end | ruby | def perform(action, workitem)
@action, @workitem = action, workitem
send(action)
write_output('') # Triggers any remaining buffered output to be sent
run_callbacks
rescue MaestroDev::Plugin::PluginError => e
write_output('') # Triggers any remaining buffered output to be sent
set_error(e.message)
rescue Exception => e
write_output('') # Triggers any remaining buffered output to be sent
lowerstack = e.backtrace.find_index(caller[0])
stack = lowerstack ? e.backtrace[0..lowerstack - 1] : e.backtrace
msg = "Unexpected error executing task: #{e.class} #{e} at\n" + stack.join("\n")
Maestro.log.warn("#{msg}\nFull stack:\n" + e.backtrace.join("\n"))
# Let user-supplied exception handler do its thing
handle_exception(e)
set_error(msg)
ensure
# Older agents expected this method to *maybe* return something
# .. something that no longer exists, but if we return anything
# it will be *wrong* :P
return nil
end | [
"def",
"perform",
"(",
"action",
",",
"workitem",
")",
"@action",
",",
"@workitem",
"=",
"action",
",",
"workitem",
"send",
"(",
"action",
")",
"write_output",
"(",
"''",
")",
"# Triggers any remaining buffered output to be sent",
"run_callbacks",
"rescue",
"MaestroDev",
"::",
"Plugin",
"::",
"PluginError",
"=>",
"e",
"write_output",
"(",
"''",
")",
"# Triggers any remaining buffered output to be sent",
"set_error",
"(",
"e",
".",
"message",
")",
"rescue",
"Exception",
"=>",
"e",
"write_output",
"(",
"''",
")",
"# Triggers any remaining buffered output to be sent",
"lowerstack",
"=",
"e",
".",
"backtrace",
".",
"find_index",
"(",
"caller",
"[",
"0",
"]",
")",
"stack",
"=",
"lowerstack",
"?",
"e",
".",
"backtrace",
"[",
"0",
"..",
"lowerstack",
"-",
"1",
"]",
":",
"e",
".",
"backtrace",
"msg",
"=",
"\"Unexpected error executing task: #{e.class} #{e} at\\n\"",
"+",
"stack",
".",
"join",
"(",
"\"\\n\"",
")",
"Maestro",
".",
"log",
".",
"warn",
"(",
"\"#{msg}\\nFull stack:\\n\"",
"+",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"# Let user-supplied exception handler do its thing",
"handle_exception",
"(",
"e",
")",
"set_error",
"(",
"msg",
")",
"ensure",
"# Older agents expected this method to *maybe* return something",
"# .. something that no longer exists, but if we return anything",
"# it will be *wrong* :P",
"return",
"nil",
"end"
] | Perform the specified action with the provided workitem. Invokes the method specified by the action parameter. | [
"Perform",
"the",
"specified",
"action",
"with",
"the",
"provided",
"workitem",
".",
"Invokes",
"the",
"method",
"specified",
"by",
"the",
"action",
"parameter",
"."
] | 9a751042040b33197b8e73a352ddf609a1e6d034 | https://github.com/maestrodev/maestro-ruby-plugin/blob/9a751042040b33197b8e73a352ddf609a1e6d034/lib/maestro_plugin/maestro_worker.rb#L100-L123 | train |
maestrodev/maestro-ruby-plugin | lib/maestro_plugin/maestro_worker.rb | Maestro.MaestroWorker.handle_exception | def handle_exception(e)
if self.class.exception_handler_method
send(self.class.exception_handler_method, e)
elsif self.class.exception_handler_block
self.class.exception_handler_block.call(e, self)
end
end | ruby | def handle_exception(e)
if self.class.exception_handler_method
send(self.class.exception_handler_method, e)
elsif self.class.exception_handler_block
self.class.exception_handler_block.call(e, self)
end
end | [
"def",
"handle_exception",
"(",
"e",
")",
"if",
"self",
".",
"class",
".",
"exception_handler_method",
"send",
"(",
"self",
".",
"class",
".",
"exception_handler_method",
",",
"e",
")",
"elsif",
"self",
".",
"class",
".",
"exception_handler_block",
"self",
".",
"class",
".",
"exception_handler_block",
".",
"call",
"(",
"e",
",",
"self",
")",
"end",
"end"
] | Fire supplied exception handlers if supplied, otherwise do nothing | [
"Fire",
"supplied",
"exception",
"handlers",
"if",
"supplied",
"otherwise",
"do",
"nothing"
] | 9a751042040b33197b8e73a352ddf609a1e6d034 | https://github.com/maestrodev/maestro-ruby-plugin/blob/9a751042040b33197b8e73a352ddf609a1e6d034/lib/maestro_plugin/maestro_worker.rb#L126-L132 | train |
maestrodev/maestro-ruby-plugin | lib/maestro_plugin/maestro_worker.rb | Maestro.MaestroWorker.save_output_value | def save_output_value(name, value)
set_field(CONTEXT_OUTPUTS_META, {}) if get_field(CONTEXT_OUTPUTS_META).nil?
get_field(CONTEXT_OUTPUTS_META)[name] = value
end | ruby | def save_output_value(name, value)
set_field(CONTEXT_OUTPUTS_META, {}) if get_field(CONTEXT_OUTPUTS_META).nil?
get_field(CONTEXT_OUTPUTS_META)[name] = value
end | [
"def",
"save_output_value",
"(",
"name",
",",
"value",
")",
"set_field",
"(",
"CONTEXT_OUTPUTS_META",
",",
"{",
"}",
")",
"if",
"get_field",
"(",
"CONTEXT_OUTPUTS_META",
")",
".",
"nil?",
"get_field",
"(",
"CONTEXT_OUTPUTS_META",
")",
"[",
"name",
"]",
"=",
"value",
"end"
] | Set a value in the context output | [
"Set",
"a",
"value",
"in",
"the",
"context",
"output"
] | 9a751042040b33197b8e73a352ddf609a1e6d034 | https://github.com/maestrodev/maestro-ruby-plugin/blob/9a751042040b33197b8e73a352ddf609a1e6d034/lib/maestro_plugin/maestro_worker.rb#L145-L148 | train |
maestrodev/maestro-ruby-plugin | lib/maestro_plugin/maestro_worker.rb | Maestro.MaestroWorker.read_output_value | def read_output_value(name)
if get_field(PREVIOUS_CONTEXT_OUTPUTS_META).nil?
set_field(CONTEXT_OUTPUTS_META, {}) if get_field(CONTEXT_OUTPUTS_META).nil?
get_field(CONTEXT_OUTPUTS_META)[name]
else
get_field(PREVIOUS_CONTEXT_OUTPUTS_META)[name]
end
end | ruby | def read_output_value(name)
if get_field(PREVIOUS_CONTEXT_OUTPUTS_META).nil?
set_field(CONTEXT_OUTPUTS_META, {}) if get_field(CONTEXT_OUTPUTS_META).nil?
get_field(CONTEXT_OUTPUTS_META)[name]
else
get_field(PREVIOUS_CONTEXT_OUTPUTS_META)[name]
end
end | [
"def",
"read_output_value",
"(",
"name",
")",
"if",
"get_field",
"(",
"PREVIOUS_CONTEXT_OUTPUTS_META",
")",
".",
"nil?",
"set_field",
"(",
"CONTEXT_OUTPUTS_META",
",",
"{",
"}",
")",
"if",
"get_field",
"(",
"CONTEXT_OUTPUTS_META",
")",
".",
"nil?",
"get_field",
"(",
"CONTEXT_OUTPUTS_META",
")",
"[",
"name",
"]",
"else",
"get_field",
"(",
"PREVIOUS_CONTEXT_OUTPUTS_META",
")",
"[",
"name",
"]",
"end",
"end"
] | Read a value from the context output | [
"Read",
"a",
"value",
"from",
"the",
"context",
"output"
] | 9a751042040b33197b8e73a352ddf609a1e6d034 | https://github.com/maestrodev/maestro-ruby-plugin/blob/9a751042040b33197b8e73a352ddf609a1e6d034/lib/maestro_plugin/maestro_worker.rb#L151-L158 | train |
maestrodev/maestro-ruby-plugin | lib/maestro_plugin/maestro_worker.rb | Maestro.MaestroWorker.set_waiting | def set_waiting(should_wait)
workitem[WAITING_META] = should_wait
send_workitem_message
rescue Exception => e
Maestro.log.warn "Failed To Send Waiting Message To Server #{e.class} #{e}: #{e.backtrace.join("\n")}"
ensure
workitem.delete(WAITING_META) unless should_wait
end | ruby | def set_waiting(should_wait)
workitem[WAITING_META] = should_wait
send_workitem_message
rescue Exception => e
Maestro.log.warn "Failed To Send Waiting Message To Server #{e.class} #{e}: #{e.backtrace.join("\n")}"
ensure
workitem.delete(WAITING_META) unless should_wait
end | [
"def",
"set_waiting",
"(",
"should_wait",
")",
"workitem",
"[",
"WAITING_META",
"]",
"=",
"should_wait",
"send_workitem_message",
"rescue",
"Exception",
"=>",
"e",
"Maestro",
".",
"log",
".",
"warn",
"\"Failed To Send Waiting Message To Server #{e.class} #{e}: #{e.backtrace.join(\"\\n\")}\"",
"ensure",
"workitem",
".",
"delete",
"(",
"WAITING_META",
")",
"unless",
"should_wait",
"end"
] | control
Sets the current task as waiting | [
"control",
"Sets",
"the",
"current",
"task",
"as",
"waiting"
] | 9a751042040b33197b8e73a352ddf609a1e6d034 | https://github.com/maestrodev/maestro-ruby-plugin/blob/9a751042040b33197b8e73a352ddf609a1e6d034/lib/maestro_plugin/maestro_worker.rb#L261-L268 | train |
maestrodev/maestro-ruby-plugin | lib/maestro_plugin/maestro_worker.rb | Maestro.MaestroWorker.cancel | def cancel
workitem[CANCEL_META] = true
send_workitem_message
rescue Exception => e
Maestro.log.warn "Failed To Send Cancel Message To Server #{e.class} #{e}: #{e.backtrace.join("\n")}"
ensure
workitem.delete(CANCEL_META)
end | ruby | def cancel
workitem[CANCEL_META] = true
send_workitem_message
rescue Exception => e
Maestro.log.warn "Failed To Send Cancel Message To Server #{e.class} #{e}: #{e.backtrace.join("\n")}"
ensure
workitem.delete(CANCEL_META)
end | [
"def",
"cancel",
"workitem",
"[",
"CANCEL_META",
"]",
"=",
"true",
"send_workitem_message",
"rescue",
"Exception",
"=>",
"e",
"Maestro",
".",
"log",
".",
"warn",
"\"Failed To Send Cancel Message To Server #{e.class} #{e}: #{e.backtrace.join(\"\\n\")}\"",
"ensure",
"workitem",
".",
"delete",
"(",
"CANCEL_META",
")",
"end"
] | Send the "cancel" message to the server | [
"Send",
"the",
"cancel",
"message",
"to",
"the",
"server"
] | 9a751042040b33197b8e73a352ddf609a1e6d034 | https://github.com/maestrodev/maestro-ruby-plugin/blob/9a751042040b33197b8e73a352ddf609a1e6d034/lib/maestro_plugin/maestro_worker.rb#L271-L278 | train |
maestrodev/maestro-ruby-plugin | lib/maestro_plugin/maestro_worker.rb | Maestro.MaestroWorker.not_needed | def not_needed
workitem[NOT_NEEDED] = true
send_workitem_message
rescue Exception => e
Maestro.log.warn "Failed To Send Not Needed Message To Server #{e.class} #{e}: #{e.backtrace.join("\n")}"
ensure
workitem.delete(NOT_NEEDED)
end | ruby | def not_needed
workitem[NOT_NEEDED] = true
send_workitem_message
rescue Exception => e
Maestro.log.warn "Failed To Send Not Needed Message To Server #{e.class} #{e}: #{e.backtrace.join("\n")}"
ensure
workitem.delete(NOT_NEEDED)
end | [
"def",
"not_needed",
"workitem",
"[",
"NOT_NEEDED",
"]",
"=",
"true",
"send_workitem_message",
"rescue",
"Exception",
"=>",
"e",
"Maestro",
".",
"log",
".",
"warn",
"\"Failed To Send Not Needed Message To Server #{e.class} #{e}: #{e.backtrace.join(\"\\n\")}\"",
"ensure",
"workitem",
".",
"delete",
"(",
"NOT_NEEDED",
")",
"end"
] | Send the "not needed" message to the server. | [
"Send",
"the",
"not",
"needed",
"message",
"to",
"the",
"server",
"."
] | 9a751042040b33197b8e73a352ddf609a1e6d034 | https://github.com/maestrodev/maestro-ruby-plugin/blob/9a751042040b33197b8e73a352ddf609a1e6d034/lib/maestro_plugin/maestro_worker.rb#L282-L289 | train |
maestrodev/maestro-ruby-plugin | lib/maestro_plugin/maestro_worker.rb | Maestro.MaestroWorker.update_fields_in_record | def update_fields_in_record(model, name_or_id, record_field, record_value)
workitem[PERSIST_META] = true
workitem[UPDATE_META] = true
workitem[MODEL_META] = model
workitem[RECORD_ID_META] = name_or_id.to_s
workitem[RECORD_FIELD_META] = record_field
workitem[RECORD_VALUE_META] = record_value
send_workitem_message
workitem.delete(PERSIST_META)
workitem.delete(UPDATE_META)
end | ruby | def update_fields_in_record(model, name_or_id, record_field, record_value)
workitem[PERSIST_META] = true
workitem[UPDATE_META] = true
workitem[MODEL_META] = model
workitem[RECORD_ID_META] = name_or_id.to_s
workitem[RECORD_FIELD_META] = record_field
workitem[RECORD_VALUE_META] = record_value
send_workitem_message
workitem.delete(PERSIST_META)
workitem.delete(UPDATE_META)
end | [
"def",
"update_fields_in_record",
"(",
"model",
",",
"name_or_id",
",",
"record_field",
",",
"record_value",
")",
"workitem",
"[",
"PERSIST_META",
"]",
"=",
"true",
"workitem",
"[",
"UPDATE_META",
"]",
"=",
"true",
"workitem",
"[",
"MODEL_META",
"]",
"=",
"model",
"workitem",
"[",
"RECORD_ID_META",
"]",
"=",
"name_or_id",
".",
"to_s",
"workitem",
"[",
"RECORD_FIELD_META",
"]",
"=",
"record_field",
"workitem",
"[",
"RECORD_VALUE_META",
"]",
"=",
"record_value",
"send_workitem_message",
"workitem",
".",
"delete",
"(",
"PERSIST_META",
")",
"workitem",
".",
"delete",
"(",
"UPDATE_META",
")",
"end"
] | end control
persistence | [
"end",
"control",
"persistence"
] | 9a751042040b33197b8e73a352ddf609a1e6d034 | https://github.com/maestrodev/maestro-ruby-plugin/blob/9a751042040b33197b8e73a352ddf609a1e6d034/lib/maestro_plugin/maestro_worker.rb#L294-L306 | train |
maestrodev/maestro-ruby-plugin | lib/maestro_plugin/maestro_worker.rb | Maestro.MaestroWorker.get_field | def get_field(field, default = nil)
value = fields[field]
value = default if !default.nil? && (value.nil? || (value.respond_to?(:empty?) && value.empty?))
value
end | ruby | def get_field(field, default = nil)
value = fields[field]
value = default if !default.nil? && (value.nil? || (value.respond_to?(:empty?) && value.empty?))
value
end | [
"def",
"get_field",
"(",
"field",
",",
"default",
"=",
"nil",
")",
"value",
"=",
"fields",
"[",
"field",
"]",
"value",
"=",
"default",
"if",
"!",
"default",
".",
"nil?",
"&&",
"(",
"value",
".",
"nil?",
"||",
"(",
"value",
".",
"respond_to?",
"(",
":empty?",
")",
"&&",
"value",
".",
"empty?",
")",
")",
"value",
"end"
] | end persistence
Get a field from workitem, supporting default value | [
"end",
"persistence",
"Get",
"a",
"field",
"from",
"workitem",
"supporting",
"default",
"value"
] | 9a751042040b33197b8e73a352ddf609a1e6d034 | https://github.com/maestrodev/maestro-ruby-plugin/blob/9a751042040b33197b8e73a352ddf609a1e6d034/lib/maestro_plugin/maestro_worker.rb#L349-L353 | train |
maestrodev/maestro-ruby-plugin | lib/maestro_plugin/maestro_worker.rb | Maestro.MaestroWorker.add_link | def add_link(name, url)
set_field(LINKS_META, []) if fields[LINKS_META].nil?
fields[LINKS_META] << {'name' => name, 'url' => url}
end | ruby | def add_link(name, url)
set_field(LINKS_META, []) if fields[LINKS_META].nil?
fields[LINKS_META] << {'name' => name, 'url' => url}
end | [
"def",
"add_link",
"(",
"name",
",",
"url",
")",
"set_field",
"(",
"LINKS_META",
",",
"[",
"]",
")",
"if",
"fields",
"[",
"LINKS_META",
"]",
".",
"nil?",
"fields",
"[",
"LINKS_META",
"]",
"<<",
"{",
"'name'",
"=>",
"name",
",",
"'url'",
"=>",
"url",
"}",
"end"
] | Adds a link to be displayed in the Maestro UI. | [
"Adds",
"a",
"link",
"to",
"be",
"displayed",
"in",
"the",
"Maestro",
"UI",
"."
] | 9a751042040b33197b8e73a352ddf609a1e6d034 | https://github.com/maestrodev/maestro-ruby-plugin/blob/9a751042040b33197b8e73a352ddf609a1e6d034/lib/maestro_plugin/maestro_worker.rb#L377-L380 | train |
maestrodev/maestro-ruby-plugin | lib/maestro_plugin/maestro_worker.rb | Maestro.MaestroWorker.as_int | def as_int(value, default = 0)
res = default
if value
if value.is_a?(Fixnum)
res = value
elsif value.respond_to?(:to_i)
res = value.to_i
end
end
res
end | ruby | def as_int(value, default = 0)
res = default
if value
if value.is_a?(Fixnum)
res = value
elsif value.respond_to?(:to_i)
res = value.to_i
end
end
res
end | [
"def",
"as_int",
"(",
"value",
",",
"default",
"=",
"0",
")",
"res",
"=",
"default",
"if",
"value",
"if",
"value",
".",
"is_a?",
"(",
"Fixnum",
")",
"res",
"=",
"value",
"elsif",
"value",
".",
"respond_to?",
"(",
":to_i",
")",
"res",
"=",
"value",
".",
"to_i",
"end",
"end",
"res",
"end"
] | Field Utility methods
Return numeric version of value | [
"Field",
"Utility",
"methods",
"Return",
"numeric",
"version",
"of",
"value"
] | 9a751042040b33197b8e73a352ddf609a1e6d034 | https://github.com/maestrodev/maestro-ruby-plugin/blob/9a751042040b33197b8e73a352ddf609a1e6d034/lib/maestro_plugin/maestro_worker.rb#L385-L397 | train |
maestrodev/maestro-ruby-plugin | lib/maestro_plugin/maestro_worker.rb | Maestro.MaestroWorker.as_boolean | def as_boolean(value)
res = false
if value
if value.is_a?(TrueClass) || value.is_a?(FalseClass)
res = value
elsif value.is_a?(Fixnum)
res = value != 0
elsif value.respond_to?(:to_s)
value = value.to_s.downcase
res = (value == 't' || value == 'true')
end
end
res
end | ruby | def as_boolean(value)
res = false
if value
if value.is_a?(TrueClass) || value.is_a?(FalseClass)
res = value
elsif value.is_a?(Fixnum)
res = value != 0
elsif value.respond_to?(:to_s)
value = value.to_s.downcase
res = (value == 't' || value == 'true')
end
end
res
end | [
"def",
"as_boolean",
"(",
"value",
")",
"res",
"=",
"false",
"if",
"value",
"if",
"value",
".",
"is_a?",
"(",
"TrueClass",
")",
"||",
"value",
".",
"is_a?",
"(",
"FalseClass",
")",
"res",
"=",
"value",
"elsif",
"value",
".",
"is_a?",
"(",
"Fixnum",
")",
"res",
"=",
"value",
"!=",
"0",
"elsif",
"value",
".",
"respond_to?",
"(",
":to_s",
")",
"value",
"=",
"value",
".",
"to_s",
".",
"downcase",
"res",
"=",
"(",
"value",
"==",
"'t'",
"||",
"value",
"==",
"'true'",
")",
"end",
"end",
"res",
"end"
] | Return boolean version of a value | [
"Return",
"boolean",
"version",
"of",
"a",
"value"
] | 9a751042040b33197b8e73a352ddf609a1e6d034 | https://github.com/maestrodev/maestro-ruby-plugin/blob/9a751042040b33197b8e73a352ddf609a1e6d034/lib/maestro_plugin/maestro_worker.rb#L400-L416 | train |
4rlm/sort_rank | lib/sort_rank/solver.rb | SortRank.Solver.parse | def parse(args={})
string_block = args.fetch(:text, nil)
string_block = sample_string_block if !string_block.present?
result_hash = {results: count_strings(string_block), text: string_block }
end | ruby | def parse(args={})
string_block = args.fetch(:text, nil)
string_block = sample_string_block if !string_block.present?
result_hash = {results: count_strings(string_block), text: string_block }
end | [
"def",
"parse",
"(",
"args",
"=",
"{",
"}",
")",
"string_block",
"=",
"args",
".",
"fetch",
"(",
":text",
",",
"nil",
")",
"string_block",
"=",
"sample_string_block",
"if",
"!",
"string_block",
".",
"present?",
"result_hash",
"=",
"{",
"results",
":",
"count_strings",
"(",
"string_block",
")",
",",
"text",
":",
"string_block",
"}",
"end"
] | AlgoService.new.parse | [
"AlgoService",
".",
"new",
".",
"parse"
] | 6d6bbb1a95094b86805969f6dd15e377014c4cfe | https://github.com/4rlm/sort_rank/blob/6d6bbb1a95094b86805969f6dd15e377014c4cfe/lib/sort_rank/solver.rb#L6-L10 | train |
flori/dslkit | lib/dslkit/polite.rb | DSLKit.ThreadLocal.instance_thread_local | def instance_thread_local(name, value = nil)
sc = class << self
extend DSLKit::ThreadLocal
self
end
sc.thread_local name, value
self
end | ruby | def instance_thread_local(name, value = nil)
sc = class << self
extend DSLKit::ThreadLocal
self
end
sc.thread_local name, value
self
end | [
"def",
"instance_thread_local",
"(",
"name",
",",
"value",
"=",
"nil",
")",
"sc",
"=",
"class",
"<<",
"self",
"extend",
"DSLKit",
"::",
"ThreadLocal",
"self",
"end",
"sc",
".",
"thread_local",
"name",
",",
"value",
"self",
"end"
] | Define a thread local variable for the current instance with name _name_.
If the value _value_ is given, it is used to initialize the variable. | [
"Define",
"a",
"thread",
"local",
"variable",
"for",
"the",
"current",
"instance",
"with",
"name",
"_name_",
".",
"If",
"the",
"value",
"_value_",
"is",
"given",
"it",
"is",
"used",
"to",
"initialize",
"the",
"variable",
"."
] | 7e731a6ab3705ce9bc6563a7e7b849a464d5cfaf | https://github.com/flori/dslkit/blob/7e731a6ab3705ce9bc6563a7e7b849a464d5cfaf/lib/dslkit/polite.rb#L97-L104 | train |
flori/dslkit | lib/dslkit/polite.rb | DSLKit.ThreadGlobal.instance_thread_global | def instance_thread_global(name, value = nil)
sc = class << self
extend DSLKit::ThreadGlobal
self
end
sc.thread_global name, value
self
end | ruby | def instance_thread_global(name, value = nil)
sc = class << self
extend DSLKit::ThreadGlobal
self
end
sc.thread_global name, value
self
end | [
"def",
"instance_thread_global",
"(",
"name",
",",
"value",
"=",
"nil",
")",
"sc",
"=",
"class",
"<<",
"self",
"extend",
"DSLKit",
"::",
"ThreadGlobal",
"self",
"end",
"sc",
".",
"thread_global",
"name",
",",
"value",
"self",
"end"
] | Define a thread global variable for the current instance with name
_name_. If the value _value_ is given, it is used to initialize the
variable. | [
"Define",
"a",
"thread",
"global",
"variable",
"for",
"the",
"current",
"instance",
"with",
"name",
"_name_",
".",
"If",
"the",
"value",
"_value_",
"is",
"given",
"it",
"is",
"used",
"to",
"initialize",
"the",
"variable",
"."
] | 7e731a6ab3705ce9bc6563a7e7b849a464d5cfaf | https://github.com/flori/dslkit/blob/7e731a6ab3705ce9bc6563a7e7b849a464d5cfaf/lib/dslkit/polite.rb#L134-L141 | train |
flori/dslkit | lib/dslkit/polite.rb | DSLKit.Deflect.deflect_start | def deflect_start(from, id, deflector)
@@sync.synchronize do
Deflect.deflecting ||= DeflectorCollection.new
Deflect.deflecting.member?(from, id) and
raise DeflectError, "#{from}##{id} is already deflected"
Deflect.deflecting.add(from, id, deflector)
from.class_eval do
define_method(id) do |*args|
if Deflect.deflecting and d = Deflect.deflecting.find(self.class, id)
d.call(self, id, *args)
else
super(*args)
end
end
end
end
end | ruby | def deflect_start(from, id, deflector)
@@sync.synchronize do
Deflect.deflecting ||= DeflectorCollection.new
Deflect.deflecting.member?(from, id) and
raise DeflectError, "#{from}##{id} is already deflected"
Deflect.deflecting.add(from, id, deflector)
from.class_eval do
define_method(id) do |*args|
if Deflect.deflecting and d = Deflect.deflecting.find(self.class, id)
d.call(self, id, *args)
else
super(*args)
end
end
end
end
end | [
"def",
"deflect_start",
"(",
"from",
",",
"id",
",",
"deflector",
")",
"@@sync",
".",
"synchronize",
"do",
"Deflect",
".",
"deflecting",
"||=",
"DeflectorCollection",
".",
"new",
"Deflect",
".",
"deflecting",
".",
"member?",
"(",
"from",
",",
"id",
")",
"and",
"raise",
"DeflectError",
",",
"\"#{from}##{id} is already deflected\"",
"Deflect",
".",
"deflecting",
".",
"add",
"(",
"from",
",",
"id",
",",
"deflector",
")",
"from",
".",
"class_eval",
"do",
"define_method",
"(",
"id",
")",
"do",
"|",
"*",
"args",
"|",
"if",
"Deflect",
".",
"deflecting",
"and",
"d",
"=",
"Deflect",
".",
"deflecting",
".",
"find",
"(",
"self",
".",
"class",
",",
"id",
")",
"d",
".",
"call",
"(",
"self",
",",
"id",
",",
"args",
")",
"else",
"super",
"(",
"args",
")",
"end",
"end",
"end",
"end",
"end"
] | Start deflecting method calls named _id_ to the _from_ class using the
Deflector instance deflector. | [
"Start",
"deflecting",
"method",
"calls",
"named",
"_id_",
"to",
"the",
"_from_",
"class",
"using",
"the",
"Deflector",
"instance",
"deflector",
"."
] | 7e731a6ab3705ce9bc6563a7e7b849a464d5cfaf | https://github.com/flori/dslkit/blob/7e731a6ab3705ce9bc6563a7e7b849a464d5cfaf/lib/dslkit/polite.rb#L461-L477 | train |
flori/dslkit | lib/dslkit/polite.rb | DSLKit.Deflect.deflect | def deflect(from, id, deflector)
@@sync.synchronize do
begin
deflect_start(from, id, deflector)
yield
ensure
deflect_stop(from, id)
end
end
end | ruby | def deflect(from, id, deflector)
@@sync.synchronize do
begin
deflect_start(from, id, deflector)
yield
ensure
deflect_stop(from, id)
end
end
end | [
"def",
"deflect",
"(",
"from",
",",
"id",
",",
"deflector",
")",
"@@sync",
".",
"synchronize",
"do",
"begin",
"deflect_start",
"(",
"from",
",",
"id",
",",
"deflector",
")",
"yield",
"ensure",
"deflect_stop",
"(",
"from",
",",
"id",
")",
"end",
"end",
"end"
] | Start deflecting method calls named _id_ to the _from_ class using the
Deflector instance deflector. After that yield to the given block and
stop deflecting again. | [
"Start",
"deflecting",
"method",
"calls",
"named",
"_id_",
"to",
"the",
"_from_",
"class",
"using",
"the",
"Deflector",
"instance",
"deflector",
".",
"After",
"that",
"yield",
"to",
"the",
"given",
"block",
"and",
"stop",
"deflecting",
"again",
"."
] | 7e731a6ab3705ce9bc6563a7e7b849a464d5cfaf | https://github.com/flori/dslkit/blob/7e731a6ab3705ce9bc6563a7e7b849a464d5cfaf/lib/dslkit/polite.rb#L494-L503 | train |
flori/dslkit | lib/dslkit/polite.rb | DSLKit.Deflect.deflect_stop | def deflect_stop(from, id)
@@sync.synchronize do
Deflect.deflecting.delete(from, id) or
raise DeflectError, "#{from}##{id} is not deflected from"
from.instance_eval { remove_method id }
end
end | ruby | def deflect_stop(from, id)
@@sync.synchronize do
Deflect.deflecting.delete(from, id) or
raise DeflectError, "#{from}##{id} is not deflected from"
from.instance_eval { remove_method id }
end
end | [
"def",
"deflect_stop",
"(",
"from",
",",
"id",
")",
"@@sync",
".",
"synchronize",
"do",
"Deflect",
".",
"deflecting",
".",
"delete",
"(",
"from",
",",
"id",
")",
"or",
"raise",
"DeflectError",
",",
"\"#{from}##{id} is not deflected from\"",
"from",
".",
"instance_eval",
"{",
"remove_method",
"id",
"}",
"end",
"end"
] | Stop deflection method calls named _id_ to class _from_. | [
"Stop",
"deflection",
"method",
"calls",
"named",
"_id_",
"to",
"class",
"_from_",
"."
] | 7e731a6ab3705ce9bc6563a7e7b849a464d5cfaf | https://github.com/flori/dslkit/blob/7e731a6ab3705ce9bc6563a7e7b849a464d5cfaf/lib/dslkit/polite.rb#L506-L512 | train |
flori/dslkit | lib/dslkit/polite.rb | DSLKit.MethodMissingDelegator.method_missing | def method_missing(id, *a, &b)
unless method_missing_delegator.nil?
method_missing_delegator.__send__(id, *a, &b)
else
super
end
end | ruby | def method_missing(id, *a, &b)
unless method_missing_delegator.nil?
method_missing_delegator.__send__(id, *a, &b)
else
super
end
end | [
"def",
"method_missing",
"(",
"id",
",",
"*",
"a",
",",
"&",
"b",
")",
"unless",
"method_missing_delegator",
".",
"nil?",
"method_missing_delegator",
".",
"__send__",
"(",
"id",
",",
"a",
",",
"b",
")",
"else",
"super",
"end",
"end"
] | Delegates all missing method calls to _method_missing_delegator_ if this
attribute has been set. Otherwise it will call super. | [
"Delegates",
"all",
"missing",
"method",
"calls",
"to",
"_method_missing_delegator_",
"if",
"this",
"attribute",
"has",
"been",
"set",
".",
"Otherwise",
"it",
"will",
"call",
"super",
"."
] | 7e731a6ab3705ce9bc6563a7e7b849a464d5cfaf | https://github.com/flori/dslkit/blob/7e731a6ab3705ce9bc6563a7e7b849a464d5cfaf/lib/dslkit/polite.rb#L598-L604 | train |
cordawyn/redlander | lib/redlander/statement.rb | Redlander.Statement.subject | def subject
if instance_variable_defined?(:@subject)
@subject
else
rdf_node = Redland.librdf_statement_get_subject(rdf_statement)
@subject = rdf_node.null? ? nil : Node.new(rdf_node)
end
end | ruby | def subject
if instance_variable_defined?(:@subject)
@subject
else
rdf_node = Redland.librdf_statement_get_subject(rdf_statement)
@subject = rdf_node.null? ? nil : Node.new(rdf_node)
end
end | [
"def",
"subject",
"if",
"instance_variable_defined?",
"(",
":@subject",
")",
"@subject",
"else",
"rdf_node",
"=",
"Redland",
".",
"librdf_statement_get_subject",
"(",
"rdf_statement",
")",
"@subject",
"=",
"rdf_node",
".",
"null?",
"?",
"nil",
":",
"Node",
".",
"new",
"(",
"rdf_node",
")",
"end",
"end"
] | Create an RDF statement.
@param [Hash] source
@option source [Node, String, URI, nil] :subject
@option source [Node, String, URI, nil] :predicate
@option source [Node, String, URI, nil] :object
@raise [NotImplementedError] if cannot create a Statement from the given source.
@raise [RedlandError] if it fails to create a Statement.
Subject of the statment.
@return [Node, nil] | [
"Create",
"an",
"RDF",
"statement",
"."
] | a5c84e15a7602c674606e531bda6a616b1237c44 | https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/statement.rb#L51-L58 | train |
cordawyn/redlander | lib/redlander/statement.rb | Redlander.Statement.predicate | def predicate
if instance_variable_defined?(:@predicate)
@predicate
else
rdf_node = Redland.librdf_statement_get_predicate(rdf_statement)
@predicate = rdf_node.null? ? nil : Node.new(rdf_node)
end
end | ruby | def predicate
if instance_variable_defined?(:@predicate)
@predicate
else
rdf_node = Redland.librdf_statement_get_predicate(rdf_statement)
@predicate = rdf_node.null? ? nil : Node.new(rdf_node)
end
end | [
"def",
"predicate",
"if",
"instance_variable_defined?",
"(",
":@predicate",
")",
"@predicate",
"else",
"rdf_node",
"=",
"Redland",
".",
"librdf_statement_get_predicate",
"(",
"rdf_statement",
")",
"@predicate",
"=",
"rdf_node",
".",
"null?",
"?",
"nil",
":",
"Node",
".",
"new",
"(",
"rdf_node",
")",
"end",
"end"
] | Predicate of the statement.
@return [Node, nil] | [
"Predicate",
"of",
"the",
"statement",
"."
] | a5c84e15a7602c674606e531bda6a616b1237c44 | https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/statement.rb#L63-L70 | train |
cordawyn/redlander | lib/redlander/statement.rb | Redlander.Statement.object | def object
if instance_variable_defined?(:@object)
@object
else
rdf_node = Redland.librdf_statement_get_object(rdf_statement)
@object = rdf_node.null? ? nil : Node.new(rdf_node)
end
end | ruby | def object
if instance_variable_defined?(:@object)
@object
else
rdf_node = Redland.librdf_statement_get_object(rdf_statement)
@object = rdf_node.null? ? nil : Node.new(rdf_node)
end
end | [
"def",
"object",
"if",
"instance_variable_defined?",
"(",
":@object",
")",
"@object",
"else",
"rdf_node",
"=",
"Redland",
".",
"librdf_statement_get_object",
"(",
"rdf_statement",
")",
"@object",
"=",
"rdf_node",
".",
"null?",
"?",
"nil",
":",
"Node",
".",
"new",
"(",
"rdf_node",
")",
"end",
"end"
] | Object of the statement.
@return [Node, nil] | [
"Object",
"of",
"the",
"statement",
"."
] | a5c84e15a7602c674606e531bda6a616b1237c44 | https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/statement.rb#L75-L82 | train |
cordawyn/redlander | lib/redlander/statement.rb | Redlander.Statement.rdf_node_from | def rdf_node_from(source)
case source
when NilClass
nil
when Node
Redland.librdf_new_node_from_node(source.rdf_node)
else
Redland.librdf_new_node_from_node(Node.new(source).rdf_node)
end
end | ruby | def rdf_node_from(source)
case source
when NilClass
nil
when Node
Redland.librdf_new_node_from_node(source.rdf_node)
else
Redland.librdf_new_node_from_node(Node.new(source).rdf_node)
end
end | [
"def",
"rdf_node_from",
"(",
"source",
")",
"case",
"source",
"when",
"NilClass",
"nil",
"when",
"Node",
"Redland",
".",
"librdf_new_node_from_node",
"(",
"source",
".",
"rdf_node",
")",
"else",
"Redland",
".",
"librdf_new_node_from_node",
"(",
"Node",
".",
"new",
"(",
"source",
")",
".",
"rdf_node",
")",
"end",
"end"
] | Create a Node from the source
and get its rdf_node, or return nil
@api private | [
"Create",
"a",
"Node",
"from",
"the",
"source",
"and",
"get",
"its",
"rdf_node",
"or",
"return",
"nil"
] | a5c84e15a7602c674606e531bda6a616b1237c44 | https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/statement.rb#L141-L150 | train |
xiaoxinghu/datacraft | lib/datacraft/runner.rb | Datacraft.Runner.run | def run(instruction)
@inst = instruction
measurements = []
# run pre_build hooks
if @inst.respond_to? :pre_hooks
measurements << Benchmark.measure('pre build:') do
@inst.pre_hooks.each(&:call)
end
end
# process the rows
measurements << Benchmark.measure('process rows:') do
@inst.options[:parallel] ? pprocess_rows : process_rows
end
# build
measurements << Benchmark.measure('build:') do
build @inst.consumers
end
# run post_build hooks
if @inst.respond_to? :post_hooks
measurements << Benchmark.measure('post build:') do
@inst.post_hooks.each(&:call)
end
end
report measurements if @inst.options[:benchmark]
end | ruby | def run(instruction)
@inst = instruction
measurements = []
# run pre_build hooks
if @inst.respond_to? :pre_hooks
measurements << Benchmark.measure('pre build:') do
@inst.pre_hooks.each(&:call)
end
end
# process the rows
measurements << Benchmark.measure('process rows:') do
@inst.options[:parallel] ? pprocess_rows : process_rows
end
# build
measurements << Benchmark.measure('build:') do
build @inst.consumers
end
# run post_build hooks
if @inst.respond_to? :post_hooks
measurements << Benchmark.measure('post build:') do
@inst.post_hooks.each(&:call)
end
end
report measurements if @inst.options[:benchmark]
end | [
"def",
"run",
"(",
"instruction",
")",
"@inst",
"=",
"instruction",
"measurements",
"=",
"[",
"]",
"# run pre_build hooks",
"if",
"@inst",
".",
"respond_to?",
":pre_hooks",
"measurements",
"<<",
"Benchmark",
".",
"measure",
"(",
"'pre build:'",
")",
"do",
"@inst",
".",
"pre_hooks",
".",
"each",
"(",
":call",
")",
"end",
"end",
"# process the rows",
"measurements",
"<<",
"Benchmark",
".",
"measure",
"(",
"'process rows:'",
")",
"do",
"@inst",
".",
"options",
"[",
":parallel",
"]",
"?",
"pprocess_rows",
":",
"process_rows",
"end",
"# build",
"measurements",
"<<",
"Benchmark",
".",
"measure",
"(",
"'build:'",
")",
"do",
"build",
"@inst",
".",
"consumers",
"end",
"# run post_build hooks",
"if",
"@inst",
".",
"respond_to?",
":post_hooks",
"measurements",
"<<",
"Benchmark",
".",
"measure",
"(",
"'post build:'",
")",
"do",
"@inst",
".",
"post_hooks",
".",
"each",
"(",
":call",
")",
"end",
"end",
"report",
"measurements",
"if",
"@inst",
".",
"options",
"[",
":benchmark",
"]",
"end"
] | run the instruction | [
"run",
"the",
"instruction"
] | 8e97ffe9aa3c59f014bee82fb7e1d41d3ce13107 | https://github.com/xiaoxinghu/datacraft/blob/8e97ffe9aa3c59f014bee82fb7e1d41d3ce13107/lib/datacraft/runner.rb#L7-L35 | train |
xiaoxinghu/datacraft | lib/datacraft/runner.rb | Datacraft.Runner.report | def report(measurements)
width = measurements.max_by { |m| m.label.size }.label.size + 1
puts "#{' ' * width}#{Benchmark::CAPTION}"
measurements.each do |m|
puts "#{m.label.to_s.ljust width} #{m}"
end
end | ruby | def report(measurements)
width = measurements.max_by { |m| m.label.size }.label.size + 1
puts "#{' ' * width}#{Benchmark::CAPTION}"
measurements.each do |m|
puts "#{m.label.to_s.ljust width} #{m}"
end
end | [
"def",
"report",
"(",
"measurements",
")",
"width",
"=",
"measurements",
".",
"max_by",
"{",
"|",
"m",
"|",
"m",
".",
"label",
".",
"size",
"}",
".",
"label",
".",
"size",
"+",
"1",
"puts",
"\"#{' ' * width}#{Benchmark::CAPTION}\"",
"measurements",
".",
"each",
"do",
"|",
"m",
"|",
"puts",
"\"#{m.label.to_s.ljust width} #{m}\"",
"end",
"end"
] | output benchmark results | [
"output",
"benchmark",
"results"
] | 8e97ffe9aa3c59f014bee82fb7e1d41d3ce13107 | https://github.com/xiaoxinghu/datacraft/blob/8e97ffe9aa3c59f014bee82fb7e1d41d3ce13107/lib/datacraft/runner.rb#L40-L46 | train |
xiaoxinghu/datacraft | lib/datacraft/runner.rb | Datacraft.Runner.process | def process(row)
@inst.tweakers.each do |tweaker|
row = tweaker.tweak row
return nil unless row
end
@inst.consumers.each do |consumer|
consumer << row
end
end | ruby | def process(row)
@inst.tweakers.each do |tweaker|
row = tweaker.tweak row
return nil unless row
end
@inst.consumers.each do |consumer|
consumer << row
end
end | [
"def",
"process",
"(",
"row",
")",
"@inst",
".",
"tweakers",
".",
"each",
"do",
"|",
"tweaker",
"|",
"row",
"=",
"tweaker",
".",
"tweak",
"row",
"return",
"nil",
"unless",
"row",
"end",
"@inst",
".",
"consumers",
".",
"each",
"do",
"|",
"consumer",
"|",
"consumer",
"<<",
"row",
"end",
"end"
] | tweak & consume one row | [
"tweak",
"&",
"consume",
"one",
"row"
] | 8e97ffe9aa3c59f014bee82fb7e1d41d3ce13107 | https://github.com/xiaoxinghu/datacraft/blob/8e97ffe9aa3c59f014bee82fb7e1d41d3ce13107/lib/datacraft/runner.rb#L58-L66 | train |
xiaoxinghu/datacraft | lib/datacraft/runner.rb | Datacraft.Runner.pprocess_rows | def pprocess_rows
thread_number = [@inst.sources.size,
@inst.options[:n_threads]].min
queue = Queue.new
@inst.sources.each { |p| queue << p }
threads = thread_number.times.map do
Thread.new do
begin
while p = queue.pop(true)
p.each { |row| process row }
end
rescue ThreadError
end
end
end
threads.each(&:join)
end | ruby | def pprocess_rows
thread_number = [@inst.sources.size,
@inst.options[:n_threads]].min
queue = Queue.new
@inst.sources.each { |p| queue << p }
threads = thread_number.times.map do
Thread.new do
begin
while p = queue.pop(true)
p.each { |row| process row }
end
rescue ThreadError
end
end
end
threads.each(&:join)
end | [
"def",
"pprocess_rows",
"thread_number",
"=",
"[",
"@inst",
".",
"sources",
".",
"size",
",",
"@inst",
".",
"options",
"[",
":n_threads",
"]",
"]",
".",
"min",
"queue",
"=",
"Queue",
".",
"new",
"@inst",
".",
"sources",
".",
"each",
"{",
"|",
"p",
"|",
"queue",
"<<",
"p",
"}",
"threads",
"=",
"thread_number",
".",
"times",
".",
"map",
"do",
"Thread",
".",
"new",
"do",
"begin",
"while",
"p",
"=",
"queue",
".",
"pop",
"(",
"true",
")",
"p",
".",
"each",
"{",
"|",
"row",
"|",
"process",
"row",
"}",
"end",
"rescue",
"ThreadError",
"end",
"end",
"end",
"threads",
".",
"each",
"(",
":join",
")",
"end"
] | process rows in parallel | [
"process",
"rows",
"in",
"parallel"
] | 8e97ffe9aa3c59f014bee82fb7e1d41d3ce13107 | https://github.com/xiaoxinghu/datacraft/blob/8e97ffe9aa3c59f014bee82fb7e1d41d3ce13107/lib/datacraft/runner.rb#L69-L85 | train |
xiaoxinghu/datacraft | lib/datacraft/runner.rb | Datacraft.Runner.build | def build(consumers)
consumers.each do |consumer|
consumer.build if consumer.respond_to? :build
consumer.close if consumer.respond_to? :close
end
end | ruby | def build(consumers)
consumers.each do |consumer|
consumer.build if consumer.respond_to? :build
consumer.close if consumer.respond_to? :close
end
end | [
"def",
"build",
"(",
"consumers",
")",
"consumers",
".",
"each",
"do",
"|",
"consumer",
"|",
"consumer",
".",
"build",
"if",
"consumer",
".",
"respond_to?",
":build",
"consumer",
".",
"close",
"if",
"consumer",
".",
"respond_to?",
":close",
"end",
"end"
] | build and close consumers | [
"build",
"and",
"close",
"consumers"
] | 8e97ffe9aa3c59f014bee82fb7e1d41d3ce13107 | https://github.com/xiaoxinghu/datacraft/blob/8e97ffe9aa3c59f014bee82fb7e1d41d3ce13107/lib/datacraft/runner.rb#L88-L93 | train |
checkdin/checkdin-ruby | lib/checkdin/campaigns.rb | Checkdin.Campaigns.campaigns | def campaigns(options={})
response = connection.get do |req|
req.url "campaigns", options
end
return_error_or_body(response)
end | ruby | def campaigns(options={})
response = connection.get do |req|
req.url "campaigns", options
end
return_error_or_body(response)
end | [
"def",
"campaigns",
"(",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"connection",
".",
"get",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"\"campaigns\"",
",",
"options",
"end",
"return_error_or_body",
"(",
"response",
")",
"end"
] | Get a list of all campaigns for the authenticating client.
@param [Hash] options
@option options Integer :limit - The maximum number of records to return. | [
"Get",
"a",
"list",
"of",
"all",
"campaigns",
"for",
"the",
"authenticating",
"client",
"."
] | c3c4b38b0f8c710e1f805100dcf3a70649215b48 | https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/campaigns.rb#L18-L23 | train |
kcierzan/Clea | lib/clea.rb | Clea.Sender.get_sender_alias | def get_sender_alias
puts "What is your name?"
while @from_alias = gets.chomp
catch :badalias do
puts "Are you sure your name is #{@from_alias}? [y/n]:"
while alias_confirmation = gets.chomp
case alias_confirmation
when 'y'
return
else
puts "Please re-enter your name:"
throw :badalias
end
end
end
end
end | ruby | def get_sender_alias
puts "What is your name?"
while @from_alias = gets.chomp
catch :badalias do
puts "Are you sure your name is #{@from_alias}? [y/n]:"
while alias_confirmation = gets.chomp
case alias_confirmation
when 'y'
return
else
puts "Please re-enter your name:"
throw :badalias
end
end
end
end
end | [
"def",
"get_sender_alias",
"puts",
"\"What is your name?\"",
"while",
"@from_alias",
"=",
"gets",
".",
"chomp",
"catch",
":badalias",
"do",
"puts",
"\"Are you sure your name is #{@from_alias}? [y/n]:\"",
"while",
"alias_confirmation",
"=",
"gets",
".",
"chomp",
"case",
"alias_confirmation",
"when",
"'y'",
"return",
"else",
"puts",
"\"Please re-enter your name:\"",
"throw",
":badalias",
"end",
"end",
"end",
"end",
"end"
] | Get user's alias and confirm | [
"Get",
"user",
"s",
"alias",
"and",
"confirm"
] | ebfa0426b139cb029e69dff1058f621bed1c8459 | https://github.com/kcierzan/Clea/blob/ebfa0426b139cb029e69dff1058f621bed1c8459/lib/clea.rb#L16-L32 | train |
kcierzan/Clea | lib/clea.rb | Clea.Sender.get_sender_gmail | def get_sender_gmail
puts "Enter your gmail address:"
while @from_address = gets.chomp
catch :badfrom do
if ValidateEmail.validate(@from_address) == true
puts "Is your email address #{@from_address}? [y/n]:"
while address_confirmation = gets.chomp
case address_confirmation
when 'y'
return
else
puts "Please re-enter your gmail address:"
throw :badfrom
end
end
else
puts "Email invalid! Please enter a valid email address:"
end
end
end
end | ruby | def get_sender_gmail
puts "Enter your gmail address:"
while @from_address = gets.chomp
catch :badfrom do
if ValidateEmail.validate(@from_address) == true
puts "Is your email address #{@from_address}? [y/n]:"
while address_confirmation = gets.chomp
case address_confirmation
when 'y'
return
else
puts "Please re-enter your gmail address:"
throw :badfrom
end
end
else
puts "Email invalid! Please enter a valid email address:"
end
end
end
end | [
"def",
"get_sender_gmail",
"puts",
"\"Enter your gmail address:\"",
"while",
"@from_address",
"=",
"gets",
".",
"chomp",
"catch",
":badfrom",
"do",
"if",
"ValidateEmail",
".",
"validate",
"(",
"@from_address",
")",
"==",
"true",
"puts",
"\"Is your email address #{@from_address}? [y/n]:\"",
"while",
"address_confirmation",
"=",
"gets",
".",
"chomp",
"case",
"address_confirmation",
"when",
"'y'",
"return",
"else",
"puts",
"\"Please re-enter your gmail address:\"",
"throw",
":badfrom",
"end",
"end",
"else",
"puts",
"\"Email invalid! Please enter a valid email address:\"",
"end",
"end",
"end",
"end"
] | Get, validate, and confirm user's email address | [
"Get",
"validate",
"and",
"confirm",
"user",
"s",
"email",
"address"
] | ebfa0426b139cb029e69dff1058f621bed1c8459 | https://github.com/kcierzan/Clea/blob/ebfa0426b139cb029e69dff1058f621bed1c8459/lib/clea.rb#L35-L55 | train |
kcierzan/Clea | lib/clea.rb | Clea.Sender.get_sender_password | def get_sender_password
puts "Enter your password:"
while @password = gets.chomp
catch :badpass do
puts "Are you sure your password is #{@password}? [y/n]:"
while pass_confirmation = gets.chomp
case pass_confirmation
when 'y'
return
else
puts "Please re-enter your password:"
throw :badpass
end
end
end
end
end | ruby | def get_sender_password
puts "Enter your password:"
while @password = gets.chomp
catch :badpass do
puts "Are you sure your password is #{@password}? [y/n]:"
while pass_confirmation = gets.chomp
case pass_confirmation
when 'y'
return
else
puts "Please re-enter your password:"
throw :badpass
end
end
end
end
end | [
"def",
"get_sender_password",
"puts",
"\"Enter your password:\"",
"while",
"@password",
"=",
"gets",
".",
"chomp",
"catch",
":badpass",
"do",
"puts",
"\"Are you sure your password is #{@password}? [y/n]:\"",
"while",
"pass_confirmation",
"=",
"gets",
".",
"chomp",
"case",
"pass_confirmation",
"when",
"'y'",
"return",
"else",
"puts",
"\"Please re-enter your password:\"",
"throw",
":badpass",
"end",
"end",
"end",
"end",
"end"
] | Get and confirm user's password | [
"Get",
"and",
"confirm",
"user",
"s",
"password"
] | ebfa0426b139cb029e69dff1058f621bed1c8459 | https://github.com/kcierzan/Clea/blob/ebfa0426b139cb029e69dff1058f621bed1c8459/lib/clea.rb#L58-L74 | train |
kcierzan/Clea | lib/clea.rb | Clea.Sender.get_recipient_data | def get_recipient_data
puts "Enter the recipient's email address:"
while @to_address = gets.chomp
catch :badto do
if ValidateEmail.validate(@to_address) == true
puts "Is the recipient's email address #{@to_address}? [y/n]:"
while to_address_confirmation = gets.chomp
case to_address_confirmation
when 'y'
return
else
puts "Please re-enter the recipient's email address:"
throw :badto
end
end
else
puts "Email invalid! Please enter a valid email address:"
end
end
end
end | ruby | def get_recipient_data
puts "Enter the recipient's email address:"
while @to_address = gets.chomp
catch :badto do
if ValidateEmail.validate(@to_address) == true
puts "Is the recipient's email address #{@to_address}? [y/n]:"
while to_address_confirmation = gets.chomp
case to_address_confirmation
when 'y'
return
else
puts "Please re-enter the recipient's email address:"
throw :badto
end
end
else
puts "Email invalid! Please enter a valid email address:"
end
end
end
end | [
"def",
"get_recipient_data",
"puts",
"\"Enter the recipient's email address:\"",
"while",
"@to_address",
"=",
"gets",
".",
"chomp",
"catch",
":badto",
"do",
"if",
"ValidateEmail",
".",
"validate",
"(",
"@to_address",
")",
"==",
"true",
"puts",
"\"Is the recipient's email address #{@to_address}? [y/n]:\"",
"while",
"to_address_confirmation",
"=",
"gets",
".",
"chomp",
"case",
"to_address_confirmation",
"when",
"'y'",
"return",
"else",
"puts",
"\"Please re-enter the recipient's email address:\"",
"throw",
":badto",
"end",
"end",
"else",
"puts",
"\"Email invalid! Please enter a valid email address:\"",
"end",
"end",
"end",
"end"
] | Get, validate, and confirm the recipient's email address. This data does not persist. | [
"Get",
"validate",
"and",
"confirm",
"the",
"recipient",
"s",
"email",
"address",
".",
"This",
"data",
"does",
"not",
"persist",
"."
] | ebfa0426b139cb029e69dff1058f621bed1c8459 | https://github.com/kcierzan/Clea/blob/ebfa0426b139cb029e69dff1058f621bed1c8459/lib/clea.rb#L86-L106 | train |
kcierzan/Clea | lib/clea.rb | Clea.Sender.send_message | def send_message
# Read the user's password from the persistent hash
stored_password = @sender_info.transaction { @sender_info[:password] }
# Initialize the gmail SMTP connection and upgrade to SSL/TLS
smtp = Net::SMTP.new('smtp.gmail.com', 587)
smtp.enable_starttls
# Open SMTP connection, send message, close the connection
smtp.start('gmail.com', @stored_from_address, stored_password, :login) do
smtp.send_message(@msg, @_stored_from_address, @to_address)
end
end | ruby | def send_message
# Read the user's password from the persistent hash
stored_password = @sender_info.transaction { @sender_info[:password] }
# Initialize the gmail SMTP connection and upgrade to SSL/TLS
smtp = Net::SMTP.new('smtp.gmail.com', 587)
smtp.enable_starttls
# Open SMTP connection, send message, close the connection
smtp.start('gmail.com', @stored_from_address, stored_password, :login) do
smtp.send_message(@msg, @_stored_from_address, @to_address)
end
end | [
"def",
"send_message",
"# Read the user's password from the persistent hash",
"stored_password",
"=",
"@sender_info",
".",
"transaction",
"{",
"@sender_info",
"[",
":password",
"]",
"}",
"# Initialize the gmail SMTP connection and upgrade to SSL/TLS",
"smtp",
"=",
"Net",
"::",
"SMTP",
".",
"new",
"(",
"'smtp.gmail.com'",
",",
"587",
")",
"smtp",
".",
"enable_starttls",
"# Open SMTP connection, send message, close the connection",
"smtp",
".",
"start",
"(",
"'gmail.com'",
",",
"@stored_from_address",
",",
"stored_password",
",",
":login",
")",
"do",
"smtp",
".",
"send_message",
"(",
"@msg",
",",
"@_stored_from_address",
",",
"@to_address",
")",
"end",
"end"
] | Open SMTP connection, pass user info as arguments, send message and close connection | [
"Open",
"SMTP",
"connection",
"pass",
"user",
"info",
"as",
"arguments",
"send",
"message",
"and",
"close",
"connection"
] | ebfa0426b139cb029e69dff1058f621bed1c8459 | https://github.com/kcierzan/Clea/blob/ebfa0426b139cb029e69dff1058f621bed1c8459/lib/clea.rb#L132-L142 | train |
amardaxini/socketlab | lib/socketlab/socketklab_request.rb | Socketlab.SocketlabRequest.set_response | def set_response(item_class_name)
if @api_response.success?
@total_count = @api_response["totalCount"]
@total_pages = @api_response["totalPages"]
@count = @api_response["count"]
@timestamp = @api_response["timestamp"]
@items = []
unless @api_response["collection"].nil?
@api_response["collection"].each do |attr_item|
item = item_class_name.new
item.set_item(attr_item)
@items << item
end
end
else
@error = @api_response.parsed_response
end
end | ruby | def set_response(item_class_name)
if @api_response.success?
@total_count = @api_response["totalCount"]
@total_pages = @api_response["totalPages"]
@count = @api_response["count"]
@timestamp = @api_response["timestamp"]
@items = []
unless @api_response["collection"].nil?
@api_response["collection"].each do |attr_item|
item = item_class_name.new
item.set_item(attr_item)
@items << item
end
end
else
@error = @api_response.parsed_response
end
end | [
"def",
"set_response",
"(",
"item_class_name",
")",
"if",
"@api_response",
".",
"success?",
"@total_count",
"=",
"@api_response",
"[",
"\"totalCount\"",
"]",
"@total_pages",
"=",
"@api_response",
"[",
"\"totalPages\"",
"]",
"@count",
"=",
"@api_response",
"[",
"\"count\"",
"]",
"@timestamp",
"=",
"@api_response",
"[",
"\"timestamp\"",
"]",
"@items",
"=",
"[",
"]",
"unless",
"@api_response",
"[",
"\"collection\"",
"]",
".",
"nil?",
"@api_response",
"[",
"\"collection\"",
"]",
".",
"each",
"do",
"|",
"attr_item",
"|",
"item",
"=",
"item_class_name",
".",
"new",
"item",
".",
"set_item",
"(",
"attr_item",
")",
"@items",
"<<",
"item",
"end",
"end",
"else",
"@error",
"=",
"@api_response",
".",
"parsed_response",
"end",
"end"
] | Assuming type is json | [
"Assuming",
"type",
"is",
"json"
] | 5f27350898d33b558c73a9685ef67bae39b857b6 | https://github.com/amardaxini/socketlab/blob/5f27350898d33b558c73a9685ef67bae39b857b6/lib/socketlab/socketklab_request.rb#L31-L48 | train |
NUBIC/aker | lib/aker/authorities/composite.rb | Aker::Authorities.Composite.poll | def poll(method, *args)
authorities.select { |a|
a.respond_to?(method)
}.collect { |a|
[a.send(method, *args), a]
}
end | ruby | def poll(method, *args)
authorities.select { |a|
a.respond_to?(method)
}.collect { |a|
[a.send(method, *args), a]
}
end | [
"def",
"poll",
"(",
"method",
",",
"*",
"args",
")",
"authorities",
".",
"select",
"{",
"|",
"a",
"|",
"a",
".",
"respond_to?",
"(",
"method",
")",
"}",
".",
"collect",
"{",
"|",
"a",
"|",
"[",
"a",
".",
"send",
"(",
"method",
",",
"args",
")",
",",
"a",
"]",
"}",
"end"
] | Invokes the specified method with the specified arguments on all
the authorities which will respond to it. | [
"Invokes",
"the",
"specified",
"method",
"with",
"the",
"specified",
"arguments",
"on",
"all",
"the",
"authorities",
"which",
"will",
"respond",
"to",
"it",
"."
] | ff43606a8812e38f96bbe71b46e7f631cbeacf1c | https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/authorities/composite.rb#L293-L299 | train |
redbubble/megaphone-client-ruby | lib/megaphone/client.rb | Megaphone.Client.publish! | def publish!(topic, subtopic, schema, partition_key, payload)
event = Event.new(topic, subtopic, origin, schema, partition_key, payload)
raise MegaphoneInvalidEventError.new(event.errors.join(', ')) unless event.valid?
unless logger.post(topic, event.to_hash)
if transient_error?(logger.last_error)
raise MegaphoneMessageDelayWarning.new(logger.last_error.message, event.stream_id)
else
raise MegaphoneUnavailableError.new(logger.last_error.message, event.stream_id)
end
end
end | ruby | def publish!(topic, subtopic, schema, partition_key, payload)
event = Event.new(topic, subtopic, origin, schema, partition_key, payload)
raise MegaphoneInvalidEventError.new(event.errors.join(', ')) unless event.valid?
unless logger.post(topic, event.to_hash)
if transient_error?(logger.last_error)
raise MegaphoneMessageDelayWarning.new(logger.last_error.message, event.stream_id)
else
raise MegaphoneUnavailableError.new(logger.last_error.message, event.stream_id)
end
end
end | [
"def",
"publish!",
"(",
"topic",
",",
"subtopic",
",",
"schema",
",",
"partition_key",
",",
"payload",
")",
"event",
"=",
"Event",
".",
"new",
"(",
"topic",
",",
"subtopic",
",",
"origin",
",",
"schema",
",",
"partition_key",
",",
"payload",
")",
"raise",
"MegaphoneInvalidEventError",
".",
"new",
"(",
"event",
".",
"errors",
".",
"join",
"(",
"', '",
")",
")",
"unless",
"event",
".",
"valid?",
"unless",
"logger",
".",
"post",
"(",
"topic",
",",
"event",
".",
"to_hash",
")",
"if",
"transient_error?",
"(",
"logger",
".",
"last_error",
")",
"raise",
"MegaphoneMessageDelayWarning",
".",
"new",
"(",
"logger",
".",
"last_error",
".",
"message",
",",
"event",
".",
"stream_id",
")",
"else",
"raise",
"MegaphoneUnavailableError",
".",
"new",
"(",
"logger",
".",
"last_error",
".",
"message",
",",
"event",
".",
"stream_id",
")",
"end",
"end",
"end"
] | Main entry point for apps using this library.
Will default to environment for host and port settings, if not passed.
Note that a missing callback_handler will result in a default handler
being assigned if the FluentLogger is used. | [
"Main",
"entry",
"point",
"for",
"apps",
"using",
"this",
"library",
".",
"Will",
"default",
"to",
"environment",
"for",
"host",
"and",
"port",
"settings",
"if",
"not",
"passed",
".",
"Note",
"that",
"a",
"missing",
"callback_handler",
"will",
"result",
"in",
"a",
"default",
"handler",
"being",
"assigned",
"if",
"the",
"FluentLogger",
"is",
"used",
"."
] | 0e9a9d6f7041852accc8e02948694539e9faea59 | https://github.com/redbubble/megaphone-client-ruby/blob/0e9a9d6f7041852accc8e02948694539e9faea59/lib/megaphone/client.rb#L25-L35 | train |
npolar/npolar-api-client-ruby | lib/npolar/api/client/npolar_api_command.rb | Npolar::Api::Client.NpolarApiCommand.run | def run
@client = JsonApiClient.new(uri)
@client.log = log
@client.header = header
@client.param = parameters
if param[:concurrency]
@client.concurrency = param[:concurrency].to_i
end
if param[:slice]
@client.slice = param[:slice].to_i
end
if uri =~ /\w+[:]\w+[@]/
username, password = URI.parse(uri).userinfo.split(":")
@client.username = username
@client.password = password
end
if param[:auth]
# Force authorization
@client.authorization = true
end
method = param[:method].upcase
response = nil
case method
when "DELETE"
response = delete
when "GET"
response = get
when "HEAD"
response = head
when "PATCH"
response = patch
when "POST"
if data.is_a? Dir
raise "Not implemented"
else
response = post(data)
end
when "PUT"
response = put(data)
else
raise ArgumentError, "Unsupported HTTP method: #{param[:method]}"
end
#Loop dirs?
if not response.nil? and (response.respond_to? :body or response.is_a? Array)
if response.is_a? Array
responses = response
else
responses = [response]
end
i = 0
responses.each do | response |
i += 1
log.debug "#{method} #{response.uri.path} [#{i}] Total time: #{response.total_time}"+
" DNS time: #{response.namelookup_time}"+
" Connect time: #{response.connect_time}"+
" Pre-transer time: #{response.pretransfer_time}"
if "HEAD" == method or headers?
puts response.response_headers
end
unless param[:join]
puts response.body
end
end
statuses = responses.map {|r| r.code }.uniq
status = statuses.map {|code| { code => responses.select {|r| code == r.code }.size } }.to_json.gsub(/["{}\[\]]/, "")
real_responses_size = responses.select {|r| r.code >= 100 }.size
log.info "Status(es): #{status}, request(s): #{responses.size}, response(s): #{real_responses_size}"
else
raise "Invalid response: #{response}"
end
if param[:join]
joined = responses.map {|r|
JSON.parse(r.body)
}
puts joined.to_json
end
end | ruby | def run
@client = JsonApiClient.new(uri)
@client.log = log
@client.header = header
@client.param = parameters
if param[:concurrency]
@client.concurrency = param[:concurrency].to_i
end
if param[:slice]
@client.slice = param[:slice].to_i
end
if uri =~ /\w+[:]\w+[@]/
username, password = URI.parse(uri).userinfo.split(":")
@client.username = username
@client.password = password
end
if param[:auth]
# Force authorization
@client.authorization = true
end
method = param[:method].upcase
response = nil
case method
when "DELETE"
response = delete
when "GET"
response = get
when "HEAD"
response = head
when "PATCH"
response = patch
when "POST"
if data.is_a? Dir
raise "Not implemented"
else
response = post(data)
end
when "PUT"
response = put(data)
else
raise ArgumentError, "Unsupported HTTP method: #{param[:method]}"
end
#Loop dirs?
if not response.nil? and (response.respond_to? :body or response.is_a? Array)
if response.is_a? Array
responses = response
else
responses = [response]
end
i = 0
responses.each do | response |
i += 1
log.debug "#{method} #{response.uri.path} [#{i}] Total time: #{response.total_time}"+
" DNS time: #{response.namelookup_time}"+
" Connect time: #{response.connect_time}"+
" Pre-transer time: #{response.pretransfer_time}"
if "HEAD" == method or headers?
puts response.response_headers
end
unless param[:join]
puts response.body
end
end
statuses = responses.map {|r| r.code }.uniq
status = statuses.map {|code| { code => responses.select {|r| code == r.code }.size } }.to_json.gsub(/["{}\[\]]/, "")
real_responses_size = responses.select {|r| r.code >= 100 }.size
log.info "Status(es): #{status}, request(s): #{responses.size}, response(s): #{real_responses_size}"
else
raise "Invalid response: #{response}"
end
if param[:join]
joined = responses.map {|r|
JSON.parse(r.body)
}
puts joined.to_json
end
end | [
"def",
"run",
"@client",
"=",
"JsonApiClient",
".",
"new",
"(",
"uri",
")",
"@client",
".",
"log",
"=",
"log",
"@client",
".",
"header",
"=",
"header",
"@client",
".",
"param",
"=",
"parameters",
"if",
"param",
"[",
":concurrency",
"]",
"@client",
".",
"concurrency",
"=",
"param",
"[",
":concurrency",
"]",
".",
"to_i",
"end",
"if",
"param",
"[",
":slice",
"]",
"@client",
".",
"slice",
"=",
"param",
"[",
":slice",
"]",
".",
"to_i",
"end",
"if",
"uri",
"=~",
"/",
"\\w",
"\\w",
"/",
"username",
",",
"password",
"=",
"URI",
".",
"parse",
"(",
"uri",
")",
".",
"userinfo",
".",
"split",
"(",
"\":\"",
")",
"@client",
".",
"username",
"=",
"username",
"@client",
".",
"password",
"=",
"password",
"end",
"if",
"param",
"[",
":auth",
"]",
"# Force authorization",
"@client",
".",
"authorization",
"=",
"true",
"end",
"method",
"=",
"param",
"[",
":method",
"]",
".",
"upcase",
"response",
"=",
"nil",
"case",
"method",
"when",
"\"DELETE\"",
"response",
"=",
"delete",
"when",
"\"GET\"",
"response",
"=",
"get",
"when",
"\"HEAD\"",
"response",
"=",
"head",
"when",
"\"PATCH\"",
"response",
"=",
"patch",
"when",
"\"POST\"",
"if",
"data",
".",
"is_a?",
"Dir",
"raise",
"\"Not implemented\"",
"else",
"response",
"=",
"post",
"(",
"data",
")",
"end",
"when",
"\"PUT\"",
"response",
"=",
"put",
"(",
"data",
")",
"else",
"raise",
"ArgumentError",
",",
"\"Unsupported HTTP method: #{param[:method]}\"",
"end",
"#Loop dirs?",
"if",
"not",
"response",
".",
"nil?",
"and",
"(",
"response",
".",
"respond_to?",
":body",
"or",
"response",
".",
"is_a?",
"Array",
")",
"if",
"response",
".",
"is_a?",
"Array",
"responses",
"=",
"response",
"else",
"responses",
"=",
"[",
"response",
"]",
"end",
"i",
"=",
"0",
"responses",
".",
"each",
"do",
"|",
"response",
"|",
"i",
"+=",
"1",
"log",
".",
"debug",
"\"#{method} #{response.uri.path} [#{i}] Total time: #{response.total_time}\"",
"+",
"\" DNS time: #{response.namelookup_time}\"",
"+",
"\" Connect time: #{response.connect_time}\"",
"+",
"\" Pre-transer time: #{response.pretransfer_time}\"",
"if",
"\"HEAD\"",
"==",
"method",
"or",
"headers?",
"puts",
"response",
".",
"response_headers",
"end",
"unless",
"param",
"[",
":join",
"]",
"puts",
"response",
".",
"body",
"end",
"end",
"statuses",
"=",
"responses",
".",
"map",
"{",
"|",
"r",
"|",
"r",
".",
"code",
"}",
".",
"uniq",
"status",
"=",
"statuses",
".",
"map",
"{",
"|",
"code",
"|",
"{",
"code",
"=>",
"responses",
".",
"select",
"{",
"|",
"r",
"|",
"code",
"==",
"r",
".",
"code",
"}",
".",
"size",
"}",
"}",
".",
"to_json",
".",
"gsub",
"(",
"/",
"\\[",
"\\]",
"/",
",",
"\"\"",
")",
"real_responses_size",
"=",
"responses",
".",
"select",
"{",
"|",
"r",
"|",
"r",
".",
"code",
">=",
"100",
"}",
".",
"size",
"log",
".",
"info",
"\"Status(es): #{status}, request(s): #{responses.size}, response(s): #{real_responses_size}\"",
"else",
"raise",
"\"Invalid response: #{response}\"",
"end",
"if",
"param",
"[",
":join",
"]",
"joined",
"=",
"responses",
".",
"map",
"{",
"|",
"r",
"|",
"JSON",
".",
"parse",
"(",
"r",
".",
"body",
")",
"}",
"puts",
"joined",
".",
"to_json",
"end",
"end"
] | Execute npolar-api command
@return [nil] | [
"Execute",
"npolar",
"-",
"api",
"command"
] | e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb | https://github.com/npolar/npolar-api-client-ruby/blob/e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb/lib/npolar/api/client/npolar_api_command.rb#L165-L259 | train |
jtzero/vigilem-core | lib/vigilem/core/hooks/conditional_hook.rb | Vigilem::Core::Hooks.ConditionalHook.enumerate | def enumerate(args={}, &block)
passed, failed = [], []
hook = self
super do |callback|
if hook.condition.call(*callback.options[:condition_args])
hook.passed << callback
callback.evaluate(args[:context], *args[:args], &args[:block])
else
hook.failed << callback
end
end
end | ruby | def enumerate(args={}, &block)
passed, failed = [], []
hook = self
super do |callback|
if hook.condition.call(*callback.options[:condition_args])
hook.passed << callback
callback.evaluate(args[:context], *args[:args], &args[:block])
else
hook.failed << callback
end
end
end | [
"def",
"enumerate",
"(",
"args",
"=",
"{",
"}",
",",
"&",
"block",
")",
"passed",
",",
"failed",
"=",
"[",
"]",
",",
"[",
"]",
"hook",
"=",
"self",
"super",
"do",
"|",
"callback",
"|",
"if",
"hook",
".",
"condition",
".",
"call",
"(",
"callback",
".",
"options",
"[",
":condition_args",
"]",
")",
"hook",
".",
"passed",
"<<",
"callback",
"callback",
".",
"evaluate",
"(",
"args",
"[",
":context",
"]",
",",
"args",
"[",
":args",
"]",
",",
"args",
"[",
":block",
"]",
")",
"else",
"hook",
".",
"failed",
"<<",
"callback",
"end",
"end",
"end"
] | enumerate over the callbacks
@param [Array] args
@param [Proc] block
@return | [
"enumerate",
"over",
"the",
"callbacks"
] | a35864229ee76800f5197e3c3c6fb2bf34a68495 | https://github.com/jtzero/vigilem-core/blob/a35864229ee76800f5197e3c3c6fb2bf34a68495/lib/vigilem/core/hooks/conditional_hook.rb#L12-L23 | train |
zealot128/poltergeist-screenshot_overview | lib/poltergeist/screenshot_overview/manager.rb | Poltergeist::ScreenshotOverview.Manager.add_image_from_rspec | def add_image_from_rspec(argument, example, url_path)
blob = caller.find{|i| i[ example.file_path.gsub(/:\d*|^\./,"") ]}
file_with_line = blob.split(":")[0,2].join(":")
filename = [example.description, argument, file_with_line, SecureRandom.hex(6) ].join(" ").gsub(/\W+/,"_") + ".jpg"
full_name = File.join(Poltergeist::ScreenshotOverview.target_directory, filename )
FileUtils.mkdir_p Poltergeist::ScreenshotOverview.target_directory
describe = example.metadata[:example_group][:description_args]
@files << Screenshot.new({
:url => url_path,
:argument => argument,
:local_image => filename,
:full_path => full_name,
:group_description => describe,
:example_description => example.description,
:file_with_line => file_with_line
})
full_name
end | ruby | def add_image_from_rspec(argument, example, url_path)
blob = caller.find{|i| i[ example.file_path.gsub(/:\d*|^\./,"") ]}
file_with_line = blob.split(":")[0,2].join(":")
filename = [example.description, argument, file_with_line, SecureRandom.hex(6) ].join(" ").gsub(/\W+/,"_") + ".jpg"
full_name = File.join(Poltergeist::ScreenshotOverview.target_directory, filename )
FileUtils.mkdir_p Poltergeist::ScreenshotOverview.target_directory
describe = example.metadata[:example_group][:description_args]
@files << Screenshot.new({
:url => url_path,
:argument => argument,
:local_image => filename,
:full_path => full_name,
:group_description => describe,
:example_description => example.description,
:file_with_line => file_with_line
})
full_name
end | [
"def",
"add_image_from_rspec",
"(",
"argument",
",",
"example",
",",
"url_path",
")",
"blob",
"=",
"caller",
".",
"find",
"{",
"|",
"i",
"|",
"i",
"[",
"example",
".",
"file_path",
".",
"gsub",
"(",
"/",
"\\d",
"\\.",
"/",
",",
"\"\"",
")",
"]",
"}",
"file_with_line",
"=",
"blob",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
",",
"2",
"]",
".",
"join",
"(",
"\":\"",
")",
"filename",
"=",
"[",
"example",
".",
"description",
",",
"argument",
",",
"file_with_line",
",",
"SecureRandom",
".",
"hex",
"(",
"6",
")",
"]",
".",
"join",
"(",
"\" \"",
")",
".",
"gsub",
"(",
"/",
"\\W",
"/",
",",
"\"_\"",
")",
"+",
"\".jpg\"",
"full_name",
"=",
"File",
".",
"join",
"(",
"Poltergeist",
"::",
"ScreenshotOverview",
".",
"target_directory",
",",
"filename",
")",
"FileUtils",
".",
"mkdir_p",
"Poltergeist",
"::",
"ScreenshotOverview",
".",
"target_directory",
"describe",
"=",
"example",
".",
"metadata",
"[",
":example_group",
"]",
"[",
":description_args",
"]",
"@files",
"<<",
"Screenshot",
".",
"new",
"(",
"{",
":url",
"=>",
"url_path",
",",
":argument",
"=>",
"argument",
",",
":local_image",
"=>",
"filename",
",",
":full_path",
"=>",
"full_name",
",",
":group_description",
"=>",
"describe",
",",
":example_description",
"=>",
"example",
".",
"description",
",",
":file_with_line",
"=>",
"file_with_line",
"}",
")",
"full_name",
"end"
] | adds image_path and metadata to our list, returns a full path where the
Engine should put the screenshot in | [
"adds",
"image_path",
"and",
"metadata",
"to",
"our",
"list",
"returns",
"a",
"full",
"path",
"where",
"the",
"Engine",
"should",
"put",
"the",
"screenshot",
"in"
] | de208475d6dac7f867243802cdc7d86b0f20564c | https://github.com/zealot128/poltergeist-screenshot_overview/blob/de208475d6dac7f867243802cdc7d86b0f20564c/lib/poltergeist/screenshot_overview/manager.rb#L85-L103 | train |
SCPR/audio_vision-ruby | lib/audio_vision/client.rb | AudioVision.Client.get | def get(path, params={})
connection.get do |request|
request.url path
request.params = params
end
end | ruby | def get(path, params={})
connection.get do |request|
request.url path
request.params = params
end
end | [
"def",
"get",
"(",
"path",
",",
"params",
"=",
"{",
"}",
")",
"connection",
".",
"get",
"do",
"|",
"request",
"|",
"request",
".",
"url",
"path",
"request",
".",
"params",
"=",
"params",
"end",
"end"
] | Get a response from the AudioVision API.
Returns a Faraday Response object.
Example:
client.get("posts/1") | [
"Get",
"a",
"response",
"from",
"the",
"AudioVision",
"API",
".",
"Returns",
"a",
"Faraday",
"Response",
"object",
"."
] | 63053edd534badb4a8d5d05b788f295ad7d19455 | https://github.com/SCPR/audio_vision-ruby/blob/63053edd534badb4a8d5d05b788f295ad7d19455/lib/audio_vision/client.rb#L11-L16 | train |
maxjacobson/todo_lint | lib/todo_lint/config_file.rb | TodoLint.ConfigFile.read_config_file | def read_config_file(file)
@config_hash = YAML.load_file(file)
@starting_path = File.expand_path(File.split(file).first)
@config_options = {}
load_tags
load_file_exclusions
load_extension_inclusions
config_options
end | ruby | def read_config_file(file)
@config_hash = YAML.load_file(file)
@starting_path = File.expand_path(File.split(file).first)
@config_options = {}
load_tags
load_file_exclusions
load_extension_inclusions
config_options
end | [
"def",
"read_config_file",
"(",
"file",
")",
"@config_hash",
"=",
"YAML",
".",
"load_file",
"(",
"file",
")",
"@starting_path",
"=",
"File",
".",
"expand_path",
"(",
"File",
".",
"split",
"(",
"file",
")",
".",
"first",
")",
"@config_options",
"=",
"{",
"}",
"load_tags",
"load_file_exclusions",
"load_extension_inclusions",
"config_options",
"end"
] | Parses the config file and loads the options
@api public
@example ConfigFile.new.read_config_file('.todo-lint.yml')
@return [Hash] parsed file-options | [
"Parses",
"the",
"config",
"file",
"and",
"loads",
"the",
"options"
] | 0d1061383ea205ef4c74edc64568e308ac1af990 | https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/config_file.rb#L10-L18 | train |
maxjacobson/todo_lint | lib/todo_lint/config_file.rb | TodoLint.ConfigFile.load_file_exclusions | def load_file_exclusions
return unless config_hash["Exclude Files"]
config_options[:excluded_files] = []
config_hash["Exclude Files"].each do |short_file|
config_options[:excluded_files] << File.join(starting_path, short_file)
end
end | ruby | def load_file_exclusions
return unless config_hash["Exclude Files"]
config_options[:excluded_files] = []
config_hash["Exclude Files"].each do |short_file|
config_options[:excluded_files] << File.join(starting_path, short_file)
end
end | [
"def",
"load_file_exclusions",
"return",
"unless",
"config_hash",
"[",
"\"Exclude Files\"",
"]",
"config_options",
"[",
":excluded_files",
"]",
"=",
"[",
"]",
"config_hash",
"[",
"\"Exclude Files\"",
"]",
".",
"each",
"do",
"|",
"short_file",
"|",
"config_options",
"[",
":excluded_files",
"]",
"<<",
"File",
".",
"join",
"(",
"starting_path",
",",
"short_file",
")",
"end",
"end"
] | Adds the exclude file options to the config_options hash
@api private
@return [Hash] | [
"Adds",
"the",
"exclude",
"file",
"options",
"to",
"the",
"config_options",
"hash"
] | 0d1061383ea205ef4c74edc64568e308ac1af990 | https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/config_file.rb#L40-L46 | train |
maxjacobson/todo_lint | lib/todo_lint/config_file.rb | TodoLint.ConfigFile.load_tags | def load_tags
config_options[:tags] = {}
return unless config_hash["Tags"]
config_hash["Tags"].each do |tag, due_date|
unless due_date.is_a? Date
raise ArgumentError, "#{due_date} is not a date"
end
config_options[:tags]["##{tag}"] = DueDate.new(due_date)
end
end | ruby | def load_tags
config_options[:tags] = {}
return unless config_hash["Tags"]
config_hash["Tags"].each do |tag, due_date|
unless due_date.is_a? Date
raise ArgumentError, "#{due_date} is not a date"
end
config_options[:tags]["##{tag}"] = DueDate.new(due_date)
end
end | [
"def",
"load_tags",
"config_options",
"[",
":tags",
"]",
"=",
"{",
"}",
"return",
"unless",
"config_hash",
"[",
"\"Tags\"",
"]",
"config_hash",
"[",
"\"Tags\"",
"]",
".",
"each",
"do",
"|",
"tag",
",",
"due_date",
"|",
"unless",
"due_date",
".",
"is_a?",
"Date",
"raise",
"ArgumentError",
",",
"\"#{due_date} is not a date\"",
"end",
"config_options",
"[",
":tags",
"]",
"[",
"\"##{tag}\"",
"]",
"=",
"DueDate",
".",
"new",
"(",
"due_date",
")",
"end",
"end"
] | Load the tags from the configuration file as DueDates
@return is irrelevant
@api private | [
"Load",
"the",
"tags",
"from",
"the",
"configuration",
"file",
"as",
"DueDates"
] | 0d1061383ea205ef4c74edc64568e308ac1af990 | https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/config_file.rb#L60-L70 | train |
nestor-custodio/automodel-sqlserver | lib/automodel/schema_inspector.rb | Automodel.SchemaInspector.columns | def columns(table_name)
table_name = table_name.to_s
@columns ||= {}
@columns[table_name] ||= if @registration[:columns].present?
@registration[:columns].call(@connection, table_name)
else
@connection.columns(table_name)
end
end | ruby | def columns(table_name)
table_name = table_name.to_s
@columns ||= {}
@columns[table_name] ||= if @registration[:columns].present?
@registration[:columns].call(@connection, table_name)
else
@connection.columns(table_name)
end
end | [
"def",
"columns",
"(",
"table_name",
")",
"table_name",
"=",
"table_name",
".",
"to_s",
"@columns",
"||=",
"{",
"}",
"@columns",
"[",
"table_name",
"]",
"||=",
"if",
"@registration",
"[",
":columns",
"]",
".",
"present?",
"@registration",
"[",
":columns",
"]",
".",
"call",
"(",
"@connection",
",",
"table_name",
")",
"else",
"@connection",
".",
"columns",
"(",
"table_name",
")",
"end",
"end"
] | Returns a list of columns for the given table.
If a matching Automodel::SchemaInspector registration is found for the connection's adapter,
and that registration specified a `:columns` Proc, the Proc is called. Otherwise, the
standard connection `#columns` is returned.
@param table_name [String]
The table whose columns should be fetched.
@return [Array<ActiveRecord::ConnectionAdapters::Column>] | [
"Returns",
"a",
"list",
"of",
"columns",
"for",
"the",
"given",
"table",
"."
] | 7269224752274f59113ccf8267fc49316062ae22 | https://github.com/nestor-custodio/automodel-sqlserver/blob/7269224752274f59113ccf8267fc49316062ae22/lib/automodel/schema_inspector.rb#L101-L110 | train |
nestor-custodio/automodel-sqlserver | lib/automodel/schema_inspector.rb | Automodel.SchemaInspector.primary_key | def primary_key(table_name)
table_name = table_name.to_s
@primary_keys ||= {}
@primary_keys[table_name] ||= if @registration[:primary_key].present?
@registration[:primary_key].call(@connection, table_name)
else
@connection.primary_key(table_name)
end
end | ruby | def primary_key(table_name)
table_name = table_name.to_s
@primary_keys ||= {}
@primary_keys[table_name] ||= if @registration[:primary_key].present?
@registration[:primary_key].call(@connection, table_name)
else
@connection.primary_key(table_name)
end
end | [
"def",
"primary_key",
"(",
"table_name",
")",
"table_name",
"=",
"table_name",
".",
"to_s",
"@primary_keys",
"||=",
"{",
"}",
"@primary_keys",
"[",
"table_name",
"]",
"||=",
"if",
"@registration",
"[",
":primary_key",
"]",
".",
"present?",
"@registration",
"[",
":primary_key",
"]",
".",
"call",
"(",
"@connection",
",",
"table_name",
")",
"else",
"@connection",
".",
"primary_key",
"(",
"table_name",
")",
"end",
"end"
] | Returns the primary key for the given table.
If a matching Automodel::SchemaInspector registration is found for the connection's adapter,
and that registration specified a `:primary_key` Proc, the Proc is called. Otherwise, the
standard connection `#primary_key` is returned.
@param table_name [String]
The table whose primary key should be fetched.
@return [String, Array<String>] | [
"Returns",
"the",
"primary",
"key",
"for",
"the",
"given",
"table",
"."
] | 7269224752274f59113ccf8267fc49316062ae22 | https://github.com/nestor-custodio/automodel-sqlserver/blob/7269224752274f59113ccf8267fc49316062ae22/lib/automodel/schema_inspector.rb#L125-L134 | train |
nestor-custodio/automodel-sqlserver | lib/automodel/schema_inspector.rb | Automodel.SchemaInspector.foreign_keys | def foreign_keys(table_name)
table_name = table_name.to_s
@foreign_keys ||= {}
@foreign_keys[table_name] ||= begin
if @registration[:foreign_keys].present?
@registration[:foreign_keys].call(@connection, table_name)
else
begin
@connection.foreign_keys(table_name)
rescue ::NoMethodError, ::NotImplementedError
## Not all ActiveRecord adapters support `#foreign_keys`. When this happens, we'll make
## a best-effort attempt to intuit relationships from the table and column names.
##
columns(table_name).map do |column|
id_pattern = %r{(?:_id|Id)$}
next unless column.name =~ id_pattern
target_table = column.name.sub(id_pattern, '')
next unless target_table.in? tables
target_column = primary_key(qualified_name(target_table, context: table_name))
next unless target_column.in? ['id', 'Id', 'ID', column.name]
ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(
table_name.split('.').last,
target_table,
name: "FK_#{SecureRandom.uuid.delete('-')}",
column: column.name,
primary_key: target_column,
on_update: nil,
on_delete: nil
)
end.compact
end
end
end
end | ruby | def foreign_keys(table_name)
table_name = table_name.to_s
@foreign_keys ||= {}
@foreign_keys[table_name] ||= begin
if @registration[:foreign_keys].present?
@registration[:foreign_keys].call(@connection, table_name)
else
begin
@connection.foreign_keys(table_name)
rescue ::NoMethodError, ::NotImplementedError
## Not all ActiveRecord adapters support `#foreign_keys`. When this happens, we'll make
## a best-effort attempt to intuit relationships from the table and column names.
##
columns(table_name).map do |column|
id_pattern = %r{(?:_id|Id)$}
next unless column.name =~ id_pattern
target_table = column.name.sub(id_pattern, '')
next unless target_table.in? tables
target_column = primary_key(qualified_name(target_table, context: table_name))
next unless target_column.in? ['id', 'Id', 'ID', column.name]
ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(
table_name.split('.').last,
target_table,
name: "FK_#{SecureRandom.uuid.delete('-')}",
column: column.name,
primary_key: target_column,
on_update: nil,
on_delete: nil
)
end.compact
end
end
end
end | [
"def",
"foreign_keys",
"(",
"table_name",
")",
"table_name",
"=",
"table_name",
".",
"to_s",
"@foreign_keys",
"||=",
"{",
"}",
"@foreign_keys",
"[",
"table_name",
"]",
"||=",
"begin",
"if",
"@registration",
"[",
":foreign_keys",
"]",
".",
"present?",
"@registration",
"[",
":foreign_keys",
"]",
".",
"call",
"(",
"@connection",
",",
"table_name",
")",
"else",
"begin",
"@connection",
".",
"foreign_keys",
"(",
"table_name",
")",
"rescue",
"::",
"NoMethodError",
",",
"::",
"NotImplementedError",
"## Not all ActiveRecord adapters support `#foreign_keys`. When this happens, we'll make",
"## a best-effort attempt to intuit relationships from the table and column names.",
"##",
"columns",
"(",
"table_name",
")",
".",
"map",
"do",
"|",
"column",
"|",
"id_pattern",
"=",
"%r{",
"}",
"next",
"unless",
"column",
".",
"name",
"=~",
"id_pattern",
"target_table",
"=",
"column",
".",
"name",
".",
"sub",
"(",
"id_pattern",
",",
"''",
")",
"next",
"unless",
"target_table",
".",
"in?",
"tables",
"target_column",
"=",
"primary_key",
"(",
"qualified_name",
"(",
"target_table",
",",
"context",
":",
"table_name",
")",
")",
"next",
"unless",
"target_column",
".",
"in?",
"[",
"'id'",
",",
"'Id'",
",",
"'ID'",
",",
"column",
".",
"name",
"]",
"ActiveRecord",
"::",
"ConnectionAdapters",
"::",
"ForeignKeyDefinition",
".",
"new",
"(",
"table_name",
".",
"split",
"(",
"'.'",
")",
".",
"last",
",",
"target_table",
",",
"name",
":",
"\"FK_#{SecureRandom.uuid.delete('-')}\"",
",",
"column",
":",
"column",
".",
"name",
",",
"primary_key",
":",
"target_column",
",",
"on_update",
":",
"nil",
",",
"on_delete",
":",
"nil",
")",
"end",
".",
"compact",
"end",
"end",
"end",
"end"
] | Returns a list of foreign keys for the given table.
If a matching Automodel::SchemaInspector registration is found for the connection's adapter,
and that registration specified a `:foreign_keys` Proc, the Proc is called. Otherwise, the
standard connection `#foreign_keys` is attempted. If that call to ``#foreign_keys` raises a
::NoMethodError or ::NotImplementedError, a best-effort attempt is made to build a list of
foreign keys based on table and column names.
@param table_name [String]
The table whose foreign keys should be fetched.
@return [Array<ActiveRecord::ConnectionAdapters::ForeignKeyDefinition>] | [
"Returns",
"a",
"list",
"of",
"foreign",
"keys",
"for",
"the",
"given",
"table",
"."
] | 7269224752274f59113ccf8267fc49316062ae22 | https://github.com/nestor-custodio/automodel-sqlserver/blob/7269224752274f59113ccf8267fc49316062ae22/lib/automodel/schema_inspector.rb#L151-L188 | train |
keita/naming | lib/naming/name-set.rb | Naming.NameSet.others | def others(array)
array.select{|elt| not(any?{|name| elt.kind_of?(name)})}
end | ruby | def others(array)
array.select{|elt| not(any?{|name| elt.kind_of?(name)})}
end | [
"def",
"others",
"(",
"array",
")",
"array",
".",
"select",
"{",
"|",
"elt",
"|",
"not",
"(",
"any?",
"{",
"|",
"name",
"|",
"elt",
".",
"kind_of?",
"(",
"name",
")",
"}",
")",
"}",
"end"
] | Collect objects from the array excluding named objects which have the
name in the set.
@param array [Array]
target of value extraction
@example
Naming::NameSet(:A, :B).values([
Naming.A(1),
Naming.B(2),
"abc",
Naming.A(3),
123,
nil
]) #=> ["abc", 123, nil] | [
"Collect",
"objects",
"from",
"the",
"array",
"excluding",
"named",
"objects",
"which",
"have",
"the",
"name",
"in",
"the",
"set",
"."
] | 70393c824982627885e78336491c75b3f13c1dc0 | https://github.com/keita/naming/blob/70393c824982627885e78336491c75b3f13c1dc0/lib/naming/name-set.rb#L44-L46 | train |
rixth/tay | lib/tay/manifest_generator.rb | Tay.ManifestGenerator.spec_as_json | def spec_as_json
json = {
:name => spec.name,
:version => spec.version,
:manifest_version => calculate_manifest_version
}
json[:description] = spec.description if spec.description
json[:icons] = spec.icons
json[:default_locale] = spec.default_locale if spec.default_locale
json[:browser_action] = action_as_json(spec.browser_action) if spec.browser_action
json[:page_action] = action_as_json(spec.page_action) if spec.page_action
json[:app] = packaged_app_as_json if spec.packaged_app
if spec.background_page
json[:background] = { :page => spec.background_page }
end
unless spec.background_scripts.empty?
json[:background] = { :scripts => spec.background_scripts }
end
json[:chrome_url_overrides] = spec.overriden_pages unless spec.overriden_pages.empty?
json[:content_scripts] = content_scripts_as_json unless spec.content_scripts.empty?
json[:content_security_policy] = spec.content_security_policy if spec.content_security_policy
json[:homepage_url] = spec.homepage if spec.homepage
json[:incognito] = spec.incognito_mode if spec.incognito_mode
json[:intents] = web_intents_as_json unless spec.web_intents.empty?
json[:minimum_chrome_version] = spec.minimum_chrome_version if spec.minimum_chrome_version
json[:nacl_modules] = nacl_modules_as_json unless spec.nacl_modules.empty?
json[:offline_enabled] = spec.offline_enabled unless spec.offline_enabled.nil?
json[:omnibox] = spec.omnibox_keyword if spec.omnibox_keyword
json[:options_page] = spec.options_page if spec.options_page
json[:permissions] = spec.permissions unless spec.permissions.empty?
json[:requirements] = requirements_as_json if has_requirements?
json[:update_url] = spec.update_url if spec.update_url
json[:web_accessible_resources] = spec.web_accessible_resources unless spec.web_accessible_resources.empty?
json
end | ruby | def spec_as_json
json = {
:name => spec.name,
:version => spec.version,
:manifest_version => calculate_manifest_version
}
json[:description] = spec.description if spec.description
json[:icons] = spec.icons
json[:default_locale] = spec.default_locale if spec.default_locale
json[:browser_action] = action_as_json(spec.browser_action) if spec.browser_action
json[:page_action] = action_as_json(spec.page_action) if spec.page_action
json[:app] = packaged_app_as_json if spec.packaged_app
if spec.background_page
json[:background] = { :page => spec.background_page }
end
unless spec.background_scripts.empty?
json[:background] = { :scripts => spec.background_scripts }
end
json[:chrome_url_overrides] = spec.overriden_pages unless spec.overriden_pages.empty?
json[:content_scripts] = content_scripts_as_json unless spec.content_scripts.empty?
json[:content_security_policy] = spec.content_security_policy if spec.content_security_policy
json[:homepage_url] = spec.homepage if spec.homepage
json[:incognito] = spec.incognito_mode if spec.incognito_mode
json[:intents] = web_intents_as_json unless spec.web_intents.empty?
json[:minimum_chrome_version] = spec.minimum_chrome_version if spec.minimum_chrome_version
json[:nacl_modules] = nacl_modules_as_json unless spec.nacl_modules.empty?
json[:offline_enabled] = spec.offline_enabled unless spec.offline_enabled.nil?
json[:omnibox] = spec.omnibox_keyword if spec.omnibox_keyword
json[:options_page] = spec.options_page if spec.options_page
json[:permissions] = spec.permissions unless spec.permissions.empty?
json[:requirements] = requirements_as_json if has_requirements?
json[:update_url] = spec.update_url if spec.update_url
json[:web_accessible_resources] = spec.web_accessible_resources unless spec.web_accessible_resources.empty?
json
end | [
"def",
"spec_as_json",
"json",
"=",
"{",
":name",
"=>",
"spec",
".",
"name",
",",
":version",
"=>",
"spec",
".",
"version",
",",
":manifest_version",
"=>",
"calculate_manifest_version",
"}",
"json",
"[",
":description",
"]",
"=",
"spec",
".",
"description",
"if",
"spec",
".",
"description",
"json",
"[",
":icons",
"]",
"=",
"spec",
".",
"icons",
"json",
"[",
":default_locale",
"]",
"=",
"spec",
".",
"default_locale",
"if",
"spec",
".",
"default_locale",
"json",
"[",
":browser_action",
"]",
"=",
"action_as_json",
"(",
"spec",
".",
"browser_action",
")",
"if",
"spec",
".",
"browser_action",
"json",
"[",
":page_action",
"]",
"=",
"action_as_json",
"(",
"spec",
".",
"page_action",
")",
"if",
"spec",
".",
"page_action",
"json",
"[",
":app",
"]",
"=",
"packaged_app_as_json",
"if",
"spec",
".",
"packaged_app",
"if",
"spec",
".",
"background_page",
"json",
"[",
":background",
"]",
"=",
"{",
":page",
"=>",
"spec",
".",
"background_page",
"}",
"end",
"unless",
"spec",
".",
"background_scripts",
".",
"empty?",
"json",
"[",
":background",
"]",
"=",
"{",
":scripts",
"=>",
"spec",
".",
"background_scripts",
"}",
"end",
"json",
"[",
":chrome_url_overrides",
"]",
"=",
"spec",
".",
"overriden_pages",
"unless",
"spec",
".",
"overriden_pages",
".",
"empty?",
"json",
"[",
":content_scripts",
"]",
"=",
"content_scripts_as_json",
"unless",
"spec",
".",
"content_scripts",
".",
"empty?",
"json",
"[",
":content_security_policy",
"]",
"=",
"spec",
".",
"content_security_policy",
"if",
"spec",
".",
"content_security_policy",
"json",
"[",
":homepage_url",
"]",
"=",
"spec",
".",
"homepage",
"if",
"spec",
".",
"homepage",
"json",
"[",
":incognito",
"]",
"=",
"spec",
".",
"incognito_mode",
"if",
"spec",
".",
"incognito_mode",
"json",
"[",
":intents",
"]",
"=",
"web_intents_as_json",
"unless",
"spec",
".",
"web_intents",
".",
"empty?",
"json",
"[",
":minimum_chrome_version",
"]",
"=",
"spec",
".",
"minimum_chrome_version",
"if",
"spec",
".",
"minimum_chrome_version",
"json",
"[",
":nacl_modules",
"]",
"=",
"nacl_modules_as_json",
"unless",
"spec",
".",
"nacl_modules",
".",
"empty?",
"json",
"[",
":offline_enabled",
"]",
"=",
"spec",
".",
"offline_enabled",
"unless",
"spec",
".",
"offline_enabled",
".",
"nil?",
"json",
"[",
":omnibox",
"]",
"=",
"spec",
".",
"omnibox_keyword",
"if",
"spec",
".",
"omnibox_keyword",
"json",
"[",
":options_page",
"]",
"=",
"spec",
".",
"options_page",
"if",
"spec",
".",
"options_page",
"json",
"[",
":permissions",
"]",
"=",
"spec",
".",
"permissions",
"unless",
"spec",
".",
"permissions",
".",
"empty?",
"json",
"[",
":requirements",
"]",
"=",
"requirements_as_json",
"if",
"has_requirements?",
"json",
"[",
":update_url",
"]",
"=",
"spec",
".",
"update_url",
"if",
"spec",
".",
"update_url",
"json",
"[",
":web_accessible_resources",
"]",
"=",
"spec",
".",
"web_accessible_resources",
"unless",
"spec",
".",
"web_accessible_resources",
".",
"empty?",
"json",
"end"
] | Return the JSON representation of the specification | [
"Return",
"the",
"JSON",
"representation",
"of",
"the",
"specification"
] | 60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5 | https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/manifest_generator.rb#L19-L55 | train |
rixth/tay | lib/tay/manifest_generator.rb | Tay.ManifestGenerator.action_as_json | def action_as_json(action)
json = {}
json[:default_title] = action.title if action.title
json[:default_icon] = action.icon if action.icon
json[:default_popup] = action.popup if action.popup
json
end | ruby | def action_as_json(action)
json = {}
json[:default_title] = action.title if action.title
json[:default_icon] = action.icon if action.icon
json[:default_popup] = action.popup if action.popup
json
end | [
"def",
"action_as_json",
"(",
"action",
")",
"json",
"=",
"{",
"}",
"json",
"[",
":default_title",
"]",
"=",
"action",
".",
"title",
"if",
"action",
".",
"title",
"json",
"[",
":default_icon",
"]",
"=",
"action",
".",
"icon",
"if",
"action",
".",
"icon",
"json",
"[",
":default_popup",
"]",
"=",
"action",
".",
"popup",
"if",
"action",
".",
"popup",
"json",
"end"
] | Return the manifest representation of a page or browser action | [
"Return",
"the",
"manifest",
"representation",
"of",
"a",
"page",
"or",
"browser",
"action"
] | 60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5 | https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/manifest_generator.rb#L68-L74 | train |
rixth/tay | lib/tay/manifest_generator.rb | Tay.ManifestGenerator.packaged_app_as_json | def packaged_app_as_json
app = spec.packaged_app
json = {
:local_path => app.page
}
unless app.container.nil?
json[:container] = app.container
if app.container == 'panel'
json[:width] = app.width
json[:height] = app.height
end
end
{ :launch => json }
end | ruby | def packaged_app_as_json
app = spec.packaged_app
json = {
:local_path => app.page
}
unless app.container.nil?
json[:container] = app.container
if app.container == 'panel'
json[:width] = app.width
json[:height] = app.height
end
end
{ :launch => json }
end | [
"def",
"packaged_app_as_json",
"app",
"=",
"spec",
".",
"packaged_app",
"json",
"=",
"{",
":local_path",
"=>",
"app",
".",
"page",
"}",
"unless",
"app",
".",
"container",
".",
"nil?",
"json",
"[",
":container",
"]",
"=",
"app",
".",
"container",
"if",
"app",
".",
"container",
"==",
"'panel'",
"json",
"[",
":width",
"]",
"=",
"app",
".",
"width",
"json",
"[",
":height",
"]",
"=",
"app",
".",
"height",
"end",
"end",
"{",
":launch",
"=>",
"json",
"}",
"end"
] | Return the manifest representation of a packaged app | [
"Return",
"the",
"manifest",
"representation",
"of",
"a",
"packaged",
"app"
] | 60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5 | https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/manifest_generator.rb#L78-L93 | train |
rixth/tay | lib/tay/manifest_generator.rb | Tay.ManifestGenerator.content_scripts_as_json | def content_scripts_as_json
spec.content_scripts.map do |cs|
cs_json = {
:matches => cs.include_patterns
}
cs_json[:exclude_matches] = cs.exclude_patterns unless cs.exclude_patterns.empty?
cs_json[:run_at] = cs.run_at if cs.run_at
cs_json[:all_frames] = cs.all_frames unless cs.all_frames.nil?
cs_json[:css] = cs.stylesheets unless cs.stylesheets.empty?
cs_json[:js] = cs.javascripts unless cs.javascripts.empty?
cs_json
end
end | ruby | def content_scripts_as_json
spec.content_scripts.map do |cs|
cs_json = {
:matches => cs.include_patterns
}
cs_json[:exclude_matches] = cs.exclude_patterns unless cs.exclude_patterns.empty?
cs_json[:run_at] = cs.run_at if cs.run_at
cs_json[:all_frames] = cs.all_frames unless cs.all_frames.nil?
cs_json[:css] = cs.stylesheets unless cs.stylesheets.empty?
cs_json[:js] = cs.javascripts unless cs.javascripts.empty?
cs_json
end
end | [
"def",
"content_scripts_as_json",
"spec",
".",
"content_scripts",
".",
"map",
"do",
"|",
"cs",
"|",
"cs_json",
"=",
"{",
":matches",
"=>",
"cs",
".",
"include_patterns",
"}",
"cs_json",
"[",
":exclude_matches",
"]",
"=",
"cs",
".",
"exclude_patterns",
"unless",
"cs",
".",
"exclude_patterns",
".",
"empty?",
"cs_json",
"[",
":run_at",
"]",
"=",
"cs",
".",
"run_at",
"if",
"cs",
".",
"run_at",
"cs_json",
"[",
":all_frames",
"]",
"=",
"cs",
".",
"all_frames",
"unless",
"cs",
".",
"all_frames",
".",
"nil?",
"cs_json",
"[",
":css",
"]",
"=",
"cs",
".",
"stylesheets",
"unless",
"cs",
".",
"stylesheets",
".",
"empty?",
"cs_json",
"[",
":js",
"]",
"=",
"cs",
".",
"javascripts",
"unless",
"cs",
".",
"javascripts",
".",
"empty?",
"cs_json",
"end",
"end"
] | Return the manifest representation of the content scripts, if any | [
"Return",
"the",
"manifest",
"representation",
"of",
"the",
"content",
"scripts",
"if",
"any"
] | 60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5 | https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/manifest_generator.rb#L97-L111 | train |
rixth/tay | lib/tay/manifest_generator.rb | Tay.ManifestGenerator.web_intents_as_json | def web_intents_as_json
spec.web_intents.map do |wi|
{
:action => wi.action,
:title => wi.title,
:href => wi.href,
:types => wi.types,
:disposition => wi.disposition
}
end
end | ruby | def web_intents_as_json
spec.web_intents.map do |wi|
{
:action => wi.action,
:title => wi.title,
:href => wi.href,
:types => wi.types,
:disposition => wi.disposition
}
end
end | [
"def",
"web_intents_as_json",
"spec",
".",
"web_intents",
".",
"map",
"do",
"|",
"wi",
"|",
"{",
":action",
"=>",
"wi",
".",
"action",
",",
":title",
"=>",
"wi",
".",
"title",
",",
":href",
"=>",
"wi",
".",
"href",
",",
":types",
"=>",
"wi",
".",
"types",
",",
":disposition",
"=>",
"wi",
".",
"disposition",
"}",
"end",
"end"
] | Return the manifest representation of handled web intents, if any | [
"Return",
"the",
"manifest",
"representation",
"of",
"handled",
"web",
"intents",
"if",
"any"
] | 60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5 | https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/manifest_generator.rb#L115-L125 | train |
redding/logsly | lib/logsly/logging182/appenders/email.rb | Logsly::Logging182::Appenders.Email.canonical_write | def canonical_write( str )
### build a mail header for RFC 822
rfc822msg = "From: #{@from}\n"
rfc822msg << "To: #{@to.join(",")}\n"
rfc822msg << "Subject: #{@subject}\n"
rfc822msg << "Date: #{Time.new.rfc822}\n"
rfc822msg << "Message-Id: <#{"%.8f" % Time.now.to_f}@#{@domain}>\n\n"
rfc822msg = rfc822msg.force_encoding(encoding) if encoding and rfc822msg.encoding != encoding
rfc822msg << str
### send email
smtp = Net::SMTP.new(@address, @port)
smtp.enable_starttls_auto if @enable_starttls_auto and smtp.respond_to? :enable_starttls_auto
smtp.start(@domain, @user_name, @password, @authentication) { |s| s.sendmail(rfc822msg, @from, @to) }
self
rescue StandardError, TimeoutError => err
self.level = :off
::Logsly::Logging182.log_internal {'e-mail notifications have been disabled'}
::Logsly::Logging182.log_internal(-2) {err}
end | ruby | def canonical_write( str )
### build a mail header for RFC 822
rfc822msg = "From: #{@from}\n"
rfc822msg << "To: #{@to.join(",")}\n"
rfc822msg << "Subject: #{@subject}\n"
rfc822msg << "Date: #{Time.new.rfc822}\n"
rfc822msg << "Message-Id: <#{"%.8f" % Time.now.to_f}@#{@domain}>\n\n"
rfc822msg = rfc822msg.force_encoding(encoding) if encoding and rfc822msg.encoding != encoding
rfc822msg << str
### send email
smtp = Net::SMTP.new(@address, @port)
smtp.enable_starttls_auto if @enable_starttls_auto and smtp.respond_to? :enable_starttls_auto
smtp.start(@domain, @user_name, @password, @authentication) { |s| s.sendmail(rfc822msg, @from, @to) }
self
rescue StandardError, TimeoutError => err
self.level = :off
::Logsly::Logging182.log_internal {'e-mail notifications have been disabled'}
::Logsly::Logging182.log_internal(-2) {err}
end | [
"def",
"canonical_write",
"(",
"str",
")",
"### build a mail header for RFC 822",
"rfc822msg",
"=",
"\"From: #{@from}\\n\"",
"rfc822msg",
"<<",
"\"To: #{@to.join(\",\")}\\n\"",
"rfc822msg",
"<<",
"\"Subject: #{@subject}\\n\"",
"rfc822msg",
"<<",
"\"Date: #{Time.new.rfc822}\\n\"",
"rfc822msg",
"<<",
"\"Message-Id: <#{\"%.8f\" % Time.now.to_f}@#{@domain}>\\n\\n\"",
"rfc822msg",
"=",
"rfc822msg",
".",
"force_encoding",
"(",
"encoding",
")",
"if",
"encoding",
"and",
"rfc822msg",
".",
"encoding",
"!=",
"encoding",
"rfc822msg",
"<<",
"str",
"### send email",
"smtp",
"=",
"Net",
"::",
"SMTP",
".",
"new",
"(",
"@address",
",",
"@port",
")",
"smtp",
".",
"enable_starttls_auto",
"if",
"@enable_starttls_auto",
"and",
"smtp",
".",
"respond_to?",
":enable_starttls_auto",
"smtp",
".",
"start",
"(",
"@domain",
",",
"@user_name",
",",
"@password",
",",
"@authentication",
")",
"{",
"|",
"s",
"|",
"s",
".",
"sendmail",
"(",
"rfc822msg",
",",
"@from",
",",
"@to",
")",
"}",
"self",
"rescue",
"StandardError",
",",
"TimeoutError",
"=>",
"err",
"self",
".",
"level",
"=",
":off",
"::",
"Logsly",
"::",
"Logging182",
".",
"log_internal",
"{",
"'e-mail notifications have been disabled'",
"}",
"::",
"Logsly",
"::",
"Logging182",
".",
"log_internal",
"(",
"-",
"2",
")",
"{",
"err",
"}",
"end"
] | This method is called by the buffering code when messages need to be
sent out as an email. | [
"This",
"method",
"is",
"called",
"by",
"the",
"buffering",
"code",
"when",
"messages",
"need",
"to",
"be",
"sent",
"out",
"as",
"an",
"email",
"."
] | a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf | https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/appenders/email.rb#L154-L174 | train |
acro5piano/selenium_standalone_dsl | lib/selenium_standalone_dsl/base.rb | SeleniumStandaloneDSL.Base.click | def click(selector, find_by: :link_text)
sleep Random.new.rand(1..2)
with_frame do
@driver.find_element(find_by, selector).click
end
sleep Random.new.rand(1..2)
end | ruby | def click(selector, find_by: :link_text)
sleep Random.new.rand(1..2)
with_frame do
@driver.find_element(find_by, selector).click
end
sleep Random.new.rand(1..2)
end | [
"def",
"click",
"(",
"selector",
",",
"find_by",
":",
":link_text",
")",
"sleep",
"Random",
".",
"new",
".",
"rand",
"(",
"1",
"..",
"2",
")",
"with_frame",
"do",
"@driver",
".",
"find_element",
"(",
"find_by",
",",
"selector",
")",
".",
"click",
"end",
"sleep",
"Random",
".",
"new",
".",
"rand",
"(",
"1",
"..",
"2",
")",
"end"
] | The following methods are utility methods for SeleniumStandaloneDsl-DSL.
You can easily handle driver with this DSL. | [
"The",
"following",
"methods",
"are",
"utility",
"methods",
"for",
"SeleniumStandaloneDsl",
"-",
"DSL",
".",
"You",
"can",
"easily",
"handle",
"driver",
"with",
"this",
"DSL",
"."
] | 3eec04012905ef35804ddf362eac69bfbe2c7646 | https://github.com/acro5piano/selenium_standalone_dsl/blob/3eec04012905ef35804ddf362eac69bfbe2c7646/lib/selenium_standalone_dsl/base.rb#L31-L37 | train |
bottiger/Blog_Basic | app/models/blog_basic/blog_post.rb | BlogBasic.BlogPost.replace_blog_image_tags | def replace_blog_image_tags
@resaving = true
self.body.gsub!(/[{]blog_image:upload[0-9]+:[a-zA-Z]+[}]/) do |image_tag|
random_id, size = image_tag.scan(/upload([0-9]+)[:]([a-zA-Z]+)/).flatten
new_id = random_id
matching_image = self.blog_images.reject {|bi| !bi.random_id || bi.random_id != random_id }.first
if matching_image
new_id = matching_image.id
end
"{blog_image:#{new_id}:#{size}}"
end
self.save
@resaving = false
return true
end | ruby | def replace_blog_image_tags
@resaving = true
self.body.gsub!(/[{]blog_image:upload[0-9]+:[a-zA-Z]+[}]/) do |image_tag|
random_id, size = image_tag.scan(/upload([0-9]+)[:]([a-zA-Z]+)/).flatten
new_id = random_id
matching_image = self.blog_images.reject {|bi| !bi.random_id || bi.random_id != random_id }.first
if matching_image
new_id = matching_image.id
end
"{blog_image:#{new_id}:#{size}}"
end
self.save
@resaving = false
return true
end | [
"def",
"replace_blog_image_tags",
"@resaving",
"=",
"true",
"self",
".",
"body",
".",
"gsub!",
"(",
"/",
"/",
")",
"do",
"|",
"image_tag",
"|",
"random_id",
",",
"size",
"=",
"image_tag",
".",
"scan",
"(",
"/",
"/",
")",
".",
"flatten",
"new_id",
"=",
"random_id",
"matching_image",
"=",
"self",
".",
"blog_images",
".",
"reject",
"{",
"|",
"bi",
"|",
"!",
"bi",
".",
"random_id",
"||",
"bi",
".",
"random_id",
"!=",
"random_id",
"}",
".",
"first",
"if",
"matching_image",
"new_id",
"=",
"matching_image",
".",
"id",
"end",
"\"{blog_image:#{new_id}:#{size}}\"",
"end",
"self",
".",
"save",
"@resaving",
"=",
"false",
"return",
"true",
"end"
] | For images that haven't been uploaded yet, they get a random image id
with 'upload' infront of it. We replace those with their new image
id | [
"For",
"images",
"that",
"haven",
"t",
"been",
"uploaded",
"yet",
"they",
"get",
"a",
"random",
"image",
"id",
"with",
"upload",
"infront",
"of",
"it",
".",
"We",
"replace",
"those",
"with",
"their",
"new",
"image",
"id"
] | 9eb8fc2e7100b93bf4193ed86671c6dd1c8fc440 | https://github.com/bottiger/Blog_Basic/blob/9eb8fc2e7100b93bf4193ed86671c6dd1c8fc440/app/models/blog_basic/blog_post.rb#L50-L70 | train |
cknadler/versed | lib/versed/schedule.rb | Versed.Schedule.incomplete_tasks | def incomplete_tasks
# TODO: refactor with reject
incomplete = []
categories.each { |c| incomplete << c if c.incomplete? }
incomplete.sort_by { |c| [-c.percent_incomplete, -c.total_min_incomplete] }
end | ruby | def incomplete_tasks
# TODO: refactor with reject
incomplete = []
categories.each { |c| incomplete << c if c.incomplete? }
incomplete.sort_by { |c| [-c.percent_incomplete, -c.total_min_incomplete] }
end | [
"def",
"incomplete_tasks",
"# TODO: refactor with reject",
"incomplete",
"=",
"[",
"]",
"categories",
".",
"each",
"{",
"|",
"c",
"|",
"incomplete",
"<<",
"c",
"if",
"c",
".",
"incomplete?",
"}",
"incomplete",
".",
"sort_by",
"{",
"|",
"c",
"|",
"[",
"-",
"c",
".",
"percent_incomplete",
",",
"-",
"c",
".",
"total_min_incomplete",
"]",
"}",
"end"
] | Returns an array of incomplete tasks. This array is sorted first by
percentage incomplete, then by total number of minutes incomplete. | [
"Returns",
"an",
"array",
"of",
"incomplete",
"tasks",
".",
"This",
"array",
"is",
"sorted",
"first",
"by",
"percentage",
"incomplete",
"then",
"by",
"total",
"number",
"of",
"minutes",
"incomplete",
"."
] | 44273de418686a6fb6f20da3b41c84b6d922cec6 | https://github.com/cknadler/versed/blob/44273de418686a6fb6f20da3b41c84b6d922cec6/lib/versed/schedule.rb#L22-L27 | train |
cknadler/versed | lib/versed/schedule.rb | Versed.Schedule.category_ids | def category_ids(entries)
category_ids = []
entries.each do |day, tasks|
category_ids += tasks.keys
end
category_ids.uniq
end | ruby | def category_ids(entries)
category_ids = []
entries.each do |day, tasks|
category_ids += tasks.keys
end
category_ids.uniq
end | [
"def",
"category_ids",
"(",
"entries",
")",
"category_ids",
"=",
"[",
"]",
"entries",
".",
"each",
"do",
"|",
"day",
",",
"tasks",
"|",
"category_ids",
"+=",
"tasks",
".",
"keys",
"end",
"category_ids",
".",
"uniq",
"end"
] | Finds all unique category ids in a log or a schedule
@param entries [Hash] A parsed log or schedule
@return [Array, String] Unique category ids | [
"Finds",
"all",
"unique",
"category",
"ids",
"in",
"a",
"log",
"or",
"a",
"schedule"
] | 44273de418686a6fb6f20da3b41c84b6d922cec6 | https://github.com/cknadler/versed/blob/44273de418686a6fb6f20da3b41c84b6d922cec6/lib/versed/schedule.rb#L90-L96 | train |
georgyangelov/vcs-toolkit | lib/vcs_toolkit/merge.rb | VCSToolkit.Merge.combine_diffs | def combine_diffs(diff_one, diff_two)
Hash.new { |hash, key| hash[key] = [[], []] }.tap do |combined_diff|
diff_one.each do |change|
combined_diff[change.old_position].first << change
end
diff_two.each do |change|
combined_diff[change.old_position].last << change
end
end
end | ruby | def combine_diffs(diff_one, diff_two)
Hash.new { |hash, key| hash[key] = [[], []] }.tap do |combined_diff|
diff_one.each do |change|
combined_diff[change.old_position].first << change
end
diff_two.each do |change|
combined_diff[change.old_position].last << change
end
end
end | [
"def",
"combine_diffs",
"(",
"diff_one",
",",
"diff_two",
")",
"Hash",
".",
"new",
"{",
"|",
"hash",
",",
"key",
"|",
"hash",
"[",
"key",
"]",
"=",
"[",
"[",
"]",
",",
"[",
"]",
"]",
"}",
".",
"tap",
"do",
"|",
"combined_diff",
"|",
"diff_one",
".",
"each",
"do",
"|",
"change",
"|",
"combined_diff",
"[",
"change",
".",
"old_position",
"]",
".",
"first",
"<<",
"change",
"end",
"diff_two",
".",
"each",
"do",
"|",
"change",
"|",
"combined_diff",
"[",
"change",
".",
"old_position",
"]",
".",
"last",
"<<",
"change",
"end",
"end",
"end"
] | Group changes by their old index.
The structure is as follows:
{
<line_number_on_ancestor> => [
[ <change>, ... ], # The changes in the first file
[ <change>, ... ] # The changes in the second file
]
} | [
"Group",
"changes",
"by",
"their",
"old",
"index",
"."
] | 9d73735da090a5e0f612aee04f423306fa512f38 | https://github.com/georgyangelov/vcs-toolkit/blob/9d73735da090a5e0f612aee04f423306fa512f38/lib/vcs_toolkit/merge.rb#L83-L93 | train |
ikayzo/SDL.rb | lib/sdl4r/tag.rb | SDL4R.Tag.children_values | def children_values(name = nil)
children_values = []
each_child(false, name) { |child|
case child.values.size
when 0
children_values << nil
when 1
children_values << child.value
else
children_values << child.values
end
}
return children_values
end | ruby | def children_values(name = nil)
children_values = []
each_child(false, name) { |child|
case child.values.size
when 0
children_values << nil
when 1
children_values << child.value
else
children_values << child.values
end
}
return children_values
end | [
"def",
"children_values",
"(",
"name",
"=",
"nil",
")",
"children_values",
"=",
"[",
"]",
"each_child",
"(",
"false",
",",
"name",
")",
"{",
"|",
"child",
"|",
"case",
"child",
".",
"values",
".",
"size",
"when",
"0",
"children_values",
"<<",
"nil",
"when",
"1",
"children_values",
"<<",
"child",
".",
"value",
"else",
"children_values",
"<<",
"child",
".",
"values",
"end",
"}",
"return",
"children_values",
"end"
] | Returns the values of all the children with the given +name+. If the child has
more than one value, all the values will be added as an array. If the child
has no value, +nil+ will be added. The search is not recursive.
_name_:: if nil, all children are considered (nil by default). | [
"Returns",
"the",
"values",
"of",
"all",
"the",
"children",
"with",
"the",
"given",
"+",
"name",
"+",
".",
"If",
"the",
"child",
"has",
"more",
"than",
"one",
"value",
"all",
"the",
"values",
"will",
"be",
"added",
"as",
"an",
"array",
".",
"If",
"the",
"child",
"has",
"no",
"value",
"+",
"nil",
"+",
"will",
"be",
"added",
".",
"The",
"search",
"is",
"not",
"recursive",
"."
] | 1663b9f5aa95d8d6269f060e343c2d2fd9309259 | https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L318-L331 | train |
ikayzo/SDL.rb | lib/sdl4r/tag.rb | SDL4R.Tag.each_child | def each_child(recursive = false, namespace = nil, name = :DEFAULT, &block)
if name == :DEFAULT
name = namespace
namespace = nil
end
@children.each do |child|
if (name.nil? or child.name == name) and
(namespace.nil? or child.namespace == namespace)
yield child
end
child.children(recursive, namespace, name, &block) if recursive
end
return nil
end | ruby | def each_child(recursive = false, namespace = nil, name = :DEFAULT, &block)
if name == :DEFAULT
name = namespace
namespace = nil
end
@children.each do |child|
if (name.nil? or child.name == name) and
(namespace.nil? or child.namespace == namespace)
yield child
end
child.children(recursive, namespace, name, &block) if recursive
end
return nil
end | [
"def",
"each_child",
"(",
"recursive",
"=",
"false",
",",
"namespace",
"=",
"nil",
",",
"name",
"=",
":DEFAULT",
",",
"&",
"block",
")",
"if",
"name",
"==",
":DEFAULT",
"name",
"=",
"namespace",
"namespace",
"=",
"nil",
"end",
"@children",
".",
"each",
"do",
"|",
"child",
"|",
"if",
"(",
"name",
".",
"nil?",
"or",
"child",
".",
"name",
"==",
"name",
")",
"and",
"(",
"namespace",
".",
"nil?",
"or",
"child",
".",
"namespace",
"==",
"namespace",
")",
"yield",
"child",
"end",
"child",
".",
"children",
"(",
"recursive",
",",
"namespace",
",",
"name",
",",
"block",
")",
"if",
"recursive",
"end",
"return",
"nil",
"end"
] | Enumerates the children +Tag+s of this Tag and calls the given block
providing it the child as parameter.
_recursive_:: if true, enumerate grand-children, etc, recursively
_namespace_:: if not nil, indicates the namespace of the children to enumerate
_name_:: if not nil, indicates the name of the children to enumerate | [
"Enumerates",
"the",
"children",
"+",
"Tag",
"+",
"s",
"of",
"this",
"Tag",
"and",
"calls",
"the",
"given",
"block",
"providing",
"it",
"the",
"child",
"as",
"parameter",
"."
] | 1663b9f5aa95d8d6269f060e343c2d2fd9309259 | https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L378-L393 | train |
ikayzo/SDL.rb | lib/sdl4r/tag.rb | SDL4R.Tag.remove_value | def remove_value(v)
index = @values.index(v)
if index
return [email protected]_at(index).nil?
else
return false
end
end | ruby | def remove_value(v)
index = @values.index(v)
if index
return [email protected]_at(index).nil?
else
return false
end
end | [
"def",
"remove_value",
"(",
"v",
")",
"index",
"=",
"@values",
".",
"index",
"(",
"v",
")",
"if",
"index",
"return",
"!",
"@values",
".",
"delete_at",
"(",
"index",
")",
".",
"nil?",
"else",
"return",
"false",
"end",
"end"
] | Removes the first occurence of the specified value from this Tag.
_v_:: The value to remove
Returns true If the value exists and is removed | [
"Removes",
"the",
"first",
"occurence",
"of",
"the",
"specified",
"value",
"from",
"this",
"Tag",
"."
] | 1663b9f5aa95d8d6269f060e343c2d2fd9309259 | https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L457-L464 | train |
ikayzo/SDL.rb | lib/sdl4r/tag.rb | SDL4R.Tag.has_attribute? | def has_attribute?(namespace = nil, key = nil)
namespace, key = to_nns namespace, key
if namespace or key
attributes = @attributesByNamespace[namespace]
return attributes.nil? ? false : attributes.has_key?(key)
else
attributes { return true }
return false
end
end | ruby | def has_attribute?(namespace = nil, key = nil)
namespace, key = to_nns namespace, key
if namespace or key
attributes = @attributesByNamespace[namespace]
return attributes.nil? ? false : attributes.has_key?(key)
else
attributes { return true }
return false
end
end | [
"def",
"has_attribute?",
"(",
"namespace",
"=",
"nil",
",",
"key",
"=",
"nil",
")",
"namespace",
",",
"key",
"=",
"to_nns",
"namespace",
",",
"key",
"if",
"namespace",
"or",
"key",
"attributes",
"=",
"@attributesByNamespace",
"[",
"namespace",
"]",
"return",
"attributes",
".",
"nil?",
"?",
"false",
":",
"attributes",
".",
"has_key?",
"(",
"key",
")",
"else",
"attributes",
"{",
"return",
"true",
"}",
"return",
"false",
"end",
"end"
] | Indicates whether there is at least an attribute in this Tag.
has_attribute?
Indicates whether there is the specified attribute exists in this Tag.
has_attribute?(key)
has_attribute?(namespace, key) | [
"Indicates",
"whether",
"there",
"is",
"at",
"least",
"an",
"attribute",
"in",
"this",
"Tag",
".",
"has_attribute?"
] | 1663b9f5aa95d8d6269f060e343c2d2fd9309259 | https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L559-L570 | train |
ikayzo/SDL.rb | lib/sdl4r/tag.rb | SDL4R.Tag.each_attribute | def each_attribute(namespace = nil, &block) # :yields: namespace, key, value
if namespace.nil?
@attributesByNamespace.each_key { |a_namespace| each_attribute(a_namespace, &block) }
else
attributes = @attributesByNamespace[namespace]
unless attributes.nil?
attributes.each_pair do |key, value|
yield namespace, key, value
end
end
end
end | ruby | def each_attribute(namespace = nil, &block) # :yields: namespace, key, value
if namespace.nil?
@attributesByNamespace.each_key { |a_namespace| each_attribute(a_namespace, &block) }
else
attributes = @attributesByNamespace[namespace]
unless attributes.nil?
attributes.each_pair do |key, value|
yield namespace, key, value
end
end
end
end | [
"def",
"each_attribute",
"(",
"namespace",
"=",
"nil",
",",
"&",
"block",
")",
"# :yields: namespace, key, value",
"if",
"namespace",
".",
"nil?",
"@attributesByNamespace",
".",
"each_key",
"{",
"|",
"a_namespace",
"|",
"each_attribute",
"(",
"a_namespace",
",",
"block",
")",
"}",
"else",
"attributes",
"=",
"@attributesByNamespace",
"[",
"namespace",
"]",
"unless",
"attributes",
".",
"nil?",
"attributes",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"yield",
"namespace",
",",
"key",
",",
"value",
"end",
"end",
"end",
"end"
] | Enumerates the attributes for the specified +namespace+.
Enumerates all the attributes by default. | [
"Enumerates",
"the",
"attributes",
"for",
"the",
"specified",
"+",
"namespace",
"+",
".",
"Enumerates",
"all",
"the",
"attributes",
"by",
"default",
"."
] | 1663b9f5aa95d8d6269f060e343c2d2fd9309259 | https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L635-L647 | train |
ikayzo/SDL.rb | lib/sdl4r/tag.rb | SDL4R.Tag.namespace= | def namespace=(a_namespace)
a_namespace = a_namespace.to_s
SDL4R.validate_identifier(a_namespace) unless a_namespace.empty?
@namespace = a_namespace
end | ruby | def namespace=(a_namespace)
a_namespace = a_namespace.to_s
SDL4R.validate_identifier(a_namespace) unless a_namespace.empty?
@namespace = a_namespace
end | [
"def",
"namespace",
"=",
"(",
"a_namespace",
")",
"a_namespace",
"=",
"a_namespace",
".",
"to_s",
"SDL4R",
".",
"validate_identifier",
"(",
"a_namespace",
")",
"unless",
"a_namespace",
".",
"empty?",
"@namespace",
"=",
"a_namespace",
"end"
] | The namespace to set. +nil+ will be coerced to the empty string.
Raises +ArgumentError+ if the namespace is non-blank and is not
a legal SDL identifier (see SDL4R#validate_identifier) | [
"The",
"namespace",
"to",
"set",
".",
"+",
"nil",
"+",
"will",
"be",
"coerced",
"to",
"the",
"empty",
"string",
"."
] | 1663b9f5aa95d8d6269f060e343c2d2fd9309259 | https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L707-L711 | train |
ikayzo/SDL.rb | lib/sdl4r/tag.rb | SDL4R.Tag.read | def read(input)
if input.is_a? String
read_from_io(true) { StringIO.new(input) }
elsif input.is_a? Pathname
read_from_io(true) { input.open("r:UTF-8") }
elsif input.is_a? URI
read_from_io(true) { input.open }
else
read_from_io(false) { input }
end
return self
end | ruby | def read(input)
if input.is_a? String
read_from_io(true) { StringIO.new(input) }
elsif input.is_a? Pathname
read_from_io(true) { input.open("r:UTF-8") }
elsif input.is_a? URI
read_from_io(true) { input.open }
else
read_from_io(false) { input }
end
return self
end | [
"def",
"read",
"(",
"input",
")",
"if",
"input",
".",
"is_a?",
"String",
"read_from_io",
"(",
"true",
")",
"{",
"StringIO",
".",
"new",
"(",
"input",
")",
"}",
"elsif",
"input",
".",
"is_a?",
"Pathname",
"read_from_io",
"(",
"true",
")",
"{",
"input",
".",
"open",
"(",
"\"r:UTF-8\"",
")",
"}",
"elsif",
"input",
".",
"is_a?",
"URI",
"read_from_io",
"(",
"true",
")",
"{",
"input",
".",
"open",
"}",
"else",
"read_from_io",
"(",
"false",
")",
"{",
"input",
"}",
"end",
"return",
"self",
"end"
] | Adds all the tags specified in the given IO, String, Pathname or URI to this Tag.
Returns this Tag after adding all the children read from +input+. | [
"Adds",
"all",
"the",
"tags",
"specified",
"in",
"the",
"given",
"IO",
"String",
"Pathname",
"or",
"URI",
"to",
"this",
"Tag",
"."
] | 1663b9f5aa95d8d6269f060e343c2d2fd9309259 | https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L717-L732 | train |
ikayzo/SDL.rb | lib/sdl4r/tag.rb | SDL4R.Tag.read_from_io | def read_from_io(close_io)
io = yield
begin
Parser.new(io).parse.each do |tag|
add_child(tag)
end
ensure
if close_io
io.close rescue IOError
end
end
end | ruby | def read_from_io(close_io)
io = yield
begin
Parser.new(io).parse.each do |tag|
add_child(tag)
end
ensure
if close_io
io.close rescue IOError
end
end
end | [
"def",
"read_from_io",
"(",
"close_io",
")",
"io",
"=",
"yield",
"begin",
"Parser",
".",
"new",
"(",
"io",
")",
".",
"parse",
".",
"each",
"do",
"|",
"tag",
"|",
"add_child",
"(",
"tag",
")",
"end",
"ensure",
"if",
"close_io",
"io",
".",
"close",
"rescue",
"IOError",
"end",
"end",
"end"
] | Reads and parses the +io+ returned by the specified block and closes this +io+ if +close_io+
is true. | [
"Reads",
"and",
"parses",
"the",
"+",
"io",
"+",
"returned",
"by",
"the",
"specified",
"block",
"and",
"closes",
"this",
"+",
"io",
"+",
"if",
"+",
"close_io",
"+",
"is",
"true",
"."
] | 1663b9f5aa95d8d6269f060e343c2d2fd9309259 | https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L736-L749 | train |
ikayzo/SDL.rb | lib/sdl4r/tag.rb | SDL4R.Tag.children_to_string | def children_to_string(line_prefix = "", s = "")
@children.each do |child|
s << child.to_string(line_prefix) << $/
end
return s
end | ruby | def children_to_string(line_prefix = "", s = "")
@children.each do |child|
s << child.to_string(line_prefix) << $/
end
return s
end | [
"def",
"children_to_string",
"(",
"line_prefix",
"=",
"\"\"",
",",
"s",
"=",
"\"\"",
")",
"@children",
".",
"each",
"do",
"|",
"child",
"|",
"s",
"<<",
"child",
".",
"to_string",
"(",
"line_prefix",
")",
"<<",
"$/",
"end",
"return",
"s",
"end"
] | Returns a string representation of the children tags.
_linePrefix_:: A prefix to insert before every line.
_s_:: a String that receives the string representation
TODO: break up long lines using the backslash | [
"Returns",
"a",
"string",
"representation",
"of",
"the",
"children",
"tags",
"."
] | 1663b9f5aa95d8d6269f060e343c2d2fd9309259 | https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L858-L864 | train |
charypar/cyclical | lib/cyclical/occurrence.rb | Cyclical.Occurrence.list_occurrences | def list_occurrences(from, direction = :forward, &block)
raise ArgumentError, "From #{from} not matching the rule #{@rule} and start time #{@start_time}" unless @rule.match?(from, @start_time)
results = []
n, current = init_loop(from, direction)
loop do
# Rails.logger.debug("Listing occurrences of #{@rule}, going #{direction.to_s}, current: #{current}")
# break on schedule span limits
return results unless (current >= @start_time) && (@rule.stop.nil? || current < @rule.stop) && (@rule.count.nil? || (n -= 1) >= 0)
# break on block condition
return results unless yield current
results << current
# step
if direction == :forward
current = @rule.next(current, @start_time)
else
current = @rule.previous(current, @start_time)
end
end
end | ruby | def list_occurrences(from, direction = :forward, &block)
raise ArgumentError, "From #{from} not matching the rule #{@rule} and start time #{@start_time}" unless @rule.match?(from, @start_time)
results = []
n, current = init_loop(from, direction)
loop do
# Rails.logger.debug("Listing occurrences of #{@rule}, going #{direction.to_s}, current: #{current}")
# break on schedule span limits
return results unless (current >= @start_time) && (@rule.stop.nil? || current < @rule.stop) && (@rule.count.nil? || (n -= 1) >= 0)
# break on block condition
return results unless yield current
results << current
# step
if direction == :forward
current = @rule.next(current, @start_time)
else
current = @rule.previous(current, @start_time)
end
end
end | [
"def",
"list_occurrences",
"(",
"from",
",",
"direction",
"=",
":forward",
",",
"&",
"block",
")",
"raise",
"ArgumentError",
",",
"\"From #{from} not matching the rule #{@rule} and start time #{@start_time}\"",
"unless",
"@rule",
".",
"match?",
"(",
"from",
",",
"@start_time",
")",
"results",
"=",
"[",
"]",
"n",
",",
"current",
"=",
"init_loop",
"(",
"from",
",",
"direction",
")",
"loop",
"do",
"# Rails.logger.debug(\"Listing occurrences of #{@rule}, going #{direction.to_s}, current: #{current}\")",
"# break on schedule span limits",
"return",
"results",
"unless",
"(",
"current",
">=",
"@start_time",
")",
"&&",
"(",
"@rule",
".",
"stop",
".",
"nil?",
"||",
"current",
"<",
"@rule",
".",
"stop",
")",
"&&",
"(",
"@rule",
".",
"count",
".",
"nil?",
"||",
"(",
"n",
"-=",
"1",
")",
">=",
"0",
")",
"# break on block condition",
"return",
"results",
"unless",
"yield",
"current",
"results",
"<<",
"current",
"# step",
"if",
"direction",
"==",
":forward",
"current",
"=",
"@rule",
".",
"next",
"(",
"current",
",",
"@start_time",
")",
"else",
"current",
"=",
"@rule",
".",
"previous",
"(",
"current",
",",
"@start_time",
")",
"end",
"end",
"end"
] | yields valid occurrences, return false from the block to stop | [
"yields",
"valid",
"occurrences",
"return",
"false",
"from",
"the",
"block",
"to",
"stop"
] | 8e45b8f83e2dd59fcad01e220412bb361867f5c6 | https://github.com/charypar/cyclical/blob/8e45b8f83e2dd59fcad01e220412bb361867f5c6/lib/cyclical/occurrence.rb#L70-L93 | train |
sanichi/icu_tournament | lib/icu_tournament/team.rb | ICU.Team.add_member | def add_member(number)
pnum = number.to_i
raise "'#{number}' is not a valid as a team member player number" if pnum == 0 && !number.to_s.match(/^[^\d]*0/)
raise "can't add duplicate player number #{pnum} to team '#{@name}'" if @members.include?(pnum)
@members.push(pnum)
end | ruby | def add_member(number)
pnum = number.to_i
raise "'#{number}' is not a valid as a team member player number" if pnum == 0 && !number.to_s.match(/^[^\d]*0/)
raise "can't add duplicate player number #{pnum} to team '#{@name}'" if @members.include?(pnum)
@members.push(pnum)
end | [
"def",
"add_member",
"(",
"number",
")",
"pnum",
"=",
"number",
".",
"to_i",
"raise",
"\"'#{number}' is not a valid as a team member player number\"",
"if",
"pnum",
"==",
"0",
"&&",
"!",
"number",
".",
"to_s",
".",
"match",
"(",
"/",
"\\d",
"/",
")",
"raise",
"\"can't add duplicate player number #{pnum} to team '#{@name}'\"",
"if",
"@members",
".",
"include?",
"(",
"pnum",
")",
"@members",
".",
"push",
"(",
"pnum",
")",
"end"
] | Add a team member referenced by any integer. | [
"Add",
"a",
"team",
"member",
"referenced",
"by",
"any",
"integer",
"."
] | badd2940189feaeb9f0edb4b4e07ff6b2548bd3d | https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/team.rb#L57-L62 | train |
sanichi/icu_tournament | lib/icu_tournament/team.rb | ICU.Team.renumber | def renumber(map)
@members.each_with_index do |pnum, index|
raise "player number #{pnum} not found in renumbering hash" unless map[pnum]
@members[index] = map[pnum]
end
self
end | ruby | def renumber(map)
@members.each_with_index do |pnum, index|
raise "player number #{pnum} not found in renumbering hash" unless map[pnum]
@members[index] = map[pnum]
end
self
end | [
"def",
"renumber",
"(",
"map",
")",
"@members",
".",
"each_with_index",
"do",
"|",
"pnum",
",",
"index",
"|",
"raise",
"\"player number #{pnum} not found in renumbering hash\"",
"unless",
"map",
"[",
"pnum",
"]",
"@members",
"[",
"index",
"]",
"=",
"map",
"[",
"pnum",
"]",
"end",
"self",
"end"
] | Renumber the players according to the supplied hash. Return self. | [
"Renumber",
"the",
"players",
"according",
"to",
"the",
"supplied",
"hash",
".",
"Return",
"self",
"."
] | badd2940189feaeb9f0edb4b4e07ff6b2548bd3d | https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/team.rb#L65-L71 | train |
mswart/cany | lib/cany/dependency.rb | Cany.Dependency.define_on_distro_release | def define_on_distro_release(distro, release, name, version=nil)
distro_releases[[distro, release]] << [name, version]
end | ruby | def define_on_distro_release(distro, release, name, version=nil)
distro_releases[[distro, release]] << [name, version]
end | [
"def",
"define_on_distro_release",
"(",
"distro",
",",
"release",
",",
"name",
",",
"version",
"=",
"nil",
")",
"distro_releases",
"[",
"[",
"distro",
",",
"release",
"]",
"]",
"<<",
"[",
"name",
",",
"version",
"]",
"end"
] | Define the package name and an optional version constraint for a distribution release
@param distro[Symbol] The distribution name like :ubuntu, :debian ...
@param release[Symbol] The distribution release like :precise for ubuntu 12.04
@param name[String] A package name
@param version[String, nil] A version constraint | [
"Define",
"the",
"package",
"name",
"and",
"an",
"optional",
"version",
"constraint",
"for",
"a",
"distribution",
"release"
] | 0d2bf4d3704d4e9a222b11f6d764b57234ddf36d | https://github.com/mswart/cany/blob/0d2bf4d3704d4e9a222b11f6d764b57234ddf36d/lib/cany/dependency.rb#L51-L53 | train |
jwtd/xively-rb-connector | lib/xively-rb-connector/connection.rb | XivelyConnector.Connection.set_httparty_options | def set_httparty_options(options={})
if options[:ssl_ca_file]
ssl_ca_file opts[:ssl_ca_file]
if options[:pem_cert_pass]
pem File.read(options[:pem_cert]), options[:pem_cert_pass]
else
pem File.read(options[:pem_cert])
end
end
end | ruby | def set_httparty_options(options={})
if options[:ssl_ca_file]
ssl_ca_file opts[:ssl_ca_file]
if options[:pem_cert_pass]
pem File.read(options[:pem_cert]), options[:pem_cert_pass]
else
pem File.read(options[:pem_cert])
end
end
end | [
"def",
"set_httparty_options",
"(",
"options",
"=",
"{",
"}",
")",
"if",
"options",
"[",
":ssl_ca_file",
"]",
"ssl_ca_file",
"opts",
"[",
":ssl_ca_file",
"]",
"if",
"options",
"[",
":pem_cert_pass",
"]",
"pem",
"File",
".",
"read",
"(",
"options",
"[",
":pem_cert",
"]",
")",
",",
"options",
"[",
":pem_cert_pass",
"]",
"else",
"pem",
"File",
".",
"read",
"(",
"options",
"[",
":pem_cert",
"]",
")",
"end",
"end",
"end"
] | Set HTTParty params that we need to set after initialize is called
These params come from @options within initialize and include the following:
:ssl_ca_file - SSL CA File for SSL connections
:format - 'json', 'xml', 'html', etc. || Defaults to 'xml'
:format_header - :format Header string || Defaults to 'application/xml'
:pem_cert - /path/to/a/pem_formatted_certificate.pem for SSL connections
:pem_cert_pass - plaintext password, not recommended! | [
"Set",
"HTTParty",
"params",
"that",
"we",
"need",
"to",
"set",
"after",
"initialize",
"is",
"called",
"These",
"params",
"come",
"from"
] | 014c2e08d2857e67d65103b84ba23a91569baecb | https://github.com/jwtd/xively-rb-connector/blob/014c2e08d2857e67d65103b84ba23a91569baecb/lib/xively-rb-connector/connection.rb#L29-L38 | train |
nsi-iff/nsicloudooo-ruby | lib/nsicloudooo/client.rb | NSICloudooo.Client.granulate | def granulate(options = {})
@request_data = Hash.new
if options[:doc_link]
insert_download_data options
else
file_data = {:doc => options[:file], :filename => options[:filename]}
@request_data.merge! file_data
end
insert_callback_data options
request = prepare_request :POST, @request_data.to_json
execute_request(request)
end | ruby | def granulate(options = {})
@request_data = Hash.new
if options[:doc_link]
insert_download_data options
else
file_data = {:doc => options[:file], :filename => options[:filename]}
@request_data.merge! file_data
end
insert_callback_data options
request = prepare_request :POST, @request_data.to_json
execute_request(request)
end | [
"def",
"granulate",
"(",
"options",
"=",
"{",
"}",
")",
"@request_data",
"=",
"Hash",
".",
"new",
"if",
"options",
"[",
":doc_link",
"]",
"insert_download_data",
"options",
"else",
"file_data",
"=",
"{",
":doc",
"=>",
"options",
"[",
":file",
"]",
",",
":filename",
"=>",
"options",
"[",
":filename",
"]",
"}",
"@request_data",
".",
"merge!",
"file_data",
"end",
"insert_callback_data",
"options",
"request",
"=",
"prepare_request",
":POST",
",",
"@request_data",
".",
"to_json",
"execute_request",
"(",
"request",
")",
"end"
] | Send a document be granulated by a nsi.cloudooo node
@param [Hash] options used to send a document to be graulated
@option options [String] file the base64 encoded file to be granulated
@option options [String] filename the filename of the document
@note the filename is very importante, the cloudooo node will convert the document based on its filename, if necessary
@option options [String] doc_link link to the document that'll be granulated
@note if provided both doc_link and file options, file will be ignored and the client will download the document instead
@option options [String] callback a callback url to the file granulation
@option options [String] verb the callback request verb, when not provided, nsi.cloudooo default to POST
@example A simple granulation
doc = Base64.encode64(File.new('document.odt', 'r').read)
nsicloudooo.granulate(:file => doc, :filename => 'document.odt')
@example Downloading and granulating from web
nsicloudooo.granulate(:doc_link => 'http://google.com/document.odt')
@example Sending a callback url
doc = Base64.encode64(File.new('document.odt', 'r').read)
nsicloudooo.granulate(:file => doc, :filename => 'document.odt', :callback => 'http://google.com')
nsicloudooo.granulate(:doc_link => 'http://google.com/document.odt', :callback => 'http://google.com')
@example Using a custom verb to the callback
doc = Base64.encode64(File.new('document.odt', 'r').read)
nsicloudooo.granulate(:file => doc, :filename => 'document.odt', :callback => 'http://google.com', :verb => "PUT")
nsicloudooo.granulate(:doc_link => 'http://google.com/document.odt', :callback => 'http://google.com', :verb => "PUT")
@return [Hash] response
* "key" [String] the key to access the granulated document if the sam node it was stored | [
"Send",
"a",
"document",
"be",
"granulated",
"by",
"a",
"nsi",
".",
"cloudooo",
"node"
] | 5cd92a0906187fa7da59d63d32608f99e22fa71d | https://github.com/nsi-iff/nsicloudooo-ruby/blob/5cd92a0906187fa7da59d63d32608f99e22fa71d/lib/nsicloudooo/client.rb#L42-L53 | train |
teodor-pripoae/scalaroid | lib/scalaroid/json_req_list.rb | Scalaroid.JSONReqList.add_write | def add_write(key, value, binary = false)
if (@is_commit)
raise RuntimeError.new('No further request supported after a commit!')
end
@requests << {'write' => {key => JSONConnection.encode_value(value, binary)}}
self
end | ruby | def add_write(key, value, binary = false)
if (@is_commit)
raise RuntimeError.new('No further request supported after a commit!')
end
@requests << {'write' => {key => JSONConnection.encode_value(value, binary)}}
self
end | [
"def",
"add_write",
"(",
"key",
",",
"value",
",",
"binary",
"=",
"false",
")",
"if",
"(",
"@is_commit",
")",
"raise",
"RuntimeError",
".",
"new",
"(",
"'No further request supported after a commit!'",
")",
"end",
"@requests",
"<<",
"{",
"'write'",
"=>",
"{",
"key",
"=>",
"JSONConnection",
".",
"encode_value",
"(",
"value",
",",
"binary",
")",
"}",
"}",
"self",
"end"
] | Adds a write operation to the request list. | [
"Adds",
"a",
"write",
"operation",
"to",
"the",
"request",
"list",
"."
] | 4e9e90e71ce3008da79a72eae40fe2f187580be2 | https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/json_req_list.rb#L23-L29 | train |
teodor-pripoae/scalaroid | lib/scalaroid/json_req_list.rb | Scalaroid.JSONReqList.add_add_del_on_list | def add_add_del_on_list(key, to_add, to_remove)
if (@is_commit)
raise RuntimeError.new('No further request supported after a commit!')
end
@requests << {'add_del_on_list' => {'key' => key, 'add' => to_add, 'del'=> to_remove}}
self
end | ruby | def add_add_del_on_list(key, to_add, to_remove)
if (@is_commit)
raise RuntimeError.new('No further request supported after a commit!')
end
@requests << {'add_del_on_list' => {'key' => key, 'add' => to_add, 'del'=> to_remove}}
self
end | [
"def",
"add_add_del_on_list",
"(",
"key",
",",
"to_add",
",",
"to_remove",
")",
"if",
"(",
"@is_commit",
")",
"raise",
"RuntimeError",
".",
"new",
"(",
"'No further request supported after a commit!'",
")",
"end",
"@requests",
"<<",
"{",
"'add_del_on_list'",
"=>",
"{",
"'key'",
"=>",
"key",
",",
"'add'",
"=>",
"to_add",
",",
"'del'",
"=>",
"to_remove",
"}",
"}",
"self",
"end"
] | Adds a add_del_on_list operation to the request list. | [
"Adds",
"a",
"add_del_on_list",
"operation",
"to",
"the",
"request",
"list",
"."
] | 4e9e90e71ce3008da79a72eae40fe2f187580be2 | https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/json_req_list.rb#L32-L38 | train |
mark-d-holmberg/handcart | lib/handcart/controller_additions.rb | Handcart.ControllerAdditions.allow_or_reject | def allow_or_reject
# We assume the the rejection action is going to be on the public controller
# since we wouldn't want to forward the rejection to the handcart
my_rejection_url = main_app.url_for({
# subdomain: '',
host: Handcart::DomainConstraint.default_constraint.domain,
controller: @rejection_url.split("#").first,
action: @rejection_url.split("#").last,
trailing_slash: false,
})
# See if they have enable IP blocking if they respond to that.
if current_handcart.respond_to?(:enable_ip_blocking?)
truthiness = current_handcart.enable_ip_blocking?
else
# Default to true
truthiness = true
end
if truthiness
ip_address = current_handcart.ip_addresses.permitted.find_by_address(request.remote_ip)
if ip_address
if Handcart.ip_authorization.strategy.is_in_range?(ip_address.address, current_handcart)
# Do nothing, let them login
else
# # The strategy doesn't match
redirect_to my_rejection_url
end
else
# No IP Address was found
redirect_to my_rejection_url
end
else
# Do nothing, blocking mode is disabled
end
end | ruby | def allow_or_reject
# We assume the the rejection action is going to be on the public controller
# since we wouldn't want to forward the rejection to the handcart
my_rejection_url = main_app.url_for({
# subdomain: '',
host: Handcart::DomainConstraint.default_constraint.domain,
controller: @rejection_url.split("#").first,
action: @rejection_url.split("#").last,
trailing_slash: false,
})
# See if they have enable IP blocking if they respond to that.
if current_handcart.respond_to?(:enable_ip_blocking?)
truthiness = current_handcart.enable_ip_blocking?
else
# Default to true
truthiness = true
end
if truthiness
ip_address = current_handcart.ip_addresses.permitted.find_by_address(request.remote_ip)
if ip_address
if Handcart.ip_authorization.strategy.is_in_range?(ip_address.address, current_handcart)
# Do nothing, let them login
else
# # The strategy doesn't match
redirect_to my_rejection_url
end
else
# No IP Address was found
redirect_to my_rejection_url
end
else
# Do nothing, blocking mode is disabled
end
end | [
"def",
"allow_or_reject",
"# We assume the the rejection action is going to be on the public controller",
"# since we wouldn't want to forward the rejection to the handcart",
"my_rejection_url",
"=",
"main_app",
".",
"url_for",
"(",
"{",
"# subdomain: '',",
"host",
":",
"Handcart",
"::",
"DomainConstraint",
".",
"default_constraint",
".",
"domain",
",",
"controller",
":",
"@rejection_url",
".",
"split",
"(",
"\"#\"",
")",
".",
"first",
",",
"action",
":",
"@rejection_url",
".",
"split",
"(",
"\"#\"",
")",
".",
"last",
",",
"trailing_slash",
":",
"false",
",",
"}",
")",
"# See if they have enable IP blocking if they respond to that.",
"if",
"current_handcart",
".",
"respond_to?",
"(",
":enable_ip_blocking?",
")",
"truthiness",
"=",
"current_handcart",
".",
"enable_ip_blocking?",
"else",
"# Default to true",
"truthiness",
"=",
"true",
"end",
"if",
"truthiness",
"ip_address",
"=",
"current_handcart",
".",
"ip_addresses",
".",
"permitted",
".",
"find_by_address",
"(",
"request",
".",
"remote_ip",
")",
"if",
"ip_address",
"if",
"Handcart",
".",
"ip_authorization",
".",
"strategy",
".",
"is_in_range?",
"(",
"ip_address",
".",
"address",
",",
"current_handcart",
")",
"# Do nothing, let them login",
"else",
"# # The strategy doesn't match",
"redirect_to",
"my_rejection_url",
"end",
"else",
"# No IP Address was found",
"redirect_to",
"my_rejection_url",
"end",
"else",
"# Do nothing, blocking mode is disabled",
"end",
"end"
] | Don't allow unauthorized or blacklisted foreign IP addresses to hit
what we assume is the session controller for the franchisee. | [
"Don",
"t",
"allow",
"unauthorized",
"or",
"blacklisted",
"foreign",
"IP",
"addresses",
"to",
"hit",
"what",
"we",
"assume",
"is",
"the",
"session",
"controller",
"for",
"the",
"franchisee",
"."
] | 9f9c7484db007066357c71c9c50f3342aab59c11 | https://github.com/mark-d-holmberg/handcart/blob/9f9c7484db007066357c71c9c50f3342aab59c11/lib/handcart/controller_additions.rb#L108-L143 | train |
ossuarium/palimpsest | lib/palimpsest/environment.rb | Palimpsest.Environment.copy | def copy(destination: site.path, mirror: false)
fail 'Must specify a destination' if destination.nil?
exclude = options[:copy_exclude]
exclude.concat config[:persistent] unless config[:persistent].nil?
Utils.copy_directory directory, destination, exclude: exclude, mirror: mirror
self
end | ruby | def copy(destination: site.path, mirror: false)
fail 'Must specify a destination' if destination.nil?
exclude = options[:copy_exclude]
exclude.concat config[:persistent] unless config[:persistent].nil?
Utils.copy_directory directory, destination, exclude: exclude, mirror: mirror
self
end | [
"def",
"copy",
"(",
"destination",
":",
"site",
".",
"path",
",",
"mirror",
":",
"false",
")",
"fail",
"'Must specify a destination'",
"if",
"destination",
".",
"nil?",
"exclude",
"=",
"options",
"[",
":copy_exclude",
"]",
"exclude",
".",
"concat",
"config",
"[",
":persistent",
"]",
"unless",
"config",
"[",
":persistent",
"]",
".",
"nil?",
"Utils",
".",
"copy_directory",
"directory",
",",
"destination",
",",
"exclude",
":",
"exclude",
",",
"mirror",
":",
"mirror",
"self",
"end"
] | Copy the contents of the working directory.
@param destination [String] path to copy environment's files to
@param mirror [Boolean] remove any non-excluded paths from destination
@return [Environment] the current environment instance | [
"Copy",
"the",
"contents",
"of",
"the",
"working",
"directory",
"."
] | 7a1d45d33ec7ed878e2b761150ec163ce2125274 | https://github.com/ossuarium/palimpsest/blob/7a1d45d33ec7ed878e2b761150ec163ce2125274/lib/palimpsest/environment.rb#L211-L217 | train |
ossuarium/palimpsest | lib/palimpsest/environment.rb | Palimpsest.Environment.populate | def populate(from: :auto)
return if populated
fail "Cannot populate without 'site'" if site.nil?
case from
when :auto
if site.respond_to?(:repository) ? site.repository : nil
populate from: :repository
else
populate from: :source
end
when :repository
fail "Cannot populate without 'reference'" if reference.empty?
repo.extract directory, reference: reference
@populated = true
when :source
source = site.source.nil? ? '.' : site.source
Utils.copy_directory source, directory, exclude: options[:copy_exclude]
@populated = true
end
self
end | ruby | def populate(from: :auto)
return if populated
fail "Cannot populate without 'site'" if site.nil?
case from
when :auto
if site.respond_to?(:repository) ? site.repository : nil
populate from: :repository
else
populate from: :source
end
when :repository
fail "Cannot populate without 'reference'" if reference.empty?
repo.extract directory, reference: reference
@populated = true
when :source
source = site.source.nil? ? '.' : site.source
Utils.copy_directory source, directory, exclude: options[:copy_exclude]
@populated = true
end
self
end | [
"def",
"populate",
"(",
"from",
":",
":auto",
")",
"return",
"if",
"populated",
"fail",
"\"Cannot populate without 'site'\"",
"if",
"site",
".",
"nil?",
"case",
"from",
"when",
":auto",
"if",
"site",
".",
"respond_to?",
"(",
":repository",
")",
"?",
"site",
".",
"repository",
":",
"nil",
"populate",
"from",
":",
":repository",
"else",
"populate",
"from",
":",
":source",
"end",
"when",
":repository",
"fail",
"\"Cannot populate without 'reference'\"",
"if",
"reference",
".",
"empty?",
"repo",
".",
"extract",
"directory",
",",
"reference",
":",
"reference",
"@populated",
"=",
"true",
"when",
":source",
"source",
"=",
"site",
".",
"source",
".",
"nil?",
"?",
"'.'",
":",
"site",
".",
"source",
"Utils",
".",
"copy_directory",
"source",
",",
"directory",
",",
"exclude",
":",
"options",
"[",
":copy_exclude",
"]",
"@populated",
"=",
"true",
"end",
"self",
"end"
] | Extracts the site's files from repository to the working directory.
@return [Environment] the current environment instance | [
"Extracts",
"the",
"site",
"s",
"files",
"from",
"repository",
"to",
"the",
"working",
"directory",
"."
] | 7a1d45d33ec7ed878e2b761150ec163ce2125274 | https://github.com/ossuarium/palimpsest/blob/7a1d45d33ec7ed878e2b761150ec163ce2125274/lib/palimpsest/environment.rb#L233-L255 | train |
ossuarium/palimpsest | lib/palimpsest/environment.rb | Palimpsest.Environment.validate_config | def validate_config
message = 'bad path in config'
# Checks the option in the asset key.
def validate_asset_options(opts)
opts.each do |k, v|
fail 'bad option in config' if k == :sprockets_options
fail message if k == :output && !Utils.safe_path?(v)
end
end
@config[:excludes].each do |v|
fail message unless Utils.safe_path? v
end unless @config[:excludes].nil?
@config[:external].each do |k, v|
next if k == :server
v.each do |repo|
fail message unless Utils.safe_path? repo[1]
end unless v.nil?
end unless @config[:external].nil?
@config[:components].each do |k, v|
# process @config[:components][:base] then go to the next option
if k == :base
fail message unless Utils.safe_path? v
next
end unless v.nil?
# process @config[:components][:paths]
if k == :paths
v.each do |path|
fail message unless Utils.safe_path? path[0]
fail message unless Utils.safe_path? path[1]
end
end
end unless @config[:components].nil?
@config[:assets].each do |k, v|
# process @config[:assets][:options] then go to the next option
if k == :options
validate_asset_options v
next
end unless v.nil?
# process @config[:assets][:sources] then go to the next option
if k == :sources
v.each_with_index do |source, _|
fail message unless Utils.safe_path? source
end
next
end
# process each asset type in @config[:assets]
v.each do |asset_key, asset_value|
# process :options
if asset_key == :options
validate_asset_options asset_value
next
end unless asset_value.nil?
# process each asset path
asset_value.each_with_index do |path, _|
fail message unless Utils.safe_path? path
end if asset_key == :paths
end
end unless @config[:assets].nil?
@config
end | ruby | def validate_config
message = 'bad path in config'
# Checks the option in the asset key.
def validate_asset_options(opts)
opts.each do |k, v|
fail 'bad option in config' if k == :sprockets_options
fail message if k == :output && !Utils.safe_path?(v)
end
end
@config[:excludes].each do |v|
fail message unless Utils.safe_path? v
end unless @config[:excludes].nil?
@config[:external].each do |k, v|
next if k == :server
v.each do |repo|
fail message unless Utils.safe_path? repo[1]
end unless v.nil?
end unless @config[:external].nil?
@config[:components].each do |k, v|
# process @config[:components][:base] then go to the next option
if k == :base
fail message unless Utils.safe_path? v
next
end unless v.nil?
# process @config[:components][:paths]
if k == :paths
v.each do |path|
fail message unless Utils.safe_path? path[0]
fail message unless Utils.safe_path? path[1]
end
end
end unless @config[:components].nil?
@config[:assets].each do |k, v|
# process @config[:assets][:options] then go to the next option
if k == :options
validate_asset_options v
next
end unless v.nil?
# process @config[:assets][:sources] then go to the next option
if k == :sources
v.each_with_index do |source, _|
fail message unless Utils.safe_path? source
end
next
end
# process each asset type in @config[:assets]
v.each do |asset_key, asset_value|
# process :options
if asset_key == :options
validate_asset_options asset_value
next
end unless asset_value.nil?
# process each asset path
asset_value.each_with_index do |path, _|
fail message unless Utils.safe_path? path
end if asset_key == :paths
end
end unless @config[:assets].nil?
@config
end | [
"def",
"validate_config",
"message",
"=",
"'bad path in config'",
"# Checks the option in the asset key.",
"def",
"validate_asset_options",
"(",
"opts",
")",
"opts",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"fail",
"'bad option in config'",
"if",
"k",
"==",
":sprockets_options",
"fail",
"message",
"if",
"k",
"==",
":output",
"&&",
"!",
"Utils",
".",
"safe_path?",
"(",
"v",
")",
"end",
"end",
"@config",
"[",
":excludes",
"]",
".",
"each",
"do",
"|",
"v",
"|",
"fail",
"message",
"unless",
"Utils",
".",
"safe_path?",
"v",
"end",
"unless",
"@config",
"[",
":excludes",
"]",
".",
"nil?",
"@config",
"[",
":external",
"]",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"next",
"if",
"k",
"==",
":server",
"v",
".",
"each",
"do",
"|",
"repo",
"|",
"fail",
"message",
"unless",
"Utils",
".",
"safe_path?",
"repo",
"[",
"1",
"]",
"end",
"unless",
"v",
".",
"nil?",
"end",
"unless",
"@config",
"[",
":external",
"]",
".",
"nil?",
"@config",
"[",
":components",
"]",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"# process @config[:components][:base] then go to the next option",
"if",
"k",
"==",
":base",
"fail",
"message",
"unless",
"Utils",
".",
"safe_path?",
"v",
"next",
"end",
"unless",
"v",
".",
"nil?",
"# process @config[:components][:paths]",
"if",
"k",
"==",
":paths",
"v",
".",
"each",
"do",
"|",
"path",
"|",
"fail",
"message",
"unless",
"Utils",
".",
"safe_path?",
"path",
"[",
"0",
"]",
"fail",
"message",
"unless",
"Utils",
".",
"safe_path?",
"path",
"[",
"1",
"]",
"end",
"end",
"end",
"unless",
"@config",
"[",
":components",
"]",
".",
"nil?",
"@config",
"[",
":assets",
"]",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"# process @config[:assets][:options] then go to the next option",
"if",
"k",
"==",
":options",
"validate_asset_options",
"v",
"next",
"end",
"unless",
"v",
".",
"nil?",
"# process @config[:assets][:sources] then go to the next option",
"if",
"k",
"==",
":sources",
"v",
".",
"each_with_index",
"do",
"|",
"source",
",",
"_",
"|",
"fail",
"message",
"unless",
"Utils",
".",
"safe_path?",
"source",
"end",
"next",
"end",
"# process each asset type in @config[:assets]",
"v",
".",
"each",
"do",
"|",
"asset_key",
",",
"asset_value",
"|",
"# process :options",
"if",
"asset_key",
"==",
":options",
"validate_asset_options",
"asset_value",
"next",
"end",
"unless",
"asset_value",
".",
"nil?",
"# process each asset path",
"asset_value",
".",
"each_with_index",
"do",
"|",
"path",
",",
"_",
"|",
"fail",
"message",
"unless",
"Utils",
".",
"safe_path?",
"path",
"end",
"if",
"asset_key",
"==",
":paths",
"end",
"end",
"unless",
"@config",
"[",
":assets",
"]",
".",
"nil?",
"@config",
"end"
] | Checks the config file for invalid settings.
@todo Refactor this.
- Checks that paths are not absolute or use `../` or `~/`. | [
"Checks",
"the",
"config",
"file",
"for",
"invalid",
"settings",
"."
] | 7a1d45d33ec7ed878e2b761150ec163ce2125274 | https://github.com/ossuarium/palimpsest/blob/7a1d45d33ec7ed878e2b761150ec163ce2125274/lib/palimpsest/environment.rb#L408-L478 | train |
npepinpe/redstruct | lib/redstruct/time_series.rb | Redstruct.TimeSeries.get | def get(options = {})
lower = nil
upper = nil
if options[:in].nil?
lower = options[:after].nil? ? '-inf' : coerce_time_milli(options[:after])
upper = options[:before].nil? ? '+inf' : [0, coerce_time_milli(options[:before])].max
else
lower = coerce_time_milli(options[:in].begin)
upper = coerce_time_milli(options[:in].end)
upper = "(#{upper}" if options[:in].exclude_end?
end
argv = [expires_at, lower, upper]
unless options[:limit].nil?
limit = options[:limit].to_i
raise ArgumentError, 'limit must be positive' unless limit.positive?
argv.push(limit, [0, options[:offset].to_i].max)
end
events = get_script(keys: @event_list.key, argv: argv)
return events.map(&method(:remove_event_id))
end | ruby | def get(options = {})
lower = nil
upper = nil
if options[:in].nil?
lower = options[:after].nil? ? '-inf' : coerce_time_milli(options[:after])
upper = options[:before].nil? ? '+inf' : [0, coerce_time_milli(options[:before])].max
else
lower = coerce_time_milli(options[:in].begin)
upper = coerce_time_milli(options[:in].end)
upper = "(#{upper}" if options[:in].exclude_end?
end
argv = [expires_at, lower, upper]
unless options[:limit].nil?
limit = options[:limit].to_i
raise ArgumentError, 'limit must be positive' unless limit.positive?
argv.push(limit, [0, options[:offset].to_i].max)
end
events = get_script(keys: @event_list.key, argv: argv)
return events.map(&method(:remove_event_id))
end | [
"def",
"get",
"(",
"options",
"=",
"{",
"}",
")",
"lower",
"=",
"nil",
"upper",
"=",
"nil",
"if",
"options",
"[",
":in",
"]",
".",
"nil?",
"lower",
"=",
"options",
"[",
":after",
"]",
".",
"nil?",
"?",
"'-inf'",
":",
"coerce_time_milli",
"(",
"options",
"[",
":after",
"]",
")",
"upper",
"=",
"options",
"[",
":before",
"]",
".",
"nil?",
"?",
"'+inf'",
":",
"[",
"0",
",",
"coerce_time_milli",
"(",
"options",
"[",
":before",
"]",
")",
"]",
".",
"max",
"else",
"lower",
"=",
"coerce_time_milli",
"(",
"options",
"[",
":in",
"]",
".",
"begin",
")",
"upper",
"=",
"coerce_time_milli",
"(",
"options",
"[",
":in",
"]",
".",
"end",
")",
"upper",
"=",
"\"(#{upper}\"",
"if",
"options",
"[",
":in",
"]",
".",
"exclude_end?",
"end",
"argv",
"=",
"[",
"expires_at",
",",
"lower",
",",
"upper",
"]",
"unless",
"options",
"[",
":limit",
"]",
".",
"nil?",
"limit",
"=",
"options",
"[",
":limit",
"]",
".",
"to_i",
"raise",
"ArgumentError",
",",
"'limit must be positive'",
"unless",
"limit",
".",
"positive?",
"argv",
".",
"push",
"(",
"limit",
",",
"[",
"0",
",",
"options",
"[",
":offset",
"]",
".",
"to_i",
"]",
".",
"max",
")",
"end",
"events",
"=",
"get_script",
"(",
"keys",
":",
"@event_list",
".",
"key",
",",
"argv",
":",
"argv",
")",
"return",
"events",
".",
"map",
"(",
"method",
"(",
":remove_event_id",
")",
")",
"end"
] | Returns data points from within a given time range.
@param [Hash] options
@option options [Time] :before optional upper bound to select events (inclusive)
@option options [Time] :after optional lower bound to select events (inclusive)
@option options [Range<Time>] :in optional range of time to select events (has priority over after/before)
@option options [Integer] :limit maximum number of events to return
@option options [Integer] :offset offset in the list (use in conjunction with limit for pagination) | [
"Returns",
"data",
"points",
"from",
"within",
"a",
"given",
"time",
"range",
"."
] | c97b45e7227f8ed9029f0effff352fc4d82dc3cb | https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/time_series.rb#L68-L91 | train |
jimjh/genie-parser | lib/spirit/logger.rb | Spirit.Logger.record | def record(action, *args)
msg = ''
msg << color(ACTION_COLORS[action])
msg << action_padding(action) + action.to_s
msg << color(:clear)
msg << ' ' + args.join(' ')
info msg
end | ruby | def record(action, *args)
msg = ''
msg << color(ACTION_COLORS[action])
msg << action_padding(action) + action.to_s
msg << color(:clear)
msg << ' ' + args.join(' ')
info msg
end | [
"def",
"record",
"(",
"action",
",",
"*",
"args",
")",
"msg",
"=",
"''",
"msg",
"<<",
"color",
"(",
"ACTION_COLORS",
"[",
"action",
"]",
")",
"msg",
"<<",
"action_padding",
"(",
"action",
")",
"+",
"action",
".",
"to_s",
"msg",
"<<",
"color",
"(",
":clear",
")",
"msg",
"<<",
"' '",
"+",
"args",
".",
"join",
"(",
"' '",
")",
"info",
"msg",
"end"
] | Record that an action has occurred. | [
"Record",
"that",
"an",
"action",
"has",
"occurred",
"."
] | d627c1c1cc07c0ea082a2599ee45cd7e7ba9c932 | https://github.com/jimjh/genie-parser/blob/d627c1c1cc07c0ea082a2599ee45cd7e7ba9c932/lib/spirit/logger.rb#L17-L24 | train |
Subsets and Splits