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
Falkor/falkorlib
lib/falkorlib/bootstrap/base.rb
FalkorLib.Bootstrap.license
def license(dir = Dir.pwd, license = FalkorLib::Config::Bootstrap::DEFAULTS[:metadata][:license], authors = '', options = { :filename => 'LICENSE' }) return if ((license.empty?) or (license == 'none') or (license =~ /^CC/)) return unless FalkorLib::Config::Bootstrap::DEFAULTS[:licenses].keys.include?( license ) info "Generate the #{license} licence file" path = normalized_path(dir) use_git = FalkorLib::Git.init?(path) rootdir = (use_git) ? FalkorLib::Git.rootdir(path) : path Dir.chdir( rootdir ) do run %( licgen #{license.downcase} #{authors} ) run %( mv LICENSE #{options[:filename]} ) if( options[:filename] and options[:filename] != 'LICENSE') end end
ruby
def license(dir = Dir.pwd, license = FalkorLib::Config::Bootstrap::DEFAULTS[:metadata][:license], authors = '', options = { :filename => 'LICENSE' }) return if ((license.empty?) or (license == 'none') or (license =~ /^CC/)) return unless FalkorLib::Config::Bootstrap::DEFAULTS[:licenses].keys.include?( license ) info "Generate the #{license} licence file" path = normalized_path(dir) use_git = FalkorLib::Git.init?(path) rootdir = (use_git) ? FalkorLib::Git.rootdir(path) : path Dir.chdir( rootdir ) do run %( licgen #{license.downcase} #{authors} ) run %( mv LICENSE #{options[:filename]} ) if( options[:filename] and options[:filename] != 'LICENSE') end end
[ "def", "license", "(", "dir", "=", "Dir", ".", "pwd", ",", "license", "=", "FalkorLib", "::", "Config", "::", "Bootstrap", "::", "DEFAULTS", "[", ":metadata", "]", "[", ":license", "]", ",", "authors", "=", "''", ",", "options", "=", "{", ":filename", "=>", "'LICENSE'", "}", ")", "return", "if", "(", "(", "license", ".", "empty?", ")", "or", "(", "license", "==", "'none'", ")", "or", "(", "license", "=~", "/", "/", ")", ")", "return", "unless", "FalkorLib", "::", "Config", "::", "Bootstrap", "::", "DEFAULTS", "[", ":licenses", "]", ".", "keys", ".", "include?", "(", "license", ")", "info", "\"Generate the #{license} licence file\"", "path", "=", "normalized_path", "(", "dir", ")", "use_git", "=", "FalkorLib", "::", "Git", ".", "init?", "(", "path", ")", "rootdir", "=", "(", "use_git", ")", "?", "FalkorLib", "::", "Git", ".", "rootdir", "(", "path", ")", ":", "path", "Dir", ".", "chdir", "(", "rootdir", ")", "do", "run", "%( licgen #{license.downcase} #{authors} )", "run", "%( mv LICENSE #{options[:filename]} )", "if", "(", "options", "[", ":filename", "]", "and", "options", "[", ":filename", "]", "!=", "'LICENSE'", ")", "end", "end" ]
select_licence license Generate the licence file Supported options: * :force [boolean] force action * :filename [string] License file name * :organization [string] Organization
[ "select_licence", "license", "Generate", "the", "licence", "file" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/bootstrap/base.rb#L477-L493
train
Falkor/falkorlib
lib/falkorlib/bootstrap/base.rb
FalkorLib.Bootstrap.guess_project_config
def guess_project_config(dir = Dir.pwd, options = {}) path = normalized_path(dir) use_git = FalkorLib::Git.init?(path) rootdir = (use_git) ? FalkorLib::Git.rootdir(path) : path local_config = FalkorLib::Config.get(rootdir, :local) return local_config[:project] if local_config[:project] # Otherwise, guess the rest of the configuration config = FalkorLib::Config::Bootstrap::DEFAULTS[:metadata].clone # Apply options (if provided) [ :name, :forge ].each do |k| config[k.to_sym] = options[k.to_sym] if options[k.to_sym] end config[:name] = ask("\tProject name: ", get_project_name(dir)) if config[:name].empty? if (use_git) config[:origin] = FalkorLib::Git.config('remote.origin.url') if config[:origin] =~ /((gforge|gitlab|github)[\.\w_-]+)[:\d\/]+(\w*)/ config[:forge] = Regexp.last_match(2).to_sym config[:by] = Regexp.last_match(3) elsif config[:forge].empty? config[:forge] = select_forge(config[:forge]).to_sym end end forges = FalkorLib::Config::Bootstrap::DEFAULTS[:forge][ config[:forge].to_sym ] default_source = case config[:forge] when :gforge 'https://' + forges[:url] + "/projects/" + config[:name].downcase when :github, :gitlab 'https://' + forges[:url] + "/" + config[:by] + "/" + config[:name].downcase else "" end config[:source] = config[:project_page] = default_source config[:issues_url] = "#{config[:project_page]}/issues" config[:license] = select_licence if config[:license].empty? [ :summary ].each do |k| config[k.to_sym] = ask( "\t" + Kernel.format("Project %-20s", k.to_s)) end config[:description] = config[:summary] config[:gitflow] = FalkorLib::GitFlow.guess_gitflow_config(rootdir) config[:make] = File.exists?(File.join(rootdir, 'Makefile')) config[:rake] = File.exists?(File.join(rootdir, 'Rakefile')) config end
ruby
def guess_project_config(dir = Dir.pwd, options = {}) path = normalized_path(dir) use_git = FalkorLib::Git.init?(path) rootdir = (use_git) ? FalkorLib::Git.rootdir(path) : path local_config = FalkorLib::Config.get(rootdir, :local) return local_config[:project] if local_config[:project] # Otherwise, guess the rest of the configuration config = FalkorLib::Config::Bootstrap::DEFAULTS[:metadata].clone # Apply options (if provided) [ :name, :forge ].each do |k| config[k.to_sym] = options[k.to_sym] if options[k.to_sym] end config[:name] = ask("\tProject name: ", get_project_name(dir)) if config[:name].empty? if (use_git) config[:origin] = FalkorLib::Git.config('remote.origin.url') if config[:origin] =~ /((gforge|gitlab|github)[\.\w_-]+)[:\d\/]+(\w*)/ config[:forge] = Regexp.last_match(2).to_sym config[:by] = Regexp.last_match(3) elsif config[:forge].empty? config[:forge] = select_forge(config[:forge]).to_sym end end forges = FalkorLib::Config::Bootstrap::DEFAULTS[:forge][ config[:forge].to_sym ] default_source = case config[:forge] when :gforge 'https://' + forges[:url] + "/projects/" + config[:name].downcase when :github, :gitlab 'https://' + forges[:url] + "/" + config[:by] + "/" + config[:name].downcase else "" end config[:source] = config[:project_page] = default_source config[:issues_url] = "#{config[:project_page]}/issues" config[:license] = select_licence if config[:license].empty? [ :summary ].each do |k| config[k.to_sym] = ask( "\t" + Kernel.format("Project %-20s", k.to_s)) end config[:description] = config[:summary] config[:gitflow] = FalkorLib::GitFlow.guess_gitflow_config(rootdir) config[:make] = File.exists?(File.join(rootdir, 'Makefile')) config[:rake] = File.exists?(File.join(rootdir, 'Rakefile')) config end
[ "def", "guess_project_config", "(", "dir", "=", "Dir", ".", "pwd", ",", "options", "=", "{", "}", ")", "path", "=", "normalized_path", "(", "dir", ")", "use_git", "=", "FalkorLib", "::", "Git", ".", "init?", "(", "path", ")", "rootdir", "=", "(", "use_git", ")", "?", "FalkorLib", "::", "Git", ".", "rootdir", "(", "path", ")", ":", "path", "local_config", "=", "FalkorLib", "::", "Config", ".", "get", "(", "rootdir", ",", ":local", ")", "return", "local_config", "[", ":project", "]", "if", "local_config", "[", ":project", "]", "config", "=", "FalkorLib", "::", "Config", "::", "Bootstrap", "::", "DEFAULTS", "[", ":metadata", "]", ".", "clone", "[", ":name", ",", ":forge", "]", ".", "each", "do", "|", "k", "|", "config", "[", "k", ".", "to_sym", "]", "=", "options", "[", "k", ".", "to_sym", "]", "if", "options", "[", "k", ".", "to_sym", "]", "end", "config", "[", ":name", "]", "=", "ask", "(", "\"\\tProject name: \"", ",", "get_project_name", "(", "dir", ")", ")", "if", "config", "[", ":name", "]", ".", "empty?", "if", "(", "use_git", ")", "config", "[", ":origin", "]", "=", "FalkorLib", "::", "Git", ".", "config", "(", "'remote.origin.url'", ")", "if", "config", "[", ":origin", "]", "=~", "/", "\\.", "\\w", "\\d", "\\/", "\\w", "/", "config", "[", ":forge", "]", "=", "Regexp", ".", "last_match", "(", "2", ")", ".", "to_sym", "config", "[", ":by", "]", "=", "Regexp", ".", "last_match", "(", "3", ")", "elsif", "config", "[", ":forge", "]", ".", "empty?", "config", "[", ":forge", "]", "=", "select_forge", "(", "config", "[", ":forge", "]", ")", ".", "to_sym", "end", "end", "forges", "=", "FalkorLib", "::", "Config", "::", "Bootstrap", "::", "DEFAULTS", "[", ":forge", "]", "[", "config", "[", ":forge", "]", ".", "to_sym", "]", "default_source", "=", "case", "config", "[", ":forge", "]", "when", ":gforge", "'https://'", "+", "forges", "[", ":url", "]", "+", "\"/projects/\"", "+", "config", "[", ":name", "]", ".", "downcase", "when", ":github", ",", ":gitlab", "'https://'", "+", "forges", "[", ":url", "]", "+", "\"/\"", "+", "config", "[", ":by", "]", "+", "\"/\"", "+", "config", "[", ":name", "]", ".", "downcase", "else", "\"\"", "end", "config", "[", ":source", "]", "=", "config", "[", ":project_page", "]", "=", "default_source", "config", "[", ":issues_url", "]", "=", "\"#{config[:project_page]}/issues\"", "config", "[", ":license", "]", "=", "select_licence", "if", "config", "[", ":license", "]", ".", "empty?", "[", ":summary", "]", ".", "each", "do", "|", "k", "|", "config", "[", "k", ".", "to_sym", "]", "=", "ask", "(", "\"\\t\"", "+", "Kernel", ".", "format", "(", "\"Project %-20s\"", ",", "k", ".", "to_s", ")", ")", "end", "config", "[", ":description", "]", "=", "config", "[", ":summary", "]", "config", "[", ":gitflow", "]", "=", "FalkorLib", "::", "GitFlow", ".", "guess_gitflow_config", "(", "rootdir", ")", "config", "[", ":make", "]", "=", "File", ".", "exists?", "(", "File", ".", "join", "(", "rootdir", ",", "'Makefile'", ")", ")", "config", "[", ":rake", "]", "=", "File", ".", "exists?", "(", "File", ".", "join", "(", "rootdir", ",", "'Rakefile'", ")", ")", "config", "end" ]
license guess_project_config Guess the project configuration
[ "license", "guess_project_config", "Guess", "the", "project", "configuration" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/bootstrap/base.rb#L499-L541
train
ohler55/opee
lib/opee/collector.rb
Opee.Collector.collect
def collect(job, path_id=nil) key = job_key(job) token = @cache[key] token = update_token(job, token, path_id) if complete?(job, token) @cache.delete(key) keep_going(job) else @cache[key] = token end end
ruby
def collect(job, path_id=nil) key = job_key(job) token = @cache[key] token = update_token(job, token, path_id) if complete?(job, token) @cache.delete(key) keep_going(job) else @cache[key] = token end end
[ "def", "collect", "(", "job", ",", "path_id", "=", "nil", ")", "key", "=", "job_key", "(", "job", ")", "token", "=", "@cache", "[", "key", "]", "token", "=", "update_token", "(", "job", ",", "token", ",", "path_id", ")", "if", "complete?", "(", "job", ",", "token", ")", "@cache", ".", "delete", "(", "key", ")", "keep_going", "(", "job", ")", "else", "@cache", "[", "key", "]", "=", "token", "end", "end" ]
Collects a job and deternines if the job should be moved on to the next Actor or if it should wait until more processing paths have finished. This method is executed asynchronously. @param [Job|Object] job data to process or pass on @param [Object] path_id identifier of the path the request came from
[ "Collects", "a", "job", "and", "deternines", "if", "the", "job", "should", "be", "moved", "on", "to", "the", "next", "Actor", "or", "if", "it", "should", "wait", "until", "more", "processing", "paths", "have", "finished", ".", "This", "method", "is", "executed", "asynchronously", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/collector.rb#L45-L55
train
ohler55/opee
lib/opee/collector.rb
Opee.Collector.update_token
def update_token(job, token, path_id) raise NotImplementedError.new("neither Collector.update_token() nor Job.update_token() are implemented") unless job.respond_to?(:update_token) job.update_token(token, path_id) end
ruby
def update_token(job, token, path_id) raise NotImplementedError.new("neither Collector.update_token() nor Job.update_token() are implemented") unless job.respond_to?(:update_token) job.update_token(token, path_id) end
[ "def", "update_token", "(", "job", ",", "token", ",", "path_id", ")", "raise", "NotImplementedError", ".", "new", "(", "\"neither Collector.update_token() nor Job.update_token() are implemented\"", ")", "unless", "job", ".", "respond_to?", "(", ":update_token", ")", "job", ".", "update_token", "(", "token", ",", "path_id", ")", "end" ]
Updates the token associated with the job. The job or the Collector subclass can use any data desired to keep track of the job's paths that have been completed. This method is executed asynchronously. @param [Object] job data to get the key for @param [Object] token current token value or nil for the first token value @param [Object] path_id an indicator of the path if used @return [Object] a token to keep track of the progress of the job
[ "Updates", "the", "token", "associated", "with", "the", "job", ".", "The", "job", "or", "the", "Collector", "subclass", "can", "use", "any", "data", "desired", "to", "keep", "track", "of", "the", "job", "s", "paths", "that", "have", "been", "completed", ".", "This", "method", "is", "executed", "asynchronously", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/collector.rb#L74-L77
train
ohler55/opee
lib/opee/collector.rb
Opee.Collector.complete?
def complete?(job, token) raise NotImplementedError.new("neither Collector.complete?() nor Job.complete?() are implemented") unless job.respond_to?(:complete?) job.complete?(token) end
ruby
def complete?(job, token) raise NotImplementedError.new("neither Collector.complete?() nor Job.complete?() are implemented") unless job.respond_to?(:complete?) job.complete?(token) end
[ "def", "complete?", "(", "job", ",", "token", ")", "raise", "NotImplementedError", ".", "new", "(", "\"neither Collector.complete?() nor Job.complete?() are implemented\"", ")", "unless", "job", ".", "respond_to?", "(", ":complete?", ")", "job", ".", "complete?", "(", "token", ")", "end" ]
Returns true if the job has been processed by all paths converging on the collector. This can be implemented in the Collector subclass or in the Job. This method is executed asynchronously. @param [Object] job data to get the key for @param [Object] token current token value or nil for the first token value @return [true|false] an indication of wether the job has completed all paths
[ "Returns", "true", "if", "the", "job", "has", "been", "processed", "by", "all", "paths", "converging", "on", "the", "collector", ".", "This", "can", "be", "implemented", "in", "the", "Collector", "subclass", "or", "in", "the", "Job", ".", "This", "method", "is", "executed", "asynchronously", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/collector.rb#L85-L88
train
ianbishop/yellow_api
lib/yellow_api/config.rb
YellowApi.Config.reset
def reset self.apikey = DEFAULT_APIKEY self.endpoint = DEFAULT_ENDPOINT self.sandbox_endpoint = DEFAULT_SANDBOX_ENDPOINT self.sandbox_enabled = DEFAULT_SANDBOX_ENABLED self.fmt = DEFAULT_FMT end
ruby
def reset self.apikey = DEFAULT_APIKEY self.endpoint = DEFAULT_ENDPOINT self.sandbox_endpoint = DEFAULT_SANDBOX_ENDPOINT self.sandbox_enabled = DEFAULT_SANDBOX_ENABLED self.fmt = DEFAULT_FMT end
[ "def", "reset", "self", ".", "apikey", "=", "DEFAULT_APIKEY", "self", ".", "endpoint", "=", "DEFAULT_ENDPOINT", "self", ".", "sandbox_endpoint", "=", "DEFAULT_SANDBOX_ENDPOINT", "self", ".", "sandbox_enabled", "=", "DEFAULT_SANDBOX_ENABLED", "self", ".", "fmt", "=", "DEFAULT_FMT", "end" ]
Reset all configurations back to defaults
[ "Reset", "all", "configurations", "back", "to", "defaults" ]
77e10948fe4eef6b6416c6fc9a597a19a41c3ff5
https://github.com/ianbishop/yellow_api/blob/77e10948fe4eef6b6416c6fc9a597a19a41c3ff5/lib/yellow_api/config.rb#L63-L69
train
polleverywhere/shart
lib/shart.rb
Shart.Sync.upload
def upload(&block) @source.files.each do |key, file| object = @target.files.create({ :key => key, :body => file, :public => true, :cache_control => 'max-age=0' # Disable cache on S3 so that future sharts are visible if folks web browsers. }) block.call file, object end end
ruby
def upload(&block) @source.files.each do |key, file| object = @target.files.create({ :key => key, :body => file, :public => true, :cache_control => 'max-age=0' # Disable cache on S3 so that future sharts are visible if folks web browsers. }) block.call file, object end end
[ "def", "upload", "(", "&", "block", ")", "@source", ".", "files", ".", "each", "do", "|", "key", ",", "file", "|", "object", "=", "@target", ".", "files", ".", "create", "(", "{", ":key", "=>", "key", ",", ":body", "=>", "file", ",", ":public", "=>", "true", ",", ":cache_control", "=>", "'max-age=0'", "}", ")", "block", ".", "call", "file", ",", "object", "end", "end" ]
Upload files from target to the source.
[ "Upload", "files", "from", "target", "to", "the", "source", "." ]
38495c68d46828641e85508610409fc8ad0ee2bb
https://github.com/polleverywhere/shart/blob/38495c68d46828641e85508610409fc8ad0ee2bb/lib/shart.rb#L86-L96
train
polleverywhere/shart
lib/shart.rb
Shart.Sync.clean
def clean(&block) @target.files.each do |object| unless @source.files.include? object.key block.call(object) object.destroy end end end
ruby
def clean(&block) @target.files.each do |object| unless @source.files.include? object.key block.call(object) object.destroy end end end
[ "def", "clean", "(", "&", "block", ")", "@target", ".", "files", ".", "each", "do", "|", "object", "|", "unless", "@source", ".", "files", ".", "include?", "object", ".", "key", "block", ".", "call", "(", "object", ")", "object", ".", "destroy", "end", "end", "end" ]
Removes files from target that don't exist on the source.
[ "Removes", "files", "from", "target", "that", "don", "t", "exist", "on", "the", "source", "." ]
38495c68d46828641e85508610409fc8ad0ee2bb
https://github.com/polleverywhere/shart/blob/38495c68d46828641e85508610409fc8ad0ee2bb/lib/shart.rb#L99-L106
train
rakeoe/rakeoe
lib/rakeoe/key_value_reader.rb
RakeOE.KeyValueReader.add
def add(key, value) if @env.has_key?(key) @env[key] += value else set(key,value) end end
ruby
def add(key, value) if @env.has_key?(key) @env[key] += value else set(key,value) end end
[ "def", "add", "(", "key", ",", "value", ")", "if", "@env", ".", "has_key?", "(", "key", ")", "@env", "[", "key", "]", "+=", "value", "else", "set", "(", "key", ",", "value", ")", "end", "end" ]
Adds a value for key @param [String] key Key that should be used for operation @param [String] value Value that should be used for operation
[ "Adds", "a", "value", "for", "key" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/key_value_reader.rb#L173-L179
train
rakeoe/rakeoe
lib/rakeoe/binary_base.rb
RakeOE.BinaryBase.handle_qt
def handle_qt unless tc.qt.check_once puts '### WARN: QT prerequisites not complete!' end @settings['ADD_CFLAGS'] += tc.qt.cflags @settings['ADD_CXXFLAGS'] += tc.qt.cflags @settings['ADD_LDFLAGS'] += tc.qt.ldflags @settings['ADD_LIBS'] += tc.qt.libs end
ruby
def handle_qt unless tc.qt.check_once puts '### WARN: QT prerequisites not complete!' end @settings['ADD_CFLAGS'] += tc.qt.cflags @settings['ADD_CXXFLAGS'] += tc.qt.cflags @settings['ADD_LDFLAGS'] += tc.qt.ldflags @settings['ADD_LIBS'] += tc.qt.libs end
[ "def", "handle_qt", "unless", "tc", ".", "qt", ".", "check_once", "puts", "'### WARN: QT prerequisites not complete!'", "end", "@settings", "[", "'ADD_CFLAGS'", "]", "+=", "tc", ".", "qt", ".", "cflags", "@settings", "[", "'ADD_CXXFLAGS'", "]", "+=", "tc", ".", "qt", ".", "cflags", "@settings", "[", "'ADD_LDFLAGS'", "]", "+=", "tc", ".", "qt", ".", "ldflags", "@settings", "[", "'ADD_LIBS'", "]", "+=", "tc", ".", "qt", ".", "libs", "end" ]
Qt special handling
[ "Qt", "special", "handling" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/binary_base.rb#L122-L130
train
rakeoe/rakeoe
lib/rakeoe/binary_base.rb
RakeOE.BinaryBase.src_directories
def src_directories(main_dir, sub_dirs, params={}) if params[:subdir_only] all_dirs=[] else all_dirs = [main_dir] end sub_dirs.each do |dir| all_dirs << "#{main_dir}/#{dir}" end all_dirs.compact end
ruby
def src_directories(main_dir, sub_dirs, params={}) if params[:subdir_only] all_dirs=[] else all_dirs = [main_dir] end sub_dirs.each do |dir| all_dirs << "#{main_dir}/#{dir}" end all_dirs.compact end
[ "def", "src_directories", "(", "main_dir", ",", "sub_dirs", ",", "params", "=", "{", "}", ")", "if", "params", "[", ":subdir_only", "]", "all_dirs", "=", "[", "]", "else", "all_dirs", "=", "[", "main_dir", "]", "end", "sub_dirs", ".", "each", "do", "|", "dir", "|", "all_dirs", "<<", "\"#{main_dir}/#{dir}\"", "end", "all_dirs", ".", "compact", "end" ]
Returns array of source code directories assembled via given parameters @param [String] main_dir Main directory where project source is located @param [Array] sub_dirs List of sub directories inside main_dir @param [Hash] params Option hash to control how directories should be added @option params [Boolean] :subdir_only If true: only return sub directories, not main_dir in result @return [Array] List of sub directories assembled from each element in sub_dirs and appended to main_dir
[ "Returns", "array", "of", "source", "code", "directories", "assembled", "via", "given", "parameters" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/binary_base.rb#L160-L171
train
rakeoe/rakeoe
lib/rakeoe/binary_base.rb
RakeOE.BinaryBase.lib_incs
def lib_incs(libs=[]) includes = Array.new libs.each do |name, param| lib_includes = PrjFileCache.exported_lib_incs(name) includes += lib_includes if lib_includes.any? end includes end
ruby
def lib_incs(libs=[]) includes = Array.new libs.each do |name, param| lib_includes = PrjFileCache.exported_lib_incs(name) includes += lib_includes if lib_includes.any? end includes end
[ "def", "lib_incs", "(", "libs", "=", "[", "]", ")", "includes", "=", "Array", ".", "new", "libs", ".", "each", "do", "|", "name", ",", "param", "|", "lib_includes", "=", "PrjFileCache", ".", "exported_lib_incs", "(", "name", ")", "includes", "+=", "lib_includes", "if", "lib_includes", ".", "any?", "end", "includes", "end" ]
Returns list of include directories for name of libraries in parameter libs @param [Array] libs List of library names @return [Array] List of includes found for given library names
[ "Returns", "list", "of", "include", "directories", "for", "name", "of", "libraries", "in", "parameter", "libs" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/binary_base.rb#L180-L187
train
rakeoe/rakeoe
lib/rakeoe/binary_base.rb
RakeOE.BinaryBase.search_files
def search_files(directories, extensions) extensions.each_with_object([]) do |ext, obj| directories.each do |dir| obj << FileList["#{dir}/*#{ext}"] end end.flatten.compact end
ruby
def search_files(directories, extensions) extensions.each_with_object([]) do |ext, obj| directories.each do |dir| obj << FileList["#{dir}/*#{ext}"] end end.flatten.compact end
[ "def", "search_files", "(", "directories", ",", "extensions", ")", "extensions", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "ext", ",", "obj", "|", "directories", ".", "each", "do", "|", "dir", "|", "obj", "<<", "FileList", "[", "\"#{dir}/*#{ext}\"", "]", "end", "end", ".", "flatten", ".", "compact", "end" ]
Search files recursively in directory with given extensions @param [Array] directories Array of directories to search @param [Array] extensions Array of file extensions to use for search @return [Array] list of all found files
[ "Search", "files", "recursively", "in", "directory", "with", "given", "extensions" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/binary_base.rb#L197-L203
train
rakeoe/rakeoe
lib/rakeoe/binary_base.rb
RakeOE.BinaryBase.find_files_relative
def find_files_relative(directory, files) return [] unless files.any? files.each_with_object([]) do |file, obj| path = "#{directory}/#{file}" obj << path if File.exist?(path) end end
ruby
def find_files_relative(directory, files) return [] unless files.any? files.each_with_object([]) do |file, obj| path = "#{directory}/#{file}" obj << path if File.exist?(path) end end
[ "def", "find_files_relative", "(", "directory", ",", "files", ")", "return", "[", "]", "unless", "files", ".", "any?", "files", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "file", ",", "obj", "|", "path", "=", "\"#{directory}/#{file}\"", "obj", "<<", "path", "if", "File", ".", "exist?", "(", "path", ")", "end", "end" ]
Search list of files relative to given directory @param [String] directory Main directory @param [Array] files List with Filenames @return [Array] List of path names of all found files
[ "Search", "list", "of", "files", "relative", "to", "given", "directory" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/binary_base.rb#L213-L219
train
rakeoe/rakeoe
lib/rakeoe/binary_base.rb
RakeOE.BinaryBase.read_prj_settings
def read_prj_settings(file) unless File.file?(file) file = File.dirname(__FILE__)+'/prj.rake' end KeyValueReader.new(file) end
ruby
def read_prj_settings(file) unless File.file?(file) file = File.dirname(__FILE__)+'/prj.rake' end KeyValueReader.new(file) end
[ "def", "read_prj_settings", "(", "file", ")", "unless", "File", ".", "file?", "(", "file", ")", "file", "=", "File", ".", "dirname", "(", "__FILE__", ")", "+", "'/prj.rake'", "end", "KeyValueReader", ".", "new", "(", "file", ")", "end" ]
Read project file if it exists @param [String] file Filename of project file @return [KeyValueReader] New KeyValueReader object with values provided via read project file
[ "Read", "project", "file", "if", "it", "exists" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/binary_base.rb#L239-L244
train
rakeoe/rakeoe
lib/rakeoe/binary_base.rb
RakeOE.BinaryBase.load_deps
def load_deps(deps) deps.each do |file| if File.file?(file) Rake::MakefileLoader.new.load(file) end end end
ruby
def load_deps(deps) deps.each do |file| if File.file?(file) Rake::MakefileLoader.new.load(file) end end end
[ "def", "load_deps", "(", "deps", ")", "deps", ".", "each", "do", "|", "file", "|", "if", "File", ".", "file?", "(", "file", ")", "Rake", "::", "MakefileLoader", ".", "new", ".", "load", "(", "file", ")", "end", "end", "end" ]
Loads dependency files if already generated @param [Array] deps List of dependency files that have been generated via e.g. 'gcc -MM'
[ "Loads", "dependency", "files", "if", "already", "generated" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/binary_base.rb#L260-L266
train
rakeoe/rakeoe
lib/rakeoe/binary_base.rb
RakeOE.BinaryBase.obj_to_source
def obj_to_source(obj, source_dir, obj_dir) stub = obj.gsub(obj_dir, source_dir).ext('') src = stub_to_src(stub) return src if src raise "No matching source for #{obj} found." end
ruby
def obj_to_source(obj, source_dir, obj_dir) stub = obj.gsub(obj_dir, source_dir).ext('') src = stub_to_src(stub) return src if src raise "No matching source for #{obj} found." end
[ "def", "obj_to_source", "(", "obj", ",", "source_dir", ",", "obj_dir", ")", "stub", "=", "obj", ".", "gsub", "(", "obj_dir", ",", "source_dir", ")", ".", "ext", "(", "''", ")", "src", "=", "stub_to_src", "(", "stub", ")", "return", "src", "if", "src", "raise", "\"No matching source for #{obj} found.\"", "end" ]
Transforms an object file name to its source file name by replacing build directory base with the source directory base and then iterating list of known sources to match @param [String] obj Object filename @param [String] source_dir Project source base directory @param [String] obj_dir Project build base directory @return [String] Mapped filename
[ "Transforms", "an", "object", "file", "name", "to", "its", "source", "file", "name", "by", "replacing", "build", "directory", "base", "with", "the", "source", "directory", "base", "and", "then", "iterating", "list", "of", "known", "sources", "to", "match" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/binary_base.rb#L315-L320
train
rakeoe/rakeoe
lib/rakeoe/binary_base.rb
RakeOE.BinaryBase.dep_to_source
def dep_to_source(dep, source_dir, dep_dir) stub = dep.gsub(dep_dir, source_dir).ext('') src = stub_to_src(stub) return src if src raise "No matching source for #{dep} found." end
ruby
def dep_to_source(dep, source_dir, dep_dir) stub = dep.gsub(dep_dir, source_dir).ext('') src = stub_to_src(stub) return src if src raise "No matching source for #{dep} found." end
[ "def", "dep_to_source", "(", "dep", ",", "source_dir", ",", "dep_dir", ")", "stub", "=", "dep", ".", "gsub", "(", "dep_dir", ",", "source_dir", ")", ".", "ext", "(", "''", ")", "src", "=", "stub_to_src", "(", "stub", ")", "return", "src", "if", "src", "raise", "\"No matching source for #{dep} found.\"", "end" ]
Transforms a dependency file name into its corresponding source file name by replacing file name extension and object directory with dependency directory. Searches through list of source files to find it. @param [String] dep Source filename @param [String] source_dir Project source base directory @param [String] dep_dir Project dependency base directory @return [String] Mapped filename
[ "Transforms", "a", "dependency", "file", "name", "into", "its", "corresponding", "source", "file", "name", "by", "replacing", "file", "name", "extension", "and", "object", "directory", "with", "dependency", "directory", ".", "Searches", "through", "list", "of", "source", "files", "to", "find", "it", "." ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/binary_base.rb#L369-L374
train
rakeoe/rakeoe
lib/rakeoe/binary_base.rb
RakeOE.BinaryBase.platform_flags_fixup
def platform_flags_fixup(libs) libs[:all].each do |lib| ps = tc.platform_settings_for(lib) unless ps.empty? @settings['ADD_CFLAGS'] += " #{ps[:CFLAGS]}" if ps[:CFLAGS] @settings['ADD_CXXFLAGS'] += " #{ps[:CXXFLAGS]}" if ps[:CXXFLAGS] # remove all -lXX settings from ps[:LDFLAGS] and use rest for @settings['ADD_LDFLAGS'], # -lXX is set in Toolchain#linker_line_for @settings['ADD_LDFLAGS'] += ps[:LDFLAGS].gsub(/(\s|^)+-l\S+/, '') if ps[:LDFLAGS] end end end
ruby
def platform_flags_fixup(libs) libs[:all].each do |lib| ps = tc.platform_settings_for(lib) unless ps.empty? @settings['ADD_CFLAGS'] += " #{ps[:CFLAGS]}" if ps[:CFLAGS] @settings['ADD_CXXFLAGS'] += " #{ps[:CXXFLAGS]}" if ps[:CXXFLAGS] # remove all -lXX settings from ps[:LDFLAGS] and use rest for @settings['ADD_LDFLAGS'], # -lXX is set in Toolchain#linker_line_for @settings['ADD_LDFLAGS'] += ps[:LDFLAGS].gsub(/(\s|^)+-l\S+/, '') if ps[:LDFLAGS] end end end
[ "def", "platform_flags_fixup", "(", "libs", ")", "libs", "[", ":all", "]", ".", "each", "do", "|", "lib", "|", "ps", "=", "tc", ".", "platform_settings_for", "(", "lib", ")", "unless", "ps", ".", "empty?", "@settings", "[", "'ADD_CFLAGS'", "]", "+=", "\" #{ps[:CFLAGS]}\"", "if", "ps", "[", ":CFLAGS", "]", "@settings", "[", "'ADD_CXXFLAGS'", "]", "+=", "\" #{ps[:CXXFLAGS]}\"", "if", "ps", "[", ":CXXFLAGS", "]", "@settings", "[", "'ADD_LDFLAGS'", "]", "+=", "ps", "[", ":LDFLAGS", "]", ".", "gsub", "(", "/", "\\s", "\\S", "/", ",", "''", ")", "if", "ps", "[", ":LDFLAGS", "]", "end", "end", "end" ]
Change ADD_CFLAGS, ADD_CXXFLAGS, ADD_LDFLAGS according to settings in platform file. @param libs [Array] Array of libraries to be considered
[ "Change", "ADD_CFLAGS", "ADD_CXXFLAGS", "ADD_LDFLAGS", "according", "to", "settings", "in", "platform", "file", "." ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/binary_base.rb#L430-L442
train
rakeoe/rakeoe
lib/rakeoe/binary_base.rb
RakeOE.BinaryBase.search_libs
def search_libs(settings) # get all libs specified in ADD_LIBS search_libs = settings['ADD_LIBS'].split our_lib_deps = [] search_libs.each do |lib| our_lib_deps << lib deps_of_lib = @@all_libs_and_deps[lib] if deps_of_lib our_lib_deps += deps_of_lib end end our_lib_deps.uniq! # match libs found by toolchain solibs_local = [] alibs_local = [] our_lib_deps.each do |lib| if PrjFileCache.contain?('LIB', lib) alibs_local << lib elsif PrjFileCache.contain?('SOLIB', lib) solibs_local << lib end end local_libs = (alibs_local + solibs_local) || [] # return value is a hash { :local => local_libs, :local_alibs => alibs_local, :local_solibs => solibs_local, :all => our_lib_deps } end
ruby
def search_libs(settings) # get all libs specified in ADD_LIBS search_libs = settings['ADD_LIBS'].split our_lib_deps = [] search_libs.each do |lib| our_lib_deps << lib deps_of_lib = @@all_libs_and_deps[lib] if deps_of_lib our_lib_deps += deps_of_lib end end our_lib_deps.uniq! # match libs found by toolchain solibs_local = [] alibs_local = [] our_lib_deps.each do |lib| if PrjFileCache.contain?('LIB', lib) alibs_local << lib elsif PrjFileCache.contain?('SOLIB', lib) solibs_local << lib end end local_libs = (alibs_local + solibs_local) || [] # return value is a hash { :local => local_libs, :local_alibs => alibs_local, :local_solibs => solibs_local, :all => our_lib_deps } end
[ "def", "search_libs", "(", "settings", ")", "search_libs", "=", "settings", "[", "'ADD_LIBS'", "]", ".", "split", "our_lib_deps", "=", "[", "]", "search_libs", ".", "each", "do", "|", "lib", "|", "our_lib_deps", "<<", "lib", "deps_of_lib", "=", "@@all_libs_and_deps", "[", "lib", "]", "if", "deps_of_lib", "our_lib_deps", "+=", "deps_of_lib", "end", "end", "our_lib_deps", ".", "uniq!", "solibs_local", "=", "[", "]", "alibs_local", "=", "[", "]", "our_lib_deps", ".", "each", "do", "|", "lib", "|", "if", "PrjFileCache", ".", "contain?", "(", "'LIB'", ",", "lib", ")", "alibs_local", "<<", "lib", "elsif", "PrjFileCache", ".", "contain?", "(", "'SOLIB'", ",", "lib", ")", "solibs_local", "<<", "lib", "end", "end", "local_libs", "=", "(", "alibs_local", "+", "solibs_local", ")", "||", "[", "]", "{", ":local", "=>", "local_libs", ",", ":local_alibs", "=>", "alibs_local", ",", ":local_solibs", "=>", "solibs_local", ",", ":all", "=>", "our_lib_deps", "}", "end" ]
Search dependent libraries as specified in ADD_LIBS setting of prj.rake file @param [String] settings The project settings definition @return [Hash] Containing the following components mapped to an array: @option return [Array] :local all local libs found by toolchain @option return [Array] :local_alibs local static libs found by toolchain @option return [Array] :local_solibs local shared libs found by toolchain @option return [Array] :all local + external libs
[ "Search", "dependent", "libraries", "as", "specified", "in", "ADD_LIBS", "setting", "of", "prj", ".", "rake", "file" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/binary_base.rb#L455-L487
train
rakeoe/rakeoe
lib/rakeoe/binary_base.rb
RakeOE.BinaryBase.paths_of_libs
def paths_of_libs(some_libs) local_libs = Array.new some_libs.each do |lib| if PrjFileCache.contain?('LIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.a" elsif PrjFileCache.contain?('SOLIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.so" end end local_libs end
ruby
def paths_of_libs(some_libs) local_libs = Array.new some_libs.each do |lib| if PrjFileCache.contain?('LIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.a" elsif PrjFileCache.contain?('SOLIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.so" end end local_libs end
[ "def", "paths_of_libs", "(", "some_libs", ")", "local_libs", "=", "Array", ".", "new", "some_libs", ".", "each", "do", "|", "lib", "|", "if", "PrjFileCache", ".", "contain?", "(", "'LIB'", ",", "lib", ")", "local_libs", "<<", "\"#{tc.settings['LIB_OUT']}/lib#{lib}.a\"", "elsif", "PrjFileCache", ".", "contain?", "(", "'SOLIB'", ",", "lib", ")", "local_libs", "<<", "\"#{tc.settings['LIB_OUT']}/lib#{lib}.so\"", "end", "end", "local_libs", "end" ]
Returns absolute paths to given libraries, if they are local libraries of the current project.
[ "Returns", "absolute", "paths", "to", "given", "libraries", "if", "they", "are", "local", "libraries", "of", "the", "current", "project", "." ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/binary_base.rb#L506-L518
train
rakeoe/rakeoe
lib/rakeoe/binary_base.rb
RakeOE.BinaryBase.paths_of_local_libs
def paths_of_local_libs local_libs = Array.new each_local_lib() do |lib| if PrjFileCache.contain?('LIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.a" elsif PrjFileCache.contain?('SOLIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.so" end end local_libs end
ruby
def paths_of_local_libs local_libs = Array.new each_local_lib() do |lib| if PrjFileCache.contain?('LIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.a" elsif PrjFileCache.contain?('SOLIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.so" end end local_libs end
[ "def", "paths_of_local_libs", "local_libs", "=", "Array", ".", "new", "each_local_lib", "(", ")", "do", "|", "lib", "|", "if", "PrjFileCache", ".", "contain?", "(", "'LIB'", ",", "lib", ")", "local_libs", "<<", "\"#{tc.settings['LIB_OUT']}/lib#{lib}.a\"", "elsif", "PrjFileCache", ".", "contain?", "(", "'SOLIB'", ",", "lib", ")", "local_libs", "<<", "\"#{tc.settings['LIB_OUT']}/lib#{lib}.so\"", "end", "end", "local_libs", "end" ]
Returns absolute paths to dependend local libraries, i.e. libraries of the current project.
[ "Returns", "absolute", "paths", "to", "dependend", "local", "libraries", "i", ".", "e", ".", "libraries", "of", "the", "current", "project", "." ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/binary_base.rb#L523-L535
train
eprothro/cassie
lib/cassie/statements/statement.rb
Cassie::Statements.Statement.to_cql
def to_cql if statement.respond_to?(:cql) && statement.respond_to?(:params) Cassie::Support::StatementParser.new(statement).to_cql else statement.to_s end end
ruby
def to_cql if statement.respond_to?(:cql) && statement.respond_to?(:params) Cassie::Support::StatementParser.new(statement).to_cql else statement.to_s end end
[ "def", "to_cql", "if", "statement", ".", "respond_to?", "(", ":cql", ")", "&&", "statement", ".", "respond_to?", "(", ":params", ")", "Cassie", "::", "Support", "::", "StatementParser", ".", "new", "(", "statement", ")", ".", "to_cql", "else", "statement", ".", "to_s", "end", "end" ]
A CQL string with inline parameters, representing the current statement as it would be executed in a CQL shell @note This CQL string does not include execution options like type hinting, idempotency, consistency level, etc -- just the raw CQL instruction and values. @return [String] @example statement.to_cql #=> "SELECT * FROM table WHERE first='evan' AND middle='thomas' and last='prothro"
[ "A", "CQL", "string", "with", "inline", "parameters", "representing", "the", "current", "statement", "as", "it", "would", "be", "executed", "in", "a", "CQL", "shell" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/statements/statement.rb#L59-L65
train
atmos/warden-googleapps
lib/warden-googleapps/gapps_openid.rb
OpenID.GoogleDiscovery.discover_user
def discover_user(domain, claimed_id) url = fetch_host_meta(domain) if url.nil? return nil # Not a Google Apps domain end xrds = fetch_xrds(domain, url) user_url, authority = get_user_xrds_url(xrds, claimed_id) user_xrds = fetch_xrds(authority, user_url, false) return if user_xrds.nil? endpoints = OpenID::OpenIDServiceEndpoint.from_xrds(claimed_id, user_xrds) return [claimed_id, OpenID.get_op_or_user_services(endpoints)] end
ruby
def discover_user(domain, claimed_id) url = fetch_host_meta(domain) if url.nil? return nil # Not a Google Apps domain end xrds = fetch_xrds(domain, url) user_url, authority = get_user_xrds_url(xrds, claimed_id) user_xrds = fetch_xrds(authority, user_url, false) return if user_xrds.nil? endpoints = OpenID::OpenIDServiceEndpoint.from_xrds(claimed_id, user_xrds) return [claimed_id, OpenID.get_op_or_user_services(endpoints)] end
[ "def", "discover_user", "(", "domain", ",", "claimed_id", ")", "url", "=", "fetch_host_meta", "(", "domain", ")", "if", "url", ".", "nil?", "return", "nil", "end", "xrds", "=", "fetch_xrds", "(", "domain", ",", "url", ")", "user_url", ",", "authority", "=", "get_user_xrds_url", "(", "xrds", ",", "claimed_id", ")", "user_xrds", "=", "fetch_xrds", "(", "authority", ",", "user_url", ",", "false", ")", "return", "if", "user_xrds", ".", "nil?", "endpoints", "=", "OpenID", "::", "OpenIDServiceEndpoint", ".", "from_xrds", "(", "claimed_id", ",", "user_xrds", ")", "return", "[", "claimed_id", ",", "OpenID", ".", "get_op_or_user_services", "(", "endpoints", ")", "]", "end" ]
Handles discovery for a user's claimed ID.
[ "Handles", "discovery", "for", "a", "user", "s", "claimed", "ID", "." ]
ca05e09eb8ad8d992df73cf8bd9eb1f097a4de85
https://github.com/atmos/warden-googleapps/blob/ca05e09eb8ad8d992df73cf8bd9eb1f097a4de85/lib/warden-googleapps/gapps_openid.rb#L98-L110
train
atmos/warden-googleapps
lib/warden-googleapps/gapps_openid.rb
OpenID.GoogleDiscovery.discover_site
def discover_site(domain) url = fetch_host_meta(domain) if url.nil? return nil # Not a Google Apps domain end xrds = fetch_xrds(domain, url) unless xrds.nil? endpoints = OpenID::OpenIDServiceEndpoint.from_xrds(domain, xrds) return [domain, OpenID.get_op_or_user_services(endpoints)] end return nil end
ruby
def discover_site(domain) url = fetch_host_meta(domain) if url.nil? return nil # Not a Google Apps domain end xrds = fetch_xrds(domain, url) unless xrds.nil? endpoints = OpenID::OpenIDServiceEndpoint.from_xrds(domain, xrds) return [domain, OpenID.get_op_or_user_services(endpoints)] end return nil end
[ "def", "discover_site", "(", "domain", ")", "url", "=", "fetch_host_meta", "(", "domain", ")", "if", "url", ".", "nil?", "return", "nil", "end", "xrds", "=", "fetch_xrds", "(", "domain", ",", "url", ")", "unless", "xrds", ".", "nil?", "endpoints", "=", "OpenID", "::", "OpenIDServiceEndpoint", ".", "from_xrds", "(", "domain", ",", "xrds", ")", "return", "[", "domain", ",", "OpenID", ".", "get_op_or_user_services", "(", "endpoints", ")", "]", "end", "return", "nil", "end" ]
Handles discovery for a domain
[ "Handles", "discovery", "for", "a", "domain" ]
ca05e09eb8ad8d992df73cf8bd9eb1f097a4de85
https://github.com/atmos/warden-googleapps/blob/ca05e09eb8ad8d992df73cf8bd9eb1f097a4de85/lib/warden-googleapps/gapps_openid.rb#L113-L124
train
atmos/warden-googleapps
lib/warden-googleapps/gapps_openid.rb
OpenID.GoogleDiscovery.fetch_host_meta
def fetch_host_meta(domain) cached_value = get_cache(domain) return cached_value unless cached_value.nil? host_meta_url = "https://www.google.com/accounts/o8/.well-known/host-meta?hd=#{CGI::escape(domain)}" http_resp = OpenID.fetch(host_meta_url) if http_resp.code != "200" and http_resp.code != "206" return nil end matches = /Link: <(.*)>/.match( http_resp.body ) if matches.nil? return nil end put_cache(domain, matches[1]) return matches[1] end
ruby
def fetch_host_meta(domain) cached_value = get_cache(domain) return cached_value unless cached_value.nil? host_meta_url = "https://www.google.com/accounts/o8/.well-known/host-meta?hd=#{CGI::escape(domain)}" http_resp = OpenID.fetch(host_meta_url) if http_resp.code != "200" and http_resp.code != "206" return nil end matches = /Link: <(.*)>/.match( http_resp.body ) if matches.nil? return nil end put_cache(domain, matches[1]) return matches[1] end
[ "def", "fetch_host_meta", "(", "domain", ")", "cached_value", "=", "get_cache", "(", "domain", ")", "return", "cached_value", "unless", "cached_value", ".", "nil?", "host_meta_url", "=", "\"https://www.google.com/accounts/o8/.well-known/host-meta?hd=#{CGI::escape(domain)}\"", "http_resp", "=", "OpenID", ".", "fetch", "(", "host_meta_url", ")", "if", "http_resp", ".", "code", "!=", "\"200\"", "and", "http_resp", ".", "code", "!=", "\"206\"", "return", "nil", "end", "matches", "=", "/", "/", ".", "match", "(", "http_resp", ".", "body", ")", "if", "matches", ".", "nil?", "return", "nil", "end", "put_cache", "(", "domain", ",", "matches", "[", "1", "]", ")", "return", "matches", "[", "1", "]", "end" ]
Kickstart the discovery process by checking against Google's well-known location for hosted domains. This gives us the location of the site's XRDS doc
[ "Kickstart", "the", "discovery", "process", "by", "checking", "against", "Google", "s", "well", "-", "known", "location", "for", "hosted", "domains", ".", "This", "gives", "us", "the", "location", "of", "the", "site", "s", "XRDS", "doc" ]
ca05e09eb8ad8d992df73cf8bd9eb1f097a4de85
https://github.com/atmos/warden-googleapps/blob/ca05e09eb8ad8d992df73cf8bd9eb1f097a4de85/lib/warden-googleapps/gapps_openid.rb#L128-L143
train
atmos/warden-googleapps
lib/warden-googleapps/gapps_openid.rb
OpenID.GoogleDiscovery.fetch_xrds
def fetch_xrds(authority, url, cache=true) return if url.nil? cached_xrds = get_cache(url) return cached_xrds unless cached_xrds.nil? http_resp = OpenID.fetch(url) return if http_resp.code != "200" and http_resp.code != "206" body = http_resp.body signature = http_resp["Signature"] signed_by = SimpleSign.verify(body, signature) if !signed_by.casecmp(authority) or !signed_by.casecmp('hosted-id.google.com') return false # Signed, but not by the right domain. end # Everything is OK if cache put_cache(url, body) end return body end
ruby
def fetch_xrds(authority, url, cache=true) return if url.nil? cached_xrds = get_cache(url) return cached_xrds unless cached_xrds.nil? http_resp = OpenID.fetch(url) return if http_resp.code != "200" and http_resp.code != "206" body = http_resp.body signature = http_resp["Signature"] signed_by = SimpleSign.verify(body, signature) if !signed_by.casecmp(authority) or !signed_by.casecmp('hosted-id.google.com') return false # Signed, but not by the right domain. end # Everything is OK if cache put_cache(url, body) end return body end
[ "def", "fetch_xrds", "(", "authority", ",", "url", ",", "cache", "=", "true", ")", "return", "if", "url", ".", "nil?", "cached_xrds", "=", "get_cache", "(", "url", ")", "return", "cached_xrds", "unless", "cached_xrds", ".", "nil?", "http_resp", "=", "OpenID", ".", "fetch", "(", "url", ")", "return", "if", "http_resp", ".", "code", "!=", "\"200\"", "and", "http_resp", ".", "code", "!=", "\"206\"", "body", "=", "http_resp", ".", "body", "signature", "=", "http_resp", "[", "\"Signature\"", "]", "signed_by", "=", "SimpleSign", ".", "verify", "(", "body", ",", "signature", ")", "if", "!", "signed_by", ".", "casecmp", "(", "authority", ")", "or", "!", "signed_by", ".", "casecmp", "(", "'hosted-id.google.com'", ")", "return", "false", "end", "if", "cache", "put_cache", "(", "url", ",", "body", ")", "end", "return", "body", "end" ]
Fetches the XRDS and verifies the signature and authority for the doc
[ "Fetches", "the", "XRDS", "and", "verifies", "the", "signature", "and", "authority", "for", "the", "doc" ]
ca05e09eb8ad8d992df73cf8bd9eb1f097a4de85
https://github.com/atmos/warden-googleapps/blob/ca05e09eb8ad8d992df73cf8bd9eb1f097a4de85/lib/warden-googleapps/gapps_openid.rb#L146-L168
train
atmos/warden-googleapps
lib/warden-googleapps/gapps_openid.rb
OpenID.GoogleDiscovery.get_user_xrds_url
def get_user_xrds_url(xrds, claimed_id) types_to_match = ['http://www.iana.org/assignments/relation/describedby'] services = OpenID::Yadis::apply_filter(claimed_id, xrds) services.each do | service | if service.match_types(types_to_match) template = REXML::XPath.first(service.service_element, '//openid:URITemplate', NAMESPACES) authority = REXML::XPath.first(service.service_element, '//openid:NextAuthority', NAMESPACES) url = template.text.gsub('{%uri}', CGI::escape(claimed_id)) return [url, authority.text] end end end
ruby
def get_user_xrds_url(xrds, claimed_id) types_to_match = ['http://www.iana.org/assignments/relation/describedby'] services = OpenID::Yadis::apply_filter(claimed_id, xrds) services.each do | service | if service.match_types(types_to_match) template = REXML::XPath.first(service.service_element, '//openid:URITemplate', NAMESPACES) authority = REXML::XPath.first(service.service_element, '//openid:NextAuthority', NAMESPACES) url = template.text.gsub('{%uri}', CGI::escape(claimed_id)) return [url, authority.text] end end end
[ "def", "get_user_xrds_url", "(", "xrds", ",", "claimed_id", ")", "types_to_match", "=", "[", "'http://www.iana.org/assignments/relation/describedby'", "]", "services", "=", "OpenID", "::", "Yadis", "::", "apply_filter", "(", "claimed_id", ",", "xrds", ")", "services", ".", "each", "do", "|", "service", "|", "if", "service", ".", "match_types", "(", "types_to_match", ")", "template", "=", "REXML", "::", "XPath", ".", "first", "(", "service", ".", "service_element", ",", "'//openid:URITemplate'", ",", "NAMESPACES", ")", "authority", "=", "REXML", "::", "XPath", ".", "first", "(", "service", ".", "service_element", ",", "'//openid:NextAuthority'", ",", "NAMESPACES", ")", "url", "=", "template", ".", "text", ".", "gsub", "(", "'{%uri}'", ",", "CGI", "::", "escape", "(", "claimed_id", ")", ")", "return", "[", "url", ",", "authority", ".", "text", "]", "end", "end", "end" ]
Process the URITemplate in the XRDS to derive the location of the claimed id's XRDS
[ "Process", "the", "URITemplate", "in", "the", "XRDS", "to", "derive", "the", "location", "of", "the", "claimed", "id", "s", "XRDS" ]
ca05e09eb8ad8d992df73cf8bd9eb1f097a4de85
https://github.com/atmos/warden-googleapps/blob/ca05e09eb8ad8d992df73cf8bd9eb1f097a4de85/lib/warden-googleapps/gapps_openid.rb#L171-L182
train
cheeyeo/pipeline
lib/pipeline/builder.rb
Pipeline.Builder.build_operation_chain
def build_operation_chain(stack) empty_op = EmptyOperation.new(nil) stack.reverse.reduce(empty_op) do |next_op, current_op| klass, args, block = current_op if Class === klass klass.new(next_op, *args, &block) elsif Proc === klass lambda do |env| next_op.call(klass.call(env, *args)) end else raise StandardError, "Invalid operation, doesn't respond to `call`: #{klass.inspect}" end end end
ruby
def build_operation_chain(stack) empty_op = EmptyOperation.new(nil) stack.reverse.reduce(empty_op) do |next_op, current_op| klass, args, block = current_op if Class === klass klass.new(next_op, *args, &block) elsif Proc === klass lambda do |env| next_op.call(klass.call(env, *args)) end else raise StandardError, "Invalid operation, doesn't respond to `call`: #{klass.inspect}" end end end
[ "def", "build_operation_chain", "(", "stack", ")", "empty_op", "=", "EmptyOperation", ".", "new", "(", "nil", ")", "stack", ".", "reverse", ".", "reduce", "(", "empty_op", ")", "do", "|", "next_op", ",", "current_op", "|", "klass", ",", "args", ",", "block", "=", "current_op", "if", "Class", "===", "klass", "klass", ".", "new", "(", "next_op", ",", "*", "args", ",", "&", "block", ")", "elsif", "Proc", "===", "klass", "lambda", "do", "|", "env", "|", "next_op", ".", "call", "(", "klass", ".", "call", "(", "env", ",", "*", "args", ")", ")", "end", "else", "raise", "StandardError", ",", "\"Invalid operation, doesn't respond to `call`: #{klass.inspect}\"", "end", "end", "end" ]
Iterate through the stack and build a single callable object which consists of each operation referencing the next one in the chain
[ "Iterate", "through", "the", "stack", "and", "build", "a", "single", "callable", "object", "which", "consists", "of", "each", "operation", "referencing", "the", "next", "one", "in", "the", "chain" ]
e31fc1c99fa9f9600479494f43479581d546349c
https://github.com/cheeyeo/pipeline/blob/e31fc1c99fa9f9600479494f43479581d546349c/lib/pipeline/builder.rb#L43-L59
train
robertwahler/repo_manager
lib/repo_manager/assets/base_asset.rb
RepoManager.BaseAsset.method_missing
def method_missing(name, *args, &block) return attributes[name.to_sym] if attributes.include?(name.to_sym) return super end
ruby
def method_missing(name, *args, &block) return attributes[name.to_sym] if attributes.include?(name.to_sym) return super end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "return", "attributes", "[", "name", ".", "to_sym", "]", "if", "attributes", ".", "include?", "(", "name", ".", "to_sym", ")", "return", "super", "end" ]
support for Mustache rendering of ad hoc user defined variables if the key exists in the hash, use if for a lookup
[ "support", "for", "Mustache", "rendering", "of", "ad", "hoc", "user", "defined", "variables", "if", "the", "key", "exists", "in", "the", "hash", "use", "if", "for", "a", "lookup" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/assets/base_asset.rb#L187-L190
train
aelogica/express_templates
lib/arbre/patches.rb
Arbre.Element.helper_method
def helper_method(name, *args, &block) if name.match /_path$/ helpers.send(name, *args, &block) elsif (const_get([name, 'engine'].join('/').classify) rescue nil) helpers.send(name, *args, &block) else current_arbre_element.add_child helpers.send(name, *args, &block) end end
ruby
def helper_method(name, *args, &block) if name.match /_path$/ helpers.send(name, *args, &block) elsif (const_get([name, 'engine'].join('/').classify) rescue nil) helpers.send(name, *args, &block) else current_arbre_element.add_child helpers.send(name, *args, &block) end end
[ "def", "helper_method", "(", "name", ",", "*", "args", ",", "&", "block", ")", "if", "name", ".", "match", "/", "/", "helpers", ".", "send", "(", "name", ",", "*", "args", ",", "&", "block", ")", "elsif", "(", "const_get", "(", "[", "name", ",", "'engine'", "]", ".", "join", "(", "'/'", ")", ".", "classify", ")", "rescue", "nil", ")", "helpers", ".", "send", "(", "name", ",", "*", "args", ",", "&", "block", ")", "else", "current_arbre_element", ".", "add_child", "helpers", ".", "send", "(", "name", ",", "*", "args", ",", "&", "block", ")", "end", "end" ]
In order to not pollute our templates with helpers. prefixed everywhere we want to try to distinguish helpers that are almost always used as parameters to other methods such as path helpers and not add them as elements
[ "In", "order", "to", "not", "pollute", "our", "templates", "with", "helpers", ".", "prefixed", "everywhere", "we", "want", "to", "try", "to", "distinguish", "helpers", "that", "are", "almost", "always", "used", "as", "parameters", "to", "other", "methods", "such", "as", "path", "helpers", "and", "not", "add", "them", "as", "elements" ]
d5d447357e737c9220ca0025feb9e6f8f6249b5b
https://github.com/aelogica/express_templates/blob/d5d447357e737c9220ca0025feb9e6f8f6249b5b/lib/arbre/patches.rb#L64-L72
train
knut2/todonotes
lib/todonotes/todonotes.rb
Todonotes.Todonotes.log2file
def log2file(filename = File.basename($0) + '.todo', level = Log4r::ALL) @logger.add( Log4r::FileOutputter.new('ToDo', :filename => filename, :level => level, :formatter => FixmeFormatter )) end
ruby
def log2file(filename = File.basename($0) + '.todo', level = Log4r::ALL) @logger.add( Log4r::FileOutputter.new('ToDo', :filename => filename, :level => level, :formatter => FixmeFormatter )) end
[ "def", "log2file", "(", "filename", "=", "File", ".", "basename", "(", "$0", ")", "+", "'.todo'", ",", "level", "=", "Log4r", "::", "ALL", ")", "@logger", ".", "add", "(", "Log4r", "::", "FileOutputter", ".", "new", "(", "'ToDo'", ",", ":filename", "=>", "filename", ",", ":level", "=>", "level", ",", ":formatter", "=>", "FixmeFormatter", ")", ")", "end" ]
=begin rdoc Write the todo's in a logging file. Default filename is $0.todo =end
[ "=", "begin", "rdoc", "Write", "the", "todo", "s", "in", "a", "logging", "file", "." ]
67e6e9402d2e67fb0cda320669dd33d737351fa4
https://github.com/knut2/todonotes/blob/67e6e9402d2e67fb0cda320669dd33d737351fa4/lib/todonotes/todonotes.rb#L46-L53
train
duritong/ruby-cobbler
lib/cobbler/base.rb
Cobbler.Base.save
def save unless [ :handle, :new, :modify, :save ].all?{|method| api_methods[method] } raise "Not all necessary api methods are defined to process this action!" end entry = self.class.find_one(name) self.class.in_transaction(true) do |token| if entry entryid = self.class.make_call(api_methods[:handle],name,token) else entryid = self.class.make_call(api_methods[:new],token) self.class.make_call(api_methods[:modify],entryid,'name', name, token) end cobbler_record_fields.each do |field| field_s = field.to_s if !locked_fields.include?(field) && user_definitions.has_key?(field_s) self.class.make_call(api_methods[:modify],entryid,field_s, user_definitions[field_s], token) end end cobbler_collections_store_callbacks.each do |callback| send(callback,entryid,token) end self.class.make_call(api_methods[:save],entryid,token) end end
ruby
def save unless [ :handle, :new, :modify, :save ].all?{|method| api_methods[method] } raise "Not all necessary api methods are defined to process this action!" end entry = self.class.find_one(name) self.class.in_transaction(true) do |token| if entry entryid = self.class.make_call(api_methods[:handle],name,token) else entryid = self.class.make_call(api_methods[:new],token) self.class.make_call(api_methods[:modify],entryid,'name', name, token) end cobbler_record_fields.each do |field| field_s = field.to_s if !locked_fields.include?(field) && user_definitions.has_key?(field_s) self.class.make_call(api_methods[:modify],entryid,field_s, user_definitions[field_s], token) end end cobbler_collections_store_callbacks.each do |callback| send(callback,entryid,token) end self.class.make_call(api_methods[:save],entryid,token) end end
[ "def", "save", "unless", "[", ":handle", ",", ":new", ",", ":modify", ",", ":save", "]", ".", "all?", "{", "|", "method", "|", "api_methods", "[", "method", "]", "}", "raise", "\"Not all necessary api methods are defined to process this action!\"", "end", "entry", "=", "self", ".", "class", ".", "find_one", "(", "name", ")", "self", ".", "class", ".", "in_transaction", "(", "true", ")", "do", "|", "token", "|", "if", "entry", "entryid", "=", "self", ".", "class", ".", "make_call", "(", "api_methods", "[", ":handle", "]", ",", "name", ",", "token", ")", "else", "entryid", "=", "self", ".", "class", ".", "make_call", "(", "api_methods", "[", ":new", "]", ",", "token", ")", "self", ".", "class", ".", "make_call", "(", "api_methods", "[", ":modify", "]", ",", "entryid", ",", "'name'", ",", "name", ",", "token", ")", "end", "cobbler_record_fields", ".", "each", "do", "|", "field", "|", "field_s", "=", "field", ".", "to_s", "if", "!", "locked_fields", ".", "include?", "(", "field", ")", "&&", "user_definitions", ".", "has_key?", "(", "field_s", ")", "self", ".", "class", ".", "make_call", "(", "api_methods", "[", ":modify", "]", ",", "entryid", ",", "field_s", ",", "user_definitions", "[", "field_s", "]", ",", "token", ")", "end", "end", "cobbler_collections_store_callbacks", ".", "each", "do", "|", "callback", "|", "send", "(", "callback", ",", "entryid", ",", "token", ")", "end", "self", ".", "class", ".", "make_call", "(", "api_methods", "[", ":save", "]", ",", "entryid", ",", "token", ")", "end", "end" ]
Save an item on the remote cobbler server This will first lookup if the item already exists on the remote server and use its handle store the attributes. Otherwise a new item is created.
[ "Save", "an", "item", "on", "the", "remote", "cobbler", "server", "This", "will", "first", "lookup", "if", "the", "item", "already", "exists", "on", "the", "remote", "server", "and", "use", "its", "handle", "store", "the", "attributes", ".", "Otherwise", "a", "new", "item", "is", "created", "." ]
bb0c49c3a8325b0861aef25e8994c468e910cb12
https://github.com/duritong/ruby-cobbler/blob/bb0c49c3a8325b0861aef25e8994c468e910cb12/lib/cobbler/base.rb#L93-L119
train
duritong/ruby-cobbler
lib/cobbler/base.rb
Cobbler.Base.remove
def remove raise "Not all necessary api methods are defined to process this action!" unless api_methods[:remove] self.class.in_transaction(true) do |token| self.class.make_call(api_methods[:remove],name,token) end end
ruby
def remove raise "Not all necessary api methods are defined to process this action!" unless api_methods[:remove] self.class.in_transaction(true) do |token| self.class.make_call(api_methods[:remove],name,token) end end
[ "def", "remove", "raise", "\"Not all necessary api methods are defined to process this action!\"", "unless", "api_methods", "[", ":remove", "]", "self", ".", "class", ".", "in_transaction", "(", "true", ")", "do", "|", "token", "|", "self", ".", "class", ".", "make_call", "(", "api_methods", "[", ":remove", "]", ",", "name", ",", "token", ")", "end", "end" ]
delete the item on the cobbler server
[ "delete", "the", "item", "on", "the", "cobbler", "server" ]
bb0c49c3a8325b0861aef25e8994c468e910cb12
https://github.com/duritong/ruby-cobbler/blob/bb0c49c3a8325b0861aef25e8994c468e910cb12/lib/cobbler/base.rb#L122-L127
train
duritong/ruby-cobbler
lib/cobbler/base.rb
Cobbler.Base.copy
def copy(newname) raise "Not all necessary api methods are defined to process this action!" unless api_methods[:copy] entry = self.class.find_one(name) if entry self.class.in_transaction(true) do |token| entryid = self.class.make_call(api_methods[:handle],name,token) self.class.make_call(api_methods[:copy],entryid,newname,token) end end end
ruby
def copy(newname) raise "Not all necessary api methods are defined to process this action!" unless api_methods[:copy] entry = self.class.find_one(name) if entry self.class.in_transaction(true) do |token| entryid = self.class.make_call(api_methods[:handle],name,token) self.class.make_call(api_methods[:copy],entryid,newname,token) end end end
[ "def", "copy", "(", "newname", ")", "raise", "\"Not all necessary api methods are defined to process this action!\"", "unless", "api_methods", "[", ":copy", "]", "entry", "=", "self", ".", "class", ".", "find_one", "(", "name", ")", "if", "entry", "self", ".", "class", ".", "in_transaction", "(", "true", ")", "do", "|", "token", "|", "entryid", "=", "self", ".", "class", ".", "make_call", "(", "api_methods", "[", ":handle", "]", ",", "name", ",", "token", ")", "self", ".", "class", ".", "make_call", "(", "api_methods", "[", ":copy", "]", ",", "entryid", ",", "newname", ",", "token", ")", "end", "end", "end" ]
copy the item on the cobbler server
[ "copy", "the", "item", "on", "the", "cobbler", "server" ]
bb0c49c3a8325b0861aef25e8994c468e910cb12
https://github.com/duritong/ruby-cobbler/blob/bb0c49c3a8325b0861aef25e8994c468e910cb12/lib/cobbler/base.rb#L130-L139
train
suculent/apprepo
lib/apprepo/setup.rb
AppRepo.Setup.generate_apprepo_file
def generate_apprepo_file(_apprepo_path, options) # v = options[:app].latest_version # generate_apprepo_file(v, File.join(apprepo_path, 'manifest.json')) # Generate the final Repofile here gem_path = Helper.gem_path('apprepo') apprepo = File.read("#{gem_path}/../assets/RepofileDefault") apprepo.gsub!('[[APP_IDENTIFIER]]', options[:app].bundle_id) apprepo.gsub!('[[APPREPO_IPA_PATH]]', options[:app].file_path) apprepo.gsub!('[[APP_VERSION]]', options[:app].version) apprepo.gsub!('[[APP_NAME]]', options[:app].name) # apprepo (was deliver) end
ruby
def generate_apprepo_file(_apprepo_path, options) # v = options[:app].latest_version # generate_apprepo_file(v, File.join(apprepo_path, 'manifest.json')) # Generate the final Repofile here gem_path = Helper.gem_path('apprepo') apprepo = File.read("#{gem_path}/../assets/RepofileDefault") apprepo.gsub!('[[APP_IDENTIFIER]]', options[:app].bundle_id) apprepo.gsub!('[[APPREPO_IPA_PATH]]', options[:app].file_path) apprepo.gsub!('[[APP_VERSION]]', options[:app].version) apprepo.gsub!('[[APP_NAME]]', options[:app].name) # apprepo (was deliver) end
[ "def", "generate_apprepo_file", "(", "_apprepo_path", ",", "options", ")", "gem_path", "=", "Helper", ".", "gem_path", "(", "'apprepo'", ")", "apprepo", "=", "File", ".", "read", "(", "\"#{gem_path}/../assets/RepofileDefault\"", ")", "apprepo", ".", "gsub!", "(", "'[[APP_IDENTIFIER]]'", ",", "options", "[", ":app", "]", ".", "bundle_id", ")", "apprepo", ".", "gsub!", "(", "'[[APPREPO_IPA_PATH]]'", ",", "options", "[", ":app", "]", ".", "file_path", ")", "apprepo", ".", "gsub!", "(", "'[[APP_VERSION]]'", ",", "options", "[", ":app", "]", ".", "version", ")", "apprepo", ".", "gsub!", "(", "'[[APP_NAME]]'", ",", "options", "[", ":app", "]", ".", "name", ")", "end" ]
This method takes care of creating a new 'apprepo' folder with metadata and screenshots folders
[ "This", "method", "takes", "care", "of", "creating", "a", "new", "apprepo", "folder", "with", "metadata", "and", "screenshots", "folders" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/setup.rb#L16-L28
train
grzlus/acts_as_nested_interval
lib/acts_as_nested_interval/class_methods.rb
ActsAsNestedInterval.ClassMethods.rebuild_nested_interval_tree!
def rebuild_nested_interval_tree! # temporary changes skip_callback :update, :before, :update_nested_interval old_default_scopes = default_scopes # save to revert later default_scope ->{ where("#{quoted_table_name}.lftq > 0") } # use lft1 > 0 as a "migrated?" flag # zero all intervals update_hash = {lftp: 0, lftq: 0} update_hash[:rgtp] = 0 if columns_hash["rgtp"] update_hash[:rgtq] = 0 if columns_hash["rgtq"] update_hash[:lft] = 0 if columns_hash["lft"] update_hash[:rgt] = 0 if columns_hash["rgt"] update_all update_hash # recompute intervals with a recursive lambda clear_cache! update_subtree = ->(node){ node.create_nested_interval node.save node.class.unscoped.where(nested_interval.foreign_key => node.id).find_each &update_subtree } unscoped.roots.find_each &update_subtree # revert changes set_callback :update, :before, :update_nested_interval self.default_scopes = old_default_scopes end
ruby
def rebuild_nested_interval_tree! # temporary changes skip_callback :update, :before, :update_nested_interval old_default_scopes = default_scopes # save to revert later default_scope ->{ where("#{quoted_table_name}.lftq > 0") } # use lft1 > 0 as a "migrated?" flag # zero all intervals update_hash = {lftp: 0, lftq: 0} update_hash[:rgtp] = 0 if columns_hash["rgtp"] update_hash[:rgtq] = 0 if columns_hash["rgtq"] update_hash[:lft] = 0 if columns_hash["lft"] update_hash[:rgt] = 0 if columns_hash["rgt"] update_all update_hash # recompute intervals with a recursive lambda clear_cache! update_subtree = ->(node){ node.create_nested_interval node.save node.class.unscoped.where(nested_interval.foreign_key => node.id).find_each &update_subtree } unscoped.roots.find_each &update_subtree # revert changes set_callback :update, :before, :update_nested_interval self.default_scopes = old_default_scopes end
[ "def", "rebuild_nested_interval_tree!", "skip_callback", ":update", ",", ":before", ",", ":update_nested_interval", "old_default_scopes", "=", "default_scopes", "default_scope", "->", "{", "where", "(", "\"#{quoted_table_name}.lftq > 0\"", ")", "}", "update_hash", "=", "{", "lftp", ":", "0", ",", "lftq", ":", "0", "}", "update_hash", "[", ":rgtp", "]", "=", "0", "if", "columns_hash", "[", "\"rgtp\"", "]", "update_hash", "[", ":rgtq", "]", "=", "0", "if", "columns_hash", "[", "\"rgtq\"", "]", "update_hash", "[", ":lft", "]", "=", "0", "if", "columns_hash", "[", "\"lft\"", "]", "update_hash", "[", ":rgt", "]", "=", "0", "if", "columns_hash", "[", "\"rgt\"", "]", "update_all", "update_hash", "clear_cache!", "update_subtree", "=", "->", "(", "node", ")", "{", "node", ".", "create_nested_interval", "node", ".", "save", "node", ".", "class", ".", "unscoped", ".", "where", "(", "nested_interval", ".", "foreign_key", "=>", "node", ".", "id", ")", ".", "find_each", "&", "update_subtree", "}", "unscoped", ".", "roots", ".", "find_each", "&", "update_subtree", "set_callback", ":update", ",", ":before", ",", ":update_nested_interval", "self", ".", "default_scopes", "=", "old_default_scopes", "end" ]
Rebuild the intervals tree
[ "Rebuild", "the", "intervals", "tree" ]
9a588bf515570e4a1e1311dc58dc5eea8bfffd8e
https://github.com/grzlus/acts_as_nested_interval/blob/9a588bf515570e4a1e1311dc58dc5eea8bfffd8e/lib/acts_as_nested_interval/class_methods.rb#L5-L31
train
bachya/cliutils
lib/cliutils/prefs/pref.rb
CLIUtils.Pref.deliver
def deliver(default = nil) # Design decision: the pre-prompt behavior # gets evaluated *once*, not every time the # user gets prompted. This prevents multiple # evaluations when bad options are provided. _eval_pre if @pre valid_option_chosen = false until valid_option_chosen response = messenger.prompt(@prompt_text, default) if validate(response) valid_option_chosen = true @answer = evaluate_behaviors(response) _eval_post if @post else messenger.error(@last_error_message) end end end
ruby
def deliver(default = nil) # Design decision: the pre-prompt behavior # gets evaluated *once*, not every time the # user gets prompted. This prevents multiple # evaluations when bad options are provided. _eval_pre if @pre valid_option_chosen = false until valid_option_chosen response = messenger.prompt(@prompt_text, default) if validate(response) valid_option_chosen = true @answer = evaluate_behaviors(response) _eval_post if @post else messenger.error(@last_error_message) end end end
[ "def", "deliver", "(", "default", "=", "nil", ")", "_eval_pre", "if", "@pre", "valid_option_chosen", "=", "false", "until", "valid_option_chosen", "response", "=", "messenger", ".", "prompt", "(", "@prompt_text", ",", "default", ")", "if", "validate", "(", "response", ")", "valid_option_chosen", "=", "true", "@answer", "=", "evaluate_behaviors", "(", "response", ")", "_eval_post", "if", "@post", "else", "messenger", ".", "error", "(", "@last_error_message", ")", "end", "end", "end" ]
Initializes a new Pref via passed-in parameters. Also initializes objects for each Validator and Behavior on this Pref. @param [Hash] params Parameters to initialize @return [void] Custom equality operator for this class. @param [Pref] other @return [Boolean] Delivers the prompt the user. Handles retries after incorrect answers, validation, behavior evaluation, and pre-/post-behaviors. @param [String] default The default option @return [void]
[ "Initializes", "a", "new", "Pref", "via", "passed", "-", "in", "parameters", ".", "Also", "initializes", "objects", "for", "each", "Validator", "and", "Behavior", "on", "this", "Pref", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/prefs/pref.rb#L114-L132
train
bachya/cliutils
lib/cliutils/prefs/pref.rb
CLIUtils.Pref.evaluate_behaviors
def evaluate_behaviors(text) modified_text = text if @behavior_objects @behavior_objects.each do |b| modified_text = b.evaluate(modified_text) end end modified_text end
ruby
def evaluate_behaviors(text) modified_text = text if @behavior_objects @behavior_objects.each do |b| modified_text = b.evaluate(modified_text) end end modified_text end
[ "def", "evaluate_behaviors", "(", "text", ")", "modified_text", "=", "text", "if", "@behavior_objects", "@behavior_objects", ".", "each", "do", "|", "b", "|", "modified_text", "=", "b", ".", "evaluate", "(", "modified_text", ")", "end", "end", "modified_text", "end" ]
Runs the passed text through this Pref's behaviors. @param [String] text The text to evaluate @return [String]
[ "Runs", "the", "passed", "text", "through", "this", "Pref", "s", "behaviors", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/prefs/pref.rb#L137-L145
train
bachya/cliutils
lib/cliutils/prefs/pref.rb
CLIUtils.Pref._check_validators
def _check_validators(text) ret = true if @validator_objects @validator_objects.each do |v| v.validate(text) unless v.is_valid @last_error_message = v.message ret = false end end end ret end
ruby
def _check_validators(text) ret = true if @validator_objects @validator_objects.each do |v| v.validate(text) unless v.is_valid @last_error_message = v.message ret = false end end end ret end
[ "def", "_check_validators", "(", "text", ")", "ret", "=", "true", "if", "@validator_objects", "@validator_objects", ".", "each", "do", "|", "v", "|", "v", ".", "validate", "(", "text", ")", "unless", "v", ".", "is_valid", "@last_error_message", "=", "v", ".", "message", "ret", "=", "false", "end", "end", "end", "ret", "end" ]
Validates a text against the validators for this Pref @param [String] text The text to validate @return [Boolean]
[ "Validates", "a", "text", "against", "the", "validators", "for", "this", "Pref" ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/prefs/pref.rb#L176-L188
train
bachya/cliutils
lib/cliutils/prefs/pref.rb
CLIUtils.Pref._init_action
def _init_action(action_hash) obj = _load_asset(ASSET_TYPE_ACTION, action_hash[:name]) obj.parameters = action_hash[:parameters] obj end
ruby
def _init_action(action_hash) obj = _load_asset(ASSET_TYPE_ACTION, action_hash[:name]) obj.parameters = action_hash[:parameters] obj end
[ "def", "_init_action", "(", "action_hash", ")", "obj", "=", "_load_asset", "(", "ASSET_TYPE_ACTION", ",", "action_hash", "[", ":name", "]", ")", "obj", ".", "parameters", "=", "action_hash", "[", ":parameters", "]", "obj", "end" ]
Attempts to instantiate a Pre or Post Action based on name; if successful, the new object gets placed in @validator_objects @param [Hash] action_hash The hash of action data (name, params, etc.) @return [void]
[ "Attempts", "to", "instantiate", "a", "Pre", "or", "Post", "Action", "based", "on", "name", ";", "if", "successful", "the", "new", "object", "gets", "placed", "in" ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/prefs/pref.rb#L216-L220
train
bachya/cliutils
lib/cliutils/prefs/pref.rb
CLIUtils.Pref._init_and_add_behavior
def _init_and_add_behavior(behavior_hash) obj = _load_asset(ASSET_TYPE_BEHAVIOR, behavior_hash[:name]) unless obj.nil? obj.parameters = behavior_hash[:parameters] @behavior_objects << obj end end
ruby
def _init_and_add_behavior(behavior_hash) obj = _load_asset(ASSET_TYPE_BEHAVIOR, behavior_hash[:name]) unless obj.nil? obj.parameters = behavior_hash[:parameters] @behavior_objects << obj end end
[ "def", "_init_and_add_behavior", "(", "behavior_hash", ")", "obj", "=", "_load_asset", "(", "ASSET_TYPE_BEHAVIOR", ",", "behavior_hash", "[", ":name", "]", ")", "unless", "obj", ".", "nil?", "obj", ".", "parameters", "=", "behavior_hash", "[", ":parameters", "]", "@behavior_objects", "<<", "obj", "end", "end" ]
Attempts to instantiate a Behavior based on name; if successful, the new object gets placed in @behavior_objects @param [Hash] behavior_hash The Behavior attributes @return [void]
[ "Attempts", "to", "instantiate", "a", "Behavior", "based", "on", "name", ";", "if", "successful", "the", "new", "object", "gets", "placed", "in" ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/prefs/pref.rb#L226-L232
train
ktemkin/ruby-ise
lib/ise/symbol.rb
ISE.Symbol.each_attribute
def each_attribute #If we weren't passed a block, return an enumerator referencing this function. return enum_for(:each_attribute) unless block_given? #Yield each of the known attributes in turn. @xml.css("symbol attr").each do |attr| yield attr.attribute('name').value, attr.attribute('value').value end end
ruby
def each_attribute #If we weren't passed a block, return an enumerator referencing this function. return enum_for(:each_attribute) unless block_given? #Yield each of the known attributes in turn. @xml.css("symbol attr").each do |attr| yield attr.attribute('name').value, attr.attribute('value').value end end
[ "def", "each_attribute", "return", "enum_for", "(", ":each_attribute", ")", "unless", "block_given?", "@xml", ".", "css", "(", "\"symbol attr\"", ")", ".", "each", "do", "|", "attr", "|", "yield", "attr", ".", "attribute", "(", "'name'", ")", ".", "value", ",", "attr", ".", "attribute", "(", "'value'", ")", ".", "value", "end", "end" ]
Iterates over each attribute present in the given symbol.
[ "Iterates", "over", "each", "attribute", "present", "in", "the", "given", "symbol", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/symbol.rb#L76-L86
train
ktemkin/ruby-ise
lib/ise/symbol.rb
ISE.Symbol.set_pin_name
def set_pin_name(node, name) return unless node.name == "pin" #Change the name of any pin-label "text attributes" that reference the given pin. original_name = get_pin_name(node) #Retrieve a collection of all attributes that match the pin's original name... pin_labels = @xml.css("symbol graph attrtext[attrname=\"PinName\"][type=\"pin #{original_name}\"]") #And modify them so they now match the new node's name. pin_labels.each { |pin| pin.attribute('type').value = "pin #{name}" } #Finally, set the name of the node itself. node.attribute("name").value = name end
ruby
def set_pin_name(node, name) return unless node.name == "pin" #Change the name of any pin-label "text attributes" that reference the given pin. original_name = get_pin_name(node) #Retrieve a collection of all attributes that match the pin's original name... pin_labels = @xml.css("symbol graph attrtext[attrname=\"PinName\"][type=\"pin #{original_name}\"]") #And modify them so they now match the new node's name. pin_labels.each { |pin| pin.attribute('type').value = "pin #{name}" } #Finally, set the name of the node itself. node.attribute("name").value = name end
[ "def", "set_pin_name", "(", "node", ",", "name", ")", "return", "unless", "node", ".", "name", "==", "\"pin\"", "original_name", "=", "get_pin_name", "(", "node", ")", "pin_labels", "=", "@xml", ".", "css", "(", "\"symbol graph attrtext[attrname=\\\"PinName\\\"][type=\\\"pin #{original_name}\\\"]\"", ")", "pin_labels", ".", "each", "{", "|", "pin", "|", "pin", ".", "attribute", "(", "'type'", ")", ".", "value", "=", "\"pin #{name}\"", "}", "node", ".", "attribute", "(", "\"name\"", ")", ".", "value", "=", "name", "end" ]
Sets name of the pin represented by the given node, updating all values
[ "Sets", "name", "of", "the", "pin", "represented", "by", "the", "given", "node", "updating", "all", "values" ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/symbol.rb#L138-L154
train
ktemkin/ruby-ise
lib/ise/symbol.rb
ISE.Symbol.set_pin_width!
def set_pin_width!(node, width) #Get the components of the given bus' name. _, left, right = parse_pin_name(get_pin_name(node)) #If the pin wasn't initially a bus, make it one. left ||= 0 right ||= 0 #If our right bound is greater than our left one, adjust it. if right > left right = left + width - 1 #Otherwise, adjust the left width. else left = right + width - 1 end #Set the pin's bounds. set_pin_bounds!(node, left, right) end
ruby
def set_pin_width!(node, width) #Get the components of the given bus' name. _, left, right = parse_pin_name(get_pin_name(node)) #If the pin wasn't initially a bus, make it one. left ||= 0 right ||= 0 #If our right bound is greater than our left one, adjust it. if right > left right = left + width - 1 #Otherwise, adjust the left width. else left = right + width - 1 end #Set the pin's bounds. set_pin_bounds!(node, left, right) end
[ "def", "set_pin_width!", "(", "node", ",", "width", ")", "_", ",", "left", ",", "right", "=", "parse_pin_name", "(", "get_pin_name", "(", "node", ")", ")", "left", "||=", "0", "right", "||=", "0", "if", "right", ">", "left", "right", "=", "left", "+", "width", "-", "1", "else", "left", "=", "right", "+", "width", "-", "1", "end", "set_pin_bounds!", "(", "node", ",", "left", ",", "right", ")", "end" ]
Adjusts the "bounds" of the given bus so the bus is of the provided width by modifying the bus's upper bound. If the node is not a bus, it will be made into a bus whose right bound is 0. node: The node to be modified. width: The width to apply.
[ "Adjusts", "the", "bounds", "of", "the", "given", "bus", "so", "the", "bus", "is", "of", "the", "provided", "width", "by", "modifying", "the", "bus", "s", "upper", "bound", ".", "If", "the", "node", "is", "not", "a", "bus", "it", "will", "be", "made", "into", "a", "bus", "whose", "right", "bound", "is", "0", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/symbol.rb#L181-L201
train
praxis/praxis-blueprints
lib/praxis-blueprints/blueprint.rb
Praxis.Blueprint.render
def render(view_name = nil, context: Attributor::DEFAULT_ROOT_CONTEXT, renderer: Renderer.new, **opts) if !view_name.nil? warn 'DEPRECATED: please do not pass the view name as the first parameter in Blueprint.render, pass through the view: named param instead.' elsif opts.key?(:view) view_name = opts[:view] end fields = opts[:fields] view_name = :default if view_name.nil? && fields.nil? if view_name unless (view = self.class.views[view_name]) raise "view with name '#{view_name.inspect}' is not defined in #{self.class}" end return view.render(self, context: context, renderer: renderer) end # Accept a simple array of fields, and transform it to a 1-level hash with true values if fields.is_a? Array fields = fields.each_with_object({}) { |field, hash| hash[field] = true } end # expand fields expanded_fields = FieldExpander.expand(self.class, fields) renderer.render(self, expanded_fields, context: context) end
ruby
def render(view_name = nil, context: Attributor::DEFAULT_ROOT_CONTEXT, renderer: Renderer.new, **opts) if !view_name.nil? warn 'DEPRECATED: please do not pass the view name as the first parameter in Blueprint.render, pass through the view: named param instead.' elsif opts.key?(:view) view_name = opts[:view] end fields = opts[:fields] view_name = :default if view_name.nil? && fields.nil? if view_name unless (view = self.class.views[view_name]) raise "view with name '#{view_name.inspect}' is not defined in #{self.class}" end return view.render(self, context: context, renderer: renderer) end # Accept a simple array of fields, and transform it to a 1-level hash with true values if fields.is_a? Array fields = fields.each_with_object({}) { |field, hash| hash[field] = true } end # expand fields expanded_fields = FieldExpander.expand(self.class, fields) renderer.render(self, expanded_fields, context: context) end
[ "def", "render", "(", "view_name", "=", "nil", ",", "context", ":", "Attributor", "::", "DEFAULT_ROOT_CONTEXT", ",", "renderer", ":", "Renderer", ".", "new", ",", "**", "opts", ")", "if", "!", "view_name", ".", "nil?", "warn", "'DEPRECATED: please do not pass the view name as the first parameter in Blueprint.render, pass through the view: named param instead.'", "elsif", "opts", ".", "key?", "(", ":view", ")", "view_name", "=", "opts", "[", ":view", "]", "end", "fields", "=", "opts", "[", ":fields", "]", "view_name", "=", ":default", "if", "view_name", ".", "nil?", "&&", "fields", ".", "nil?", "if", "view_name", "unless", "(", "view", "=", "self", ".", "class", ".", "views", "[", "view_name", "]", ")", "raise", "\"view with name '#{view_name.inspect}' is not defined in #{self.class}\"", "end", "return", "view", ".", "render", "(", "self", ",", "context", ":", "context", ",", "renderer", ":", "renderer", ")", "end", "if", "fields", ".", "is_a?", "Array", "fields", "=", "fields", ".", "each_with_object", "(", "{", "}", ")", "{", "|", "field", ",", "hash", "|", "hash", "[", "field", "]", "=", "true", "}", "end", "expanded_fields", "=", "FieldExpander", ".", "expand", "(", "self", ".", "class", ",", "fields", ")", "renderer", ".", "render", "(", "self", ",", "expanded_fields", ",", "context", ":", "context", ")", "end" ]
Render the wrapped data with the given view
[ "Render", "the", "wrapped", "data", "with", "the", "given", "view" ]
57b9f9d81d313a7c7bf3e9eebb4b8153c3b48f1c
https://github.com/praxis/praxis-blueprints/blob/57b9f9d81d313a7c7bf3e9eebb4b8153c3b48f1c/lib/praxis-blueprints/blueprint.rb#L293-L319
train
eprothro/cassie
lib/cassie/schema/migration/dsl/column_operations.rb
Cassie::Schema::Migration::DSL.ColumnOperations.add_column
def add_column(table_name, column_name, type, options = {}) table_definition = TableDefinition.new if !table_definition.respond_to?(type) raise Errors::MigrationDefinitionError("Type '#{type}' is not valid for cassandra migration.") end table_definition.send(type, column_name, options) announce_operation "add_column(#{column_name}, #{type})" cql = "ALTER TABLE #{table_name} ADD " cql << table_definition.to_add_column_cql announce_suboperation cql execute cql end
ruby
def add_column(table_name, column_name, type, options = {}) table_definition = TableDefinition.new if !table_definition.respond_to?(type) raise Errors::MigrationDefinitionError("Type '#{type}' is not valid for cassandra migration.") end table_definition.send(type, column_name, options) announce_operation "add_column(#{column_name}, #{type})" cql = "ALTER TABLE #{table_name} ADD " cql << table_definition.to_add_column_cql announce_suboperation cql execute cql end
[ "def", "add_column", "(", "table_name", ",", "column_name", ",", "type", ",", "options", "=", "{", "}", ")", "table_definition", "=", "TableDefinition", ".", "new", "if", "!", "table_definition", ".", "respond_to?", "(", "type", ")", "raise", "Errors", "::", "MigrationDefinitionError", "(", "\"Type '#{type}' is not valid for cassandra migration.\"", ")", "end", "table_definition", ".", "send", "(", "type", ",", "column_name", ",", "options", ")", "announce_operation", "\"add_column(#{column_name}, #{type})\"", "cql", "=", "\"ALTER TABLE #{table_name} ADD \"", "cql", "<<", "table_definition", ".", "to_add_column_cql", "announce_suboperation", "cql", "execute", "cql", "end" ]
Adds a column to a table. options: same options you would pass to create a table with that column (i.e. :limit might be applicable)
[ "Adds", "a", "column", "to", "a", "table", "." ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/migration/dsl/column_operations.rb#L14-L30
train
xlab-si/server-sent-events-ruby
lib/server_sent_events/client.rb
ServerSentEvents.Client.listen
def listen Net::HTTP.start(@address.host, @address.port) do |http| # TODO(@tadeboro): Add support for adding custom headers (auth) http.request(Net::HTTP::Get.new(@address)) do |response| # TODO(@tadeboro): Handle non-200 here response.read_body do |chunk| @parser.push(chunk).each { |e| yield(e) } end end end end
ruby
def listen Net::HTTP.start(@address.host, @address.port) do |http| # TODO(@tadeboro): Add support for adding custom headers (auth) http.request(Net::HTTP::Get.new(@address)) do |response| # TODO(@tadeboro): Handle non-200 here response.read_body do |chunk| @parser.push(chunk).each { |e| yield(e) } end end end end
[ "def", "listen", "Net", "::", "HTTP", ".", "start", "(", "@address", ".", "host", ",", "@address", ".", "port", ")", "do", "|", "http", "|", "http", ".", "request", "(", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "@address", ")", ")", "do", "|", "response", "|", "response", ".", "read_body", "do", "|", "chunk", "|", "@parser", ".", "push", "(", "chunk", ")", ".", "each", "{", "|", "e", "|", "yield", "(", "e", ")", "}", "end", "end", "end", "end" ]
Create new SSE client. Note that creating new client does not establish connection to the server. Connection is established by the {#listen} call and torn down automatically when {#listen returns}. @param address [URI] endpoint to connect to @param parser [Parser] object that should be used to parse incoming data @param headers [Hash] additional headers that should be added to request Listen for events from the server. To perform some action when event arrives, specify a block that gets executed eact time new event is availble like this: client.listen { |e| puts e }
[ "Create", "new", "SSE", "client", "." ]
f57491a8ab3b08662f657668d3ffe6725dd251db
https://github.com/xlab-si/server-sent-events-ruby/blob/f57491a8ab3b08662f657668d3ffe6725dd251db/lib/server_sent_events/client.rb#L33-L43
train
dennmart/wanikani-gem
lib/wanikani/srs.rb
Wanikani.SRS.srs_distribution
def srs_distribution(item_type = "all") raise ArgumentError, "Please use a valid SRS type (or none for all types)" if !ITEM_TYPES.include?(item_type) response = api_response("srs-distribution") srs_distribution = response["requested_information"] return srs_distribution if item_type == "all" return srs_distribution[item_type] end
ruby
def srs_distribution(item_type = "all") raise ArgumentError, "Please use a valid SRS type (or none for all types)" if !ITEM_TYPES.include?(item_type) response = api_response("srs-distribution") srs_distribution = response["requested_information"] return srs_distribution if item_type == "all" return srs_distribution[item_type] end
[ "def", "srs_distribution", "(", "item_type", "=", "\"all\"", ")", "raise", "ArgumentError", ",", "\"Please use a valid SRS type (or none for all types)\"", "if", "!", "ITEM_TYPES", ".", "include?", "(", "item_type", ")", "response", "=", "api_response", "(", "\"srs-distribution\"", ")", "srs_distribution", "=", "response", "[", "\"requested_information\"", "]", "return", "srs_distribution", "if", "item_type", "==", "\"all\"", "return", "srs_distribution", "[", "item_type", "]", "end" ]
Gets the counts for each SRS level and item types. @param item_type [String] the SRS level that will be returned. @return [Hash] the SRS information for each level for the user.
[ "Gets", "the", "counts", "for", "each", "SRS", "level", "and", "item", "types", "." ]
70f9e4289f758c9663c0ee4d1172acb711487df9
https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/srs.rb#L10-L18
train
dennmart/wanikani-gem
lib/wanikani/srs.rb
Wanikani.SRS.srs_items_by_type
def srs_items_by_type(item_type) raise ArgumentError, "Please use a valid SRS type." if !ITEM_TYPES.include?(item_type) || item_type == "all" items_by_type = [] %w(radicals kanji vocabulary).each do |type| items = send("#{type}_list") items.reject! { |item| item["user_specific"].nil? || item["user_specific"]["srs"] != item_type }.map! do |item| item.merge!("type" => (type == 'radicals' ? 'radical' : type)) end items_by_type << items end items_by_type.flatten end
ruby
def srs_items_by_type(item_type) raise ArgumentError, "Please use a valid SRS type." if !ITEM_TYPES.include?(item_type) || item_type == "all" items_by_type = [] %w(radicals kanji vocabulary).each do |type| items = send("#{type}_list") items.reject! { |item| item["user_specific"].nil? || item["user_specific"]["srs"] != item_type }.map! do |item| item.merge!("type" => (type == 'radicals' ? 'radical' : type)) end items_by_type << items end items_by_type.flatten end
[ "def", "srs_items_by_type", "(", "item_type", ")", "raise", "ArgumentError", ",", "\"Please use a valid SRS type.\"", "if", "!", "ITEM_TYPES", ".", "include?", "(", "item_type", ")", "||", "item_type", "==", "\"all\"", "items_by_type", "=", "[", "]", "%w(", "radicals", "kanji", "vocabulary", ")", ".", "each", "do", "|", "type", "|", "items", "=", "send", "(", "\"#{type}_list\"", ")", "items", ".", "reject!", "{", "|", "item", "|", "item", "[", "\"user_specific\"", "]", ".", "nil?", "||", "item", "[", "\"user_specific\"", "]", "[", "\"srs\"", "]", "!=", "item_type", "}", ".", "map!", "do", "|", "item", "|", "item", ".", "merge!", "(", "\"type\"", "=>", "(", "type", "==", "'radicals'", "?", "'radical'", ":", "type", ")", ")", "end", "items_by_type", "<<", "items", "end", "items_by_type", ".", "flatten", "end" ]
Gets all items for a specific SRS level. @param item_type [String] the SRS level for the items returned. @return [Array<Hash>] all the items matching the specified SRS for each level for the user.
[ "Gets", "all", "items", "for", "a", "specific", "SRS", "level", "." ]
70f9e4289f758c9663c0ee4d1172acb711487df9
https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/srs.rb#L24-L37
train
ohler55/opee
lib/opee/queue.rb
Opee.Queue.add
def add(job) if @workers.empty? @work_queue.insert(0, job) else worker = @workers.pop() ask_worker(worker, job) end end
ruby
def add(job) if @workers.empty? @work_queue.insert(0, job) else worker = @workers.pop() ask_worker(worker, job) end end
[ "def", "add", "(", "job", ")", "if", "@workers", ".", "empty?", "@work_queue", ".", "insert", "(", "0", ",", "job", ")", "else", "worker", "=", "@workers", ".", "pop", "(", ")", "ask_worker", "(", "worker", ",", "job", ")", "end", "end" ]
Places a job on the work queue. This method is executed asynchronously. @param [Object] job work to be processed
[ "Places", "a", "job", "on", "the", "work", "queue", ".", "This", "method", "is", "executed", "asynchronously", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/queue.rb#L78-L85
train
ohler55/opee
lib/opee/queue.rb
Opee.Queue.ready
def ready(worker) if @work_queue.empty? @workers.insert(0, worker) unless @workers.include?(worker) else job = @work_queue.pop() @add_thread.wakeup() unless @add_thread.nil? ask_worker(worker, job) end end
ruby
def ready(worker) if @work_queue.empty? @workers.insert(0, worker) unless @workers.include?(worker) else job = @work_queue.pop() @add_thread.wakeup() unless @add_thread.nil? ask_worker(worker, job) end end
[ "def", "ready", "(", "worker", ")", "if", "@work_queue", ".", "empty?", "@workers", ".", "insert", "(", "0", ",", "worker", ")", "unless", "@workers", ".", "include?", "(", "worker", ")", "else", "job", "=", "@work_queue", ".", "pop", "(", ")", "@add_thread", ".", "wakeup", "(", ")", "unless", "@add_thread", ".", "nil?", "ask_worker", "(", "worker", ",", "job", ")", "end", "end" ]
Identifies a worker as available to process jobs when they become available. This method is executed asynchronously. @param [Actor] worker Actor that responds to the method to be called
[ "Identifies", "a", "worker", "as", "available", "to", "process", "jobs", "when", "they", "become", "available", ".", "This", "method", "is", "executed", "asynchronously", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/queue.rb#L90-L98
train
mLewisLogic/saddle
lib/saddle/requester.rb
Saddle.Requester.post
def post(url, data={}, options={}) response = connection.post do |req| req.saddle_options = options req.url(url) req.body = data end handle_response(response) end
ruby
def post(url, data={}, options={}) response = connection.post do |req| req.saddle_options = options req.url(url) req.body = data end handle_response(response) end
[ "def", "post", "(", "url", ",", "data", "=", "{", "}", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "saddle_options", "=", "options", "req", ".", "url", "(", "url", ")", "req", ".", "body", "=", "data", "end", "handle_response", "(", "response", ")", "end" ]
Make a POST request
[ "Make", "a", "POST", "request" ]
9f470a948039dbedb75655d883e714a29b273961
https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/requester.rb#L91-L98
train
mLewisLogic/saddle
lib/saddle/requester.rb
Saddle.Requester.delete
def delete(url, params={}, options={}) response = connection.delete do |req| req.saddle_options = options req.url(url, params) end handle_response(response) end
ruby
def delete(url, params={}, options={}) response = connection.delete do |req| req.saddle_options = options req.url(url, params) end handle_response(response) end
[ "def", "delete", "(", "url", ",", "params", "=", "{", "}", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "delete", "do", "|", "req", "|", "req", ".", "saddle_options", "=", "options", "req", ".", "url", "(", "url", ",", "params", ")", "end", "handle_response", "(", "response", ")", "end" ]
Make a DELETE request
[ "Make", "a", "DELETE", "request" ]
9f470a948039dbedb75655d883e714a29b273961
https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/requester.rb#L111-L117
train
mLewisLogic/saddle
lib/saddle/requester.rb
Saddle.Requester.connection
def connection @connection ||= Faraday.new(base_url, :builder_class => Saddle::RackBuilder) do |connection| # Include the requester level options connection.builder.saddle_options[:client_options] = @options # Config options connection.options[:timeout] = @timeout connection.builder.saddle_options[:request_style] = @request_style connection.builder.saddle_options[:num_retries] = @num_retries connection.builder.saddle_options[:client] = @parent_client # Support default return values upon exception connection.use(Saddle::Middleware::Response::DefaultResponse) # Hard timeout on the entire request connection.use(Saddle::Middleware::RubyTimeout) # Set up a user agent connection.use(Saddle::Middleware::Request::UserAgent) # Set up the path prefix if needed connection.use(Saddle::Middleware::Request::PathPrefix) # Apply additional implementation-specific middlewares @additional_middlewares.each do |m| m[:args] ? connection.use(m[:klass], *m[:args]) : connection.use(m[:klass]) end # Request encoding connection.use(Saddle::Middleware::Request::JsonEncoded) connection.use(Saddle::Middleware::Request::UrlEncoded) # Automatic retries connection.use(Saddle::Middleware::Request::Retry) # Raise exceptions on 4xx and 5xx errors connection.use(Saddle::Middleware::Response::RaiseError) # Handle parsing out the response if it's JSON connection.use(Saddle::Middleware::Response::ParseJson) # Set up instrumentation around the adapter for extensibility connection.use(FaradayMiddleware::Instrumentation) # Add in extra env data if needed connection.use(Saddle::Middleware::ExtraEnv) # Set up our adapter if @stubs.nil? # Use the default adapter connection.adapter(@http_adapter[:key], *@http_adapter[:args]) else # Use the test adapter connection.adapter(:test, @stubs) end end end
ruby
def connection @connection ||= Faraday.new(base_url, :builder_class => Saddle::RackBuilder) do |connection| # Include the requester level options connection.builder.saddle_options[:client_options] = @options # Config options connection.options[:timeout] = @timeout connection.builder.saddle_options[:request_style] = @request_style connection.builder.saddle_options[:num_retries] = @num_retries connection.builder.saddle_options[:client] = @parent_client # Support default return values upon exception connection.use(Saddle::Middleware::Response::DefaultResponse) # Hard timeout on the entire request connection.use(Saddle::Middleware::RubyTimeout) # Set up a user agent connection.use(Saddle::Middleware::Request::UserAgent) # Set up the path prefix if needed connection.use(Saddle::Middleware::Request::PathPrefix) # Apply additional implementation-specific middlewares @additional_middlewares.each do |m| m[:args] ? connection.use(m[:klass], *m[:args]) : connection.use(m[:klass]) end # Request encoding connection.use(Saddle::Middleware::Request::JsonEncoded) connection.use(Saddle::Middleware::Request::UrlEncoded) # Automatic retries connection.use(Saddle::Middleware::Request::Retry) # Raise exceptions on 4xx and 5xx errors connection.use(Saddle::Middleware::Response::RaiseError) # Handle parsing out the response if it's JSON connection.use(Saddle::Middleware::Response::ParseJson) # Set up instrumentation around the adapter for extensibility connection.use(FaradayMiddleware::Instrumentation) # Add in extra env data if needed connection.use(Saddle::Middleware::ExtraEnv) # Set up our adapter if @stubs.nil? # Use the default adapter connection.adapter(@http_adapter[:key], *@http_adapter[:args]) else # Use the test adapter connection.adapter(:test, @stubs) end end end
[ "def", "connection", "@connection", "||=", "Faraday", ".", "new", "(", "base_url", ",", ":builder_class", "=>", "Saddle", "::", "RackBuilder", ")", "do", "|", "connection", "|", "connection", ".", "builder", ".", "saddle_options", "[", ":client_options", "]", "=", "@options", "connection", ".", "options", "[", ":timeout", "]", "=", "@timeout", "connection", ".", "builder", ".", "saddle_options", "[", ":request_style", "]", "=", "@request_style", "connection", ".", "builder", ".", "saddle_options", "[", ":num_retries", "]", "=", "@num_retries", "connection", ".", "builder", ".", "saddle_options", "[", ":client", "]", "=", "@parent_client", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Response", "::", "DefaultResponse", ")", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "RubyTimeout", ")", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Request", "::", "UserAgent", ")", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Request", "::", "PathPrefix", ")", "@additional_middlewares", ".", "each", "do", "|", "m", "|", "m", "[", ":args", "]", "?", "connection", ".", "use", "(", "m", "[", ":klass", "]", ",", "*", "m", "[", ":args", "]", ")", ":", "connection", ".", "use", "(", "m", "[", ":klass", "]", ")", "end", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Request", "::", "JsonEncoded", ")", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Request", "::", "UrlEncoded", ")", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Request", "::", "Retry", ")", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Response", "::", "RaiseError", ")", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Response", "::", "ParseJson", ")", "connection", ".", "use", "(", "FaradayMiddleware", "::", "Instrumentation", ")", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "ExtraEnv", ")", "if", "@stubs", ".", "nil?", "connection", ".", "adapter", "(", "@http_adapter", "[", ":key", "]", ",", "*", "@http_adapter", "[", ":args", "]", ")", "else", "connection", ".", "adapter", "(", ":test", ",", "@stubs", ")", "end", "end", "end" ]
Build a connection instance, wrapped in the middleware that we want
[ "Build", "a", "connection", "instance", "wrapped", "in", "the", "middleware", "that", "we", "want" ]
9f470a948039dbedb75655d883e714a29b273961
https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/requester.rb#L134-L190
train
devs-ruby/devs
lib/devs/container.rb
DEVS.Container.remove_child
def remove_child(child) child = child.name if child.is_a?(Model) children.delete(child) end
ruby
def remove_child(child) child = child.name if child.is_a?(Model) children.delete(child) end
[ "def", "remove_child", "(", "child", ")", "child", "=", "child", ".", "name", "if", "child", ".", "is_a?", "(", "Model", ")", "children", ".", "delete", "(", "child", ")", "end" ]
Deletes the specified child from children list @param child [Model,String,Symbol] the child to remove @return [Model] the deleted child, or nil if no matching component is found.
[ "Deletes", "the", "specified", "child", "from", "children", "list" ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/container.rb#L57-L60
train
devs-ruby/devs
lib/devs/container.rb
DEVS.Container.attach
def attach(p1, to:, between: nil, and: nil) p2 = to sender = between # use binding#local_variable_get because 'and:' keyword argument clashes # with the language reserved keyword. receiver = binding.local_variable_get(:and) raise ArgumentError.new("'between:' keyword was omitted, 'p1' should be a Port.") if sender.nil? && !p1.is_a?(Port) raise ArgumentError.new("'and:' keyword was omitted, 'to:' should be a Port") if receiver.nil? && !p2.is_a?(Port) a = if p1.is_a?(Port) then p1.host elsif sender.is_a?(Coupleable) then sender elsif sender == @name then self else fetch_child(sender); end b = if p2.is_a?(Port) then p2.host elsif receiver.is_a?(Coupleable) then receiver elsif receiver == @name then self else fetch_child(receiver); end if has_child?(a) && has_child?(b) # IC p1 = a.output_port(p1) unless p1.is_a?(Port) p2 = b.input_port(p2) unless p2.is_a?(Port) raise InvalidPortTypeError.new unless p1.output? && p2.input? raise FeedbackLoopError.new("#{a} must be different than #{b}") if a.object_id == b.object_id _internal_couplings[p1] << p2 elsif a == self && has_child?(b) # EIC p1 = a.input_port(p1) unless p1.is_a?(Port) p2 = b.input_port(p2) unless p2.is_a?(Port) raise InvalidPortTypeError.new unless p1.input? && p2.input? _input_couplings[p1] << p2 elsif has_child?(a) && b == self # EOC p1 = a.output_port(p1) unless p1.is_a?(Port) p2 = b.output_port(p2) unless p2.is_a?(Port) raise InvalidPortTypeError.new unless p1.output? && p2.output? _output_couplings[p1] << p2 else raise InvalidPortHostError.new("Illegal coupling between #{p1} and #{p2}") end end
ruby
def attach(p1, to:, between: nil, and: nil) p2 = to sender = between # use binding#local_variable_get because 'and:' keyword argument clashes # with the language reserved keyword. receiver = binding.local_variable_get(:and) raise ArgumentError.new("'between:' keyword was omitted, 'p1' should be a Port.") if sender.nil? && !p1.is_a?(Port) raise ArgumentError.new("'and:' keyword was omitted, 'to:' should be a Port") if receiver.nil? && !p2.is_a?(Port) a = if p1.is_a?(Port) then p1.host elsif sender.is_a?(Coupleable) then sender elsif sender == @name then self else fetch_child(sender); end b = if p2.is_a?(Port) then p2.host elsif receiver.is_a?(Coupleable) then receiver elsif receiver == @name then self else fetch_child(receiver); end if has_child?(a) && has_child?(b) # IC p1 = a.output_port(p1) unless p1.is_a?(Port) p2 = b.input_port(p2) unless p2.is_a?(Port) raise InvalidPortTypeError.new unless p1.output? && p2.input? raise FeedbackLoopError.new("#{a} must be different than #{b}") if a.object_id == b.object_id _internal_couplings[p1] << p2 elsif a == self && has_child?(b) # EIC p1 = a.input_port(p1) unless p1.is_a?(Port) p2 = b.input_port(p2) unless p2.is_a?(Port) raise InvalidPortTypeError.new unless p1.input? && p2.input? _input_couplings[p1] << p2 elsif has_child?(a) && b == self # EOC p1 = a.output_port(p1) unless p1.is_a?(Port) p2 = b.output_port(p2) unless p2.is_a?(Port) raise InvalidPortTypeError.new unless p1.output? && p2.output? _output_couplings[p1] << p2 else raise InvalidPortHostError.new("Illegal coupling between #{p1} and #{p2}") end end
[ "def", "attach", "(", "p1", ",", "to", ":", ",", "between", ":", "nil", ",", "and", ":", "nil", ")", "p2", "=", "to", "sender", "=", "between", "receiver", "=", "binding", ".", "local_variable_get", "(", ":and", ")", "raise", "ArgumentError", ".", "new", "(", "\"'between:' keyword was omitted, 'p1' should be a Port.\"", ")", "if", "sender", ".", "nil?", "&&", "!", "p1", ".", "is_a?", "(", "Port", ")", "raise", "ArgumentError", ".", "new", "(", "\"'and:' keyword was omitted, 'to:' should be a Port\"", ")", "if", "receiver", ".", "nil?", "&&", "!", "p2", ".", "is_a?", "(", "Port", ")", "a", "=", "if", "p1", ".", "is_a?", "(", "Port", ")", "then", "p1", ".", "host", "elsif", "sender", ".", "is_a?", "(", "Coupleable", ")", "then", "sender", "elsif", "sender", "==", "@name", "then", "self", "else", "fetch_child", "(", "sender", ")", ";", "end", "b", "=", "if", "p2", ".", "is_a?", "(", "Port", ")", "then", "p2", ".", "host", "elsif", "receiver", ".", "is_a?", "(", "Coupleable", ")", "then", "receiver", "elsif", "receiver", "==", "@name", "then", "self", "else", "fetch_child", "(", "receiver", ")", ";", "end", "if", "has_child?", "(", "a", ")", "&&", "has_child?", "(", "b", ")", "p1", "=", "a", ".", "output_port", "(", "p1", ")", "unless", "p1", ".", "is_a?", "(", "Port", ")", "p2", "=", "b", ".", "input_port", "(", "p2", ")", "unless", "p2", ".", "is_a?", "(", "Port", ")", "raise", "InvalidPortTypeError", ".", "new", "unless", "p1", ".", "output?", "&&", "p2", ".", "input?", "raise", "FeedbackLoopError", ".", "new", "(", "\"#{a} must be different than #{b}\"", ")", "if", "a", ".", "object_id", "==", "b", ".", "object_id", "_internal_couplings", "[", "p1", "]", "<<", "p2", "elsif", "a", "==", "self", "&&", "has_child?", "(", "b", ")", "p1", "=", "a", ".", "input_port", "(", "p1", ")", "unless", "p1", ".", "is_a?", "(", "Port", ")", "p2", "=", "b", ".", "input_port", "(", "p2", ")", "unless", "p2", ".", "is_a?", "(", "Port", ")", "raise", "InvalidPortTypeError", ".", "new", "unless", "p1", ".", "input?", "&&", "p2", ".", "input?", "_input_couplings", "[", "p1", "]", "<<", "p2", "elsif", "has_child?", "(", "a", ")", "&&", "b", "==", "self", "p1", "=", "a", ".", "output_port", "(", "p1", ")", "unless", "p1", ".", "is_a?", "(", "Port", ")", "p2", "=", "b", ".", "output_port", "(", "p2", ")", "unless", "p2", ".", "is_a?", "(", "Port", ")", "raise", "InvalidPortTypeError", ".", "new", "unless", "p1", ".", "output?", "&&", "p2", ".", "output?", "_output_couplings", "[", "p1", "]", "<<", "p2", "else", "raise", "InvalidPortHostError", ".", "new", "(", "\"Illegal coupling between #{p1} and #{p2}\"", ")", "end", "end" ]
Adds a coupling to self between two ports. Depending on *p1* and *to* hosts, the function will create an internal coupling (IC), an external input coupling (EIC) or an external output coupling (EOC). @overload attach(p1, to:) @param p1 [Port] the sender port of the coupling @param to [Port] the receiver port of the coupling @overload attach(p1, to:, between:, and:) @param p1 [Port,Symbol,String] the sender port of the coupling @param to [Port,Symbol,String] the receiver port of the coupling @param between [Coupleable,Symbol,String] the sender @param and [Coupleable,Symbol,String] the receiver @raise [FeedbackLoopError] if *p1* and *p2* hosts are the same child when constructing an internal coupling. Direct feedback loops are not allowed, i.e, no output port of a component may be connected to an input port of the same component. @raise [InvalidPortTypeError] if given ports are not of the expected IO modes (:input or :output). @raise [InvalidPortHostError] if no coupling can be established from given ports hosts. @note If given port names *p1* and *p2* doesn't exist within their host (respectively *sender* and *receiver*), they will be automatically generated. @example Attach two ports together to form a new coupling attach component1.output_port(:out) to: component2.input_port(:in) # IC attach self.input_port(:in) to: child.input_port(:in) # EIC attach child.output_port(:out) to: self.output_port(:out) # EOC @example Attach specified ports and components to form a new coupling attach :out, to: :in, between: :component1, and: :component2 attach :in, to: :in, between: self, and: child
[ "Adds", "a", "coupling", "to", "self", "between", "two", "ports", "." ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/container.rb#L257-L296
train
suculent/apprepo
lib/apprepo/manifest.rb
AppRepo.Manifest.manifest_as_json
def manifest_as_json structure = { appcode: appcode, filename: filename, bundle_identifier: bundle_identifier, bundle_version: bundle_version, title: title, subtitle: subtitle, notify: notify } fputs structure end
ruby
def manifest_as_json structure = { appcode: appcode, filename: filename, bundle_identifier: bundle_identifier, bundle_version: bundle_version, title: title, subtitle: subtitle, notify: notify } fputs structure end
[ "def", "manifest_as_json", "structure", "=", "{", "appcode", ":", "appcode", ",", "filename", ":", "filename", ",", "bundle_identifier", ":", "bundle_identifier", ",", "bundle_version", ":", "bundle_version", ",", "title", ":", "title", ",", "subtitle", ":", "subtitle", ",", "notify", ":", "notify", "}", "fputs", "structure", "end" ]
Provide JSON serialized data
[ "Provide", "JSON", "serialized", "data" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/manifest.rb#L28-L40
train
eanlain/calligraphy
lib/calligraphy/resource/file_resource.rb
Calligraphy.FileResource.copy_options
def copy_options(options) copy_options = { can_copy: false, ancestor_exist: false, locked: false } destination = copy_destination options to_path = join_paths @root_dir, destination to_path_exists = File.exist? to_path copy_options[:ancestor_exist] = File.exist? parent_path destination copy_options[:locked] = can_copy_locked_option to_path, to_path_exists copy_options = can_copy_option copy_options, options, to_path_exists copy_options end
ruby
def copy_options(options) copy_options = { can_copy: false, ancestor_exist: false, locked: false } destination = copy_destination options to_path = join_paths @root_dir, destination to_path_exists = File.exist? to_path copy_options[:ancestor_exist] = File.exist? parent_path destination copy_options[:locked] = can_copy_locked_option to_path, to_path_exists copy_options = can_copy_option copy_options, options, to_path_exists copy_options end
[ "def", "copy_options", "(", "options", ")", "copy_options", "=", "{", "can_copy", ":", "false", ",", "ancestor_exist", ":", "false", ",", "locked", ":", "false", "}", "destination", "=", "copy_destination", "options", "to_path", "=", "join_paths", "@root_dir", ",", "destination", "to_path_exists", "=", "File", ".", "exist?", "to_path", "copy_options", "[", ":ancestor_exist", "]", "=", "File", ".", "exist?", "parent_path", "destination", "copy_options", "[", ":locked", "]", "=", "can_copy_locked_option", "to_path", ",", "to_path_exists", "copy_options", "=", "can_copy_option", "copy_options", ",", "options", ",", "to_path_exists", "copy_options", "end" ]
Responsible for returning a hash with keys indicating if the resource can be copied, if an ancestor exists, or if the copy destinatin is locked. Return hash should contain `can_copy`, `ancestor_exist`, and `locked` keys with boolean values. Used in COPY and MOVE (which inherits from COPY) requests.
[ "Responsible", "for", "returning", "a", "hash", "with", "keys", "indicating", "if", "the", "resource", "can", "be", "copied", "if", "an", "ancestor", "exists", "or", "if", "the", "copy", "destinatin", "is", "locked", "." ]
19290d38322287fcb8e0152a7ed3b7f01033b57e
https://github.com/eanlain/calligraphy/blob/19290d38322287fcb8e0152a7ed3b7f01033b57e/lib/calligraphy/resource/file_resource.rb#L73-L84
train
fulldecent/structured-acceptance-test
implementations/ruby/lib/process.rb
StatModule.Process.print
def print(formatted = nil) result = name unless version.nil? result += ", version #{version}" end if formatted result = "#{FORMATTING_STAR.colorize(:yellow)} #{result}" end result end
ruby
def print(formatted = nil) result = name unless version.nil? result += ", version #{version}" end if formatted result = "#{FORMATTING_STAR.colorize(:yellow)} #{result}" end result end
[ "def", "print", "(", "formatted", "=", "nil", ")", "result", "=", "name", "unless", "version", ".", "nil?", "result", "+=", "\", version #{version}\"", "end", "if", "formatted", "result", "=", "\"#{FORMATTING_STAR.colorize(:yellow)} #{result}\"", "end", "result", "end" ]
Get formatted information about process Params: +formatted+:: indicate weather print boring or pretty colorful process
[ "Get", "formatted", "information", "about", "process" ]
9766f4863a8bcfdf6ac50a7aa36cce0314481118
https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/process.rb#L141-L150
train
addagger/html_slicer
lib/html_slicer/interface.rb
HtmlSlicer.Interface.source
def source case options[:processors].present? when true then HtmlSlicer::Process.iterate(@env.send(@method_name), options[:processors]) else @env.send(@method_name) end end
ruby
def source case options[:processors].present? when true then HtmlSlicer::Process.iterate(@env.send(@method_name), options[:processors]) else @env.send(@method_name) end end
[ "def", "source", "case", "options", "[", ":processors", "]", ".", "present?", "when", "true", "then", "HtmlSlicer", "::", "Process", ".", "iterate", "(", "@env", ".", "send", "(", "@method_name", ")", ",", "options", "[", ":processors", "]", ")", "else", "@env", ".", "send", "(", "@method_name", ")", "end", "end" ]
Getting source content
[ "Getting", "source", "content" ]
bbe6ab55a0d0335621079c304af534959b518d8b
https://github.com/addagger/html_slicer/blob/bbe6ab55a0d0335621079c304af534959b518d8b/lib/html_slicer/interface.rb#L40-L46
train
addagger/html_slicer
lib/html_slicer/interface.rb
HtmlSlicer.Interface.slice!
def slice!(slice = nil) raise(Exception, "Slicing unavailable!") unless sliced? if slice.present? if slice.to_i.in?(1..slice_number) @current_slice = slice.to_i else raise(ArgumentError, "Slice number must be Integer in (1..#{slice_number}). #{slice.inspect} passed.") end end self end
ruby
def slice!(slice = nil) raise(Exception, "Slicing unavailable!") unless sliced? if slice.present? if slice.to_i.in?(1..slice_number) @current_slice = slice.to_i else raise(ArgumentError, "Slice number must be Integer in (1..#{slice_number}). #{slice.inspect} passed.") end end self end
[ "def", "slice!", "(", "slice", "=", "nil", ")", "raise", "(", "Exception", ",", "\"Slicing unavailable!\"", ")", "unless", "sliced?", "if", "slice", ".", "present?", "if", "slice", ".", "to_i", ".", "in?", "(", "1", "..", "slice_number", ")", "@current_slice", "=", "slice", ".", "to_i", "else", "raise", "(", "ArgumentError", ",", "\"Slice number must be Integer in (1..#{slice_number}). #{slice.inspect} passed.\"", ")", "end", "end", "self", "end" ]
General slicing method. Passing the argument changes the +current_slice+.
[ "General", "slicing", "method", ".", "Passing", "the", "argument", "changes", "the", "+", "current_slice", "+", "." ]
bbe6ab55a0d0335621079c304af534959b518d8b
https://github.com/addagger/html_slicer/blob/bbe6ab55a0d0335621079c304af534959b518d8b/lib/html_slicer/interface.rb#L99-L109
train
addagger/html_slicer
lib/html_slicer/interface.rb
HtmlSlicer.Interface.view
def view(node, slice, &block) slice = slice.to_i case node when ::HTML::Tag then children_view = node.children.map {|child| view(child, slice, &block)}.compact.join if resized? resizing.resize_node(node) end if sliced? if slicing.map.get(node, slice) || children_view.present? if node.closing == :close "</#{node.name}>" else s = "<#{node.name}" node.attributes.each do |k,v| s << " #{k}" s << "=\"#{v}\"" if String === v end s << " /" if node.closing == :self s << ">" s += children_view s << "</#{node.name}>" if node.closing != :self && !node.children.empty? s end end else node.to_s end when ::HTML::Text then if sliced? if range = slicing.map.get(node, slice) (range.is_a?(Array) ? node.content[Range.new(*range)] : node.content).tap do |export| unless range == true || (range.is_a?(Array) && range.last == -1) # broken text export << slicing.options.text_break if slicing.options.text_break if block_given? yield self, export end end end end else node.to_s end when ::HTML::CDATA then node.to_s when ::HTML::Node then node.children.map {|child| view(child, slice, &block)}.compact.join end end
ruby
def view(node, slice, &block) slice = slice.to_i case node when ::HTML::Tag then children_view = node.children.map {|child| view(child, slice, &block)}.compact.join if resized? resizing.resize_node(node) end if sliced? if slicing.map.get(node, slice) || children_view.present? if node.closing == :close "</#{node.name}>" else s = "<#{node.name}" node.attributes.each do |k,v| s << " #{k}" s << "=\"#{v}\"" if String === v end s << " /" if node.closing == :self s << ">" s += children_view s << "</#{node.name}>" if node.closing != :self && !node.children.empty? s end end else node.to_s end when ::HTML::Text then if sliced? if range = slicing.map.get(node, slice) (range.is_a?(Array) ? node.content[Range.new(*range)] : node.content).tap do |export| unless range == true || (range.is_a?(Array) && range.last == -1) # broken text export << slicing.options.text_break if slicing.options.text_break if block_given? yield self, export end end end end else node.to_s end when ::HTML::CDATA then node.to_s when ::HTML::Node then node.children.map {|child| view(child, slice, &block)}.compact.join end end
[ "def", "view", "(", "node", ",", "slice", ",", "&", "block", ")", "slice", "=", "slice", ".", "to_i", "case", "node", "when", "::", "HTML", "::", "Tag", "then", "children_view", "=", "node", ".", "children", ".", "map", "{", "|", "child", "|", "view", "(", "child", ",", "slice", ",", "&", "block", ")", "}", ".", "compact", ".", "join", "if", "resized?", "resizing", ".", "resize_node", "(", "node", ")", "end", "if", "sliced?", "if", "slicing", ".", "map", ".", "get", "(", "node", ",", "slice", ")", "||", "children_view", ".", "present?", "if", "node", ".", "closing", "==", ":close", "\"</#{node.name}>\"", "else", "s", "=", "\"<#{node.name}\"", "node", ".", "attributes", ".", "each", "do", "|", "k", ",", "v", "|", "s", "<<", "\" #{k}\"", "s", "<<", "\"=\\\"#{v}\\\"\"", "if", "String", "===", "v", "end", "s", "<<", "\" /\"", "if", "node", ".", "closing", "==", ":self", "s", "<<", "\">\"", "s", "+=", "children_view", "s", "<<", "\"</#{node.name}>\"", "if", "node", ".", "closing", "!=", ":self", "&&", "!", "node", ".", "children", ".", "empty?", "s", "end", "end", "else", "node", ".", "to_s", "end", "when", "::", "HTML", "::", "Text", "then", "if", "sliced?", "if", "range", "=", "slicing", ".", "map", ".", "get", "(", "node", ",", "slice", ")", "(", "range", ".", "is_a?", "(", "Array", ")", "?", "node", ".", "content", "[", "Range", ".", "new", "(", "*", "range", ")", "]", ":", "node", ".", "content", ")", ".", "tap", "do", "|", "export", "|", "unless", "range", "==", "true", "||", "(", "range", ".", "is_a?", "(", "Array", ")", "&&", "range", ".", "last", "==", "-", "1", ")", "export", "<<", "slicing", ".", "options", ".", "text_break", "if", "slicing", ".", "options", ".", "text_break", "if", "block_given?", "yield", "self", ",", "export", "end", "end", "end", "end", "else", "node", ".", "to_s", "end", "when", "::", "HTML", "::", "CDATA", "then", "node", ".", "to_s", "when", "::", "HTML", "::", "Node", "then", "node", ".", "children", ".", "map", "{", "|", "child", "|", "view", "(", "child", ",", "slice", ",", "&", "block", ")", "}", ".", "compact", ".", "join", "end", "end" ]
Return a textual representation of the node including all children.
[ "Return", "a", "textual", "representation", "of", "the", "node", "including", "all", "children", "." ]
bbe6ab55a0d0335621079c304af534959b518d8b
https://github.com/addagger/html_slicer/blob/bbe6ab55a0d0335621079c304af534959b518d8b/lib/html_slicer/interface.rb#L138-L186
train
eprothro/cassie
lib/cassie/schema/versioning.rb
Cassie::Schema.Versioning.version
def version SelectVersionsQuery.new.fetch_first || Version.new('0') rescue Cassandra::Errors::InvalidError raise uninitialized_error end
ruby
def version SelectVersionsQuery.new.fetch_first || Version.new('0') rescue Cassandra::Errors::InvalidError raise uninitialized_error end
[ "def", "version", "SelectVersionsQuery", ".", "new", ".", "fetch_first", "||", "Version", ".", "new", "(", "'0'", ")", "rescue", "Cassandra", "::", "Errors", "::", "InvalidError", "raise", "uninitialized_error", "end" ]
The current schema version @return [Version]
[ "The", "current", "schema", "version" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/versioning.rb#L18-L22
train
eprothro/cassie
lib/cassie/schema/versioning.rb
Cassie::Schema.Versioning.record_version
def record_version(version, set_execution_metadata=true) time = Time.now version.id ||= Cassandra::TimeUuid::Generator.new.at(time) if set_execution_metadata version.executed_at = time version.executor = Etc.getlogin rescue '<unknown>' end InsertVersionQuery.new(version: version).execute! @applied_versions = nil rescue StandardError => e version.id = nil version.executed_at = nil version.executor = nil raise e end
ruby
def record_version(version, set_execution_metadata=true) time = Time.now version.id ||= Cassandra::TimeUuid::Generator.new.at(time) if set_execution_metadata version.executed_at = time version.executor = Etc.getlogin rescue '<unknown>' end InsertVersionQuery.new(version: version).execute! @applied_versions = nil rescue StandardError => e version.id = nil version.executed_at = nil version.executor = nil raise e end
[ "def", "record_version", "(", "version", ",", "set_execution_metadata", "=", "true", ")", "time", "=", "Time", ".", "now", "version", ".", "id", "||=", "Cassandra", "::", "TimeUuid", "::", "Generator", ".", "new", ".", "at", "(", "time", ")", "if", "set_execution_metadata", "version", ".", "executed_at", "=", "time", "version", ".", "executor", "=", "Etc", ".", "getlogin", "rescue", "'<unknown>'", "end", "InsertVersionQuery", ".", "new", "(", "version", ":", "version", ")", ".", "execute!", "@applied_versions", "=", "nil", "rescue", "StandardError", "=>", "e", "version", ".", "id", "=", "nil", "version", ".", "executed_at", "=", "nil", "version", ".", "executor", "=", "nil", "raise", "e", "end" ]
Record a version in the schema version store. This should only be done if the version has been sucesfully migrated @param [Version] The version to record @param [Boolean] set_execution_metadata Determines whether or not to populate the version object with execution tracking info (+id+, +executed_at+, and +executor+). @return [Boolean] whether succesfull or not @raises [StandardError] if version could not be recorded. If this happens, execution_metadata will not be preset on the version object.
[ "Record", "a", "version", "in", "the", "schema", "version", "store", ".", "This", "should", "only", "be", "done", "if", "the", "version", "has", "been", "sucesfully", "migrated" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/versioning.rb#L48-L64
train
eprothro/cassie
lib/cassie/schema/versioning.rb
Cassie::Schema.Versioning.load_applied_versions
def load_applied_versions database_versions.tap do |versions| versions.each{|v| VersionObjectLoader.new(v).load } end rescue Cassandra::Errors::InvalidError => e raise uninitialized_error end
ruby
def load_applied_versions database_versions.tap do |versions| versions.each{|v| VersionObjectLoader.new(v).load } end rescue Cassandra::Errors::InvalidError => e raise uninitialized_error end
[ "def", "load_applied_versions", "database_versions", ".", "tap", "do", "|", "versions", "|", "versions", ".", "each", "{", "|", "v", "|", "VersionObjectLoader", ".", "new", "(", "v", ")", ".", "load", "}", "end", "rescue", "Cassandra", "::", "Errors", "::", "InvalidError", "=>", "e", "raise", "uninitialized_error", "end" ]
load version migration class from disk
[ "load", "version", "migration", "class", "from", "disk" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/versioning.rb#L121-L127
train
mackwic/slack-rtmapi
lib/slack-rtmapi/client.rb
SlackRTM.Client.init
def init return if @has_been_init @socket = init_socket(@socket) @socket.connect # costly and blocking ! internalWrapper = (Struct.new :url, :socket do def write(*args) self.socket.write(*args) end end).new @url.to_s, @socket # this, also, is costly and blocking @driver = WebSocket::Driver.client internalWrapper @driver.on :open do @connected = true unless @callbacks[:open].nil? @callbacks[:open].call end end @driver.on :error do |event| @connected = false unless @callbacks[:error].nil? @callbacks[:error].call end end @driver.on :message do |event| data = JSON.parse event.data unless @callbacks[:message].nil? @callbacks[:message].call data end end @driver.start @has_been_init = true end
ruby
def init return if @has_been_init @socket = init_socket(@socket) @socket.connect # costly and blocking ! internalWrapper = (Struct.new :url, :socket do def write(*args) self.socket.write(*args) end end).new @url.to_s, @socket # this, also, is costly and blocking @driver = WebSocket::Driver.client internalWrapper @driver.on :open do @connected = true unless @callbacks[:open].nil? @callbacks[:open].call end end @driver.on :error do |event| @connected = false unless @callbacks[:error].nil? @callbacks[:error].call end end @driver.on :message do |event| data = JSON.parse event.data unless @callbacks[:message].nil? @callbacks[:message].call data end end @driver.start @has_been_init = true end
[ "def", "init", "return", "if", "@has_been_init", "@socket", "=", "init_socket", "(", "@socket", ")", "@socket", ".", "connect", "internalWrapper", "=", "(", "Struct", ".", "new", ":url", ",", ":socket", "do", "def", "write", "(", "*", "args", ")", "self", ".", "socket", ".", "write", "(", "*", "args", ")", "end", "end", ")", ".", "new", "@url", ".", "to_s", ",", "@socket", "@driver", "=", "WebSocket", "::", "Driver", ".", "client", "internalWrapper", "@driver", ".", "on", ":open", "do", "@connected", "=", "true", "unless", "@callbacks", "[", ":open", "]", ".", "nil?", "@callbacks", "[", ":open", "]", ".", "call", "end", "end", "@driver", ".", "on", ":error", "do", "|", "event", "|", "@connected", "=", "false", "unless", "@callbacks", "[", ":error", "]", ".", "nil?", "@callbacks", "[", ":error", "]", ".", "call", "end", "end", "@driver", ".", "on", ":message", "do", "|", "event", "|", "data", "=", "JSON", ".", "parse", "event", ".", "data", "unless", "@callbacks", "[", ":message", "]", ".", "nil?", "@callbacks", "[", ":message", "]", ".", "call", "data", "end", "end", "@driver", ".", "start", "@has_been_init", "=", "true", "end" ]
This init has been delayed because the SSL handshake is a blocking and expensive call
[ "This", "init", "has", "been", "delayed", "because", "the", "SSL", "handshake", "is", "a", "blocking", "and", "expensive", "call" ]
5c217ba97dcab1801360b03cd3c26e8cab682fe9
https://github.com/mackwic/slack-rtmapi/blob/5c217ba97dcab1801360b03cd3c26e8cab682fe9/lib/slack-rtmapi/client.rb#L42-L78
train
mackwic/slack-rtmapi
lib/slack-rtmapi/client.rb
SlackRTM.Client.inner_loop
def inner_loop return if @stop data = @socket.readpartial 4096 return if data.nil? or data.empty? @driver.parse data @msg_queue.each {|msg| @driver.text msg} @msg_queue.clear end
ruby
def inner_loop return if @stop data = @socket.readpartial 4096 return if data.nil? or data.empty? @driver.parse data @msg_queue.each {|msg| @driver.text msg} @msg_queue.clear end
[ "def", "inner_loop", "return", "if", "@stop", "data", "=", "@socket", ".", "readpartial", "4096", "return", "if", "data", ".", "nil?", "or", "data", ".", "empty?", "@driver", ".", "parse", "data", "@msg_queue", ".", "each", "{", "|", "msg", "|", "@driver", ".", "text", "msg", "}", "@msg_queue", ".", "clear", "end" ]
All the polling work is done here
[ "All", "the", "polling", "work", "is", "done", "here" ]
5c217ba97dcab1801360b03cd3c26e8cab682fe9
https://github.com/mackwic/slack-rtmapi/blob/5c217ba97dcab1801360b03cd3c26e8cab682fe9/lib/slack-rtmapi/client.rb#L85-L93
train
bachya/cliutils
lib/cliutils/messenger.rb
CLIUtils.Messenger.error
def error(m) puts _word_wrap(m, '# ').red @targets.each { |_, t| t.error(m) } end
ruby
def error(m) puts _word_wrap(m, '# ').red @targets.each { |_, t| t.error(m) } end
[ "def", "error", "(", "m", ")", "puts", "_word_wrap", "(", "m", ",", "'# '", ")", ".", "red", "@targets", ".", "each", "{", "|", "_", ",", "t", "|", "t", ".", "error", "(", "m", ")", "}", "end" ]
Outputs a formatted-red error message. @param [String] m The message to output @return [void]
[ "Outputs", "a", "formatted", "-", "red", "error", "message", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/messenger.rb#L42-L45
train
bachya/cliutils
lib/cliutils/messenger.rb
CLIUtils.Messenger.info
def info(m) puts _word_wrap(m, '# ').blue @targets.each { |_, t| t.info(m) } end
ruby
def info(m) puts _word_wrap(m, '# ').blue @targets.each { |_, t| t.info(m) } end
[ "def", "info", "(", "m", ")", "puts", "_word_wrap", "(", "m", ",", "'# '", ")", ".", "blue", "@targets", ".", "each", "{", "|", "_", ",", "t", "|", "t", ".", "info", "(", "m", ")", "}", "end" ]
Outputs a formatted-blue informational message. @param [String] m The message to output @return [void]
[ "Outputs", "a", "formatted", "-", "blue", "informational", "message", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/messenger.rb#L50-L53
train
bachya/cliutils
lib/cliutils/messenger.rb
CLIUtils.Messenger.section
def section(m) puts _word_wrap(m, '---> ').purple @targets.each { |_, t| t.section(m) } end
ruby
def section(m) puts _word_wrap(m, '---> ').purple @targets.each { |_, t| t.section(m) } end
[ "def", "section", "(", "m", ")", "puts", "_word_wrap", "(", "m", ",", "'-", ")", ".", "purple", "@targets", ".", "each", "{", "|", "_", ",", "t", "|", "t", ".", "section", "(", "m", ")", "}", "end" ]
Outputs a formatted-purple section message. @param [String] m The message to output @return [void]
[ "Outputs", "a", "formatted", "-", "purple", "section", "message", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/messenger.rb#L97-L100
train
bachya/cliutils
lib/cliutils/messenger.rb
CLIUtils.Messenger.success
def success(m) puts _word_wrap(m, '# ').green @targets.each { |_, t| t.success(m) } end
ruby
def success(m) puts _word_wrap(m, '# ').green @targets.each { |_, t| t.success(m) } end
[ "def", "success", "(", "m", ")", "puts", "_word_wrap", "(", "m", ",", "'# '", ")", ".", "green", "@targets", ".", "each", "{", "|", "_", ",", "t", "|", "t", ".", "success", "(", "m", ")", "}", "end" ]
Outputs a formatted-green success message. @param [String] m The message to output @return [void]
[ "Outputs", "a", "formatted", "-", "green", "success", "message", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/messenger.rb#L105-L108
train
bachya/cliutils
lib/cliutils/messenger.rb
CLIUtils.Messenger.warn
def warn(m) puts _word_wrap(m, '# ').yellow @targets.each { |_, t| t.warn(m) } end
ruby
def warn(m) puts _word_wrap(m, '# ').yellow @targets.each { |_, t| t.warn(m) } end
[ "def", "warn", "(", "m", ")", "puts", "_word_wrap", "(", "m", ",", "'# '", ")", ".", "yellow", "@targets", ".", "each", "{", "|", "_", ",", "t", "|", "t", ".", "warn", "(", "m", ")", "}", "end" ]
Outputs a formatted-yellow warning message. @param [String] m The message to output @return [void]
[ "Outputs", "a", "formatted", "-", "yellow", "warning", "message", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/messenger.rb#L113-L116
train
ExerciciosResolvidos/latex_to_png
lib/latex_to_png.rb
LatexToPng.Convert.size_in_points
def size_in_points size_in_pixels size = Sizes.invert[size_in_pixels] return (size.nil?)? size_in_points("#{size_in_pixels.to_i + 1}px") : size end
ruby
def size_in_points size_in_pixels size = Sizes.invert[size_in_pixels] return (size.nil?)? size_in_points("#{size_in_pixels.to_i + 1}px") : size end
[ "def", "size_in_points", "size_in_pixels", "size", "=", "Sizes", ".", "invert", "[", "size_in_pixels", "]", "return", "(", "size", ".", "nil?", ")", "?", "size_in_points", "(", "\"#{size_in_pixels.to_i + 1}px\"", ")", ":", "size", "end" ]
or formula or filepath
[ "or", "formula", "or", "filepath" ]
527bb57b48022a69b76c69c7a4d9c7fb745c3125
https://github.com/ExerciciosResolvidos/latex_to_png/blob/527bb57b48022a69b76c69c7a4d9c7fb745c3125/lib/latex_to_png.rb#L56-L59
train
nysa/ruby-opencnam
lib/opencnam/parsers.rb
Opencnam.Parsers.parse_json
def parse_json(json) hash = JSON.parse(json, :symbolize_names => true) # Convert hash[:created] and hash[:updated] to Time objects if hash[:created] hash.merge!({ :created => parse_iso_date_string(hash[:created]) }) end if hash[:updated] hash.merge!({ :updated => parse_iso_date_string(hash[:updated]) }) end hash end
ruby
def parse_json(json) hash = JSON.parse(json, :symbolize_names => true) # Convert hash[:created] and hash[:updated] to Time objects if hash[:created] hash.merge!({ :created => parse_iso_date_string(hash[:created]) }) end if hash[:updated] hash.merge!({ :updated => parse_iso_date_string(hash[:updated]) }) end hash end
[ "def", "parse_json", "(", "json", ")", "hash", "=", "JSON", ".", "parse", "(", "json", ",", ":symbolize_names", "=>", "true", ")", "if", "hash", "[", ":created", "]", "hash", ".", "merge!", "(", "{", ":created", "=>", "parse_iso_date_string", "(", "hash", "[", ":created", "]", ")", "}", ")", "end", "if", "hash", "[", ":updated", "]", "hash", ".", "merge!", "(", "{", ":updated", "=>", "parse_iso_date_string", "(", "hash", "[", ":updated", "]", ")", "}", ")", "end", "hash", "end" ]
Parses a JSON string. @param [String] json the JSON formatted string @return [Hash]
[ "Parses", "a", "JSON", "string", "." ]
7c9e62f6efc59466ab307977bc04070d19c4cadf
https://github.com/nysa/ruby-opencnam/blob/7c9e62f6efc59466ab307977bc04070d19c4cadf/lib/opencnam/parsers.rb#L18-L31
train
upserve/giraph
lib/giraph/schema.rb
Giraph.Schema.execute
def execute(query, **args) args = args .merge(with_giraph_root(args)) .merge(with_giraph_resolvers(args)) super(query, **args) end
ruby
def execute(query, **args) args = args .merge(with_giraph_root(args)) .merge(with_giraph_resolvers(args)) super(query, **args) end
[ "def", "execute", "(", "query", ",", "**", "args", ")", "args", "=", "args", ".", "merge", "(", "with_giraph_root", "(", "args", ")", ")", ".", "merge", "(", "with_giraph_resolvers", "(", "args", ")", ")", "super", "(", "query", ",", "**", "args", ")", "end" ]
Extract special arguments for resolver objects, let the rest pass-through Defer the execution only after setting up context and root_value with resolvers and remote arguments
[ "Extract", "special", "arguments", "for", "resolver", "objects", "let", "the", "rest", "pass", "-", "through", "Defer", "the", "execution", "only", "after", "setting", "up", "context", "and", "root_value", "with", "resolvers", "and", "remote", "arguments" ]
b3d26bbf29d4e9ef8a5787ccb4c4e2bc9d36cd4f
https://github.com/upserve/giraph/blob/b3d26bbf29d4e9ef8a5787ccb4c4e2bc9d36cd4f/lib/giraph/schema.rb#L15-L21
train
igor-makarov/cocoapods-repo-cdn
lib/cdn_source.rb
Pod.CDNSource.specification_path
def specification_path(name, version) raise ArgumentError, 'No name' unless name raise ArgumentError, 'No version' unless version relative_podspec = pod_path_partial(name).join("#{version}/#{name}.podspec.json") download_file(relative_podspec) pod_path(name).join("#{version}/#{name}.podspec.json") end
ruby
def specification_path(name, version) raise ArgumentError, 'No name' unless name raise ArgumentError, 'No version' unless version relative_podspec = pod_path_partial(name).join("#{version}/#{name}.podspec.json") download_file(relative_podspec) pod_path(name).join("#{version}/#{name}.podspec.json") end
[ "def", "specification_path", "(", "name", ",", "version", ")", "raise", "ArgumentError", ",", "'No name'", "unless", "name", "raise", "ArgumentError", ",", "'No version'", "unless", "version", "relative_podspec", "=", "pod_path_partial", "(", "name", ")", ".", "join", "(", "\"#{version}/#{name}.podspec.json\"", ")", "download_file", "(", "relative_podspec", ")", "pod_path", "(", "name", ")", ".", "join", "(", "\"#{version}/#{name}.podspec.json\"", ")", "end" ]
Returns the path of the specification with the given name and version. @param [String] name the name of the Pod. @param [Version,String] version the version for the specification. @return [Pathname] The path of the specification.
[ "Returns", "the", "path", "of", "the", "specification", "with", "the", "given", "name", "and", "version", "." ]
45d9d3fc779297ec9c67312de2f9bb819d29ba8d
https://github.com/igor-makarov/cocoapods-repo-cdn/blob/45d9d3fc779297ec9c67312de2f9bb819d29ba8d/lib/cdn_source.rb#L174-L181
train
rthbound/pay_dirt
lib/pay_dirt/use_case.rb
PayDirt.UseCase.load_options
def load_options(*required_options, options) # Load required options required_options.each { |o| options = load_option(o, options) } # Load remaining options options.each_key { |k| options = load_option(k, options) } block_given? ? yield : options end
ruby
def load_options(*required_options, options) # Load required options required_options.each { |o| options = load_option(o, options) } # Load remaining options options.each_key { |k| options = load_option(k, options) } block_given? ? yield : options end
[ "def", "load_options", "(", "*", "required_options", ",", "options", ")", "required_options", ".", "each", "{", "|", "o", "|", "options", "=", "load_option", "(", "o", ",", "options", ")", "}", "options", ".", "each_key", "{", "|", "k", "|", "options", "=", "load_option", "(", "k", ",", "options", ")", "}", "block_given?", "?", "yield", ":", "options", "end" ]
Load instance variables from the provided hash of dependencies. Raises if any required dependencies (+required_options+) are missing from +options+ hash. Optionally, takes and yields a block after loading options. Use this to validate dependencies. @param [List<String,Symbol>] option_names list of keys representing required dependencies @param [Hash] options A hash of dependencies @public
[ "Load", "instance", "variables", "from", "the", "provided", "hash", "of", "dependencies", "." ]
9bf92cb1125e2e5f6eb08600b6c7f33e5030291c
https://github.com/rthbound/pay_dirt/blob/9bf92cb1125e2e5f6eb08600b6c7f33e5030291c/lib/pay_dirt/use_case.rb#L17-L25
train
mLewisLogic/saddle
lib/saddle/method_tree_builder.rb
Saddle.MethodTreeBuilder.build_tree
def build_tree(requester) root_node = build_root_node(requester) # Search out the implementations directory structure for endpoints if defined?(self.implementation_root) # For each endpoints directory, recurse down it to load the modules endpoints_directories.each do |endpoints_directories| Dir["#{endpoints_directories}/**/*.rb"].each { |f| require(f) } end build_node_children(self.endpoints_module, root_node, requester) end root_node end
ruby
def build_tree(requester) root_node = build_root_node(requester) # Search out the implementations directory structure for endpoints if defined?(self.implementation_root) # For each endpoints directory, recurse down it to load the modules endpoints_directories.each do |endpoints_directories| Dir["#{endpoints_directories}/**/*.rb"].each { |f| require(f) } end build_node_children(self.endpoints_module, root_node, requester) end root_node end
[ "def", "build_tree", "(", "requester", ")", "root_node", "=", "build_root_node", "(", "requester", ")", "if", "defined?", "(", "self", ".", "implementation_root", ")", "endpoints_directories", ".", "each", "do", "|", "endpoints_directories", "|", "Dir", "[", "\"#{endpoints_directories}/**/*.rb\"", "]", ".", "each", "{", "|", "f", "|", "require", "(", "f", ")", "}", "end", "build_node_children", "(", "self", ".", "endpoints_module", ",", "root_node", ",", "requester", ")", "end", "root_node", "end" ]
Build out the endpoint structure from the root of the implementation
[ "Build", "out", "the", "endpoint", "structure", "from", "the", "root", "of", "the", "implementation" ]
9f470a948039dbedb75655d883e714a29b273961
https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/method_tree_builder.rb#L17-L28
train
mLewisLogic/saddle
lib/saddle/method_tree_builder.rb
Saddle.MethodTreeBuilder.build_root_node
def build_root_node(requester) if defined?(self.implementation_root) root_endpoint_file = File.join( self.implementation_root, 'root_endpoint.rb' ) if File.file?(root_endpoint_file) warn "[DEPRECATION] `root_endpoint.rb` is deprecated. Please use `ABSOLUTE_PATH` in your endpoints." # Load it and create our base endpoint require(root_endpoint_file) # RootEndpoint is the special class name for a root endpoint root_node_class = self.implementation_module::RootEndpoint else # 'root_endpoint.rb' doesn't exist, so create a dummy endpoint root_node_class = Saddle::RootEndpoint end else # we don't even have an implementation root, so create a dummy endpoint root_node_class = Saddle::RootEndpoint end root_node_class.new(requester, nil, self) end
ruby
def build_root_node(requester) if defined?(self.implementation_root) root_endpoint_file = File.join( self.implementation_root, 'root_endpoint.rb' ) if File.file?(root_endpoint_file) warn "[DEPRECATION] `root_endpoint.rb` is deprecated. Please use `ABSOLUTE_PATH` in your endpoints." # Load it and create our base endpoint require(root_endpoint_file) # RootEndpoint is the special class name for a root endpoint root_node_class = self.implementation_module::RootEndpoint else # 'root_endpoint.rb' doesn't exist, so create a dummy endpoint root_node_class = Saddle::RootEndpoint end else # we don't even have an implementation root, so create a dummy endpoint root_node_class = Saddle::RootEndpoint end root_node_class.new(requester, nil, self) end
[ "def", "build_root_node", "(", "requester", ")", "if", "defined?", "(", "self", ".", "implementation_root", ")", "root_endpoint_file", "=", "File", ".", "join", "(", "self", ".", "implementation_root", ",", "'root_endpoint.rb'", ")", "if", "File", ".", "file?", "(", "root_endpoint_file", ")", "warn", "\"[DEPRECATION] `root_endpoint.rb` is deprecated. Please use `ABSOLUTE_PATH` in your endpoints.\"", "require", "(", "root_endpoint_file", ")", "root_node_class", "=", "self", ".", "implementation_module", "::", "RootEndpoint", "else", "root_node_class", "=", "Saddle", "::", "RootEndpoint", "end", "else", "root_node_class", "=", "Saddle", "::", "RootEndpoint", "end", "root_node_class", ".", "new", "(", "requester", ",", "nil", ",", "self", ")", "end" ]
Build our root node here. The root node is special in that it lives below the 'endpoints' directory, and so we need to manually check if it exists.
[ "Build", "our", "root", "node", "here", ".", "The", "root", "node", "is", "special", "in", "that", "it", "lives", "below", "the", "endpoints", "directory", "and", "so", "we", "need", "to", "manually", "check", "if", "it", "exists", "." ]
9f470a948039dbedb75655d883e714a29b273961
https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/method_tree_builder.rb#L33-L54
train
mLewisLogic/saddle
lib/saddle/method_tree_builder.rb
Saddle.MethodTreeBuilder.build_node_children
def build_node_children(current_module, current_node, requester) return unless current_module current_module.constants.each do |const_symbol| const = current_module.const_get(const_symbol) if const.class == Module # A module means that it's a branch # Build the branch out with a base endpoint branch_node = current_node._build_and_attach_node( Saddle::TraversalEndpoint, const_symbol.to_s.underscore ) # Build out the branch's endpoints on the new branch node self.build_node_children(const, branch_node, requester) end if const < Saddle::TraversalEndpoint # A class means that it's a node # Build out this endpoint on the current node current_node._build_and_attach_node(const) end end end
ruby
def build_node_children(current_module, current_node, requester) return unless current_module current_module.constants.each do |const_symbol| const = current_module.const_get(const_symbol) if const.class == Module # A module means that it's a branch # Build the branch out with a base endpoint branch_node = current_node._build_and_attach_node( Saddle::TraversalEndpoint, const_symbol.to_s.underscore ) # Build out the branch's endpoints on the new branch node self.build_node_children(const, branch_node, requester) end if const < Saddle::TraversalEndpoint # A class means that it's a node # Build out this endpoint on the current node current_node._build_and_attach_node(const) end end end
[ "def", "build_node_children", "(", "current_module", ",", "current_node", ",", "requester", ")", "return", "unless", "current_module", "current_module", ".", "constants", ".", "each", "do", "|", "const_symbol", "|", "const", "=", "current_module", ".", "const_get", "(", "const_symbol", ")", "if", "const", ".", "class", "==", "Module", "branch_node", "=", "current_node", ".", "_build_and_attach_node", "(", "Saddle", "::", "TraversalEndpoint", ",", "const_symbol", ".", "to_s", ".", "underscore", ")", "self", ".", "build_node_children", "(", "const", ",", "branch_node", ",", "requester", ")", "end", "if", "const", "<", "Saddle", "::", "TraversalEndpoint", "current_node", ".", "_build_and_attach_node", "(", "const", ")", "end", "end", "end" ]
Build out the traversal tree by module namespace
[ "Build", "out", "the", "traversal", "tree", "by", "module", "namespace" ]
9f470a948039dbedb75655d883e714a29b273961
https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/method_tree_builder.rb#L58-L80
train
FormAPI/formapi-ruby
lib/form_api/api/client.rb
FormAPI.Client.combine_submissions
def combine_submissions(options) unless options[:submission_ids].is_a?(::Array) raise InvalidDataError, "submission_ids is required, and must be an Array." end options[:source_pdfs] = options[:submission_ids].map do |id| { type: 'submission', id: id } end options.delete :submission_ids combine_pdfs(options) end
ruby
def combine_submissions(options) unless options[:submission_ids].is_a?(::Array) raise InvalidDataError, "submission_ids is required, and must be an Array." end options[:source_pdfs] = options[:submission_ids].map do |id| { type: 'submission', id: id } end options.delete :submission_ids combine_pdfs(options) end
[ "def", "combine_submissions", "(", "options", ")", "unless", "options", "[", ":submission_ids", "]", ".", "is_a?", "(", "::", "Array", ")", "raise", "InvalidDataError", ",", "\"submission_ids is required, and must be an Array.\"", "end", "options", "[", ":source_pdfs", "]", "=", "options", "[", ":submission_ids", "]", ".", "map", "do", "|", "id", "|", "{", "type", ":", "'submission'", ",", "id", ":", "id", "}", "end", "options", ".", "delete", ":submission_ids", "combine_pdfs", "(", "options", ")", "end" ]
Alias for combine_pdfs, for backwards compatibility
[ "Alias", "for", "combine_pdfs", "for", "backwards", "compatibility" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/client.rb#L143-L153
train
devs-ruby/devs
lib/devs/atomic_model.rb
DEVS.AtomicModel.ensure_output_port
def ensure_output_port(port) raise ArgumentError, "port argument cannot be nil" if port.nil? unless port.kind_of?(Port) port = output_port(port) raise ArgumentError, "the given port doesn't exists" if port.nil? end unless port.host == self raise InvalidPortHostError, "The given port doesn't belong to this \ model" end unless port.output? raise InvalidPortTypeError, "The given port isn't an output port" end port end
ruby
def ensure_output_port(port) raise ArgumentError, "port argument cannot be nil" if port.nil? unless port.kind_of?(Port) port = output_port(port) raise ArgumentError, "the given port doesn't exists" if port.nil? end unless port.host == self raise InvalidPortHostError, "The given port doesn't belong to this \ model" end unless port.output? raise InvalidPortTypeError, "The given port isn't an output port" end port end
[ "def", "ensure_output_port", "(", "port", ")", "raise", "ArgumentError", ",", "\"port argument cannot be nil\"", "if", "port", ".", "nil?", "unless", "port", ".", "kind_of?", "(", "Port", ")", "port", "=", "output_port", "(", "port", ")", "raise", "ArgumentError", ",", "\"the given port doesn't exists\"", "if", "port", ".", "nil?", "end", "unless", "port", ".", "host", "==", "self", "raise", "InvalidPortHostError", ",", "\"The given port doesn't belong to this \\ model\"", "end", "unless", "port", ".", "output?", "raise", "InvalidPortTypeError", ",", "\"The given port isn't an output port\"", "end", "port", "end" ]
Finds and checks if the given port is an output port @api private @param port [Port, String, Symbol] the port or its name @return [Port] the matching port @raise [NoSuchPortError] if the given port doesn't exists @raise [InvalidPortHostError] if the given port doesn't belong to this model @raise [InvalidPortTypeError] if the given port isn't an output port
[ "Finds", "and", "checks", "if", "the", "given", "port", "is", "an", "output", "port" ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/atomic_model.rb#L95-L109
train
j0hnds/cron-spec
lib/cron-spec/cron_specification.rb
CronSpec.CronSpecification.is_specification_in_effect?
def is_specification_in_effect?(time=Time.now) idx = 0 test_results = @cron_values.collect do | cvalues | time_value = time.send(TimeMethods[idx]) idx += 1 !cvalues.detect { | cv | cv.is_effective?(time_value) }.nil? end.all? end
ruby
def is_specification_in_effect?(time=Time.now) idx = 0 test_results = @cron_values.collect do | cvalues | time_value = time.send(TimeMethods[idx]) idx += 1 !cvalues.detect { | cv | cv.is_effective?(time_value) }.nil? end.all? end
[ "def", "is_specification_in_effect?", "(", "time", "=", "Time", ".", "now", ")", "idx", "=", "0", "test_results", "=", "@cron_values", ".", "collect", "do", "|", "cvalues", "|", "time_value", "=", "time", ".", "send", "(", "TimeMethods", "[", "idx", "]", ")", "idx", "+=", "1", "!", "cvalues", ".", "detect", "{", "|", "cv", "|", "cv", ".", "is_effective?", "(", "time_value", ")", "}", ".", "nil?", "end", ".", "all?", "end" ]
Constructs a new CronSpecification with a textual cron specificiation. A broad cron syntax is supported: * * * * * - - - - - | | | | | | | | | +----- day of week (0 - 6) (Sunday=0) | | | +---------- month (1 - 12) | | +--------------- day of month (1 - 31) | +-------------------- hour (0 - 23) +------------------------- min (0 - 59) The following named entries can be used: * Day of week - sun, mon, tue, wed, thu, fri, sat * Month - jan feb mar apr may jun jul aug sep oct nov dec The following constructs are supported: * Ranges are supported (e.g. 2-10 or mon-fri) * Multiple values are supported (e.g. 2,3,8 or mon,wed,fri) * Wildcards are supported (e.g. *) * Step values are supported (e.g. */4) * Combinations of all but wildcard are supported (e.g. 2,*/3,8-10) A single space is required between each group. Return true if the specified time falls within the definition of the CronSpecification. The parameter defaults to the current time.
[ "Constructs", "a", "new", "CronSpecification", "with", "a", "textual", "cron", "specificiation", "." ]
ac6dfa5cb312ec6d855ddde4e46d0bf2916121aa
https://github.com/j0hnds/cron-spec/blob/ac6dfa5cb312ec6d855ddde4e46d0bf2916121aa/lib/cron-spec/cron_specification.rb#L89-L97
train
thelazycamel/rubychain
lib/rubychain/block.rb
Rubychain.Block.hash_block
def hash_block hash_string = [index,timestamp,data,prev_hash].join sha = Digest::SHA256.new sha.update(hash_string) sha.hexdigest end
ruby
def hash_block hash_string = [index,timestamp,data,prev_hash].join sha = Digest::SHA256.new sha.update(hash_string) sha.hexdigest end
[ "def", "hash_block", "hash_string", "=", "[", "index", ",", "timestamp", ",", "data", ",", "prev_hash", "]", ".", "join", "sha", "=", "Digest", "::", "SHA256", ".", "new", "sha", ".", "update", "(", "hash_string", ")", "sha", ".", "hexdigest", "end" ]
Create the blocks hash by encrypting all the blocks data using SHA256
[ "Create", "the", "blocks", "hash", "by", "encrypting", "all", "the", "blocks", "data", "using", "SHA256" ]
7671fe6d25f818a88c8a62c3167438837d37740d
https://github.com/thelazycamel/rubychain/blob/7671fe6d25f818a88c8a62c3167438837d37740d/lib/rubychain/block.rb#L18-L23
train
bachya/cliutils
lib/cliutils/prefs.rb
CLIUtils.Prefs.ask
def ask # First, deliver all the prompts that don't have # any prerequisites. @prompts.reject { |p| p.prereqs }.each do |p| _deliver_prompt(p) end # After the "non-prerequisite" prompts are delivered, # deliver any that require prerequisites. @prompts.select { |p| p.prereqs }.each do |p| _deliver_prompt(p) if _prereqs_fulfilled?(p) end end
ruby
def ask # First, deliver all the prompts that don't have # any prerequisites. @prompts.reject { |p| p.prereqs }.each do |p| _deliver_prompt(p) end # After the "non-prerequisite" prompts are delivered, # deliver any that require prerequisites. @prompts.select { |p| p.prereqs }.each do |p| _deliver_prompt(p) if _prereqs_fulfilled?(p) end end
[ "def", "ask", "@prompts", ".", "reject", "{", "|", "p", "|", "p", ".", "prereqs", "}", ".", "each", "do", "|", "p", "|", "_deliver_prompt", "(", "p", ")", "end", "@prompts", ".", "select", "{", "|", "p", "|", "p", ".", "prereqs", "}", ".", "each", "do", "|", "p", "|", "_deliver_prompt", "(", "p", ")", "if", "_prereqs_fulfilled?", "(", "p", ")", "end", "end" ]
Reads prompt data from and stores it. @param [<String, Hash, Array>] data Filepath to YAML, Hash, or Array @param [Configurator] configurator Source of defailt values @return [void] Runs through all of the prompt questions and collects answers from the user. Note that all questions w/o prerequisites are examined first; once those are complete, questions w/ prerequisites are examined. @return [void]
[ "Reads", "prompt", "data", "from", "and", "stores", "it", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/prefs.rb#L78-L90
train
bachya/cliutils
lib/cliutils/prefs.rb
CLIUtils.Prefs._prereqs_fulfilled?
def _prereqs_fulfilled?(p) ret = true p.prereqs.each do |req| a = @prompts.find do |answer| answer.config_key == req[:config_key] && answer.answer == req[:config_value] end ret = false if a.nil? end ret end
ruby
def _prereqs_fulfilled?(p) ret = true p.prereqs.each do |req| a = @prompts.find do |answer| answer.config_key == req[:config_key] && answer.answer == req[:config_value] end ret = false if a.nil? end ret end
[ "def", "_prereqs_fulfilled?", "(", "p", ")", "ret", "=", "true", "p", ".", "prereqs", ".", "each", "do", "|", "req", "|", "a", "=", "@prompts", ".", "find", "do", "|", "answer", "|", "answer", ".", "config_key", "==", "req", "[", ":config_key", "]", "&&", "answer", ".", "answer", "==", "req", "[", ":config_value", "]", "end", "ret", "=", "false", "if", "a", ".", "nil?", "end", "ret", "end" ]
Utility method for determining whether a prompt's prerequisites have already been fulfilled. @param [Hash] p The prompt @return [void]
[ "Utility", "method", "for", "determining", "whether", "a", "prompt", "s", "prerequisites", "have", "already", "been", "fulfilled", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/prefs.rb#L171-L181
train
ohler55/opee
lib/opee/askqueue.rb
Opee.AskQueue.ask_worker
def ask_worker(worker, job) raise NoMethodError.new("undefined method for #{job.class}. Expected a method invocation") unless job.is_a?(Actor::Act) worker.ask(job.op, *job.args) end
ruby
def ask_worker(worker, job) raise NoMethodError.new("undefined method for #{job.class}. Expected a method invocation") unless job.is_a?(Actor::Act) worker.ask(job.op, *job.args) end
[ "def", "ask_worker", "(", "worker", ",", "job", ")", "raise", "NoMethodError", ".", "new", "(", "\"undefined method for #{job.class}. Expected a method invocation\"", ")", "unless", "job", ".", "is_a?", "(", "Actor", "::", "Act", ")", "worker", ".", "ask", "(", "job", ".", "op", ",", "*", "job", ".", "args", ")", "end" ]
Asks the worker to invoke the method of an Act Object.
[ "Asks", "the", "worker", "to", "invoke", "the", "method", "of", "an", "Act", "Object", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/askqueue.rb#L23-L26
train
ktemkin/ruby-ise
lib/ise/project.rb
ISE.Project.set_property
def set_property(name, value, mark_non_default=true) #Set the node's property, as specified. node = get_property_node(name) node.attribute("value").value = value #If the mark non-default option is set, mark the state is not a default value. node.attribute("valueState").value = 'non-default' if mark_non_default end
ruby
def set_property(name, value, mark_non_default=true) #Set the node's property, as specified. node = get_property_node(name) node.attribute("value").value = value #If the mark non-default option is set, mark the state is not a default value. node.attribute("valueState").value = 'non-default' if mark_non_default end
[ "def", "set_property", "(", "name", ",", "value", ",", "mark_non_default", "=", "true", ")", "node", "=", "get_property_node", "(", "name", ")", "node", ".", "attribute", "(", "\"value\"", ")", ".", "value", "=", "value", "node", ".", "attribute", "(", "\"valueState\"", ")", ".", "value", "=", "'non-default'", "if", "mark_non_default", "end" ]
Sets the value of an ISE project property.
[ "Sets", "the", "value", "of", "an", "ISE", "project", "property", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/project.rb#L33-L42
train
ktemkin/ruby-ise
lib/ise/project.rb
ISE.Project.minimize_runtime!
def minimize_runtime! #Compute the path in which temporary synthesis files should be created. shortname = CGI::escape(get_property(ShortNameProperty)) temp_path = Dir::mktmpdir([shortname, '']) #Synthesize from RAM. set_property(WorkingDirectoryProperty, temp_path) #Ask the project to focus on runtime over performance. set_property(GoalProperty, 'Minimum Runtime') end
ruby
def minimize_runtime! #Compute the path in which temporary synthesis files should be created. shortname = CGI::escape(get_property(ShortNameProperty)) temp_path = Dir::mktmpdir([shortname, '']) #Synthesize from RAM. set_property(WorkingDirectoryProperty, temp_path) #Ask the project to focus on runtime over performance. set_property(GoalProperty, 'Minimum Runtime') end
[ "def", "minimize_runtime!", "shortname", "=", "CGI", "::", "escape", "(", "get_property", "(", "ShortNameProperty", ")", ")", "temp_path", "=", "Dir", "::", "mktmpdir", "(", "[", "shortname", ",", "''", "]", ")", "set_property", "(", "WorkingDirectoryProperty", ",", "temp_path", ")", "set_property", "(", "GoalProperty", ",", "'Minimum Runtime'", ")", "end" ]
Attempts to minimize synthesis runtime of a _single run_. This will place all intermediary files in RAM- which means that synthesis results won't be preserved between reboots!
[ "Attempts", "to", "minimize", "synthesis", "runtime", "of", "a", "_single", "run_", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/project.rb#L50-L62
train
ktemkin/ruby-ise
lib/ise/project.rb
ISE.Project.top_level_file
def top_level_file(absolute_path=true) path = get_property(TopLevelFileProperty) #If the absolute_path flag is set, and we know how, expand the file path. if absolute_path path = File.expand_path(path, @base_path) end #Return the relevant path. path end
ruby
def top_level_file(absolute_path=true) path = get_property(TopLevelFileProperty) #If the absolute_path flag is set, and we know how, expand the file path. if absolute_path path = File.expand_path(path, @base_path) end #Return the relevant path. path end
[ "def", "top_level_file", "(", "absolute_path", "=", "true", ")", "path", "=", "get_property", "(", "TopLevelFileProperty", ")", "if", "absolute_path", "path", "=", "File", ".", "expand_path", "(", "path", ",", "@base_path", ")", "end", "path", "end" ]
Returns a path to the top-level file in the given project. absoulute_path: If set when the project file's path is known, an absolute path will be returned.
[ "Returns", "a", "path", "to", "the", "top", "-", "level", "file", "in", "the", "given", "project", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/project.rb#L69-L81
train
ktemkin/ruby-ise
lib/ise/project.rb
ISE.Project.bit_file
def bit_file #Determine ISE's working directory. working_directory = get_property(WorkingDirectoryProperty) #Find an absolute path at which the most recently generated bit file should reside. name = get_property(OutputNameProperty) name = File.expand_path("#{working_directory}/#{name}.bit", @base_path) #If it exists, return it. File::exists?(name) ? name : nil end
ruby
def bit_file #Determine ISE's working directory. working_directory = get_property(WorkingDirectoryProperty) #Find an absolute path at which the most recently generated bit file should reside. name = get_property(OutputNameProperty) name = File.expand_path("#{working_directory}/#{name}.bit", @base_path) #If it exists, return it. File::exists?(name) ? name : nil end
[ "def", "bit_file", "working_directory", "=", "get_property", "(", "WorkingDirectoryProperty", ")", "name", "=", "get_property", "(", "OutputNameProperty", ")", "name", "=", "File", ".", "expand_path", "(", "\"#{working_directory}/#{name}.bit\"", ",", "@base_path", ")", "File", "::", "exists?", "(", "name", ")", "?", "name", ":", "nil", "end" ]
Returns the best-guess path to the most recently generated bit file, or nil if we weren't able to find one.
[ "Returns", "the", "best", "-", "guess", "path", "to", "the", "most", "recently", "generated", "bit", "file", "or", "nil", "if", "we", "weren", "t", "able", "to", "find", "one", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/project.rb#L94-L106
train
addagger/html_slicer
lib/html_slicer/installer.rb
HtmlSlicer.Installer.slice
def slice(*args, &block) attr_name = args.first raise(NameError, "Attribute name expected!") unless attr_name options = args.extract_options! config = HtmlSlicer.config(options.delete(:config)).duplicate # Configuration instance for each single one implementation if options.present? # Accepts options from args options.each do |key, value| config.send("#{key}=", value) end end if block_given? # Accepts options from block yield config end if config.processors Array.wrap(config.processors).each do |name| HtmlSlicer.load_processor!(name) end end method_name = config.as||"#{attr_name}_slice" config.cache_to = "#{method_name}_cache" if config.cache_to == true class_eval do define_method method_name do var_name = "@_#{method_name}" instance_variable_get(var_name)||instance_variable_set(var_name, HtmlSlicer::Interface.new(self, attr_name, config.config)) end end if config.cache_to && self.superclass == ActiveRecord::Base before_save do send(method_name).load! end end end
ruby
def slice(*args, &block) attr_name = args.first raise(NameError, "Attribute name expected!") unless attr_name options = args.extract_options! config = HtmlSlicer.config(options.delete(:config)).duplicate # Configuration instance for each single one implementation if options.present? # Accepts options from args options.each do |key, value| config.send("#{key}=", value) end end if block_given? # Accepts options from block yield config end if config.processors Array.wrap(config.processors).each do |name| HtmlSlicer.load_processor!(name) end end method_name = config.as||"#{attr_name}_slice" config.cache_to = "#{method_name}_cache" if config.cache_to == true class_eval do define_method method_name do var_name = "@_#{method_name}" instance_variable_get(var_name)||instance_variable_set(var_name, HtmlSlicer::Interface.new(self, attr_name, config.config)) end end if config.cache_to && self.superclass == ActiveRecord::Base before_save do send(method_name).load! end end end
[ "def", "slice", "(", "*", "args", ",", "&", "block", ")", "attr_name", "=", "args", ".", "first", "raise", "(", "NameError", ",", "\"Attribute name expected!\"", ")", "unless", "attr_name", "options", "=", "args", ".", "extract_options!", "config", "=", "HtmlSlicer", ".", "config", "(", "options", ".", "delete", "(", ":config", ")", ")", ".", "duplicate", "if", "options", ".", "present?", "options", ".", "each", "do", "|", "key", ",", "value", "|", "config", ".", "send", "(", "\"#{key}=\"", ",", "value", ")", "end", "end", "if", "block_given?", "yield", "config", "end", "if", "config", ".", "processors", "Array", ".", "wrap", "(", "config", ".", "processors", ")", ".", "each", "do", "|", "name", "|", "HtmlSlicer", ".", "load_processor!", "(", "name", ")", "end", "end", "method_name", "=", "config", ".", "as", "||", "\"#{attr_name}_slice\"", "config", ".", "cache_to", "=", "\"#{method_name}_cache\"", "if", "config", ".", "cache_to", "==", "true", "class_eval", "do", "define_method", "method_name", "do", "var_name", "=", "\"@_#{method_name}\"", "instance_variable_get", "(", "var_name", ")", "||", "instance_variable_set", "(", "var_name", ",", "HtmlSlicer", "::", "Interface", ".", "new", "(", "self", ",", "attr_name", ",", "config", ".", "config", ")", ")", "end", "end", "if", "config", ".", "cache_to", "&&", "self", ".", "superclass", "==", "ActiveRecord", "::", "Base", "before_save", "do", "send", "(", "method_name", ")", ".", "load!", "end", "end", "end" ]
The basic implementation method. slice <method_name>, <configuration>, [:config => <:style>]* where: * <method_name> - any method or local variable which returns source String (can be called with .send()). * <configuration> - Hash of configuration options and/or +:config+ parameter. === Example: class Article < ActiveRecord::Base slice :content, :as => :paged, :slice => {:maximum => 2000}, :resize => {:width => 600} end === Where: * <tt>:content</tt> is a method name or local variable, that return a target String object. * <tt>:as</tt> is a name of basic accessor for result. * <tt>:slice</tt> is a hash of +slicing options+. * <tt>:resize</tt> is a hash of +resizing options+. You can define any configuration key you want. Otherwise, default configuration options (if available) will be picked up automatically. === All configuration keys: * <tt>:as</tt> is a name of basic accessor for sliced +object+. * <tt>:slice</tt> is a hash of slicing options*. * <tt>:resize</tt> is a hash of resizing options*. * <tt>:processors</tt> - processors names*. * <tt>:window</tt> - parameter for ActionView: The "inner window" size (4 by default). * <tt>:outer_window</tt> - parameter for ActionView: The "outer window" size (0 by default). * <tt>:left</tt> - parameter for ActionView: The "left outer window" size (0 by default). * <tt>:right</tt> - parameter for ActionView: The "right outer window" size (0 by default). * <tt>:params</tt> - parameter for ActionView: url_for parameters for the links (:controller, :action, etc.) * <tt>:param_name</tt> - parameter for ActionView: parameter name for slice number in the links. Accepts +symbol+, +string+, +array+. * <tt>:remote</tt> - parameter for ActionView: Ajax? (false by default) === Block-style configuration example: slice *args do |config| config.as = :paged config.slice.merge! {:maximum => 1500} config.resize = nil end # *args = method name or local variable, and/or +:config+ parameter. === Premature configuration (+:config+ parameter): Stylizied general configuration can be used for many implementations, such as: # For example, we set the global stylized config: HtmlSlicer.configure(:paged_config) do |config| config.as = :page config.slice = {:maximum => 300} config.window = 4 config.outer_window = 0 config.left = 0 config.right = 0 config.param_name = :slice end # Now we can use it as next: slice *args, :config => :paged_config You can also pass another configuration options directrly as arguments and/or the block to clarify the config along with used global: slice *args, :as => :chapter, :config => :paged_config do |config| config.slice.merge! {:unit => {:tag => 'h1', :class => 'chapter'}, :maximum => 1} end === Skipping slicing: To skip slicing (for example, if you want to use only resizing feature) you can nilify +slice+ option at all: slice :content, :slice => nil, :resize => {:width => 300} Notice: without +:slice+ neither +:resize+ options, using HtmlSlicer becomes meaningless. :) === See README.rdoc for details about +:slice+ and +:resize+ options etc.
[ "The", "basic", "implementation", "method", "." ]
bbe6ab55a0d0335621079c304af534959b518d8b
https://github.com/addagger/html_slicer/blob/bbe6ab55a0d0335621079c304af534959b518d8b/lib/html_slicer/installer.rb#L88-L120
train
mpakus/uniqable
lib/uniqable.rb
Uniqable.ClassMethods.uniqable
def uniqable(*fields, to_param: nil) fields = [:uid] if fields.blank? fields.each do |name| before_create { |record| record.uniqable_uid(name) } end define_singleton_method :uniqable_fields do fields end return if to_param.blank? # :to_param option define_method :to_param do public_send(to_param) end end
ruby
def uniqable(*fields, to_param: nil) fields = [:uid] if fields.blank? fields.each do |name| before_create { |record| record.uniqable_uid(name) } end define_singleton_method :uniqable_fields do fields end return if to_param.blank? # :to_param option define_method :to_param do public_send(to_param) end end
[ "def", "uniqable", "(", "*", "fields", ",", "to_param", ":", "nil", ")", "fields", "=", "[", ":uid", "]", "if", "fields", ".", "blank?", "fields", ".", "each", "do", "|", "name", "|", "before_create", "{", "|", "record", "|", "record", ".", "uniqable_uid", "(", "name", ")", "}", "end", "define_singleton_method", ":uniqable_fields", "do", "fields", "end", "return", "if", "to_param", ".", "blank?", "define_method", ":to_param", "do", "public_send", "(", "to_param", ")", "end", "end" ]
Uniqable fields and options declaration @example: uniqable :uid, :slug, to_param: :uid rubocop:disable Metrics/MethodLength
[ "Uniqable", "fields", "and", "options", "declaration" ]
8a4828c73ba967b6cd046580e2358ea169ea122f
https://github.com/mpakus/uniqable/blob/8a4828c73ba967b6cd046580e2358ea169ea122f/lib/uniqable.rb#L17-L30
train
CultureHQ/paperweight
lib/paperweight/download.rb
Paperweight.Download.normalize_download
def normalize_download(file) return file unless file.is_a?(StringIO) # We need to open it in binary mode for Windows users. Tempfile.new('download-', binmode: true).tap do |tempfile| # IO.copy_stream is the most efficient way of data transfer. IO.copy_stream(file, tempfile.path) # We add the metadata that open-uri puts on the file # (e.g. #content_type) OpenURI::Meta.init(tempfile) end end
ruby
def normalize_download(file) return file unless file.is_a?(StringIO) # We need to open it in binary mode for Windows users. Tempfile.new('download-', binmode: true).tap do |tempfile| # IO.copy_stream is the most efficient way of data transfer. IO.copy_stream(file, tempfile.path) # We add the metadata that open-uri puts on the file # (e.g. #content_type) OpenURI::Meta.init(tempfile) end end
[ "def", "normalize_download", "(", "file", ")", "return", "file", "unless", "file", ".", "is_a?", "(", "StringIO", ")", "Tempfile", ".", "new", "(", "'download-'", ",", "binmode", ":", "true", ")", ".", "tap", "do", "|", "tempfile", "|", "IO", ".", "copy_stream", "(", "file", ",", "tempfile", ".", "path", ")", "OpenURI", "::", "Meta", ".", "init", "(", "tempfile", ")", "end", "end" ]
open-uri will return a StringIO instead of a Tempfile if the filesize is less than 10 KB, so we patch this behaviour by converting it into a Tempfile.
[ "open", "-", "uri", "will", "return", "a", "StringIO", "instead", "of", "a", "Tempfile", "if", "the", "filesize", "is", "less", "than", "10", "KB", "so", "we", "patch", "this", "behaviour", "by", "converting", "it", "into", "a", "Tempfile", "." ]
dfd91e1a6708b56f01de46f793fba5fca17d7e45
https://github.com/CultureHQ/paperweight/blob/dfd91e1a6708b56f01de46f793fba5fca17d7e45/lib/paperweight/download.rb#L43-L55
train
eprothro/cassie
lib/cassie/schema/structure_dumper.rb
Cassie::Schema.StructureDumper.keyspace_structure
def keyspace_structure @keyspace_structure ||= begin args = ["-e", "'DESCRIBE KEYSPACE #{Cassie.configuration[:keyspace]}'"] runner = Cassie::Support::SystemCommand.new("cqlsh", args) runner.succeed runner.output end end
ruby
def keyspace_structure @keyspace_structure ||= begin args = ["-e", "'DESCRIBE KEYSPACE #{Cassie.configuration[:keyspace]}'"] runner = Cassie::Support::SystemCommand.new("cqlsh", args) runner.succeed runner.output end end
[ "def", "keyspace_structure", "@keyspace_structure", "||=", "begin", "args", "=", "[", "\"-e\"", ",", "\"'DESCRIBE KEYSPACE #{Cassie.configuration[:keyspace]}'\"", "]", "runner", "=", "Cassie", "::", "Support", "::", "SystemCommand", ".", "new", "(", "\"cqlsh\"", ",", "args", ")", "runner", ".", "succeed", "runner", ".", "output", "end", "end" ]
Fetch the CQL that can be used to recreate the current environment's keyspace @return [String] CQL commands @raise [RuntimeError] if the {Cassie.configuration[:keyspace]} keyspace could not be described.
[ "Fetch", "the", "CQL", "that", "can", "be", "used", "to", "recreate", "the", "current", "environment", "s", "keyspace" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/structure_dumper.rb#L22-L30
train
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.remarks
def remarks(keyword=nil) if keyword.nil? @remarks else ukw = keyword.upcase @remarks.find_all {|r| r[:keyword] == (ukw)} end end
ruby
def remarks(keyword=nil) if keyword.nil? @remarks else ukw = keyword.upcase @remarks.find_all {|r| r[:keyword] == (ukw)} end end
[ "def", "remarks", "(", "keyword", "=", "nil", ")", "if", "keyword", ".", "nil?", "@remarks", "else", "ukw", "=", "keyword", ".", "upcase", "@remarks", ".", "find_all", "{", "|", "r", "|", "r", "[", ":keyword", "]", "==", "(", "ukw", ")", "}", "end", "end" ]
Return the remark-elements found in the document. If _keyword_ is nil then return all remarks, else only the ones with the right keyword.
[ "Return", "the", "remark", "-", "elements", "found", "in", "the", "document", ".", "If", "_keyword_", "is", "nil", "then", "return", "all", "remarks", "else", "only", "the", "ones", "with", "the", "right", "keyword", "." ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L64-L71
train
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.find_section_title
def find_section_title(node) title = node.find_first('./db:title') if title.nil? title = node.find_first './db:info/db:title' end if title.nil? "" else title.content end end
ruby
def find_section_title(node) title = node.find_first('./db:title') if title.nil? title = node.find_first './db:info/db:title' end if title.nil? "" else title.content end end
[ "def", "find_section_title", "(", "node", ")", "title", "=", "node", ".", "find_first", "(", "'./db:title'", ")", "if", "title", ".", "nil?", "title", "=", "node", ".", "find_first", "'./db:info/db:title'", "end", "if", "title", ".", "nil?", "\"\"", "else", "title", ".", "content", "end", "end" ]
Find the _title_ of the current section. That element is either directly following or inside an _info_ element. Return the empty string if no title can be found.
[ "Find", "the", "_title_", "of", "the", "current", "section", ".", "That", "element", "is", "either", "directly", "following", "or", "inside", "an", "_info_", "element", ".", "Return", "the", "empty", "string", "if", "no", "title", "can", "be", "found", "." ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L98-L108
train
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.check_node
def check_node(node, level, ctr) if (@@text_elements.include? node.name) ctr << {:type => :para, :level => level, :words => count_content_words(node)} elsif (@@section_elements.include? node.name) title = find_section_title(node) ctr << {:type => :section, :level => level, :title => title, :name => node.name} node.children.each {|inner_elem| check_node(inner_elem, level+1, ctr)} if node.children? else node.children.each {|inner_elem| check_node(inner_elem, level+1, ctr)} if node.children? end ctr end
ruby
def check_node(node, level, ctr) if (@@text_elements.include? node.name) ctr << {:type => :para, :level => level, :words => count_content_words(node)} elsif (@@section_elements.include? node.name) title = find_section_title(node) ctr << {:type => :section, :level => level, :title => title, :name => node.name} node.children.each {|inner_elem| check_node(inner_elem, level+1, ctr)} if node.children? else node.children.each {|inner_elem| check_node(inner_elem, level+1, ctr)} if node.children? end ctr end
[ "def", "check_node", "(", "node", ",", "level", ",", "ctr", ")", "if", "(", "@@text_elements", ".", "include?", "node", ".", "name", ")", "ctr", "<<", "{", ":type", "=>", ":para", ",", ":level", "=>", "level", ",", ":words", "=>", "count_content_words", "(", "node", ")", "}", "elsif", "(", "@@section_elements", ".", "include?", "node", ".", "name", ")", "title", "=", "find_section_title", "(", "node", ")", "ctr", "<<", "{", ":type", "=>", ":section", ",", ":level", "=>", "level", ",", ":title", "=>", "title", ",", ":name", "=>", "node", ".", "name", "}", "node", ".", "children", ".", "each", "{", "|", "inner_elem", "|", "check_node", "(", "inner_elem", ",", "level", "+", "1", ",", "ctr", ")", "}", "if", "node", ".", "children?", "else", "node", ".", "children", ".", "each", "{", "|", "inner_elem", "|", "check_node", "(", "inner_elem", ",", "level", "+", "1", ",", "ctr", ")", "}", "if", "node", ".", "children?", "end", "ctr", "end" ]
Check the document elements for content and type recursively, starting at the current node. Returns an array with paragraph and section maps.
[ "Check", "the", "document", "elements", "for", "content", "and", "type", "recursively", "starting", "at", "the", "current", "node", ".", "Returns", "an", "array", "with", "paragraph", "and", "section", "maps", "." ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L114-L126
train
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.is_docbook?
def is_docbook?(doc) dbns = doc.root.namespaces.default (!dbns.nil? && (dbns.href.casecmp(DOCBOOK_NS) == 0)) end
ruby
def is_docbook?(doc) dbns = doc.root.namespaces.default (!dbns.nil? && (dbns.href.casecmp(DOCBOOK_NS) == 0)) end
[ "def", "is_docbook?", "(", "doc", ")", "dbns", "=", "doc", ".", "root", ".", "namespaces", ".", "default", "(", "!", "dbns", ".", "nil?", "&&", "(", "dbns", ".", "href", ".", "casecmp", "(", "DOCBOOK_NS", ")", "==", "0", ")", ")", "end" ]
Check whether the document has a DocBook default namespace
[ "Check", "whether", "the", "document", "has", "a", "DocBook", "default", "namespace" ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L129-L132
train