repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
ekylibre/active_list | lib/active_list/generator/finder.rb | ActiveList.Generator.select_data_code | def select_data_code(options = {})
paginate = (options.key?(:paginate) ? options[:paginate] : @table.paginate?)
# Check order
unless @table.options.keys.include?(:order)
columns = @table.table_columns
@table.options[:order] = (columns.any? ? columns.first.name.to_sym : { id: :desc })
end
class_name = @table.model.name
class_name = "(controller_name != '#{class_name.tableize}' ? controller_name.to_s.classify.constantize : #{class_name})" if collection?
# Find data
query_code = class_name.to_s
query_code << scope_code if scope_code
query_code << ".select(#{select_code})" if select_code
query_code << ".from(#{from_code})" if from_code
query_code << ".where(#{conditions_code})" unless @table.options[:conditions].blank?
query_code << ".joins(#{@table.options[:joins].inspect})" unless @table.options[:joins].blank?
unless includes_reflections.empty?
expr = includes_reflections.inspect[1..-2]
query_code << ".includes(#{expr})"
query_code << ".references(#{expr})"
end
code = ''
code << "#{query_code}\n"
code << if @table.options[:count].present?
"#{var_name(:count)} = #{query_code}.count(#{@table.options[:count].inspect})\n"
else
"#{var_name(:count)} = #{query_code}.count\n"
end
query_code << ".group(#{@table.options[:group].inspect})" unless @table.options[:group].blank?
query_code << ".reorder(#{var_name(:order)})"
if paginate
code << "#{var_name(:limit)} = (#{var_name(:params)}[:per_page] || 25).to_i\n"
code << "if params[:page]\n"
code << " #{var_name(:page)} = (#{var_name(:params)}[:page] || 1).to_i\n"
code << "elsif params['#{table.name}-id'] and #{var_name(:index)} = #{query_code}.pluck(:id).index(params['#{table.name}-id'].to_i)\n"
# Find page of request element
code << " #{var_name(:page)} = (#{var_name(:index)}.to_f / #{var_name(:limit)}).floor + 1\n"
code << "else\n"
code << " #{var_name(:page)} = 1\n"
code << "end\n"
code << "#{var_name(:page)} = 1 if #{var_name(:page)} < 1\n"
code << "#{var_name(:offset)} = (#{var_name(:page)} - 1) * #{var_name(:limit)}\n"
code << "#{var_name(:last)} = (#{var_name(:count)}.to_f / #{var_name(:limit)}).ceil.to_i\n"
code << "#{var_name(:last)} = 1 if #{var_name(:last)} < 1\n"
code << "return #{view_method_name}(options.merge(page: 1)) if 1 > #{var_name(:page)}\n"
code << "return #{view_method_name}(options.merge(page: #{var_name(:last)})) if #{var_name(:page)} > #{var_name(:last)}\n"
query_code << ".offset(#{var_name(:offset)})"
query_code << ".limit(#{var_name(:limit)})"
end
code << "#{records_variable_name} = #{query_code} || {}\n"
code
end | ruby | def select_data_code(options = {})
paginate = (options.key?(:paginate) ? options[:paginate] : @table.paginate?)
# Check order
unless @table.options.keys.include?(:order)
columns = @table.table_columns
@table.options[:order] = (columns.any? ? columns.first.name.to_sym : { id: :desc })
end
class_name = @table.model.name
class_name = "(controller_name != '#{class_name.tableize}' ? controller_name.to_s.classify.constantize : #{class_name})" if collection?
# Find data
query_code = class_name.to_s
query_code << scope_code if scope_code
query_code << ".select(#{select_code})" if select_code
query_code << ".from(#{from_code})" if from_code
query_code << ".where(#{conditions_code})" unless @table.options[:conditions].blank?
query_code << ".joins(#{@table.options[:joins].inspect})" unless @table.options[:joins].blank?
unless includes_reflections.empty?
expr = includes_reflections.inspect[1..-2]
query_code << ".includes(#{expr})"
query_code << ".references(#{expr})"
end
code = ''
code << "#{query_code}\n"
code << if @table.options[:count].present?
"#{var_name(:count)} = #{query_code}.count(#{@table.options[:count].inspect})\n"
else
"#{var_name(:count)} = #{query_code}.count\n"
end
query_code << ".group(#{@table.options[:group].inspect})" unless @table.options[:group].blank?
query_code << ".reorder(#{var_name(:order)})"
if paginate
code << "#{var_name(:limit)} = (#{var_name(:params)}[:per_page] || 25).to_i\n"
code << "if params[:page]\n"
code << " #{var_name(:page)} = (#{var_name(:params)}[:page] || 1).to_i\n"
code << "elsif params['#{table.name}-id'] and #{var_name(:index)} = #{query_code}.pluck(:id).index(params['#{table.name}-id'].to_i)\n"
# Find page of request element
code << " #{var_name(:page)} = (#{var_name(:index)}.to_f / #{var_name(:limit)}).floor + 1\n"
code << "else\n"
code << " #{var_name(:page)} = 1\n"
code << "end\n"
code << "#{var_name(:page)} = 1 if #{var_name(:page)} < 1\n"
code << "#{var_name(:offset)} = (#{var_name(:page)} - 1) * #{var_name(:limit)}\n"
code << "#{var_name(:last)} = (#{var_name(:count)}.to_f / #{var_name(:limit)}).ceil.to_i\n"
code << "#{var_name(:last)} = 1 if #{var_name(:last)} < 1\n"
code << "return #{view_method_name}(options.merge(page: 1)) if 1 > #{var_name(:page)}\n"
code << "return #{view_method_name}(options.merge(page: #{var_name(:last)})) if #{var_name(:page)} > #{var_name(:last)}\n"
query_code << ".offset(#{var_name(:offset)})"
query_code << ".limit(#{var_name(:limit)})"
end
code << "#{records_variable_name} = #{query_code} || {}\n"
code
end | [
"def",
"select_data_code",
"(",
"options",
"=",
"{",
"}",
")",
"paginate",
"=",
"(",
"options",
".",
"key?",
"(",
":paginate",
")",
"?",
"options",
"[",
":paginate",
"]",
":",
"@table",
".",
"paginate?",
")",
"unless",
"@table",
".",
"options",
".",
"keys",
".",
"include?",
"(",
":order",
")",
"columns",
"=",
"@table",
".",
"table_columns",
"@table",
".",
"options",
"[",
":order",
"]",
"=",
"(",
"columns",
".",
"any?",
"?",
"columns",
".",
"first",
".",
"name",
".",
"to_sym",
":",
"{",
"id",
":",
":desc",
"}",
")",
"end",
"class_name",
"=",
"@table",
".",
"model",
".",
"name",
"class_name",
"=",
"\"(controller_name != '#{class_name.tableize}' ? controller_name.to_s.classify.constantize : #{class_name})\"",
"if",
"collection?",
"query_code",
"=",
"class_name",
".",
"to_s",
"query_code",
"<<",
"scope_code",
"if",
"scope_code",
"query_code",
"<<",
"\".select(#{select_code})\"",
"if",
"select_code",
"query_code",
"<<",
"\".from(#{from_code})\"",
"if",
"from_code",
"query_code",
"<<",
"\".where(#{conditions_code})\"",
"unless",
"@table",
".",
"options",
"[",
":conditions",
"]",
".",
"blank?",
"query_code",
"<<",
"\".joins(#{@table.options[:joins].inspect})\"",
"unless",
"@table",
".",
"options",
"[",
":joins",
"]",
".",
"blank?",
"unless",
"includes_reflections",
".",
"empty?",
"expr",
"=",
"includes_reflections",
".",
"inspect",
"[",
"1",
"..",
"-",
"2",
"]",
"query_code",
"<<",
"\".includes(#{expr})\"",
"query_code",
"<<",
"\".references(#{expr})\"",
"end",
"code",
"=",
"''",
"code",
"<<",
"\"#{query_code}\\n\"",
"code",
"<<",
"if",
"@table",
".",
"options",
"[",
":count",
"]",
".",
"present?",
"\"#{var_name(:count)} = #{query_code}.count(#{@table.options[:count].inspect})\\n\"",
"else",
"\"#{var_name(:count)} = #{query_code}.count\\n\"",
"end",
"query_code",
"<<",
"\".group(#{@table.options[:group].inspect})\"",
"unless",
"@table",
".",
"options",
"[",
":group",
"]",
".",
"blank?",
"query_code",
"<<",
"\".reorder(#{var_name(:order)})\"",
"if",
"paginate",
"code",
"<<",
"\"#{var_name(:limit)} = (#{var_name(:params)}[:per_page] || 25).to_i\\n\"",
"code",
"<<",
"\"if params[:page]\\n\"",
"code",
"<<",
"\" #{var_name(:page)} = (#{var_name(:params)}[:page] || 1).to_i\\n\"",
"code",
"<<",
"\"elsif params['#{table.name}-id'] and #{var_name(:index)} = #{query_code}.pluck(:id).index(params['#{table.name}-id'].to_i)\\n\"",
"code",
"<<",
"\" #{var_name(:page)} = (#{var_name(:index)}.to_f / #{var_name(:limit)}).floor + 1\\n\"",
"code",
"<<",
"\"else\\n\"",
"code",
"<<",
"\" #{var_name(:page)} = 1\\n\"",
"code",
"<<",
"\"end\\n\"",
"code",
"<<",
"\"#{var_name(:page)} = 1 if #{var_name(:page)} < 1\\n\"",
"code",
"<<",
"\"#{var_name(:offset)} = (#{var_name(:page)} - 1) * #{var_name(:limit)}\\n\"",
"code",
"<<",
"\"#{var_name(:last)} = (#{var_name(:count)}.to_f / #{var_name(:limit)}).ceil.to_i\\n\"",
"code",
"<<",
"\"#{var_name(:last)} = 1 if #{var_name(:last)} < 1\\n\"",
"code",
"<<",
"\"return #{view_method_name}(options.merge(page: 1)) if 1 > #{var_name(:page)}\\n\"",
"code",
"<<",
"\"return #{view_method_name}(options.merge(page: #{var_name(:last)})) if #{var_name(:page)} > #{var_name(:last)}\\n\"",
"query_code",
"<<",
"\".offset(#{var_name(:offset)})\"",
"query_code",
"<<",
"\".limit(#{var_name(:limit)})\"",
"end",
"code",
"<<",
"\"#{records_variable_name} = #{query_code} || {}\\n\"",
"code",
"end"
]
| Generate select code for the table taking all parameters in account | [
"Generate",
"select",
"code",
"for",
"the",
"table",
"taking",
"all",
"parameters",
"in",
"account"
]
| 7d27d246ae6834af68eadcb567597bd78487d5fd | https://github.com/ekylibre/active_list/blob/7d27d246ae6834af68eadcb567597bd78487d5fd/lib/active_list/generator/finder.rb#L5-L66 | train |
ekylibre/active_list | lib/active_list/generator/finder.rb | ActiveList.Generator.includes_reflections | def includes_reflections
hash = []
@table.columns.each do |column|
hash << column.reflection.name if column.respond_to?(:reflection)
end
hash
end | ruby | def includes_reflections
hash = []
@table.columns.each do |column|
hash << column.reflection.name if column.respond_to?(:reflection)
end
hash
end | [
"def",
"includes_reflections",
"hash",
"=",
"[",
"]",
"@table",
".",
"columns",
".",
"each",
"do",
"|",
"column",
"|",
"hash",
"<<",
"column",
".",
"reflection",
".",
"name",
"if",
"column",
".",
"respond_to?",
"(",
":reflection",
")",
"end",
"hash",
"end"
]
| Compute includes Hash | [
"Compute",
"includes",
"Hash"
]
| 7d27d246ae6834af68eadcb567597bd78487d5fd | https://github.com/ekylibre/active_list/blob/7d27d246ae6834af68eadcb567597bd78487d5fd/lib/active_list/generator/finder.rb#L71-L77 | train |
ekylibre/active_list | lib/active_list/generator/finder.rb | ActiveList.Generator.conditions_code | def conditions_code
conditions = @table.options[:conditions]
code = ''
case conditions
when Array
case conditions[0]
when String # SQL
code << '[' + conditions.first.inspect
code << conditions[1..-1].collect { |p| ', ' + sanitize_condition(p) }.join if conditions.size > 1
code << ']'
when Symbol # Method
raise 'What?' # Amazingly explicit.
# code << conditions.first.to_s + '('
# code << conditions[1..-1].collect { |p| sanitize_condition(p) }.join(', ') if conditions.size > 1
# code << ')'
else
raise ArgumentError, 'First element of an Array can only be String or Symbol.'
end
when Hash # SQL
code << '{' + conditions.collect { |key, value| key.to_s + ': ' + sanitize_condition(value) }.join(',') + '}'
when Symbol # Method
code << conditions.to_s + '(options)'
when CodeString
code << '(' + conditions.gsub(/\s*\n\s*/, ';') + ')'
when String
code << conditions.inspect
else
raise ArgumentError, "Unsupported type for conditions: #{conditions.inspect}"
end
code
end | ruby | def conditions_code
conditions = @table.options[:conditions]
code = ''
case conditions
when Array
case conditions[0]
when String # SQL
code << '[' + conditions.first.inspect
code << conditions[1..-1].collect { |p| ', ' + sanitize_condition(p) }.join if conditions.size > 1
code << ']'
when Symbol # Method
raise 'What?' # Amazingly explicit.
# code << conditions.first.to_s + '('
# code << conditions[1..-1].collect { |p| sanitize_condition(p) }.join(', ') if conditions.size > 1
# code << ')'
else
raise ArgumentError, 'First element of an Array can only be String or Symbol.'
end
when Hash # SQL
code << '{' + conditions.collect { |key, value| key.to_s + ': ' + sanitize_condition(value) }.join(',') + '}'
when Symbol # Method
code << conditions.to_s + '(options)'
when CodeString
code << '(' + conditions.gsub(/\s*\n\s*/, ';') + ')'
when String
code << conditions.inspect
else
raise ArgumentError, "Unsupported type for conditions: #{conditions.inspect}"
end
code
end | [
"def",
"conditions_code",
"conditions",
"=",
"@table",
".",
"options",
"[",
":conditions",
"]",
"code",
"=",
"''",
"case",
"conditions",
"when",
"Array",
"case",
"conditions",
"[",
"0",
"]",
"when",
"String",
"code",
"<<",
"'['",
"+",
"conditions",
".",
"first",
".",
"inspect",
"code",
"<<",
"conditions",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"collect",
"{",
"|",
"p",
"|",
"', '",
"+",
"sanitize_condition",
"(",
"p",
")",
"}",
".",
"join",
"if",
"conditions",
".",
"size",
">",
"1",
"code",
"<<",
"']'",
"when",
"Symbol",
"raise",
"'What?'",
"else",
"raise",
"ArgumentError",
",",
"'First element of an Array can only be String or Symbol.'",
"end",
"when",
"Hash",
"code",
"<<",
"'{'",
"+",
"conditions",
".",
"collect",
"{",
"|",
"key",
",",
"value",
"|",
"key",
".",
"to_s",
"+",
"': '",
"+",
"sanitize_condition",
"(",
"value",
")",
"}",
".",
"join",
"(",
"','",
")",
"+",
"'}'",
"when",
"Symbol",
"code",
"<<",
"conditions",
".",
"to_s",
"+",
"'(options)'",
"when",
"CodeString",
"code",
"<<",
"'('",
"+",
"conditions",
".",
"gsub",
"(",
"/",
"\\s",
"\\n",
"\\s",
"/",
",",
"';'",
")",
"+",
"')'",
"when",
"String",
"code",
"<<",
"conditions",
".",
"inspect",
"else",
"raise",
"ArgumentError",
",",
"\"Unsupported type for conditions: #{conditions.inspect}\"",
"end",
"code",
"end"
]
| Generate the code from a conditions option | [
"Generate",
"the",
"code",
"from",
"a",
"conditions",
"option"
]
| 7d27d246ae6834af68eadcb567597bd78487d5fd | https://github.com/ekylibre/active_list/blob/7d27d246ae6834af68eadcb567597bd78487d5fd/lib/active_list/generator/finder.rb#L90-L120 | train |
rahmal/rconfig | lib/rconfig/utils.rb | RConfig.Utils.default_load_paths | def default_load_paths
paths = []
# Check for Rails config path
paths << "#{::Rails.root}/config" if rails?
# Check for defined constants
paths << CONFIG_ROOT if defined?(CONFIG_ROOT) && Dir.exists?(CONFIG_ROOT)
paths << CONFIG_PATH if defined?(CONFIG_PATH) && Dir.exists?(CONFIG_PATH)
# Check for config directory in app root
config_dir = File.join(app_root, 'config')
paths << config_dir if Dir.exists?(config_dir)
paths
end | ruby | def default_load_paths
paths = []
# Check for Rails config path
paths << "#{::Rails.root}/config" if rails?
# Check for defined constants
paths << CONFIG_ROOT if defined?(CONFIG_ROOT) && Dir.exists?(CONFIG_ROOT)
paths << CONFIG_PATH if defined?(CONFIG_PATH) && Dir.exists?(CONFIG_PATH)
# Check for config directory in app root
config_dir = File.join(app_root, 'config')
paths << config_dir if Dir.exists?(config_dir)
paths
end | [
"def",
"default_load_paths",
"paths",
"=",
"[",
"]",
"paths",
"<<",
"\"#{::Rails.root}/config\"",
"if",
"rails?",
"paths",
"<<",
"CONFIG_ROOT",
"if",
"defined?",
"(",
"CONFIG_ROOT",
")",
"&&",
"Dir",
".",
"exists?",
"(",
"CONFIG_ROOT",
")",
"paths",
"<<",
"CONFIG_PATH",
"if",
"defined?",
"(",
"CONFIG_PATH",
")",
"&&",
"Dir",
".",
"exists?",
"(",
"CONFIG_PATH",
")",
"config_dir",
"=",
"File",
".",
"join",
"(",
"app_root",
",",
"'config'",
")",
"paths",
"<<",
"config_dir",
"if",
"Dir",
".",
"exists?",
"(",
"config_dir",
")",
"paths",
"end"
]
| Checks environment for default configuration load paths. Adds them to load paths if found. | [
"Checks",
"environment",
"for",
"default",
"configuration",
"load",
"paths",
".",
"Adds",
"them",
"to",
"load",
"paths",
"if",
"found",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/utils.rb#L28-L43 | train |
rahmal/rconfig | lib/rconfig/utils.rb | RConfig.Utils.read | def read(file, name, ext)
contents = File.read(file) # Read the contents from the file.
contents = ERB.new(contents).result # Evaluate any ruby code using ERB.
parse(contents, name, ext) # Parse the contents based on the file type
end | ruby | def read(file, name, ext)
contents = File.read(file) # Read the contents from the file.
contents = ERB.new(contents).result # Evaluate any ruby code using ERB.
parse(contents, name, ext) # Parse the contents based on the file type
end | [
"def",
"read",
"(",
"file",
",",
"name",
",",
"ext",
")",
"contents",
"=",
"File",
".",
"read",
"(",
"file",
")",
"contents",
"=",
"ERB",
".",
"new",
"(",
"contents",
")",
".",
"result",
"parse",
"(",
"contents",
",",
"name",
",",
"ext",
")",
"end"
]
| Reads and parses the config data from the specified file. | [
"Reads",
"and",
"parses",
"the",
"config",
"data",
"from",
"the",
"specified",
"file",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/utils.rb#L78-L82 | train |
rahmal/rconfig | lib/rconfig/utils.rb | RConfig.Utils.parse | def parse(contents, name, ext)
hash = case ext
when *YML_FILE_TYPES
YAML::load(contents)
when *XML_FILE_TYPES
parse_xml(contents, name)
when *CNF_FILE_TYPES
RConfig::PropertiesFile.parse(contents)
else
raise ConfigError, "Unknown File type: #{ext}"
end
hash.freeze
end | ruby | def parse(contents, name, ext)
hash = case ext
when *YML_FILE_TYPES
YAML::load(contents)
when *XML_FILE_TYPES
parse_xml(contents, name)
when *CNF_FILE_TYPES
RConfig::PropertiesFile.parse(contents)
else
raise ConfigError, "Unknown File type: #{ext}"
end
hash.freeze
end | [
"def",
"parse",
"(",
"contents",
",",
"name",
",",
"ext",
")",
"hash",
"=",
"case",
"ext",
"when",
"*",
"YML_FILE_TYPES",
"YAML",
"::",
"load",
"(",
"contents",
")",
"when",
"*",
"XML_FILE_TYPES",
"parse_xml",
"(",
"contents",
",",
"name",
")",
"when",
"*",
"CNF_FILE_TYPES",
"RConfig",
"::",
"PropertiesFile",
".",
"parse",
"(",
"contents",
")",
"else",
"raise",
"ConfigError",
",",
"\"Unknown File type: #{ext}\"",
"end",
"hash",
".",
"freeze",
"end"
]
| Parses contents of the config file based on file type.
XML files expect the root element to be the same as the
file name. | [
"Parses",
"contents",
"of",
"the",
"config",
"file",
"based",
"on",
"file",
"type",
".",
"XML",
"files",
"expect",
"the",
"root",
"element",
"to",
"be",
"the",
"same",
"as",
"the",
"file",
"name",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/utils.rb#L89-L101 | train |
rahmal/rconfig | lib/rconfig/utils.rb | RConfig.Utils.parse_xml | def parse_xml(contents, name)
hash = Hash.from_xml(contents)
hash = hash[name] if hash.size == 1 && hash.key?(name) # xml document could have root tag matching the file name.
RConfig::PropertiesFile.parse_references(hash)
end | ruby | def parse_xml(contents, name)
hash = Hash.from_xml(contents)
hash = hash[name] if hash.size == 1 && hash.key?(name) # xml document could have root tag matching the file name.
RConfig::PropertiesFile.parse_references(hash)
end | [
"def",
"parse_xml",
"(",
"contents",
",",
"name",
")",
"hash",
"=",
"Hash",
".",
"from_xml",
"(",
"contents",
")",
"hash",
"=",
"hash",
"[",
"name",
"]",
"if",
"hash",
".",
"size",
"==",
"1",
"&&",
"hash",
".",
"key?",
"(",
"name",
")",
"RConfig",
"::",
"PropertiesFile",
".",
"parse_references",
"(",
"hash",
")",
"end"
]
| Parses xml file and processes any references in the property values. | [
"Parses",
"xml",
"file",
"and",
"processes",
"any",
"references",
"in",
"the",
"property",
"values",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/utils.rb#L105-L109 | train |
rahmal/rconfig | lib/rconfig/utils.rb | RConfig.Utils.merge_hashes | def merge_hashes(hashes)
hashes.inject({}) { |n, h| n.weave(h, true) }
end | ruby | def merge_hashes(hashes)
hashes.inject({}) { |n, h| n.weave(h, true) }
end | [
"def",
"merge_hashes",
"(",
"hashes",
")",
"hashes",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"n",
",",
"h",
"|",
"n",
".",
"weave",
"(",
"h",
",",
"true",
")",
"}",
"end"
]
| Returns a merge of hashes. | [
"Returns",
"a",
"merge",
"of",
"hashes",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/utils.rb#L114-L116 | train |
rahmal/rconfig | lib/rconfig/utils.rb | RConfig.Utils.make_indifferent | def make_indifferent(hash)
case hash
when Hash
unless hash.frozen?
hash.each do |k, v|
hash[k] = make_indifferent(v)
end
hash = RConfig::Config.new.merge!(hash).freeze
end
logger.debug "make_indefferent: x = #{hash.inspect}:#{hash.class}"
when Array
unless hash.frozen?
hash.collect! do |v|
make_indifferent(v)
end
hash.freeze
end
# Freeze Strings.
when String
hash.freeze
end
hash
end | ruby | def make_indifferent(hash)
case hash
when Hash
unless hash.frozen?
hash.each do |k, v|
hash[k] = make_indifferent(v)
end
hash = RConfig::Config.new.merge!(hash).freeze
end
logger.debug "make_indefferent: x = #{hash.inspect}:#{hash.class}"
when Array
unless hash.frozen?
hash.collect! do |v|
make_indifferent(v)
end
hash.freeze
end
# Freeze Strings.
when String
hash.freeze
end
hash
end | [
"def",
"make_indifferent",
"(",
"hash",
")",
"case",
"hash",
"when",
"Hash",
"unless",
"hash",
".",
"frozen?",
"hash",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"hash",
"[",
"k",
"]",
"=",
"make_indifferent",
"(",
"v",
")",
"end",
"hash",
"=",
"RConfig",
"::",
"Config",
".",
"new",
".",
"merge!",
"(",
"hash",
")",
".",
"freeze",
"end",
"logger",
".",
"debug",
"\"make_indefferent: x = #{hash.inspect}:#{hash.class}\"",
"when",
"Array",
"unless",
"hash",
".",
"frozen?",
"hash",
".",
"collect!",
"do",
"|",
"v",
"|",
"make_indifferent",
"(",
"v",
")",
"end",
"hash",
".",
"freeze",
"end",
"when",
"String",
"hash",
".",
"freeze",
"end",
"hash",
"end"
]
| Recursively makes hashes into frozen IndifferentAccess Config Hash
Arrays are also traversed and frozen. | [
"Recursively",
"makes",
"hashes",
"into",
"frozen",
"IndifferentAccess",
"Config",
"Hash",
"Arrays",
"are",
"also",
"traversed",
"and",
"frozen",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/utils.rb#L122-L144 | train |
rahmal/rconfig | lib/rconfig/utils.rb | RConfig.Utils.flush_cache | def flush_cache(name=nil)
if name
name = name.to_s
self.cache_hash[name] &&= nil
else
logger.warn "RConfig: Flushing config data cache."
self.suffixes = {}
self.cache = {}
self.cache_files = {}
self.cache_hash = {}
self.last_auto_check = {}
self
end
end | ruby | def flush_cache(name=nil)
if name
name = name.to_s
self.cache_hash[name] &&= nil
else
logger.warn "RConfig: Flushing config data cache."
self.suffixes = {}
self.cache = {}
self.cache_files = {}
self.cache_hash = {}
self.last_auto_check = {}
self
end
end | [
"def",
"flush_cache",
"(",
"name",
"=",
"nil",
")",
"if",
"name",
"name",
"=",
"name",
".",
"to_s",
"self",
".",
"cache_hash",
"[",
"name",
"]",
"&&=",
"nil",
"else",
"logger",
".",
"warn",
"\"RConfig: Flushing config data cache.\"",
"self",
".",
"suffixes",
"=",
"{",
"}",
"self",
".",
"cache",
"=",
"{",
"}",
"self",
".",
"cache_files",
"=",
"{",
"}",
"self",
".",
"cache_hash",
"=",
"{",
"}",
"self",
".",
"last_auto_check",
"=",
"{",
"}",
"self",
"end",
"end"
]
| If a config file name is specified, flushes cached config values
for specified config file. Otherwise, flushes all cached config data.
The latter should be avoided in production environments, if possible. | [
"If",
"a",
"config",
"file",
"name",
"is",
"specified",
"flushes",
"cached",
"config",
"values",
"for",
"specified",
"config",
"file",
".",
"Otherwise",
"flushes",
"all",
"cached",
"config",
"data",
".",
"The",
"latter",
"should",
"be",
"avoided",
"in",
"production",
"environments",
"if",
"possible",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/utils.rb#L150-L163 | train |
rahmal/rconfig | lib/rconfig/cascade.rb | RConfig.Cascade.overlay= | def overlay=(value)
reload(false) if self.overlay != value
self.overlay = value && value.dup.freeze
end | ruby | def overlay=(value)
reload(false) if self.overlay != value
self.overlay = value && value.dup.freeze
end | [
"def",
"overlay",
"=",
"(",
"value",
")",
"reload",
"(",
"false",
")",
"if",
"self",
".",
"overlay",
"!=",
"value",
"self",
".",
"overlay",
"=",
"value",
"&&",
"value",
".",
"dup",
".",
"freeze",
"end"
]
| Sets a custome overlay for | [
"Sets",
"a",
"custome",
"overlay",
"for"
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/cascade.rb#L7-L10 | train |
rahmal/rconfig | lib/rconfig/cascade.rb | RConfig.Cascade.suffixes_for | def suffixes_for(name)
name = name.to_s
self.suffixes[name] ||= begin
ol = overlay
name_x = name.dup
if name_x.sub!(/_([A-Z]+)$/, '')
ol = $1
end
name_x.freeze
result = if ol
ol_ = ol.upcase
ol = ol.downcase
x = []
SUFFIXES.each do |suffix|
# Standard, no overlay:
# e.g.: database_<suffix>.yml
x << suffix
# Overlay:
# e.g.: database_(US|GB)_<suffix>.yml
x << [ol_, suffix]
end
[name_x, x.freeze]
else
[name.dup.freeze, SUFFIXES.freeze]
end
result.freeze
logger.debug "suffixes(#{name}) => #{result.inspect}"
result
end
end | ruby | def suffixes_for(name)
name = name.to_s
self.suffixes[name] ||= begin
ol = overlay
name_x = name.dup
if name_x.sub!(/_([A-Z]+)$/, '')
ol = $1
end
name_x.freeze
result = if ol
ol_ = ol.upcase
ol = ol.downcase
x = []
SUFFIXES.each do |suffix|
# Standard, no overlay:
# e.g.: database_<suffix>.yml
x << suffix
# Overlay:
# e.g.: database_(US|GB)_<suffix>.yml
x << [ol_, suffix]
end
[name_x, x.freeze]
else
[name.dup.freeze, SUFFIXES.freeze]
end
result.freeze
logger.debug "suffixes(#{name}) => #{result.inspect}"
result
end
end | [
"def",
"suffixes_for",
"(",
"name",
")",
"name",
"=",
"name",
".",
"to_s",
"self",
".",
"suffixes",
"[",
"name",
"]",
"||=",
"begin",
"ol",
"=",
"overlay",
"name_x",
"=",
"name",
".",
"dup",
"if",
"name_x",
".",
"sub!",
"(",
"/",
"/",
",",
"''",
")",
"ol",
"=",
"$1",
"end",
"name_x",
".",
"freeze",
"result",
"=",
"if",
"ol",
"ol_",
"=",
"ol",
".",
"upcase",
"ol",
"=",
"ol",
".",
"downcase",
"x",
"=",
"[",
"]",
"SUFFIXES",
".",
"each",
"do",
"|",
"suffix",
"|",
"x",
"<<",
"suffix",
"x",
"<<",
"[",
"ol_",
",",
"suffix",
"]",
"end",
"[",
"name_x",
",",
"x",
".",
"freeze",
"]",
"else",
"[",
"name",
".",
"dup",
".",
"freeze",
",",
"SUFFIXES",
".",
"freeze",
"]",
"end",
"result",
".",
"freeze",
"logger",
".",
"debug",
"\"suffixes(#{name}) => #{result.inspect}\"",
"result",
"end",
"end"
]
| Returns a list of suffixes to try for a given config name.
A config name with an explicit overlay (e.g.: 'name_GB')
overrides any current _overlay.
This allows code to specifically ask for config overlays
for a particular locale. | [
"Returns",
"a",
"list",
"of",
"suffixes",
"to",
"try",
"for",
"a",
"given",
"config",
"name",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/cascade.rb#L21-L53 | train |
rahmal/rconfig | lib/rconfig/core_methods.rb | RConfig.CoreMethods.load_config_files | def load_config_files(name, force=false)
name = name.to_s
# Return last config file hash list loaded,
# if reload is disabled and files have already been loaded.
return self.cache_config_files[name] if self.reload_disabled? && self.cache_config_files[name]
logger.info "Loading config files for: #{name}"
logger.debug "load_config_files(#{name.inspect})"
# Get current time for checking last loaded status.
now = Time.now
# Get array of all the existing files file the config name.
config_files = self.get_config_files(name)
# Get all the data from all yaml files into as configs
configs = config_files.collect do |f|
name, name_with_suffix, filename, ext, modified_time = * f
# Get the cached file info the specific file, if
# it's been loaded before.
config_data, last_modified, last_loaded = self.cache[filename]
logger.debug "f = #{f.inspect}\n" +
"cache #{name_with_suffix} filename = #{filename.inspect}\n" +
"cache #{name_with_suffix} config_data = #{config_data.inspect}\n" +
"cache #{name_with_suffix} last_modified = #{last_modified.inspect}\n" +
"cache #{name_with_suffix} last_loaded = #{last_loaded.inspect}\n"
# Load the file if its never been loaded or its been more than
# so many minutes since last load attempt. (default: 5 minutes)
if config_data.blank? || (now - last_loaded > self.reload_interval)
if force || config_data.blank? || modified_time != last_modified
logger.debug "modified_time #{name.inspect} #{filename.inspect} " +
"changed #{modified_time != last_modified} : #{modified_time.inspect} #{last_modified.inspect}"
logger.debug "RConfig: loading #{filename.inspect}"
config_data = read(filename, name, ext) # Get contents from config file
logger.debug "RConfig: loaded #{filename.inspect} => #{config_data.inspect}"
(self.config_loaded ||= {})[name] = config_files # add files to the loaded files cache
self.cache[filename] = [config_data, modified_time, now] # Save cached config file contents, and modified_time.
logger.debug "cache[#{filename.inspect}] = #{self.cache[filename].inspect}"
self.cache_hash[name] = nil # Flush merged hash cache.
self.cache_files[name] = config_files # Config files changed or disappeared.
end # if config_data == nil || (now - last_loaded > self.reload_interval)
end # if force || config_data == nil || modified_time != last_modified
config_data
end # config_files.collect
configs.compact!
logger.debug "load_config_files(#{name.inspect}) => #{configs.inspect}"
# Keep last loaded config files around in case self.reload_dsabled.
self.cache_config_files[name] = configs #unless configs.empty?
configs
end | ruby | def load_config_files(name, force=false)
name = name.to_s
# Return last config file hash list loaded,
# if reload is disabled and files have already been loaded.
return self.cache_config_files[name] if self.reload_disabled? && self.cache_config_files[name]
logger.info "Loading config files for: #{name}"
logger.debug "load_config_files(#{name.inspect})"
# Get current time for checking last loaded status.
now = Time.now
# Get array of all the existing files file the config name.
config_files = self.get_config_files(name)
# Get all the data from all yaml files into as configs
configs = config_files.collect do |f|
name, name_with_suffix, filename, ext, modified_time = * f
# Get the cached file info the specific file, if
# it's been loaded before.
config_data, last_modified, last_loaded = self.cache[filename]
logger.debug "f = #{f.inspect}\n" +
"cache #{name_with_suffix} filename = #{filename.inspect}\n" +
"cache #{name_with_suffix} config_data = #{config_data.inspect}\n" +
"cache #{name_with_suffix} last_modified = #{last_modified.inspect}\n" +
"cache #{name_with_suffix} last_loaded = #{last_loaded.inspect}\n"
# Load the file if its never been loaded or its been more than
# so many minutes since last load attempt. (default: 5 minutes)
if config_data.blank? || (now - last_loaded > self.reload_interval)
if force || config_data.blank? || modified_time != last_modified
logger.debug "modified_time #{name.inspect} #{filename.inspect} " +
"changed #{modified_time != last_modified} : #{modified_time.inspect} #{last_modified.inspect}"
logger.debug "RConfig: loading #{filename.inspect}"
config_data = read(filename, name, ext) # Get contents from config file
logger.debug "RConfig: loaded #{filename.inspect} => #{config_data.inspect}"
(self.config_loaded ||= {})[name] = config_files # add files to the loaded files cache
self.cache[filename] = [config_data, modified_time, now] # Save cached config file contents, and modified_time.
logger.debug "cache[#{filename.inspect}] = #{self.cache[filename].inspect}"
self.cache_hash[name] = nil # Flush merged hash cache.
self.cache_files[name] = config_files # Config files changed or disappeared.
end # if config_data == nil || (now - last_loaded > self.reload_interval)
end # if force || config_data == nil || modified_time != last_modified
config_data
end # config_files.collect
configs.compact!
logger.debug "load_config_files(#{name.inspect}) => #{configs.inspect}"
# Keep last loaded config files around in case self.reload_dsabled.
self.cache_config_files[name] = configs #unless configs.empty?
configs
end | [
"def",
"load_config_files",
"(",
"name",
",",
"force",
"=",
"false",
")",
"name",
"=",
"name",
".",
"to_s",
"return",
"self",
".",
"cache_config_files",
"[",
"name",
"]",
"if",
"self",
".",
"reload_disabled?",
"&&",
"self",
".",
"cache_config_files",
"[",
"name",
"]",
"logger",
".",
"info",
"\"Loading config files for: #{name}\"",
"logger",
".",
"debug",
"\"load_config_files(#{name.inspect})\"",
"now",
"=",
"Time",
".",
"now",
"config_files",
"=",
"self",
".",
"get_config_files",
"(",
"name",
")",
"configs",
"=",
"config_files",
".",
"collect",
"do",
"|",
"f",
"|",
"name",
",",
"name_with_suffix",
",",
"filename",
",",
"ext",
",",
"modified_time",
"=",
"*",
"f",
"config_data",
",",
"last_modified",
",",
"last_loaded",
"=",
"self",
".",
"cache",
"[",
"filename",
"]",
"logger",
".",
"debug",
"\"f = #{f.inspect}\\n\"",
"+",
"\"cache #{name_with_suffix} filename = #{filename.inspect}\\n\"",
"+",
"\"cache #{name_with_suffix} config_data = #{config_data.inspect}\\n\"",
"+",
"\"cache #{name_with_suffix} last_modified = #{last_modified.inspect}\\n\"",
"+",
"\"cache #{name_with_suffix} last_loaded = #{last_loaded.inspect}\\n\"",
"if",
"config_data",
".",
"blank?",
"||",
"(",
"now",
"-",
"last_loaded",
">",
"self",
".",
"reload_interval",
")",
"if",
"force",
"||",
"config_data",
".",
"blank?",
"||",
"modified_time",
"!=",
"last_modified",
"logger",
".",
"debug",
"\"modified_time #{name.inspect} #{filename.inspect} \"",
"+",
"\"changed #{modified_time != last_modified} : #{modified_time.inspect} #{last_modified.inspect}\"",
"logger",
".",
"debug",
"\"RConfig: loading #{filename.inspect}\"",
"config_data",
"=",
"read",
"(",
"filename",
",",
"name",
",",
"ext",
")",
"logger",
".",
"debug",
"\"RConfig: loaded #{filename.inspect} => #{config_data.inspect}\"",
"(",
"self",
".",
"config_loaded",
"||=",
"{",
"}",
")",
"[",
"name",
"]",
"=",
"config_files",
"self",
".",
"cache",
"[",
"filename",
"]",
"=",
"[",
"config_data",
",",
"modified_time",
",",
"now",
"]",
"logger",
".",
"debug",
"\"cache[#{filename.inspect}] = #{self.cache[filename].inspect}\"",
"self",
".",
"cache_hash",
"[",
"name",
"]",
"=",
"nil",
"self",
".",
"cache_files",
"[",
"name",
"]",
"=",
"config_files",
"end",
"end",
"config_data",
"end",
"configs",
".",
"compact!",
"logger",
".",
"debug",
"\"load_config_files(#{name.inspect}) => #{configs.inspect}\"",
"self",
".",
"cache_config_files",
"[",
"name",
"]",
"=",
"configs",
"configs",
"end"
]
| Get each config file's yaml hash for the given config name,
to be merged later. Files will only be loaded if they have
not been loaded before or the files have changed within the
last five minutes, or force is explicitly set to true. | [
"Get",
"each",
"config",
"file",
"s",
"yaml",
"hash",
"for",
"the",
"given",
"config",
"name",
"to",
"be",
"merged",
"later",
".",
"Files",
"will",
"only",
"be",
"loaded",
"if",
"they",
"have",
"not",
"been",
"loaded",
"before",
"or",
"the",
"files",
"have",
"changed",
"within",
"the",
"last",
"five",
"minutes",
"or",
"force",
"is",
"explicitly",
"set",
"to",
"true",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/core_methods.rb#L14-L81 | train |
rahmal/rconfig | lib/rconfig/core_methods.rb | RConfig.CoreMethods.config_changed? | def config_changed?(name)
logger.debug "config_changed?(#{name.inspect})"
name = name.to_s
!(self.cache_files[name] === get_config_files(name))
end | ruby | def config_changed?(name)
logger.debug "config_changed?(#{name.inspect})"
name = name.to_s
!(self.cache_files[name] === get_config_files(name))
end | [
"def",
"config_changed?",
"(",
"name",
")",
"logger",
".",
"debug",
"\"config_changed?(#{name.inspect})\"",
"name",
"=",
"name",
".",
"to_s",
"!",
"(",
"self",
".",
"cache_files",
"[",
"name",
"]",
"===",
"get_config_files",
"(",
"name",
")",
")",
"end"
]
| Returns whether or not the config for the given config name has changed
since it was last loaded.
Returns true if any files for config have changes since
last load. | [
"Returns",
"whether",
"or",
"not",
"the",
"config",
"for",
"the",
"given",
"config",
"name",
"has",
"changed",
"since",
"it",
"was",
"last",
"loaded",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/core_methods.rb#L131-L135 | train |
rahmal/rconfig | lib/rconfig/core_methods.rb | RConfig.CoreMethods.get_config_data | def get_config_data(name)
logger.debug "get_config_data(#{name.inspect})"
name = name.to_s
unless result = self.cache_hash[name]
result = self.cache_hash[name] =
make_indifferent(
merge_hashes(
load_config_files(name)
)
)
logger.debug "get_config_data(#{name.inspect}): reloaded"
end
result
end | ruby | def get_config_data(name)
logger.debug "get_config_data(#{name.inspect})"
name = name.to_s
unless result = self.cache_hash[name]
result = self.cache_hash[name] =
make_indifferent(
merge_hashes(
load_config_files(name)
)
)
logger.debug "get_config_data(#{name.inspect}): reloaded"
end
result
end | [
"def",
"get_config_data",
"(",
"name",
")",
"logger",
".",
"debug",
"\"get_config_data(#{name.inspect})\"",
"name",
"=",
"name",
".",
"to_s",
"unless",
"result",
"=",
"self",
".",
"cache_hash",
"[",
"name",
"]",
"result",
"=",
"self",
".",
"cache_hash",
"[",
"name",
"]",
"=",
"make_indifferent",
"(",
"merge_hashes",
"(",
"load_config_files",
"(",
"name",
")",
")",
")",
"logger",
".",
"debug",
"\"get_config_data(#{name.inspect}): reloaded\"",
"end",
"result",
"end"
]
| Get the merged config hash for the named file.
Returns a cached indifferent access faker hash merged
from all config files for a name. | [
"Get",
"the",
"merged",
"config",
"hash",
"for",
"the",
"named",
"file",
".",
"Returns",
"a",
"cached",
"indifferent",
"access",
"faker",
"hash",
"merged",
"from",
"all",
"config",
"files",
"for",
"a",
"name",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/core_methods.rb#L143-L158 | train |
rahmal/rconfig | lib/rconfig/core_methods.rb | RConfig.CoreMethods.check_for_changes | def check_for_changes(name=nil)
changed = []
if name == nil
self.cache_hash.keys.dup.each do |name|
if reload_on_change(name)
changed << name
end
end
else
name = name.to_s
if reload_on_change(name)
changed << name
end
end
logger.debug "check_for_changes(#{name.inspect}) => #{changed.inspect}"
changed
end | ruby | def check_for_changes(name=nil)
changed = []
if name == nil
self.cache_hash.keys.dup.each do |name|
if reload_on_change(name)
changed << name
end
end
else
name = name.to_s
if reload_on_change(name)
changed << name
end
end
logger.debug "check_for_changes(#{name.inspect}) => #{changed.inspect}"
changed
end | [
"def",
"check_for_changes",
"(",
"name",
"=",
"nil",
")",
"changed",
"=",
"[",
"]",
"if",
"name",
"==",
"nil",
"self",
".",
"cache_hash",
".",
"keys",
".",
"dup",
".",
"each",
"do",
"|",
"name",
"|",
"if",
"reload_on_change",
"(",
"name",
")",
"changed",
"<<",
"name",
"end",
"end",
"else",
"name",
"=",
"name",
".",
"to_s",
"if",
"reload_on_change",
"(",
"name",
")",
"changed",
"<<",
"name",
"end",
"end",
"logger",
".",
"debug",
"\"check_for_changes(#{name.inspect}) => #{changed.inspect}\"",
"changed",
"end"
]
| If name is specified, checks that file for changes and
reloads it if there are. Otherwise, checks all files
in the cache, reloading the changed files. | [
"If",
"name",
"is",
"specified",
"checks",
"that",
"file",
"for",
"changes",
"and",
"reloads",
"it",
"if",
"there",
"are",
".",
"Otherwise",
"checks",
"all",
"files",
"in",
"the",
"cache",
"reloading",
"the",
"changed",
"files",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/core_methods.rb#L164-L180 | train |
rahmal/rconfig | lib/rconfig/core_methods.rb | RConfig.CoreMethods.reload_on_change | def reload_on_change(name)
logger.debug "reload_on_change(#{name.inspect}), reload_disabled=#{self.reload_disabled?}"
if changed = config_changed?(name) && reload?
if self.cache_hash[name]
flush_cache(name) # flush cached config values.
fire_on_load(name) # force on_load triggers.
end
end
changed
end | ruby | def reload_on_change(name)
logger.debug "reload_on_change(#{name.inspect}), reload_disabled=#{self.reload_disabled?}"
if changed = config_changed?(name) && reload?
if self.cache_hash[name]
flush_cache(name) # flush cached config values.
fire_on_load(name) # force on_load triggers.
end
end
changed
end | [
"def",
"reload_on_change",
"(",
"name",
")",
"logger",
".",
"debug",
"\"reload_on_change(#{name.inspect}), reload_disabled=#{self.reload_disabled?}\"",
"if",
"changed",
"=",
"config_changed?",
"(",
"name",
")",
"&&",
"reload?",
"if",
"self",
".",
"cache_hash",
"[",
"name",
"]",
"flush_cache",
"(",
"name",
")",
"fire_on_load",
"(",
"name",
")",
"end",
"end",
"changed",
"end"
]
| If config files have changed, caches are flushed, on_load triggers are run. | [
"If",
"config",
"files",
"have",
"changed",
"caches",
"are",
"flushed",
"on_load",
"triggers",
"are",
"run",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/core_methods.rb#L184-L193 | train |
rahmal/rconfig | lib/rconfig/core_methods.rb | RConfig.CoreMethods.with_file | def with_file(name, *args)
logger.debug "with_file(#{name.inspect}, #{args.inspect})"
result = args.inject(config_for(name)) { |v, i|
logger.debug "v = #{v.inspect}, i = #{i.inspect}"
case v
when Hash
v[i.to_s]
when Array
i.is_a?(Integer) ? v[i] : nil
else
nil
end
}
logger.debug "with_file(#{name.inspect}, #{args.inspect}) => #{result.inspect}"
result
end | ruby | def with_file(name, *args)
logger.debug "with_file(#{name.inspect}, #{args.inspect})"
result = args.inject(config_for(name)) { |v, i|
logger.debug "v = #{v.inspect}, i = #{i.inspect}"
case v
when Hash
v[i.to_s]
when Array
i.is_a?(Integer) ? v[i] : nil
else
nil
end
}
logger.debug "with_file(#{name.inspect}, #{args.inspect}) => #{result.inspect}"
result
end | [
"def",
"with_file",
"(",
"name",
",",
"*",
"args",
")",
"logger",
".",
"debug",
"\"with_file(#{name.inspect}, #{args.inspect})\"",
"result",
"=",
"args",
".",
"inject",
"(",
"config_for",
"(",
"name",
")",
")",
"{",
"|",
"v",
",",
"i",
"|",
"logger",
".",
"debug",
"\"v = #{v.inspect}, i = #{i.inspect}\"",
"case",
"v",
"when",
"Hash",
"v",
"[",
"i",
".",
"to_s",
"]",
"when",
"Array",
"i",
".",
"is_a?",
"(",
"Integer",
")",
"?",
"v",
"[",
"i",
"]",
":",
"nil",
"else",
"nil",
"end",
"}",
"logger",
".",
"debug",
"\"with_file(#{name.inspect}, #{args.inspect}) => #{result.inspect}\"",
"result",
"end"
]
| Get the value specified by the args, in the file specified by th name | [
"Get",
"the",
"value",
"specified",
"by",
"the",
"args",
"in",
"the",
"file",
"specified",
"by",
"th",
"name"
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/core_methods.rb#L231-L246 | train |
rahmal/rconfig | lib/rconfig/core_methods.rb | RConfig.CoreMethods.config_for | def config_for(name)
name = name.to_s
check_for_changes(name) if auto_check?(name)
data = get_config_data(name)
logger.debug "config_for(#{name.inspect}) => #{data.inspect}"
data
end | ruby | def config_for(name)
name = name.to_s
check_for_changes(name) if auto_check?(name)
data = get_config_data(name)
logger.debug "config_for(#{name.inspect}) => #{data.inspect}"
data
end | [
"def",
"config_for",
"(",
"name",
")",
"name",
"=",
"name",
".",
"to_s",
"check_for_changes",
"(",
"name",
")",
"if",
"auto_check?",
"(",
"name",
")",
"data",
"=",
"get_config_data",
"(",
"name",
")",
"logger",
".",
"debug",
"\"config_for(#{name.inspect}) => #{data.inspect}\"",
"data",
"end"
]
| Get a hash of merged config data.
Will auto check every 5 minutes, for longer running apps, unless reload is disabled. | [
"Get",
"a",
"hash",
"of",
"merged",
"config",
"data",
".",
"Will",
"auto",
"check",
"every",
"5",
"minutes",
"for",
"longer",
"running",
"apps",
"unless",
"reload",
"is",
"disabled",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/core_methods.rb#L252-L258 | train |
rahmal/rconfig | lib/rconfig/core_methods.rb | RConfig.CoreMethods.method_missing | def method_missing(method, * args)
value = with_file(method, * args)
logger.debug "#{self}.method_missing(#{method.inspect}, #{args.inspect}) => #{value.inspect}"
value
end | ruby | def method_missing(method, * args)
value = with_file(method, * args)
logger.debug "#{self}.method_missing(#{method.inspect}, #{args.inspect}) => #{value.inspect}"
value
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
")",
"value",
"=",
"with_file",
"(",
"method",
",",
"*",
"args",
")",
"logger",
".",
"debug",
"\"#{self}.method_missing(#{method.inspect}, #{args.inspect}) => #{value.inspect}\"",
"value",
"end"
]
| Short-hand access to config file by its name.
Example:
RConfig.provider(:foo) => RConfig.with_file(:provider).foo
RConfig.provider.foo => RConfig.with_file(:provider).foo | [
"Short",
"-",
"hand",
"access",
"to",
"config",
"file",
"by",
"its",
"name",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/core_methods.rb#L268-L272 | train |
propublica/simpler-tiles | lib/simpler_tiles/layer/vector_layer.rb | SimplerTiles.VectorLayer.query | def query(sql, &blk)
layer = SimplerTiles::Query.new(sql, &blk)
add_query layer
end | ruby | def query(sql, &blk)
layer = SimplerTiles::Query.new(sql, &blk)
add_query layer
end | [
"def",
"query",
"(",
"sql",
",",
"&",
"blk",
")",
"layer",
"=",
"SimplerTiles",
"::",
"Query",
".",
"new",
"(",
"sql",
",",
"&",
"blk",
")",
"add_query",
"layer",
"end"
]
| Add a query to this Layer's c list. | [
"Add",
"a",
"query",
"to",
"this",
"Layer",
"s",
"c",
"list",
"."
]
| 9d00f769102acbed02d30429598408c487d6c663 | https://github.com/propublica/simpler-tiles/blob/9d00f769102acbed02d30429598408c487d6c663/lib/simpler_tiles/layer/vector_layer.rb#L13-L16 | train |
propublica/simpler-tiles | lib/simpler_tiles/map.rb | SimplerTiles.Map.layer | def layer(source, &blk)
layer = SimplerTiles::VectorLayer.new(source, &blk)
add_vector_layer layer
end | ruby | def layer(source, &blk)
layer = SimplerTiles::VectorLayer.new(source, &blk)
add_vector_layer layer
end | [
"def",
"layer",
"(",
"source",
",",
"&",
"blk",
")",
"layer",
"=",
"SimplerTiles",
"::",
"VectorLayer",
".",
"new",
"(",
"source",
",",
"&",
"blk",
")",
"add_vector_layer",
"layer",
"end"
]
| Add a layer to the c list of layers and yield the new layer. | [
"Add",
"a",
"layer",
"to",
"the",
"c",
"list",
"of",
"layers",
"and",
"yield",
"the",
"new",
"layer",
"."
]
| 9d00f769102acbed02d30429598408c487d6c663 | https://github.com/propublica/simpler-tiles/blob/9d00f769102acbed02d30429598408c487d6c663/lib/simpler_tiles/map.rb#L13-L16 | train |
propublica/simpler-tiles | lib/simpler_tiles/map.rb | SimplerTiles.Map.raster_layer | def raster_layer(source, &blk)
layer = SimplerTiles::RasterLayer.new(source, &blk)
add_raster_layer layer
end | ruby | def raster_layer(source, &blk)
layer = SimplerTiles::RasterLayer.new(source, &blk)
add_raster_layer layer
end | [
"def",
"raster_layer",
"(",
"source",
",",
"&",
"blk",
")",
"layer",
"=",
"SimplerTiles",
"::",
"RasterLayer",
".",
"new",
"(",
"source",
",",
"&",
"blk",
")",
"add_raster_layer",
"layer",
"end"
]
| Add a raster layer | [
"Add",
"a",
"raster",
"layer"
]
| 9d00f769102acbed02d30429598408c487d6c663 | https://github.com/propublica/simpler-tiles/blob/9d00f769102acbed02d30429598408c487d6c663/lib/simpler_tiles/map.rb#L19-L22 | train |
propublica/simpler-tiles | lib/simpler_tiles/map.rb | SimplerTiles.Map.ar_layer | def ar_layer(&blk)
if !defined?(ActiveRecord)
raise "ActiveRecord not available"
end
config = ActiveRecord::Base.connection.instance_variable_get("@config")
params = {
:dbname => config[:database],
:user => config[:username],
:host => config[:host],
:port => config[:port],
:password => config[:password]
}
conn = "PG:" + params.reject {|k,v| v.nil? }.map {|k,v| "#{k}=#{v}"}.join(' ')
layer conn, &blk
end | ruby | def ar_layer(&blk)
if !defined?(ActiveRecord)
raise "ActiveRecord not available"
end
config = ActiveRecord::Base.connection.instance_variable_get("@config")
params = {
:dbname => config[:database],
:user => config[:username],
:host => config[:host],
:port => config[:port],
:password => config[:password]
}
conn = "PG:" + params.reject {|k,v| v.nil? }.map {|k,v| "#{k}=#{v}"}.join(' ')
layer conn, &blk
end | [
"def",
"ar_layer",
"(",
"&",
"blk",
")",
"if",
"!",
"defined?",
"(",
"ActiveRecord",
")",
"raise",
"\"ActiveRecord not available\"",
"end",
"config",
"=",
"ActiveRecord",
"::",
"Base",
".",
"connection",
".",
"instance_variable_get",
"(",
"\"@config\"",
")",
"params",
"=",
"{",
":dbname",
"=>",
"config",
"[",
":database",
"]",
",",
":user",
"=>",
"config",
"[",
":username",
"]",
",",
":host",
"=>",
"config",
"[",
":host",
"]",
",",
":port",
"=>",
"config",
"[",
":port",
"]",
",",
":password",
"=>",
"config",
"[",
":password",
"]",
"}",
"conn",
"=",
"\"PG:\"",
"+",
"params",
".",
"reject",
"{",
"|",
"k",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"\"#{k}=#{v}\"",
"}",
".",
"join",
"(",
"' '",
")",
"layer",
"conn",
",",
"&",
"blk",
"end"
]
| A convienence method to use Active Record configuration and add a new
layer. | [
"A",
"convienence",
"method",
"to",
"use",
"Active",
"Record",
"configuration",
"and",
"add",
"a",
"new",
"layer",
"."
]
| 9d00f769102acbed02d30429598408c487d6c663 | https://github.com/propublica/simpler-tiles/blob/9d00f769102acbed02d30429598408c487d6c663/lib/simpler_tiles/map.rb#L26-L43 | train |
propublica/simpler-tiles | lib/simpler_tiles/map.rb | SimplerTiles.Map.to_png | def to_png
data = ""
to_png_stream Proc.new { |chunk| data += chunk }
yield data if block_given?
data
end | ruby | def to_png
data = ""
to_png_stream Proc.new { |chunk| data += chunk }
yield data if block_given?
data
end | [
"def",
"to_png",
"data",
"=",
"\"\"",
"to_png_stream",
"Proc",
".",
"new",
"{",
"|",
"chunk",
"|",
"data",
"+=",
"chunk",
"}",
"yield",
"data",
"if",
"block_given?",
"data",
"end"
]
| Render the data to a blob of png data. | [
"Render",
"the",
"data",
"to",
"a",
"blob",
"of",
"png",
"data",
"."
]
| 9d00f769102acbed02d30429598408c487d6c663 | https://github.com/propublica/simpler-tiles/blob/9d00f769102acbed02d30429598408c487d6c663/lib/simpler_tiles/map.rb#L46-L51 | train |
propublica/simpler-tiles | lib/simpler_tiles/query.rb | SimplerTiles.Query.styles | def styles(styles)
styles.each do |k,v|
style = SimplerTiles::Style.new k, v
add_style style
end
end | ruby | def styles(styles)
styles.each do |k,v|
style = SimplerTiles::Style.new k, v
add_style style
end
end | [
"def",
"styles",
"(",
"styles",
")",
"styles",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"style",
"=",
"SimplerTiles",
"::",
"Style",
".",
"new",
"k",
",",
"v",
"add_style",
"style",
"end",
"end"
]
| Initialize a query with a string containing OGR SQL.
Styles will take a hash of style declarations and adds them to the internal
c list. | [
"Initialize",
"a",
"query",
"with",
"a",
"string",
"containing",
"OGR",
"SQL",
".",
"Styles",
"will",
"take",
"a",
"hash",
"of",
"style",
"declarations",
"and",
"adds",
"them",
"to",
"the",
"internal",
"c",
"list",
"."
]
| 9d00f769102acbed02d30429598408c487d6c663 | https://github.com/propublica/simpler-tiles/blob/9d00f769102acbed02d30429598408c487d6c663/lib/simpler_tiles/query.rb#L15-L20 | train |
rahmal/rconfig | lib/rconfig/load_paths.rb | RConfig.LoadPaths.add_load_path | def add_load_path(path)
if path = parse_load_paths(path).first # only accept first one.
self.load_paths << path
self.load_paths.uniq!
return reload(true) # Load Paths have changed so force a reload
end
false
end | ruby | def add_load_path(path)
if path = parse_load_paths(path).first # only accept first one.
self.load_paths << path
self.load_paths.uniq!
return reload(true) # Load Paths have changed so force a reload
end
false
end | [
"def",
"add_load_path",
"(",
"path",
")",
"if",
"path",
"=",
"parse_load_paths",
"(",
"path",
")",
".",
"first",
"self",
".",
"load_paths",
"<<",
"path",
"self",
".",
"load_paths",
".",
"uniq!",
"return",
"reload",
"(",
"true",
")",
"end",
"false",
"end"
]
| Adds the specified path to the list of directories to search for
configuration files.
It only allows one path to be entered at a time. | [
"Adds",
"the",
"specified",
"path",
"to",
"the",
"list",
"of",
"directories",
"to",
"search",
"for",
"configuration",
"files",
".",
"It",
"only",
"allows",
"one",
"path",
"to",
"be",
"entered",
"at",
"a",
"time",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/load_paths.rb#L21-L28 | train |
rahmal/rconfig | lib/rconfig/reload.rb | RConfig.Reload.enable_reload= | def enable_reload=(reload)
raise ArgumentError, 'Argument must be true or false.' unless [true, false].include?(reload)
self.enable_reload = reload
end | ruby | def enable_reload=(reload)
raise ArgumentError, 'Argument must be true or false.' unless [true, false].include?(reload)
self.enable_reload = reload
end | [
"def",
"enable_reload",
"=",
"(",
"reload",
")",
"raise",
"ArgumentError",
",",
"'Argument must be true or false.'",
"unless",
"[",
"true",
",",
"false",
"]",
".",
"include?",
"(",
"reload",
")",
"self",
".",
"enable_reload",
"=",
"reload",
"end"
]
| Sets the flag indicating whether or not reload should be executed. | [
"Sets",
"the",
"flag",
"indicating",
"whether",
"or",
"not",
"reload",
"should",
"be",
"executed",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/reload.rb#L16-L19 | train |
rahmal/rconfig | lib/rconfig/reload.rb | RConfig.Reload.reload_interval= | def reload_interval=(interval)
raise ArgumentError, 'Argument must be Integer.' unless interval.kind_of?(Integer)
self.enable_reload = false if interval == 0 # Sett
self.reload_interval = interval
end | ruby | def reload_interval=(interval)
raise ArgumentError, 'Argument must be Integer.' unless interval.kind_of?(Integer)
self.enable_reload = false if interval == 0 # Sett
self.reload_interval = interval
end | [
"def",
"reload_interval",
"=",
"(",
"interval",
")",
"raise",
"ArgumentError",
",",
"'Argument must be Integer.'",
"unless",
"interval",
".",
"kind_of?",
"(",
"Integer",
")",
"self",
".",
"enable_reload",
"=",
"false",
"if",
"interval",
"==",
"0",
"self",
".",
"reload_interval",
"=",
"interval",
"end"
]
| Sets the number of seconds between reloading of config files
and automatic reload checks. Defaults to 5 minutes. Setting | [
"Sets",
"the",
"number",
"of",
"seconds",
"between",
"reloading",
"of",
"config",
"files",
"and",
"automatic",
"reload",
"checks",
".",
"Defaults",
"to",
"5",
"minutes",
".",
"Setting"
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/reload.rb#L25-L29 | train |
rahmal/rconfig | lib/rconfig/reload.rb | RConfig.Reload.reload | def reload(force=false)
raise ArgumentError, 'Argument must be true or false.' unless [true, false].include?(force)
if force || reload?
flush_cache
return true
end
false
end | ruby | def reload(force=false)
raise ArgumentError, 'Argument must be true or false.' unless [true, false].include?(force)
if force || reload?
flush_cache
return true
end
false
end | [
"def",
"reload",
"(",
"force",
"=",
"false",
")",
"raise",
"ArgumentError",
",",
"'Argument must be true or false.'",
"unless",
"[",
"true",
",",
"false",
"]",
".",
"include?",
"(",
"force",
")",
"if",
"force",
"||",
"reload?",
"flush_cache",
"return",
"true",
"end",
"false",
"end"
]
| Flushes cached config data, so that it can be reloaded from disk.
It is recommended that this should be used with caution, and any
need to reload in a production setting should minimized or
completely avoided if possible. | [
"Flushes",
"cached",
"config",
"data",
"so",
"that",
"it",
"can",
"be",
"reloaded",
"from",
"disk",
".",
"It",
"is",
"recommended",
"that",
"this",
"should",
"be",
"used",
"with",
"caution",
"and",
"any",
"need",
"to",
"reload",
"in",
"a",
"production",
"setting",
"should",
"minimized",
"or",
"completely",
"avoided",
"if",
"possible",
"."
]
| 528c2fca29fcba4eb495ae443fa04269278d226b | https://github.com/rahmal/rconfig/blob/528c2fca29fcba4eb495ae443fa04269278d226b/lib/rconfig/reload.rb#L36-L43 | train |
metanorma/isodoc | lib/isodoc/function/utils.rb | IsoDoc::Function.Utils.noko | def noko(&block)
doc = ::Nokogiri::XML.parse(NOKOHEAD)
fragment = doc.fragment("")
::Nokogiri::XML::Builder.with fragment, &block
fragment.to_xml(encoding: "US-ASCII").lines.map do |l|
l.gsub(/\s*\n/, "")
end
end | ruby | def noko(&block)
doc = ::Nokogiri::XML.parse(NOKOHEAD)
fragment = doc.fragment("")
::Nokogiri::XML::Builder.with fragment, &block
fragment.to_xml(encoding: "US-ASCII").lines.map do |l|
l.gsub(/\s*\n/, "")
end
end | [
"def",
"noko",
"(",
"&",
"block",
")",
"doc",
"=",
"::",
"Nokogiri",
"::",
"XML",
".",
"parse",
"(",
"NOKOHEAD",
")",
"fragment",
"=",
"doc",
".",
"fragment",
"(",
"\"\"",
")",
"::",
"Nokogiri",
"::",
"XML",
"::",
"Builder",
".",
"with",
"fragment",
",",
"&",
"block",
"fragment",
".",
"to_xml",
"(",
"encoding",
":",
"\"US-ASCII\"",
")",
".",
"lines",
".",
"map",
"do",
"|",
"l",
"|",
"l",
".",
"gsub",
"(",
"/",
"\\s",
"\\n",
"/",
",",
"\"\"",
")",
"end",
"end"
]
| block for processing XML document fragments as XHTML,
to allow for HTMLentities | [
"block",
"for",
"processing",
"XML",
"document",
"fragments",
"as",
"XHTML",
"to",
"allow",
"for",
"HTMLentities"
]
| b8b51a28f9aecb7ce3ec1028317e94d0d623036a | https://github.com/metanorma/isodoc/blob/b8b51a28f9aecb7ce3ec1028317e94d0d623036a/lib/isodoc/function/utils.rb#L27-L34 | train |
metanorma/isodoc | lib/isodoc/function/xref_gen.rb | IsoDoc::Function.XrefGen.anchor_names | def anchor_names(docxml)
initial_anchor_names(docxml)
back_anchor_names(docxml)
# preempt clause notes with all other types of note
note_anchor_names(docxml.xpath(ns("//table | //example | //formula | "\
"//figure")))
note_anchor_names(docxml.xpath(ns(SECTIONS_XPATH)))
example_anchor_names(docxml.xpath(ns(SECTIONS_XPATH)))
list_anchor_names(docxml.xpath(ns(SECTIONS_XPATH)))
end | ruby | def anchor_names(docxml)
initial_anchor_names(docxml)
back_anchor_names(docxml)
# preempt clause notes with all other types of note
note_anchor_names(docxml.xpath(ns("//table | //example | //formula | "\
"//figure")))
note_anchor_names(docxml.xpath(ns(SECTIONS_XPATH)))
example_anchor_names(docxml.xpath(ns(SECTIONS_XPATH)))
list_anchor_names(docxml.xpath(ns(SECTIONS_XPATH)))
end | [
"def",
"anchor_names",
"(",
"docxml",
")",
"initial_anchor_names",
"(",
"docxml",
")",
"back_anchor_names",
"(",
"docxml",
")",
"note_anchor_names",
"(",
"docxml",
".",
"xpath",
"(",
"ns",
"(",
"\"//table | //example | //formula | \"",
"\"//figure\"",
")",
")",
")",
"note_anchor_names",
"(",
"docxml",
".",
"xpath",
"(",
"ns",
"(",
"SECTIONS_XPATH",
")",
")",
")",
"example_anchor_names",
"(",
"docxml",
".",
"xpath",
"(",
"ns",
"(",
"SECTIONS_XPATH",
")",
")",
")",
"list_anchor_names",
"(",
"docxml",
".",
"xpath",
"(",
"ns",
"(",
"SECTIONS_XPATH",
")",
")",
")",
"end"
]
| extract names for all anchors, xref and label | [
"extract",
"names",
"for",
"all",
"anchors",
"xref",
"and",
"label"
]
| b8b51a28f9aecb7ce3ec1028317e94d0d623036a | https://github.com/metanorma/isodoc/blob/b8b51a28f9aecb7ce3ec1028317e94d0d623036a/lib/isodoc/function/xref_gen.rb#L125-L134 | train |
metanorma/isodoc | lib/isodoc/function/cleanup.rb | IsoDoc::Function.Cleanup.figure_cleanup | def figure_cleanup(docxml)
docxml.xpath(FIGURE_WITH_FOOTNOTES).each do |f|
key = figure_get_or_make_dl(f)
f.xpath(".//aside").each do |aside|
figure_aside_process(f, aside, key)
end
end
docxml
end | ruby | def figure_cleanup(docxml)
docxml.xpath(FIGURE_WITH_FOOTNOTES).each do |f|
key = figure_get_or_make_dl(f)
f.xpath(".//aside").each do |aside|
figure_aside_process(f, aside, key)
end
end
docxml
end | [
"def",
"figure_cleanup",
"(",
"docxml",
")",
"docxml",
".",
"xpath",
"(",
"FIGURE_WITH_FOOTNOTES",
")",
".",
"each",
"do",
"|",
"f",
"|",
"key",
"=",
"figure_get_or_make_dl",
"(",
"f",
")",
"f",
".",
"xpath",
"(",
"\".//aside\"",
")",
".",
"each",
"do",
"|",
"aside",
"|",
"figure_aside_process",
"(",
"f",
",",
"aside",
",",
"key",
")",
"end",
"end",
"docxml",
"end"
]
| move footnotes into key, and get rid of footnote reference
since it is in diagram | [
"move",
"footnotes",
"into",
"key",
"and",
"get",
"rid",
"of",
"footnote",
"reference",
"since",
"it",
"is",
"in",
"diagram"
]
| b8b51a28f9aecb7ce3ec1028317e94d0d623036a | https://github.com/metanorma/isodoc/blob/b8b51a28f9aecb7ce3ec1028317e94d0d623036a/lib/isodoc/function/cleanup.rb#L58-L66 | train |
metanorma/isodoc | lib/isodoc/function/xref_sect_gen.rb | IsoDoc::Function.XrefSectGen.preface_names | def preface_names(clause)
return if clause.nil?
@anchors[clause["id"]] =
{ label: nil, level: 1, xref: preface_clause_name(clause), type: "clause" }
clause.xpath(ns("./clause | ./terms | ./term | ./definitions | ./references")).each_with_index do |c, i|
preface_names1(c, c.at(ns("./title"))&.text, "#{preface_clause_name(clause)}, #{i+1}", 2)
end
end | ruby | def preface_names(clause)
return if clause.nil?
@anchors[clause["id"]] =
{ label: nil, level: 1, xref: preface_clause_name(clause), type: "clause" }
clause.xpath(ns("./clause | ./terms | ./term | ./definitions | ./references")).each_with_index do |c, i|
preface_names1(c, c.at(ns("./title"))&.text, "#{preface_clause_name(clause)}, #{i+1}", 2)
end
end | [
"def",
"preface_names",
"(",
"clause",
")",
"return",
"if",
"clause",
".",
"nil?",
"@anchors",
"[",
"clause",
"[",
"\"id\"",
"]",
"]",
"=",
"{",
"label",
":",
"nil",
",",
"level",
":",
"1",
",",
"xref",
":",
"preface_clause_name",
"(",
"clause",
")",
",",
"type",
":",
"\"clause\"",
"}",
"clause",
".",
"xpath",
"(",
"ns",
"(",
"\"./clause | ./terms | ./term | ./definitions | ./references\"",
")",
")",
".",
"each_with_index",
"do",
"|",
"c",
",",
"i",
"|",
"preface_names1",
"(",
"c",
",",
"c",
".",
"at",
"(",
"ns",
"(",
"\"./title\"",
")",
")",
"&.",
"text",
",",
"\"#{preface_clause_name(clause)}, #{i+1}\"",
",",
"2",
")",
"end",
"end"
]
| in StanDoc, prefaces have no numbering; they are referenced only by title | [
"in",
"StanDoc",
"prefaces",
"have",
"no",
"numbering",
";",
"they",
"are",
"referenced",
"only",
"by",
"title"
]
| b8b51a28f9aecb7ce3ec1028317e94d0d623036a | https://github.com/metanorma/isodoc/blob/b8b51a28f9aecb7ce3ec1028317e94d0d623036a/lib/isodoc/function/xref_sect_gen.rb#L40-L47 | train |
customink/strainer | lib/strainer/sandbox.rb | Strainer.Sandbox.destroy_sandbox | def destroy_sandbox
if File.directory?(Strainer.sandbox_path)
Strainer.ui.debug " Destroying sandbox at '#{Strainer.sandbox_path}'"
FileUtils.rm_rf(Strainer.sandbox_path)
else
Strainer.ui.debug " Sandbox does not exist... skipping"
end
end | ruby | def destroy_sandbox
if File.directory?(Strainer.sandbox_path)
Strainer.ui.debug " Destroying sandbox at '#{Strainer.sandbox_path}'"
FileUtils.rm_rf(Strainer.sandbox_path)
else
Strainer.ui.debug " Sandbox does not exist... skipping"
end
end | [
"def",
"destroy_sandbox",
"if",
"File",
".",
"directory?",
"(",
"Strainer",
".",
"sandbox_path",
")",
"Strainer",
".",
"ui",
".",
"debug",
"\" Destroying sandbox at '#{Strainer.sandbox_path}'\"",
"FileUtils",
".",
"rm_rf",
"(",
"Strainer",
".",
"sandbox_path",
")",
"else",
"Strainer",
".",
"ui",
".",
"debug",
"\" Sandbox does not exist... skipping\"",
"end",
"end"
]
| Destroy the current sandbox, if it exists | [
"Destroy",
"the",
"current",
"sandbox",
"if",
"it",
"exists"
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/sandbox.rb#L70-L77 | train |
customink/strainer | lib/strainer/sandbox.rb | Strainer.Sandbox.create_sandbox | def create_sandbox
unless File.directory?(Strainer.sandbox_path)
Strainer.ui.debug " Creating sandbox at '#{Strainer.sandbox_path}'"
FileUtils.mkdir_p(Strainer.sandbox_path)
end
copy_globals
place_knife_rb
copy_cookbooks
end | ruby | def create_sandbox
unless File.directory?(Strainer.sandbox_path)
Strainer.ui.debug " Creating sandbox at '#{Strainer.sandbox_path}'"
FileUtils.mkdir_p(Strainer.sandbox_path)
end
copy_globals
place_knife_rb
copy_cookbooks
end | [
"def",
"create_sandbox",
"unless",
"File",
".",
"directory?",
"(",
"Strainer",
".",
"sandbox_path",
")",
"Strainer",
".",
"ui",
".",
"debug",
"\" Creating sandbox at '#{Strainer.sandbox_path}'\"",
"FileUtils",
".",
"mkdir_p",
"(",
"Strainer",
".",
"sandbox_path",
")",
"end",
"copy_globals",
"place_knife_rb",
"copy_cookbooks",
"end"
]
| Create the sandbox unless it already exits | [
"Create",
"the",
"sandbox",
"unless",
"it",
"already",
"exits"
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/sandbox.rb#L80-L89 | train |
customink/strainer | lib/strainer/sandbox.rb | Strainer.Sandbox.load_cookbooks | def load_cookbooks(cookbook_names)
Strainer.ui.debug "Sandbox#load_cookbooks(#{cookbook_names.inspect})"
cookbook_names.collect{ |cookbook_name| load_cookbook(cookbook_name) }
end | ruby | def load_cookbooks(cookbook_names)
Strainer.ui.debug "Sandbox#load_cookbooks(#{cookbook_names.inspect})"
cookbook_names.collect{ |cookbook_name| load_cookbook(cookbook_name) }
end | [
"def",
"load_cookbooks",
"(",
"cookbook_names",
")",
"Strainer",
".",
"ui",
".",
"debug",
"\"Sandbox#load_cookbooks(#{cookbook_names.inspect})\"",
"cookbook_names",
".",
"collect",
"{",
"|",
"cookbook_name",
"|",
"load_cookbook",
"(",
"cookbook_name",
")",
"}",
"end"
]
| Load a cookbook from the given array of cookbook names
@param [Array<String>] cookbook_names
the list of cookbooks to search for
@return [Array<Berkshelf::CachedCookbook>]
the array of cached cookbooks | [
"Load",
"a",
"cookbook",
"from",
"the",
"given",
"array",
"of",
"cookbook",
"names"
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/sandbox.rb#L145-L148 | train |
customink/strainer | lib/strainer/sandbox.rb | Strainer.Sandbox.load_cookbook | def load_cookbook(cookbook_name)
Strainer.ui.debug "Sandbox#load_cookbook('#{cookbook_name.inspect}')"
cookbook_path = cookbooks_paths.find { |path| path.join(cookbook_name).exist? }
cookbook = if cookbook_path
path = cookbook_path.join(cookbook_name)
Strainer.ui.debug " found cookbook at '#{path}'"
begin
Berkshelf::CachedCookbook.from_path(path)
rescue Berkshelf::CookbookNotFound
raise Strainer::Error::CookbookNotFound, "'#{path}' existed, but I could not extract a cookbook. Is there a 'metadata.rb'?"
end
else
Strainer.ui.debug " did not find '#{cookbook_name}' in any of the sources - resorting to the default cookbook_store..."
Berkshelf.cookbook_store.cookbooks(cookbook_name).last
end
cookbook || raise(Strainer::Error::CookbookNotFound, "Could not find '#{cookbook_name}' in any of the sources.")
end | ruby | def load_cookbook(cookbook_name)
Strainer.ui.debug "Sandbox#load_cookbook('#{cookbook_name.inspect}')"
cookbook_path = cookbooks_paths.find { |path| path.join(cookbook_name).exist? }
cookbook = if cookbook_path
path = cookbook_path.join(cookbook_name)
Strainer.ui.debug " found cookbook at '#{path}'"
begin
Berkshelf::CachedCookbook.from_path(path)
rescue Berkshelf::CookbookNotFound
raise Strainer::Error::CookbookNotFound, "'#{path}' existed, but I could not extract a cookbook. Is there a 'metadata.rb'?"
end
else
Strainer.ui.debug " did not find '#{cookbook_name}' in any of the sources - resorting to the default cookbook_store..."
Berkshelf.cookbook_store.cookbooks(cookbook_name).last
end
cookbook || raise(Strainer::Error::CookbookNotFound, "Could not find '#{cookbook_name}' in any of the sources.")
end | [
"def",
"load_cookbook",
"(",
"cookbook_name",
")",
"Strainer",
".",
"ui",
".",
"debug",
"\"Sandbox#load_cookbook('#{cookbook_name.inspect}')\"",
"cookbook_path",
"=",
"cookbooks_paths",
".",
"find",
"{",
"|",
"path",
"|",
"path",
".",
"join",
"(",
"cookbook_name",
")",
".",
"exist?",
"}",
"cookbook",
"=",
"if",
"cookbook_path",
"path",
"=",
"cookbook_path",
".",
"join",
"(",
"cookbook_name",
")",
"Strainer",
".",
"ui",
".",
"debug",
"\" found cookbook at '#{path}'\"",
"begin",
"Berkshelf",
"::",
"CachedCookbook",
".",
"from_path",
"(",
"path",
")",
"rescue",
"Berkshelf",
"::",
"CookbookNotFound",
"raise",
"Strainer",
"::",
"Error",
"::",
"CookbookNotFound",
",",
"\"'#{path}' existed, but I could not extract a cookbook. Is there a 'metadata.rb'?\"",
"end",
"else",
"Strainer",
".",
"ui",
".",
"debug",
"\" did not find '#{cookbook_name}' in any of the sources - resorting to the default cookbook_store...\"",
"Berkshelf",
".",
"cookbook_store",
".",
"cookbooks",
"(",
"cookbook_name",
")",
".",
"last",
"end",
"cookbook",
"||",
"raise",
"(",
"Strainer",
"::",
"Error",
"::",
"CookbookNotFound",
",",
"\"Could not find '#{cookbook_name}' in any of the sources.\"",
")",
"end"
]
| Load an individual cookbook by its name
@param [String] cookbook_name
the name of the cookbook to load
@return [Berkshelf::CachedCookbook]
the cached cookbook
@raise [Strainer::Error::CookbookNotFound]
when the cookbook was not found in any of the sources | [
"Load",
"an",
"individual",
"cookbook",
"by",
"its",
"name"
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/sandbox.rb#L158-L177 | train |
customink/strainer | lib/strainer/sandbox.rb | Strainer.Sandbox.load_self | def load_self
Strainer.ui.debug "Sandbox#load_self"
begin
Berkshelf::CachedCookbook.from_path(File.expand_path('.'))
rescue Berkshelf::CookbookNotFound
raise Strainer::Error::CookbookNotFound, "'#{File.expand_path('.')}' existed, but I could not extract a cookbook. Is there a 'metadata.rb'?"
end
end | ruby | def load_self
Strainer.ui.debug "Sandbox#load_self"
begin
Berkshelf::CachedCookbook.from_path(File.expand_path('.'))
rescue Berkshelf::CookbookNotFound
raise Strainer::Error::CookbookNotFound, "'#{File.expand_path('.')}' existed, but I could not extract a cookbook. Is there a 'metadata.rb'?"
end
end | [
"def",
"load_self",
"Strainer",
".",
"ui",
".",
"debug",
"\"Sandbox#load_self\"",
"begin",
"Berkshelf",
"::",
"CachedCookbook",
".",
"from_path",
"(",
"File",
".",
"expand_path",
"(",
"'.'",
")",
")",
"rescue",
"Berkshelf",
"::",
"CookbookNotFound",
"raise",
"Strainer",
"::",
"Error",
"::",
"CookbookNotFound",
",",
"\"'#{File.expand_path('.')}' existed, but I could not extract a cookbook. Is there a 'metadata.rb'?\"",
"end",
"end"
]
| Load the current root entirely as a cookbook. This is useful when testing within
a cookbook, instead of a chef repo | [
"Load",
"the",
"current",
"root",
"entirely",
"as",
"a",
"cookbook",
".",
"This",
"is",
"useful",
"when",
"testing",
"within",
"a",
"cookbook",
"instead",
"of",
"a",
"chef",
"repo"
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/sandbox.rb#L181-L189 | train |
customink/strainer | lib/strainer/sandbox.rb | Strainer.Sandbox.cookbooks_and_dependencies | def cookbooks_and_dependencies
loaded_dependencies = Hash.new(false)
dependencies = @cookbooks.dup
dependencies.each do |cookbook|
loaded_dependencies[cookbook.cookbook_name] = true
cookbook.metadata.dependencies.keys.each do |dependency_name|
unless loaded_dependencies[dependency_name]
dependencies << load_cookbook(dependency_name)
loaded_dependencies[dependency_name] = true
end
end
end
end | ruby | def cookbooks_and_dependencies
loaded_dependencies = Hash.new(false)
dependencies = @cookbooks.dup
dependencies.each do |cookbook|
loaded_dependencies[cookbook.cookbook_name] = true
cookbook.metadata.dependencies.keys.each do |dependency_name|
unless loaded_dependencies[dependency_name]
dependencies << load_cookbook(dependency_name)
loaded_dependencies[dependency_name] = true
end
end
end
end | [
"def",
"cookbooks_and_dependencies",
"loaded_dependencies",
"=",
"Hash",
".",
"new",
"(",
"false",
")",
"dependencies",
"=",
"@cookbooks",
".",
"dup",
"dependencies",
".",
"each",
"do",
"|",
"cookbook",
"|",
"loaded_dependencies",
"[",
"cookbook",
".",
"cookbook_name",
"]",
"=",
"true",
"cookbook",
".",
"metadata",
".",
"dependencies",
".",
"keys",
".",
"each",
"do",
"|",
"dependency_name",
"|",
"unless",
"loaded_dependencies",
"[",
"dependency_name",
"]",
"dependencies",
"<<",
"load_cookbook",
"(",
"dependency_name",
")",
"loaded_dependencies",
"[",
"dependency_name",
"]",
"=",
"true",
"end",
"end",
"end",
"end"
]
| Collect all cookbooks and the dependencies specified in their metadata.rb
for copying
@return [Array<Berkshelf::CachedCookbook>]
a list of cached cookbooks | [
"Collect",
"all",
"cookbooks",
"and",
"the",
"dependencies",
"specified",
"in",
"their",
"metadata",
".",
"rb",
"for",
"copying"
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/sandbox.rb#L216-L230 | train |
customink/strainer | lib/strainer/sandbox.rb | Strainer.Sandbox.chef_repo? | def chef_repo?
@_chef_repo ||= begin
chef_folders = %w(.chef certificates config cookbooks data_bags environments roles)
(root_folders & chef_folders).size > 2
end
end | ruby | def chef_repo?
@_chef_repo ||= begin
chef_folders = %w(.chef certificates config cookbooks data_bags environments roles)
(root_folders & chef_folders).size > 2
end
end | [
"def",
"chef_repo?",
"@_chef_repo",
"||=",
"begin",
"chef_folders",
"=",
"%w(",
".chef",
"certificates",
"config",
"cookbooks",
"data_bags",
"environments",
"roles",
")",
"(",
"root_folders",
"&",
"chef_folders",
")",
".",
"size",
">",
"2",
"end",
"end"
]
| Determines if the current project is a chef repo
@return [Boolean]
true if the current project is a chef repo, false otherwise | [
"Determines",
"if",
"the",
"current",
"project",
"is",
"a",
"chef",
"repo"
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/sandbox.rb#L244-L249 | train |
customink/strainer | lib/strainer/sandbox.rb | Strainer.Sandbox.root_folders | def root_folders
@root_folders ||= Dir.glob("#{Dir.pwd}/*", File::FNM_DOTMATCH).collect do |f|
File.basename(f) if File.directory?(f)
end.reject { |dir| %w(. ..).include?(dir) }.compact!
end | ruby | def root_folders
@root_folders ||= Dir.glob("#{Dir.pwd}/*", File::FNM_DOTMATCH).collect do |f|
File.basename(f) if File.directory?(f)
end.reject { |dir| %w(. ..).include?(dir) }.compact!
end | [
"def",
"root_folders",
"@root_folders",
"||=",
"Dir",
".",
"glob",
"(",
"\"#{Dir.pwd}/*\"",
",",
"File",
"::",
"FNM_DOTMATCH",
")",
".",
"collect",
"do",
"|",
"f",
"|",
"File",
".",
"basename",
"(",
"f",
")",
"if",
"File",
".",
"directory?",
"(",
"f",
")",
"end",
".",
"reject",
"{",
"|",
"dir",
"|",
"%w(",
".",
"..",
")",
".",
"include?",
"(",
"dir",
")",
"}",
".",
"compact!",
"end"
]
| Return a list of all directory folders at the root of the repo.
This is useful for detecting if it's a chef repo or cookbook
repo.
@return [Array]
the list of root-level directories | [
"Return",
"a",
"list",
"of",
"all",
"directory",
"folders",
"at",
"the",
"root",
"of",
"the",
"repo",
".",
"This",
"is",
"useful",
"for",
"detecting",
"if",
"it",
"s",
"a",
"chef",
"repo",
"or",
"cookbook",
"repo",
"."
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/sandbox.rb#L257-L261 | train |
customink/strainer | lib/strainer/runner.rb | Strainer.Runner.run! | def run!
@cookbooks.each do |name, c|
cookbook = c[:cookbook]
strainerfile = c[:strainerfile]
Strainer.ui.debug "Starting Runner for #{cookbook.cookbook_name} (#{cookbook.version})"
Strainer.ui.header("# Straining '#{cookbook.cookbook_name} (v#{cookbook.version})'")
strainerfile.commands.each do |command|
success = command.run!
@report[cookbook.cookbook_name] ||= {}
@report[cookbook.cookbook_name][command.label] = success
Strainer.ui.debug "Strainer::Runner#report: #{@report.inspect}"
if options[:fail_fast] && !success
Strainer.ui.debug "Run was not successful and --fail-fast was specified"
Strainer.ui.fatal "Exited early because '--fail-fast' was specified. Some tests may have been skipped!"
return false
end
end
end
# Move the logfile back over
if File.exist?(Strainer.sandbox_path.join('strainer.out'))
FileUtils.mv(Strainer.logfile_path, Strainer.sandbox_path.join('strainer.out'))
end
success = @report.values.collect(&:values).flatten.all?
msg = success ? "Strainer marked build OK" : "Strainer marked build as failure"
Strainer.ui.say msg
return success
end | ruby | def run!
@cookbooks.each do |name, c|
cookbook = c[:cookbook]
strainerfile = c[:strainerfile]
Strainer.ui.debug "Starting Runner for #{cookbook.cookbook_name} (#{cookbook.version})"
Strainer.ui.header("# Straining '#{cookbook.cookbook_name} (v#{cookbook.version})'")
strainerfile.commands.each do |command|
success = command.run!
@report[cookbook.cookbook_name] ||= {}
@report[cookbook.cookbook_name][command.label] = success
Strainer.ui.debug "Strainer::Runner#report: #{@report.inspect}"
if options[:fail_fast] && !success
Strainer.ui.debug "Run was not successful and --fail-fast was specified"
Strainer.ui.fatal "Exited early because '--fail-fast' was specified. Some tests may have been skipped!"
return false
end
end
end
# Move the logfile back over
if File.exist?(Strainer.sandbox_path.join('strainer.out'))
FileUtils.mv(Strainer.logfile_path, Strainer.sandbox_path.join('strainer.out'))
end
success = @report.values.collect(&:values).flatten.all?
msg = success ? "Strainer marked build OK" : "Strainer marked build as failure"
Strainer.ui.say msg
return success
end | [
"def",
"run!",
"@cookbooks",
".",
"each",
"do",
"|",
"name",
",",
"c",
"|",
"cookbook",
"=",
"c",
"[",
":cookbook",
"]",
"strainerfile",
"=",
"c",
"[",
":strainerfile",
"]",
"Strainer",
".",
"ui",
".",
"debug",
"\"Starting Runner for #{cookbook.cookbook_name} (#{cookbook.version})\"",
"Strainer",
".",
"ui",
".",
"header",
"(",
"\"# Straining '#{cookbook.cookbook_name} (v#{cookbook.version})'\"",
")",
"strainerfile",
".",
"commands",
".",
"each",
"do",
"|",
"command",
"|",
"success",
"=",
"command",
".",
"run!",
"@report",
"[",
"cookbook",
".",
"cookbook_name",
"]",
"||=",
"{",
"}",
"@report",
"[",
"cookbook",
".",
"cookbook_name",
"]",
"[",
"command",
".",
"label",
"]",
"=",
"success",
"Strainer",
".",
"ui",
".",
"debug",
"\"Strainer::Runner#report: #{@report.inspect}\"",
"if",
"options",
"[",
":fail_fast",
"]",
"&&",
"!",
"success",
"Strainer",
".",
"ui",
".",
"debug",
"\"Run was not successful and --fail-fast was specified\"",
"Strainer",
".",
"ui",
".",
"fatal",
"\"Exited early because '--fail-fast' was specified. Some tests may have been skipped!\"",
"return",
"false",
"end",
"end",
"end",
"if",
"File",
".",
"exist?",
"(",
"Strainer",
".",
"sandbox_path",
".",
"join",
"(",
"'strainer.out'",
")",
")",
"FileUtils",
".",
"mv",
"(",
"Strainer",
".",
"logfile_path",
",",
"Strainer",
".",
"sandbox_path",
".",
"join",
"(",
"'strainer.out'",
")",
")",
"end",
"success",
"=",
"@report",
".",
"values",
".",
"collect",
"(",
"&",
":values",
")",
".",
"flatten",
".",
"all?",
"msg",
"=",
"success",
"?",
"\"Strainer marked build OK\"",
":",
"\"Strainer marked build as failure\"",
"Strainer",
".",
"ui",
".",
"say",
"msg",
"return",
"success",
"end"
]
| Creates a Strainer runner
@param [Array<String>] cookbook_names
an array of cookbook_names to test and load into the sandbox
@param [Hash] options
a list of options to pass along
Runs the Strainer runner | [
"Creates",
"a",
"Strainer",
"runner"
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/runner.rb#L44-L78 | train |
customink/strainer | lib/strainer/strainerfile.rb | Strainer.Strainerfile.commands | def commands
@commands ||= if @options[:except]
@all_commands.reject{ |command| @options[:except].include?(command.label) }
elsif @options[:only]
@all_commands.select{ |command| @options[:only].include?(command.label) }
else
@all_commands
end
end | ruby | def commands
@commands ||= if @options[:except]
@all_commands.reject{ |command| @options[:except].include?(command.label) }
elsif @options[:only]
@all_commands.select{ |command| @options[:only].include?(command.label) }
else
@all_commands
end
end | [
"def",
"commands",
"@commands",
"||=",
"if",
"@options",
"[",
":except",
"]",
"@all_commands",
".",
"reject",
"{",
"|",
"command",
"|",
"@options",
"[",
":except",
"]",
".",
"include?",
"(",
"command",
".",
"label",
")",
"}",
"elsif",
"@options",
"[",
":only",
"]",
"@all_commands",
".",
"select",
"{",
"|",
"command",
"|",
"@options",
"[",
":only",
"]",
".",
"include?",
"(",
"command",
".",
"label",
")",
"}",
"else",
"@all_commands",
"end",
"end"
]
| Instantiate an instance of this class from a cookbook
@param [Berkshelf::CachedCookbook] cookbook
the cached cookbook to search for a Strainerfile
@param [Hash] options
a list of options to pass along
@return [Strainerfile]
an instance of this class
Get the list of commands to run, filtered by the `@options` hash for either
`:ignore` or `:only`
@return [Array<Strainer::Command>]
the list of commands to execute | [
"Instantiate",
"an",
"instance",
"of",
"this",
"class",
"from",
"a",
"cookbook"
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/strainerfile.rb#L62-L70 | train |
customink/strainer | lib/strainer/strainerfile.rb | Strainer.Strainerfile.load! | def load!
return if @all_commands
contents = File.read @strainerfile
contents.strip!
contents.gsub! '$COOKBOOK', @cookbook.cookbook_name
contents.gsub! '$SANDBOX', Strainer.sandbox_path.to_s
# Drop empty lines and comments
lines = contents.split("\n")
lines.reject!{ |line| line.strip.empty? || line.strip.start_with?('#') }
lines.compact!
lines ||= []
# Parse the line and split it into the label and command parts
#
# @example Example Line
# foodcritic -f any phantomjs
@all_commands = lines.collect{ |line| Command.new(line, @cookbook, @options) }
end | ruby | def load!
return if @all_commands
contents = File.read @strainerfile
contents.strip!
contents.gsub! '$COOKBOOK', @cookbook.cookbook_name
contents.gsub! '$SANDBOX', Strainer.sandbox_path.to_s
# Drop empty lines and comments
lines = contents.split("\n")
lines.reject!{ |line| line.strip.empty? || line.strip.start_with?('#') }
lines.compact!
lines ||= []
# Parse the line and split it into the label and command parts
#
# @example Example Line
# foodcritic -f any phantomjs
@all_commands = lines.collect{ |line| Command.new(line, @cookbook, @options) }
end | [
"def",
"load!",
"return",
"if",
"@all_commands",
"contents",
"=",
"File",
".",
"read",
"@strainerfile",
"contents",
".",
"strip!",
"contents",
".",
"gsub!",
"'$COOKBOOK'",
",",
"@cookbook",
".",
"cookbook_name",
"contents",
".",
"gsub!",
"'$SANDBOX'",
",",
"Strainer",
".",
"sandbox_path",
".",
"to_s",
"lines",
"=",
"contents",
".",
"split",
"(",
"\"\\n\"",
")",
"lines",
".",
"reject!",
"{",
"|",
"line",
"|",
"line",
".",
"strip",
".",
"empty?",
"||",
"line",
".",
"strip",
".",
"start_with?",
"(",
"'#'",
")",
"}",
"lines",
".",
"compact!",
"lines",
"||=",
"[",
"]",
"@all_commands",
"=",
"lines",
".",
"collect",
"{",
"|",
"line",
"|",
"Command",
".",
"new",
"(",
"line",
",",
"@cookbook",
",",
"@options",
")",
"}",
"end"
]
| Parse the given Strainerfile | [
"Parse",
"the",
"given",
"Strainerfile"
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/strainerfile.rb#L80-L98 | train |
customink/strainer | lib/strainer/command.rb | Strainer.Command.speak | def speak(message, options = {})
message.to_s.strip.split("\n").each do |line|
next if line.strip.empty?
line.gsub! Strainer.sandbox_path.to_s, @cookbook.original_path.dirname.to_s
Strainer.ui.say label_with_padding + line, options
end
end | ruby | def speak(message, options = {})
message.to_s.strip.split("\n").each do |line|
next if line.strip.empty?
line.gsub! Strainer.sandbox_path.to_s, @cookbook.original_path.dirname.to_s
Strainer.ui.say label_with_padding + line, options
end
end | [
"def",
"speak",
"(",
"message",
",",
"options",
"=",
"{",
"}",
")",
"message",
".",
"to_s",
".",
"strip",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"each",
"do",
"|",
"line",
"|",
"next",
"if",
"line",
".",
"strip",
".",
"empty?",
"line",
".",
"gsub!",
"Strainer",
".",
"sandbox_path",
".",
"to_s",
",",
"@cookbook",
".",
"original_path",
".",
"dirname",
".",
"to_s",
"Strainer",
".",
"ui",
".",
"say",
"label_with_padding",
"+",
"line",
",",
"options",
"end",
"end"
]
| Have this command output text, prefixing with its output with the
command name
@param [String] message
the message to speak
@param [Hash] options
a list of options to pass along | [
"Have",
"this",
"command",
"output",
"text",
"prefixing",
"with",
"its",
"output",
"with",
"the",
"command",
"name"
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/command.rb#L99-L106 | train |
customink/strainer | lib/strainer/command.rb | Strainer.Command.inside_sandbox | def inside_sandbox(&block)
Strainer.ui.debug "Changing working directory to '#{Strainer.sandbox_path}'"
original_pwd = ENV['PWD']
ENV['PWD'] = Strainer.sandbox_path.to_s
success = Dir.chdir(Strainer.sandbox_path, &block)
ENV['PWD'] = original_pwd
Strainer.ui.debug "Restored working directory to '#{original_pwd}'"
success
end | ruby | def inside_sandbox(&block)
Strainer.ui.debug "Changing working directory to '#{Strainer.sandbox_path}'"
original_pwd = ENV['PWD']
ENV['PWD'] = Strainer.sandbox_path.to_s
success = Dir.chdir(Strainer.sandbox_path, &block)
ENV['PWD'] = original_pwd
Strainer.ui.debug "Restored working directory to '#{original_pwd}'"
success
end | [
"def",
"inside_sandbox",
"(",
"&",
"block",
")",
"Strainer",
".",
"ui",
".",
"debug",
"\"Changing working directory to '#{Strainer.sandbox_path}'\"",
"original_pwd",
"=",
"ENV",
"[",
"'PWD'",
"]",
"ENV",
"[",
"'PWD'",
"]",
"=",
"Strainer",
".",
"sandbox_path",
".",
"to_s",
"success",
"=",
"Dir",
".",
"chdir",
"(",
"Strainer",
".",
"sandbox_path",
",",
"&",
"block",
")",
"ENV",
"[",
"'PWD'",
"]",
"=",
"original_pwd",
"Strainer",
".",
"ui",
".",
"debug",
"\"Restored working directory to '#{original_pwd}'\"",
"success",
"end"
]
| Execute a block inside the sandbox directory defined in 'Strainer.sandbox_path'.
This will first change the 'PWD' env variable to the sandbox path, and then
pass the given block into 'Dir.chdir'. 'PWD' is restored to the original value
when the block is finished.
@yield The block to execute inside the sandbox
@return [Boolean]
`true` if the command exited successfully, `false` otherwise | [
"Execute",
"a",
"block",
"inside",
"the",
"sandbox",
"directory",
"defined",
"in",
"Strainer",
".",
"sandbox_path",
".",
"This",
"will",
"first",
"change",
"the",
"PWD",
"env",
"variable",
"to",
"the",
"sandbox",
"path",
"and",
"then",
"pass",
"the",
"given",
"block",
"into",
"Dir",
".",
"chdir",
".",
"PWD",
"is",
"restored",
"to",
"the",
"original",
"value",
"when",
"the",
"block",
"is",
"finished",
"."
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/command.rb#L145-L155 | train |
customink/strainer | lib/strainer/command.rb | Strainer.Command.inside_cookbook | def inside_cookbook(&block)
cookbook_path = File.join(Strainer.sandbox_path.to_s, @cookbook.cookbook_name)
Strainer.ui.debug "Changing working directory to '#{cookbook_path}'"
original_pwd = ENV['PWD']
ENV['PWD'] = cookbook_path
success = Dir.chdir(cookbook_path, &block)
ENV['PWD'] = original_pwd
Strainer.ui.debug "Restoring working directory to '#{original_pwd}'"
success
end | ruby | def inside_cookbook(&block)
cookbook_path = File.join(Strainer.sandbox_path.to_s, @cookbook.cookbook_name)
Strainer.ui.debug "Changing working directory to '#{cookbook_path}'"
original_pwd = ENV['PWD']
ENV['PWD'] = cookbook_path
success = Dir.chdir(cookbook_path, &block)
ENV['PWD'] = original_pwd
Strainer.ui.debug "Restoring working directory to '#{original_pwd}'"
success
end | [
"def",
"inside_cookbook",
"(",
"&",
"block",
")",
"cookbook_path",
"=",
"File",
".",
"join",
"(",
"Strainer",
".",
"sandbox_path",
".",
"to_s",
",",
"@cookbook",
".",
"cookbook_name",
")",
"Strainer",
".",
"ui",
".",
"debug",
"\"Changing working directory to '#{cookbook_path}'\"",
"original_pwd",
"=",
"ENV",
"[",
"'PWD'",
"]",
"ENV",
"[",
"'PWD'",
"]",
"=",
"cookbook_path",
"success",
"=",
"Dir",
".",
"chdir",
"(",
"cookbook_path",
",",
"&",
"block",
")",
"ENV",
"[",
"'PWD'",
"]",
"=",
"original_pwd",
"Strainer",
".",
"ui",
".",
"debug",
"\"Restoring working directory to '#{original_pwd}'\"",
"success",
"end"
]
| Execute a block inside the sandboxed cookbook directory.
@yield The block to execute inside the cookbook sandbox
@return [Boolean]
`true` if the command exited successfully, `false` otherwise | [
"Execute",
"a",
"block",
"inside",
"the",
"sandboxed",
"cookbook",
"directory",
"."
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/command.rb#L162-L173 | train |
customink/strainer | lib/strainer/command.rb | Strainer.Command.run_as_pty | def run_as_pty(command)
Strainer.ui.debug 'Using PTY'
PTY.spawn(command) do |r, _, pid|
begin
r.sync
r.each_line { |line| speak line }
rescue Errno::EIO => e
# Ignore this. Otherwise errors will be thrown whenever
# the process is closed
ensure
::Process.wait pid
end
end
end | ruby | def run_as_pty(command)
Strainer.ui.debug 'Using PTY'
PTY.spawn(command) do |r, _, pid|
begin
r.sync
r.each_line { |line| speak line }
rescue Errno::EIO => e
# Ignore this. Otherwise errors will be thrown whenever
# the process is closed
ensure
::Process.wait pid
end
end
end | [
"def",
"run_as_pty",
"(",
"command",
")",
"Strainer",
".",
"ui",
".",
"debug",
"'Using PTY'",
"PTY",
".",
"spawn",
"(",
"command",
")",
"do",
"|",
"r",
",",
"_",
",",
"pid",
"|",
"begin",
"r",
".",
"sync",
"r",
".",
"each_line",
"{",
"|",
"line",
"|",
"speak",
"line",
"}",
"rescue",
"Errno",
"::",
"EIO",
"=>",
"e",
"ensure",
"::",
"Process",
".",
"wait",
"pid",
"end",
"end",
"end"
]
| Run a command using PTY
@param [String] command
the command to run | [
"Run",
"a",
"command",
"using",
"PTY"
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/command.rb#L179-L192 | train |
customink/strainer | lib/strainer/ui.rb | Strainer.UI.error | def error(message, color = :red)
Strainer.log.error(message)
return if quiet?
message = set_color(message, *color) if color
super(message)
end | ruby | def error(message, color = :red)
Strainer.log.error(message)
return if quiet?
message = set_color(message, *color) if color
super(message)
end | [
"def",
"error",
"(",
"message",
",",
"color",
"=",
":red",
")",
"Strainer",
".",
"log",
".",
"error",
"(",
"message",
")",
"return",
"if",
"quiet?",
"message",
"=",
"set_color",
"(",
"message",
",",
"*",
"color",
")",
"if",
"color",
"super",
"(",
"message",
")",
"end"
]
| Print a red error message to the STDERR.
@param [String] message
the message to print
@param [Symbol] color
the color to use | [
"Print",
"a",
"red",
"error",
"message",
"to",
"the",
"STDERR",
"."
]
| 5a49c4f7896e35e402777395b8160a0b5623546d | https://github.com/customink/strainer/blob/5a49c4f7896e35e402777395b8160a0b5623546d/lib/strainer/ui.rb#L104-L110 | train |
berk/tr8n | lib/tr8n/token.rb | Tr8n.Token.token_value | def token_value(object, options, language)
# token is an array
if object.is_a?(Array)
# if you provided an array, it better have some values
if object.empty?
return raise Tr8n::TokenException.new("Invalid array value for a token: #{full_name}")
end
# if the first value of an array is an array handle it here
if object.first.kind_of?(Enumerable)
return token_array_value(object, options, language)
end
# if the first item in the array is an object, process it
return evaluate_token_method_array(object.first, object, options, language)
elsif object.is_a?(Hash)
# if object is a hash, it must be of a form: {:object => {}, :value => "", :attribute => ""}
# either value can be passed, or the attribute. attribute will be used first
if object[:object].nil?
return raise Tr8n::TokenException.new("Hash token is missing an object key for a token: #{full_name}")
end
value = object[:value]
unless object[:attribute].blank?
value = object[:object][object[:attribute]]
end
if value.blank?
return raise Tr8n::TokenException.new("Hash object is missing a value or attribute key for a token: #{full_name}")
end
object = value
end
# simple token
sanitize_token_value(object, object.to_s, options, language)
end | ruby | def token_value(object, options, language)
# token is an array
if object.is_a?(Array)
# if you provided an array, it better have some values
if object.empty?
return raise Tr8n::TokenException.new("Invalid array value for a token: #{full_name}")
end
# if the first value of an array is an array handle it here
if object.first.kind_of?(Enumerable)
return token_array_value(object, options, language)
end
# if the first item in the array is an object, process it
return evaluate_token_method_array(object.first, object, options, language)
elsif object.is_a?(Hash)
# if object is a hash, it must be of a form: {:object => {}, :value => "", :attribute => ""}
# either value can be passed, or the attribute. attribute will be used first
if object[:object].nil?
return raise Tr8n::TokenException.new("Hash token is missing an object key for a token: #{full_name}")
end
value = object[:value]
unless object[:attribute].blank?
value = object[:object][object[:attribute]]
end
if value.blank?
return raise Tr8n::TokenException.new("Hash object is missing a value or attribute key for a token: #{full_name}")
end
object = value
end
# simple token
sanitize_token_value(object, object.to_s, options, language)
end | [
"def",
"token_value",
"(",
"object",
",",
"options",
",",
"language",
")",
"if",
"object",
".",
"is_a?",
"(",
"Array",
")",
"if",
"object",
".",
"empty?",
"return",
"raise",
"Tr8n",
"::",
"TokenException",
".",
"new",
"(",
"\"Invalid array value for a token: #{full_name}\"",
")",
"end",
"if",
"object",
".",
"first",
".",
"kind_of?",
"(",
"Enumerable",
")",
"return",
"token_array_value",
"(",
"object",
",",
"options",
",",
"language",
")",
"end",
"return",
"evaluate_token_method_array",
"(",
"object",
".",
"first",
",",
"object",
",",
"options",
",",
"language",
")",
"elsif",
"object",
".",
"is_a?",
"(",
"Hash",
")",
"if",
"object",
"[",
":object",
"]",
".",
"nil?",
"return",
"raise",
"Tr8n",
"::",
"TokenException",
".",
"new",
"(",
"\"Hash token is missing an object key for a token: #{full_name}\"",
")",
"end",
"value",
"=",
"object",
"[",
":value",
"]",
"unless",
"object",
"[",
":attribute",
"]",
".",
"blank?",
"value",
"=",
"object",
"[",
":object",
"]",
"[",
"object",
"[",
":attribute",
"]",
"]",
"end",
"if",
"value",
".",
"blank?",
"return",
"raise",
"Tr8n",
"::",
"TokenException",
".",
"new",
"(",
"\"Hash object is missing a value or attribute key for a token: #{full_name}\"",
")",
"end",
"object",
"=",
"value",
"end",
"sanitize_token_value",
"(",
"object",
",",
"object",
".",
"to_s",
",",
"options",
",",
"language",
")",
"end"
]
| evaluate all possible methods for the token value and return sanitized result | [
"evaluate",
"all",
"possible",
"methods",
"for",
"the",
"token",
"value",
"and",
"return",
"sanitized",
"result"
]
| b95c42c55f429348524841a683de7d7f2e13e8a3 | https://github.com/berk/tr8n/blob/b95c42c55f429348524841a683de7d7f2e13e8a3/lib/tr8n/token.rb#L378-L415 | train |
berk/tr8n | app/controllers/tr8n/language_controller.rb | Tr8n.LanguageController.update_rules | def update_rules
@rules = rules_by_dependency(parse_language_rules)
unless params[:rule_action]
return render(:partial => "edit_rules")
end
if params[:rule_action].index("add_at")
position = params[:rule_action].split("_").last.to_i
cls = Tr8n::Config.language_rule_dependencies[params[:rule_type]]
@rules[cls.dependency].insert(position, cls.new(:language => tr8n_current_language))
elsif params[:rule_action].index("delete_at")
position = params[:rule_action].split("_").last.to_i
cls = Tr8n::Config.language_rule_dependencies[params[:rule_type]]
@rules[cls.dependency].delete_at(position)
end
render :partial => "edit_rules"
end | ruby | def update_rules
@rules = rules_by_dependency(parse_language_rules)
unless params[:rule_action]
return render(:partial => "edit_rules")
end
if params[:rule_action].index("add_at")
position = params[:rule_action].split("_").last.to_i
cls = Tr8n::Config.language_rule_dependencies[params[:rule_type]]
@rules[cls.dependency].insert(position, cls.new(:language => tr8n_current_language))
elsif params[:rule_action].index("delete_at")
position = params[:rule_action].split("_").last.to_i
cls = Tr8n::Config.language_rule_dependencies[params[:rule_type]]
@rules[cls.dependency].delete_at(position)
end
render :partial => "edit_rules"
end | [
"def",
"update_rules",
"@rules",
"=",
"rules_by_dependency",
"(",
"parse_language_rules",
")",
"unless",
"params",
"[",
":rule_action",
"]",
"return",
"render",
"(",
":partial",
"=>",
"\"edit_rules\"",
")",
"end",
"if",
"params",
"[",
":rule_action",
"]",
".",
"index",
"(",
"\"add_at\"",
")",
"position",
"=",
"params",
"[",
":rule_action",
"]",
".",
"split",
"(",
"\"_\"",
")",
".",
"last",
".",
"to_i",
"cls",
"=",
"Tr8n",
"::",
"Config",
".",
"language_rule_dependencies",
"[",
"params",
"[",
":rule_type",
"]",
"]",
"@rules",
"[",
"cls",
".",
"dependency",
"]",
".",
"insert",
"(",
"position",
",",
"cls",
".",
"new",
"(",
":language",
"=>",
"tr8n_current_language",
")",
")",
"elsif",
"params",
"[",
":rule_action",
"]",
".",
"index",
"(",
"\"delete_at\"",
")",
"position",
"=",
"params",
"[",
":rule_action",
"]",
".",
"split",
"(",
"\"_\"",
")",
".",
"last",
".",
"to_i",
"cls",
"=",
"Tr8n",
"::",
"Config",
".",
"language_rule_dependencies",
"[",
"params",
"[",
":rule_type",
"]",
"]",
"@rules",
"[",
"cls",
".",
"dependency",
"]",
".",
"delete_at",
"(",
"position",
")",
"end",
"render",
":partial",
"=>",
"\"edit_rules\"",
"end"
]
| ajax method for updating language rules in edit mode | [
"ajax",
"method",
"for",
"updating",
"language",
"rules",
"in",
"edit",
"mode"
]
| b95c42c55f429348524841a683de7d7f2e13e8a3 | https://github.com/berk/tr8n/blob/b95c42c55f429348524841a683de7d7f2e13e8a3/app/controllers/tr8n/language_controller.rb#L99-L117 | train |
berk/tr8n | app/controllers/tr8n/language_controller.rb | Tr8n.LanguageController.update_language_cases | def update_language_cases
@cases = parse_language_cases
unless params[:case_action]
return render(:partial => "edit_cases")
end
if params[:case_action].index("add_at")
position = params[:case_action].split("_").last.to_i
@cases.insert(position, Tr8n::LanguageCase.new(:language => tr8n_current_language))
elsif params[:case_action].index("delete_at")
position = params[:case_action].split("_").last.to_i
@cases.delete_at(position)
elsif params[:case_action].index("clear_all")
@cases = []
end
render :partial => "edit_language_cases"
end | ruby | def update_language_cases
@cases = parse_language_cases
unless params[:case_action]
return render(:partial => "edit_cases")
end
if params[:case_action].index("add_at")
position = params[:case_action].split("_").last.to_i
@cases.insert(position, Tr8n::LanguageCase.new(:language => tr8n_current_language))
elsif params[:case_action].index("delete_at")
position = params[:case_action].split("_").last.to_i
@cases.delete_at(position)
elsif params[:case_action].index("clear_all")
@cases = []
end
render :partial => "edit_language_cases"
end | [
"def",
"update_language_cases",
"@cases",
"=",
"parse_language_cases",
"unless",
"params",
"[",
":case_action",
"]",
"return",
"render",
"(",
":partial",
"=>",
"\"edit_cases\"",
")",
"end",
"if",
"params",
"[",
":case_action",
"]",
".",
"index",
"(",
"\"add_at\"",
")",
"position",
"=",
"params",
"[",
":case_action",
"]",
".",
"split",
"(",
"\"_\"",
")",
".",
"last",
".",
"to_i",
"@cases",
".",
"insert",
"(",
"position",
",",
"Tr8n",
"::",
"LanguageCase",
".",
"new",
"(",
":language",
"=>",
"tr8n_current_language",
")",
")",
"elsif",
"params",
"[",
":case_action",
"]",
".",
"index",
"(",
"\"delete_at\"",
")",
"position",
"=",
"params",
"[",
":case_action",
"]",
".",
"split",
"(",
"\"_\"",
")",
".",
"last",
".",
"to_i",
"@cases",
".",
"delete_at",
"(",
"position",
")",
"elsif",
"params",
"[",
":case_action",
"]",
".",
"index",
"(",
"\"clear_all\"",
")",
"@cases",
"=",
"[",
"]",
"end",
"render",
":partial",
"=>",
"\"edit_language_cases\"",
"end"
]
| ajax method for updating language cases in edit mode | [
"ajax",
"method",
"for",
"updating",
"language",
"cases",
"in",
"edit",
"mode"
]
| b95c42c55f429348524841a683de7d7f2e13e8a3 | https://github.com/berk/tr8n/blob/b95c42c55f429348524841a683de7d7f2e13e8a3/app/controllers/tr8n/language_controller.rb#L120-L138 | train |
berk/tr8n | app/controllers/tr8n/language_controller.rb | Tr8n.LanguageController.update_language_case_rules | def update_language_case_rules
cases = parse_language_cases
case_index = params[:case_index].to_i
lcase = cases[case_index]
if params[:case_action].index("add_rule_at")
position = params[:case_action].split("_").last.to_i
rule_data = params[:edit_rule].merge(:language => tr8n_current_language)
lcase.language_case_rules.insert(position, Tr8n::LanguageCaseRule.new(rule_data))
elsif params[:case_action].index("update_rule_at")
position = params[:case_action].split("_").last.to_i
rule_data = params[:edit_rule].merge(:language => tr8n_current_language)
lcase.language_case_rules[position].definition = params[:edit_rule][:definition]
elsif params[:case_action].index("move_rule_up_at")
position = params[:case_action].split("_").last.to_i
temp_node = lcase.language_case_rules[position-1]
lcase.language_case_rules[position-1] = lcase.language_case_rules[position]
lcase.language_case_rules[position] = temp_node
elsif params[:case_action].index("move_rule_down_at")
position = params[:case_action].split("_").last.to_i
temp_node = lcase.language_case_rules[position+1]
lcase.language_case_rules[position+1] = lcase.language_case_rules[position]
lcase.language_case_rules[position] = temp_node
elsif params[:case_action].index("delete_rule_at")
position = params[:case_action].split("_").last.to_i
lcase.language_case_rules.delete_at(position)
elsif params[:case_action].index("clear_all")
lcase.language_case_rules = []
end
render(:partial => "edit_language_case_rules", :locals => {:lcase => lcase, :case_index => case_index})
end | ruby | def update_language_case_rules
cases = parse_language_cases
case_index = params[:case_index].to_i
lcase = cases[case_index]
if params[:case_action].index("add_rule_at")
position = params[:case_action].split("_").last.to_i
rule_data = params[:edit_rule].merge(:language => tr8n_current_language)
lcase.language_case_rules.insert(position, Tr8n::LanguageCaseRule.new(rule_data))
elsif params[:case_action].index("update_rule_at")
position = params[:case_action].split("_").last.to_i
rule_data = params[:edit_rule].merge(:language => tr8n_current_language)
lcase.language_case_rules[position].definition = params[:edit_rule][:definition]
elsif params[:case_action].index("move_rule_up_at")
position = params[:case_action].split("_").last.to_i
temp_node = lcase.language_case_rules[position-1]
lcase.language_case_rules[position-1] = lcase.language_case_rules[position]
lcase.language_case_rules[position] = temp_node
elsif params[:case_action].index("move_rule_down_at")
position = params[:case_action].split("_").last.to_i
temp_node = lcase.language_case_rules[position+1]
lcase.language_case_rules[position+1] = lcase.language_case_rules[position]
lcase.language_case_rules[position] = temp_node
elsif params[:case_action].index("delete_rule_at")
position = params[:case_action].split("_").last.to_i
lcase.language_case_rules.delete_at(position)
elsif params[:case_action].index("clear_all")
lcase.language_case_rules = []
end
render(:partial => "edit_language_case_rules", :locals => {:lcase => lcase, :case_index => case_index})
end | [
"def",
"update_language_case_rules",
"cases",
"=",
"parse_language_cases",
"case_index",
"=",
"params",
"[",
":case_index",
"]",
".",
"to_i",
"lcase",
"=",
"cases",
"[",
"case_index",
"]",
"if",
"params",
"[",
":case_action",
"]",
".",
"index",
"(",
"\"add_rule_at\"",
")",
"position",
"=",
"params",
"[",
":case_action",
"]",
".",
"split",
"(",
"\"_\"",
")",
".",
"last",
".",
"to_i",
"rule_data",
"=",
"params",
"[",
":edit_rule",
"]",
".",
"merge",
"(",
":language",
"=>",
"tr8n_current_language",
")",
"lcase",
".",
"language_case_rules",
".",
"insert",
"(",
"position",
",",
"Tr8n",
"::",
"LanguageCaseRule",
".",
"new",
"(",
"rule_data",
")",
")",
"elsif",
"params",
"[",
":case_action",
"]",
".",
"index",
"(",
"\"update_rule_at\"",
")",
"position",
"=",
"params",
"[",
":case_action",
"]",
".",
"split",
"(",
"\"_\"",
")",
".",
"last",
".",
"to_i",
"rule_data",
"=",
"params",
"[",
":edit_rule",
"]",
".",
"merge",
"(",
":language",
"=>",
"tr8n_current_language",
")",
"lcase",
".",
"language_case_rules",
"[",
"position",
"]",
".",
"definition",
"=",
"params",
"[",
":edit_rule",
"]",
"[",
":definition",
"]",
"elsif",
"params",
"[",
":case_action",
"]",
".",
"index",
"(",
"\"move_rule_up_at\"",
")",
"position",
"=",
"params",
"[",
":case_action",
"]",
".",
"split",
"(",
"\"_\"",
")",
".",
"last",
".",
"to_i",
"temp_node",
"=",
"lcase",
".",
"language_case_rules",
"[",
"position",
"-",
"1",
"]",
"lcase",
".",
"language_case_rules",
"[",
"position",
"-",
"1",
"]",
"=",
"lcase",
".",
"language_case_rules",
"[",
"position",
"]",
"lcase",
".",
"language_case_rules",
"[",
"position",
"]",
"=",
"temp_node",
"elsif",
"params",
"[",
":case_action",
"]",
".",
"index",
"(",
"\"move_rule_down_at\"",
")",
"position",
"=",
"params",
"[",
":case_action",
"]",
".",
"split",
"(",
"\"_\"",
")",
".",
"last",
".",
"to_i",
"temp_node",
"=",
"lcase",
".",
"language_case_rules",
"[",
"position",
"+",
"1",
"]",
"lcase",
".",
"language_case_rules",
"[",
"position",
"+",
"1",
"]",
"=",
"lcase",
".",
"language_case_rules",
"[",
"position",
"]",
"lcase",
".",
"language_case_rules",
"[",
"position",
"]",
"=",
"temp_node",
"elsif",
"params",
"[",
":case_action",
"]",
".",
"index",
"(",
"\"delete_rule_at\"",
")",
"position",
"=",
"params",
"[",
":case_action",
"]",
".",
"split",
"(",
"\"_\"",
")",
".",
"last",
".",
"to_i",
"lcase",
".",
"language_case_rules",
".",
"delete_at",
"(",
"position",
")",
"elsif",
"params",
"[",
":case_action",
"]",
".",
"index",
"(",
"\"clear_all\"",
")",
"lcase",
".",
"language_case_rules",
"=",
"[",
"]",
"end",
"render",
"(",
":partial",
"=>",
"\"edit_language_case_rules\"",
",",
":locals",
"=>",
"{",
":lcase",
"=>",
"lcase",
",",
":case_index",
"=>",
"case_index",
"}",
")",
"end"
]
| ajax method for updating language case rules in edit mode | [
"ajax",
"method",
"for",
"updating",
"language",
"case",
"rules",
"in",
"edit",
"mode"
]
| b95c42c55f429348524841a683de7d7f2e13e8a3 | https://github.com/berk/tr8n/blob/b95c42c55f429348524841a683de7d7f2e13e8a3/app/controllers/tr8n/language_controller.rb#L141-L178 | train |
berk/tr8n | app/controllers/tr8n/language_controller.rb | Tr8n.LanguageController.select | def select
@inline_translations_allowed = false
@inline_translations_enabled = false
if tr8n_current_user_is_translator?
unless tr8n_current_translator.blocked?
@inline_translations_allowed = true
@inline_translations_enabled = tr8n_current_translator.enable_inline_translations?
end
else
@inline_translations_allowed = Tr8n::Config.open_registration_mode?
end
@inline_translations_allowed = true if tr8n_current_user_is_admin?
@source_url = request.env['HTTP_REFERER']
@source_url.gsub!("locale", "previous_locale") if @source_url
@all_languages = Tr8n::Language.enabled_languages
@user_languages = Tr8n::LanguageUser.languages_for(tr8n_current_user) unless tr8n_current_user_is_guest?
render_lightbox
end | ruby | def select
@inline_translations_allowed = false
@inline_translations_enabled = false
if tr8n_current_user_is_translator?
unless tr8n_current_translator.blocked?
@inline_translations_allowed = true
@inline_translations_enabled = tr8n_current_translator.enable_inline_translations?
end
else
@inline_translations_allowed = Tr8n::Config.open_registration_mode?
end
@inline_translations_allowed = true if tr8n_current_user_is_admin?
@source_url = request.env['HTTP_REFERER']
@source_url.gsub!("locale", "previous_locale") if @source_url
@all_languages = Tr8n::Language.enabled_languages
@user_languages = Tr8n::LanguageUser.languages_for(tr8n_current_user) unless tr8n_current_user_is_guest?
render_lightbox
end | [
"def",
"select",
"@inline_translations_allowed",
"=",
"false",
"@inline_translations_enabled",
"=",
"false",
"if",
"tr8n_current_user_is_translator?",
"unless",
"tr8n_current_translator",
".",
"blocked?",
"@inline_translations_allowed",
"=",
"true",
"@inline_translations_enabled",
"=",
"tr8n_current_translator",
".",
"enable_inline_translations?",
"end",
"else",
"@inline_translations_allowed",
"=",
"Tr8n",
"::",
"Config",
".",
"open_registration_mode?",
"end",
"@inline_translations_allowed",
"=",
"true",
"if",
"tr8n_current_user_is_admin?",
"@source_url",
"=",
"request",
".",
"env",
"[",
"'HTTP_REFERER'",
"]",
"@source_url",
".",
"gsub!",
"(",
"\"locale\"",
",",
"\"previous_locale\"",
")",
"if",
"@source_url",
"@all_languages",
"=",
"Tr8n",
"::",
"Language",
".",
"enabled_languages",
"@user_languages",
"=",
"Tr8n",
"::",
"LanguageUser",
".",
"languages_for",
"(",
"tr8n_current_user",
")",
"unless",
"tr8n_current_user_is_guest?",
"render_lightbox",
"end"
]
| language selector window | [
"language",
"selector",
"window"
]
| b95c42c55f429348524841a683de7d7f2e13e8a3 | https://github.com/berk/tr8n/blob/b95c42c55f429348524841a683de7d7f2e13e8a3/app/controllers/tr8n/language_controller.rb#L181-L203 | train |
berk/tr8n | app/controllers/tr8n/language_controller.rb | Tr8n.LanguageController.switch | def switch
language_action = params[:language_action]
return redirect_to_source if tr8n_current_user_is_guest?
if tr8n_current_user_is_translator? # translator mode
if language_action == "toggle_inline_mode"
if tr8n_current_translator.enable_inline_translations?
language_action = "disable_inline_mode"
else
language_action = "enable_inline_mode"
end
end
if language_action == "enable_inline_mode"
tr8n_current_translator.enable_inline_translations!
elsif language_action == "disable_inline_mode"
tr8n_current_translator.disable_inline_translations!
elsif language_action == "switch_language"
tr8n_current_translator.switched_language!(Tr8n::Language.find_by_locale(params[:locale]))
end
elsif language_action == "switch_language" # non-translator mode
Tr8n::LanguageUser.create_or_touch(tr8n_current_user, Tr8n::Language.find_by_locale(params[:locale]))
elsif language_action == "become_translator" # non-translator mode
Tr8n::Translator.register
elsif language_action == "enable_inline_mode" or language_action == "toggle_inline_mode" # non-translator mode
Tr8n::Translator.register.enable_inline_translations!
end
redirect_to_source
end | ruby | def switch
language_action = params[:language_action]
return redirect_to_source if tr8n_current_user_is_guest?
if tr8n_current_user_is_translator? # translator mode
if language_action == "toggle_inline_mode"
if tr8n_current_translator.enable_inline_translations?
language_action = "disable_inline_mode"
else
language_action = "enable_inline_mode"
end
end
if language_action == "enable_inline_mode"
tr8n_current_translator.enable_inline_translations!
elsif language_action == "disable_inline_mode"
tr8n_current_translator.disable_inline_translations!
elsif language_action == "switch_language"
tr8n_current_translator.switched_language!(Tr8n::Language.find_by_locale(params[:locale]))
end
elsif language_action == "switch_language" # non-translator mode
Tr8n::LanguageUser.create_or_touch(tr8n_current_user, Tr8n::Language.find_by_locale(params[:locale]))
elsif language_action == "become_translator" # non-translator mode
Tr8n::Translator.register
elsif language_action == "enable_inline_mode" or language_action == "toggle_inline_mode" # non-translator mode
Tr8n::Translator.register.enable_inline_translations!
end
redirect_to_source
end | [
"def",
"switch",
"language_action",
"=",
"params",
"[",
":language_action",
"]",
"return",
"redirect_to_source",
"if",
"tr8n_current_user_is_guest?",
"if",
"tr8n_current_user_is_translator?",
"if",
"language_action",
"==",
"\"toggle_inline_mode\"",
"if",
"tr8n_current_translator",
".",
"enable_inline_translations?",
"language_action",
"=",
"\"disable_inline_mode\"",
"else",
"language_action",
"=",
"\"enable_inline_mode\"",
"end",
"end",
"if",
"language_action",
"==",
"\"enable_inline_mode\"",
"tr8n_current_translator",
".",
"enable_inline_translations!",
"elsif",
"language_action",
"==",
"\"disable_inline_mode\"",
"tr8n_current_translator",
".",
"disable_inline_translations!",
"elsif",
"language_action",
"==",
"\"switch_language\"",
"tr8n_current_translator",
".",
"switched_language!",
"(",
"Tr8n",
"::",
"Language",
".",
"find_by_locale",
"(",
"params",
"[",
":locale",
"]",
")",
")",
"end",
"elsif",
"language_action",
"==",
"\"switch_language\"",
"Tr8n",
"::",
"LanguageUser",
".",
"create_or_touch",
"(",
"tr8n_current_user",
",",
"Tr8n",
"::",
"Language",
".",
"find_by_locale",
"(",
"params",
"[",
":locale",
"]",
")",
")",
"elsif",
"language_action",
"==",
"\"become_translator\"",
"Tr8n",
"::",
"Translator",
".",
"register",
"elsif",
"language_action",
"==",
"\"enable_inline_mode\"",
"or",
"language_action",
"==",
"\"toggle_inline_mode\"",
"Tr8n",
"::",
"Translator",
".",
"register",
".",
"enable_inline_translations!",
"end",
"redirect_to_source",
"end"
]
| language selector processor | [
"language",
"selector",
"processor"
]
| b95c42c55f429348524841a683de7d7f2e13e8a3 | https://github.com/berk/tr8n/blob/b95c42c55f429348524841a683de7d7f2e13e8a3/app/controllers/tr8n/language_controller.rb#L222-L252 | train |
berk/tr8n | app/controllers/tr8n/language_controller.rb | Tr8n.LanguageController.parse_language_rules | def parse_language_rules
rulz = []
return rulz unless params[:rules]
Tr8n::Config.language_rule_classes.each do |cls|
next unless params[:rules][cls.dependency]
index = 0
while params[:rules][cls.dependency]["#{index}"]
rule_params = params[:rules][cls.dependency]["#{index}"]
rule_definition = params[:rules][cls.dependency]["#{index}"][:definition]
if rule_params.delete(:reset_values) == "true"
rule_definition = {}
end
rule_id = rule_params[:id]
keyword = rule_params[:keyword]
if rule_id.blank?
rulz << cls.new(:keyword => keyword, :definition => rule_definition)
else
rule = cls.find_by_id(rule_id)
rule = cls.new unless rule
rule.keyword = keyword
rule.definition = rule_definition
rulz << rule
end
index += 1
end
end
rulz
end | ruby | def parse_language_rules
rulz = []
return rulz unless params[:rules]
Tr8n::Config.language_rule_classes.each do |cls|
next unless params[:rules][cls.dependency]
index = 0
while params[:rules][cls.dependency]["#{index}"]
rule_params = params[:rules][cls.dependency]["#{index}"]
rule_definition = params[:rules][cls.dependency]["#{index}"][:definition]
if rule_params.delete(:reset_values) == "true"
rule_definition = {}
end
rule_id = rule_params[:id]
keyword = rule_params[:keyword]
if rule_id.blank?
rulz << cls.new(:keyword => keyword, :definition => rule_definition)
else
rule = cls.find_by_id(rule_id)
rule = cls.new unless rule
rule.keyword = keyword
rule.definition = rule_definition
rulz << rule
end
index += 1
end
end
rulz
end | [
"def",
"parse_language_rules",
"rulz",
"=",
"[",
"]",
"return",
"rulz",
"unless",
"params",
"[",
":rules",
"]",
"Tr8n",
"::",
"Config",
".",
"language_rule_classes",
".",
"each",
"do",
"|",
"cls",
"|",
"next",
"unless",
"params",
"[",
":rules",
"]",
"[",
"cls",
".",
"dependency",
"]",
"index",
"=",
"0",
"while",
"params",
"[",
":rules",
"]",
"[",
"cls",
".",
"dependency",
"]",
"[",
"\"#{index}\"",
"]",
"rule_params",
"=",
"params",
"[",
":rules",
"]",
"[",
"cls",
".",
"dependency",
"]",
"[",
"\"#{index}\"",
"]",
"rule_definition",
"=",
"params",
"[",
":rules",
"]",
"[",
"cls",
".",
"dependency",
"]",
"[",
"\"#{index}\"",
"]",
"[",
":definition",
"]",
"if",
"rule_params",
".",
"delete",
"(",
":reset_values",
")",
"==",
"\"true\"",
"rule_definition",
"=",
"{",
"}",
"end",
"rule_id",
"=",
"rule_params",
"[",
":id",
"]",
"keyword",
"=",
"rule_params",
"[",
":keyword",
"]",
"if",
"rule_id",
".",
"blank?",
"rulz",
"<<",
"cls",
".",
"new",
"(",
":keyword",
"=>",
"keyword",
",",
":definition",
"=>",
"rule_definition",
")",
"else",
"rule",
"=",
"cls",
".",
"find_by_id",
"(",
"rule_id",
")",
"rule",
"=",
"cls",
".",
"new",
"unless",
"rule",
"rule",
".",
"keyword",
"=",
"keyword",
"rule",
".",
"definition",
"=",
"rule_definition",
"rulz",
"<<",
"rule",
"end",
"index",
"+=",
"1",
"end",
"end",
"rulz",
"end"
]
| parse with safety - we don't want to disconnect existing translations from those rules | [
"parse",
"with",
"safety",
"-",
"we",
"don",
"t",
"want",
"to",
"disconnect",
"existing",
"translations",
"from",
"those",
"rules"
]
| b95c42c55f429348524841a683de7d7f2e13e8a3 | https://github.com/berk/tr8n/blob/b95c42c55f429348524841a683de7d7f2e13e8a3/app/controllers/tr8n/language_controller.rb#L275-L308 | train |
berk/tr8n | app/controllers/tr8n/language_cases_controller.rb | Tr8n.LanguageCasesController.index | def index
@maps = Tr8n::LanguageCaseValueMap.where("language_id = ? and (reported is null or reported = ?)", tr8n_current_language.id, false)
@maps = @maps.where("keyword like ?", "%#{params[:search]}%") unless params[:search].blank?
@maps = @maps.order("updated_at desc").page(page).per(per_page)
end | ruby | def index
@maps = Tr8n::LanguageCaseValueMap.where("language_id = ? and (reported is null or reported = ?)", tr8n_current_language.id, false)
@maps = @maps.where("keyword like ?", "%#{params[:search]}%") unless params[:search].blank?
@maps = @maps.order("updated_at desc").page(page).per(per_page)
end | [
"def",
"index",
"@maps",
"=",
"Tr8n",
"::",
"LanguageCaseValueMap",
".",
"where",
"(",
"\"language_id = ? and (reported is null or reported = ?)\"",
",",
"tr8n_current_language",
".",
"id",
",",
"false",
")",
"@maps",
"=",
"@maps",
".",
"where",
"(",
"\"keyword like ?\"",
",",
"\"%#{params[:search]}%\"",
")",
"unless",
"params",
"[",
":search",
"]",
".",
"blank?",
"@maps",
"=",
"@maps",
".",
"order",
"(",
"\"updated_at desc\"",
")",
".",
"page",
"(",
"page",
")",
".",
"per",
"(",
"per_page",
")",
"end"
]
| used by a client app | [
"used",
"by",
"a",
"client",
"app"
]
| b95c42c55f429348524841a683de7d7f2e13e8a3 | https://github.com/berk/tr8n/blob/b95c42c55f429348524841a683de7d7f2e13e8a3/app/controllers/tr8n/language_cases_controller.rb#L31-L35 | train |
berk/tr8n | app/controllers/tr8n/base_controller.rb | Tr8n.BaseController.validate_current_translator | def validate_current_translator
if tr8n_current_user_is_translator? and tr8n_current_translator.blocked?
trfe("Your translation privileges have been revoked. Please contact the site administrator for more details.")
return redirect_to(Tr8n::Config.default_url)
end
return if Tr8n::Config.current_user_is_translator?
redirect_to("/tr8n/translator/registration")
end | ruby | def validate_current_translator
if tr8n_current_user_is_translator? and tr8n_current_translator.blocked?
trfe("Your translation privileges have been revoked. Please contact the site administrator for more details.")
return redirect_to(Tr8n::Config.default_url)
end
return if Tr8n::Config.current_user_is_translator?
redirect_to("/tr8n/translator/registration")
end | [
"def",
"validate_current_translator",
"if",
"tr8n_current_user_is_translator?",
"and",
"tr8n_current_translator",
".",
"blocked?",
"trfe",
"(",
"\"Your translation privileges have been revoked. Please contact the site administrator for more details.\"",
")",
"return",
"redirect_to",
"(",
"Tr8n",
"::",
"Config",
".",
"default_url",
")",
"end",
"return",
"if",
"Tr8n",
"::",
"Config",
".",
"current_user_is_translator?",
"redirect_to",
"(",
"\"/tr8n/translator/registration\"",
")",
"end"
]
| make sure that the current user is a translator | [
"make",
"sure",
"that",
"the",
"current",
"user",
"is",
"a",
"translator"
]
| b95c42c55f429348524841a683de7d7f2e13e8a3 | https://github.com/berk/tr8n/blob/b95c42c55f429348524841a683de7d7f2e13e8a3/app/controllers/tr8n/base_controller.rb#L133-L142 | train |
berk/tr8n | app/controllers/tr8n/base_controller.rb | Tr8n.BaseController.validate_language_management | def validate_language_management
# admins can do everything
return if tr8n_current_user_is_admin?
if tr8n_current_language.default?
trfe("Only administrators can modify this language")
return redirect_to(tr8n_features_tabs.first[:link])
end
unless tr8n_current_user_is_translator? and tr8n_current_translator.manager?
trfe("In order to manage a language you first must request to become a manager of that language.")
return redirect_to(tr8n_features_tabs.first[:link])
end
end | ruby | def validate_language_management
# admins can do everything
return if tr8n_current_user_is_admin?
if tr8n_current_language.default?
trfe("Only administrators can modify this language")
return redirect_to(tr8n_features_tabs.first[:link])
end
unless tr8n_current_user_is_translator? and tr8n_current_translator.manager?
trfe("In order to manage a language you first must request to become a manager of that language.")
return redirect_to(tr8n_features_tabs.first[:link])
end
end | [
"def",
"validate_language_management",
"return",
"if",
"tr8n_current_user_is_admin?",
"if",
"tr8n_current_language",
".",
"default?",
"trfe",
"(",
"\"Only administrators can modify this language\"",
")",
"return",
"redirect_to",
"(",
"tr8n_features_tabs",
".",
"first",
"[",
":link",
"]",
")",
"end",
"unless",
"tr8n_current_user_is_translator?",
"and",
"tr8n_current_translator",
".",
"manager?",
"trfe",
"(",
"\"In order to manage a language you first must request to become a manager of that language.\"",
")",
"return",
"redirect_to",
"(",
"tr8n_features_tabs",
".",
"first",
"[",
":link",
"]",
")",
"end",
"end"
]
| make sure that the current user is a language manager | [
"make",
"sure",
"that",
"the",
"current",
"user",
"is",
"a",
"language",
"manager"
]
| b95c42c55f429348524841a683de7d7f2e13e8a3 | https://github.com/berk/tr8n/blob/b95c42c55f429348524841a683de7d7f2e13e8a3/app/controllers/tr8n/base_controller.rb#L145-L158 | train |
rapid7/elasticsearch-drain | lib/elasticsearch/drain.rb | Elasticsearch.Drain.client | def client
return @client unless @client.nil?
@client = ::Elasticsearch::Client.new(
hosts: hosts,
retry_on_failure: true,
log: true,
logger: ::Logger.new('es_client.log', 10, 1_024_000)
)
end | ruby | def client
return @client unless @client.nil?
@client = ::Elasticsearch::Client.new(
hosts: hosts,
retry_on_failure: true,
log: true,
logger: ::Logger.new('es_client.log', 10, 1_024_000)
)
end | [
"def",
"client",
"return",
"@client",
"unless",
"@client",
".",
"nil?",
"@client",
"=",
"::",
"Elasticsearch",
"::",
"Client",
".",
"new",
"(",
"hosts",
":",
"hosts",
",",
"retry_on_failure",
":",
"true",
",",
"log",
":",
"true",
",",
"logger",
":",
"::",
"Logger",
".",
"new",
"(",
"'es_client.log'",
",",
"10",
",",
"1_024_000",
")",
")",
"end"
]
| Sets up the Elasticsearch client
@option [String] :hosts ('localhost:9200') The Elasticsearch hosts
to connect to
@return [Elasticsearch::Transport::Client] Elasticsearch transport client
The Elasticsearch client object | [
"Sets",
"up",
"the",
"Elasticsearch",
"client"
]
| c2e47d0bfbeeb96eb9ebbb4627d0d127faf1f730 | https://github.com/rapid7/elasticsearch-drain/blob/c2e47d0bfbeeb96eb9ebbb4627d0d127faf1f730/lib/elasticsearch/drain.rb#L26-L34 | train |
berk/tr8n | lib/tr8n/extensions/action_view_extension.rb | Tr8n.ActionViewExtension.tr8n_client_sdk_tag | def tr8n_client_sdk_tag(opts = {})
# opts[:default_source] ||= tr8n_default_client_source
opts[:scheduler_interval] ||= Tr8n::Config.default_client_interval
opts[:enable_inline_translations] = (Tr8n::Config.current_user_is_translator? and Tr8n::Config.current_translator.enable_inline_translations? and (not Tr8n::Config.current_language.default?))
opts[:default_decorations] = Tr8n::Config.default_decoration_tokens
opts[:default_tokens] = Tr8n::Config.default_data_tokens
opts[:rules] = {
:number => Tr8n::Config.rules_engine[:numeric_rule],
:gender => Tr8n::Config.rules_engine[:gender_rule],
:list => Tr8n::Config.rules_engine[:gender_list_rule],
:date => Tr8n::Config.rules_engine[:date_rule]
}
# build a list of actual rules of the language
client_var_name = opts[:client_var_name] || :tr8nProxy
opts.merge!(:enable_tml => Tr8n::Config.enable_tml?)
"<script>Tr8n.SDK.Proxy.init(#{opts.to_json});</script>".html_safe
end | ruby | def tr8n_client_sdk_tag(opts = {})
# opts[:default_source] ||= tr8n_default_client_source
opts[:scheduler_interval] ||= Tr8n::Config.default_client_interval
opts[:enable_inline_translations] = (Tr8n::Config.current_user_is_translator? and Tr8n::Config.current_translator.enable_inline_translations? and (not Tr8n::Config.current_language.default?))
opts[:default_decorations] = Tr8n::Config.default_decoration_tokens
opts[:default_tokens] = Tr8n::Config.default_data_tokens
opts[:rules] = {
:number => Tr8n::Config.rules_engine[:numeric_rule],
:gender => Tr8n::Config.rules_engine[:gender_rule],
:list => Tr8n::Config.rules_engine[:gender_list_rule],
:date => Tr8n::Config.rules_engine[:date_rule]
}
# build a list of actual rules of the language
client_var_name = opts[:client_var_name] || :tr8nProxy
opts.merge!(:enable_tml => Tr8n::Config.enable_tml?)
"<script>Tr8n.SDK.Proxy.init(#{opts.to_json});</script>".html_safe
end | [
"def",
"tr8n_client_sdk_tag",
"(",
"opts",
"=",
"{",
"}",
")",
"opts",
"[",
":scheduler_interval",
"]",
"||=",
"Tr8n",
"::",
"Config",
".",
"default_client_interval",
"opts",
"[",
":enable_inline_translations",
"]",
"=",
"(",
"Tr8n",
"::",
"Config",
".",
"current_user_is_translator?",
"and",
"Tr8n",
"::",
"Config",
".",
"current_translator",
".",
"enable_inline_translations?",
"and",
"(",
"not",
"Tr8n",
"::",
"Config",
".",
"current_language",
".",
"default?",
")",
")",
"opts",
"[",
":default_decorations",
"]",
"=",
"Tr8n",
"::",
"Config",
".",
"default_decoration_tokens",
"opts",
"[",
":default_tokens",
"]",
"=",
"Tr8n",
"::",
"Config",
".",
"default_data_tokens",
"opts",
"[",
":rules",
"]",
"=",
"{",
":number",
"=>",
"Tr8n",
"::",
"Config",
".",
"rules_engine",
"[",
":numeric_rule",
"]",
",",
":gender",
"=>",
"Tr8n",
"::",
"Config",
".",
"rules_engine",
"[",
":gender_rule",
"]",
",",
":list",
"=>",
"Tr8n",
"::",
"Config",
".",
"rules_engine",
"[",
":gender_list_rule",
"]",
",",
":date",
"=>",
"Tr8n",
"::",
"Config",
".",
"rules_engine",
"[",
":date_rule",
"]",
"}",
"client_var_name",
"=",
"opts",
"[",
":client_var_name",
"]",
"||",
":tr8nProxy",
"opts",
".",
"merge!",
"(",
":enable_tml",
"=>",
"Tr8n",
"::",
"Config",
".",
"enable_tml?",
")",
"\"<script>Tr8n.SDK.Proxy.init(#{opts.to_json});</script>\"",
".",
"html_safe",
"end"
]
| Creates an instance of tr8nProxy object | [
"Creates",
"an",
"instance",
"of",
"tr8nProxy",
"object"
]
| b95c42c55f429348524841a683de7d7f2e13e8a3 | https://github.com/berk/tr8n/blob/b95c42c55f429348524841a683de7d7f2e13e8a3/lib/tr8n/extensions/action_view_extension.rb#L61-L82 | train |
kayac/rebi | lib/rebi/zip_helper.rb | Rebi.ZipHelper.gen | def gen
log("Creating zip archivement", env_conf.name)
start = Time.now
ebextensions = env_conf.ebextensions
tmp_file = raw_zip_archive
tmp_folder = Dir.mktmpdir
Zip::File.open(tmp_file.path) do |z|
ebextensions.each do |ex_folder|
z.remove_folder ex_folder unless ex_folder == ".ebextensions"
Dir.glob("#{ex_folder}/*.config*") do |fname|
next unless File.file?(fname)
basename = File.basename(fname)
source_file = fname
if fname.match(/\.erb$/)
next unless y = YAML::load(ErbHelper.new(File.read(fname), env_conf).result)
basename = basename.gsub(/\.erb$/,'')
source_file = "#{tmp_folder}/#{basename}"
File.open(source_file, 'w') do |f|
f.write y.to_yaml
end
end
target = ".ebextensions/#{basename}"
z.remove target if z.find_entry target
z.remove fname if z.find_entry fname
z.add target, source_file
end
end
dockerrun_file = env_conf.dockerrun || "Dockerrun.aws.json"
if File.exists?(dockerrun_file)
dockerrun = JSON.parse ErbHelper.new(File.read(dockerrun_file), env_conf).result
tmp_dockerrun = "#{tmp_folder}/Dockerrun.aws.json"
File.open(tmp_dockerrun, 'w') do |f|
f.write dockerrun.to_json
end
z.remove env_conf.dockerrun if z.find_entry env_conf.dockerrun
z.remove "Dockerrun.aws.json" if z.find_entry "Dockerrun.aws.json"
z.add "Dockerrun.aws.json", tmp_dockerrun
end
end
FileUtils.rm_rf tmp_folder
log("Zip was created in: #{Time.now - start}s", env_conf.name)
return {
label: Time.now.strftime("app_#{env_conf.name}_#{version_label}_%Y%m%d_%H%M%S"),
file: File.open(tmp_file.path),
message: message,
}
end | ruby | def gen
log("Creating zip archivement", env_conf.name)
start = Time.now
ebextensions = env_conf.ebextensions
tmp_file = raw_zip_archive
tmp_folder = Dir.mktmpdir
Zip::File.open(tmp_file.path) do |z|
ebextensions.each do |ex_folder|
z.remove_folder ex_folder unless ex_folder == ".ebextensions"
Dir.glob("#{ex_folder}/*.config*") do |fname|
next unless File.file?(fname)
basename = File.basename(fname)
source_file = fname
if fname.match(/\.erb$/)
next unless y = YAML::load(ErbHelper.new(File.read(fname), env_conf).result)
basename = basename.gsub(/\.erb$/,'')
source_file = "#{tmp_folder}/#{basename}"
File.open(source_file, 'w') do |f|
f.write y.to_yaml
end
end
target = ".ebextensions/#{basename}"
z.remove target if z.find_entry target
z.remove fname if z.find_entry fname
z.add target, source_file
end
end
dockerrun_file = env_conf.dockerrun || "Dockerrun.aws.json"
if File.exists?(dockerrun_file)
dockerrun = JSON.parse ErbHelper.new(File.read(dockerrun_file), env_conf).result
tmp_dockerrun = "#{tmp_folder}/Dockerrun.aws.json"
File.open(tmp_dockerrun, 'w') do |f|
f.write dockerrun.to_json
end
z.remove env_conf.dockerrun if z.find_entry env_conf.dockerrun
z.remove "Dockerrun.aws.json" if z.find_entry "Dockerrun.aws.json"
z.add "Dockerrun.aws.json", tmp_dockerrun
end
end
FileUtils.rm_rf tmp_folder
log("Zip was created in: #{Time.now - start}s", env_conf.name)
return {
label: Time.now.strftime("app_#{env_conf.name}_#{version_label}_%Y%m%d_%H%M%S"),
file: File.open(tmp_file.path),
message: message,
}
end | [
"def",
"gen",
"log",
"(",
"\"Creating zip archivement\"",
",",
"env_conf",
".",
"name",
")",
"start",
"=",
"Time",
".",
"now",
"ebextensions",
"=",
"env_conf",
".",
"ebextensions",
"tmp_file",
"=",
"raw_zip_archive",
"tmp_folder",
"=",
"Dir",
".",
"mktmpdir",
"Zip",
"::",
"File",
".",
"open",
"(",
"tmp_file",
".",
"path",
")",
"do",
"|",
"z",
"|",
"ebextensions",
".",
"each",
"do",
"|",
"ex_folder",
"|",
"z",
".",
"remove_folder",
"ex_folder",
"unless",
"ex_folder",
"==",
"\".ebextensions\"",
"Dir",
".",
"glob",
"(",
"\"#{ex_folder}/*.config*\"",
")",
"do",
"|",
"fname",
"|",
"next",
"unless",
"File",
".",
"file?",
"(",
"fname",
")",
"basename",
"=",
"File",
".",
"basename",
"(",
"fname",
")",
"source_file",
"=",
"fname",
"if",
"fname",
".",
"match",
"(",
"/",
"\\.",
"/",
")",
"next",
"unless",
"y",
"=",
"YAML",
"::",
"load",
"(",
"ErbHelper",
".",
"new",
"(",
"File",
".",
"read",
"(",
"fname",
")",
",",
"env_conf",
")",
".",
"result",
")",
"basename",
"=",
"basename",
".",
"gsub",
"(",
"/",
"\\.",
"/",
",",
"''",
")",
"source_file",
"=",
"\"#{tmp_folder}/#{basename}\"",
"File",
".",
"open",
"(",
"source_file",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"y",
".",
"to_yaml",
"end",
"end",
"target",
"=",
"\".ebextensions/#{basename}\"",
"z",
".",
"remove",
"target",
"if",
"z",
".",
"find_entry",
"target",
"z",
".",
"remove",
"fname",
"if",
"z",
".",
"find_entry",
"fname",
"z",
".",
"add",
"target",
",",
"source_file",
"end",
"end",
"dockerrun_file",
"=",
"env_conf",
".",
"dockerrun",
"||",
"\"Dockerrun.aws.json\"",
"if",
"File",
".",
"exists?",
"(",
"dockerrun_file",
")",
"dockerrun",
"=",
"JSON",
".",
"parse",
"ErbHelper",
".",
"new",
"(",
"File",
".",
"read",
"(",
"dockerrun_file",
")",
",",
"env_conf",
")",
".",
"result",
"tmp_dockerrun",
"=",
"\"#{tmp_folder}/Dockerrun.aws.json\"",
"File",
".",
"open",
"(",
"tmp_dockerrun",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"dockerrun",
".",
"to_json",
"end",
"z",
".",
"remove",
"env_conf",
".",
"dockerrun",
"if",
"z",
".",
"find_entry",
"env_conf",
".",
"dockerrun",
"z",
".",
"remove",
"\"Dockerrun.aws.json\"",
"if",
"z",
".",
"find_entry",
"\"Dockerrun.aws.json\"",
"z",
".",
"add",
"\"Dockerrun.aws.json\"",
",",
"tmp_dockerrun",
"end",
"end",
"FileUtils",
".",
"rm_rf",
"tmp_folder",
"log",
"(",
"\"Zip was created in: #{Time.now - start}s\"",
",",
"env_conf",
".",
"name",
")",
"return",
"{",
"label",
":",
"Time",
".",
"now",
".",
"strftime",
"(",
"\"app_#{env_conf.name}_#{version_label}_%Y%m%d_%H%M%S\"",
")",
",",
"file",
":",
"File",
".",
"open",
"(",
"tmp_file",
".",
"path",
")",
",",
"message",
":",
"message",
",",
"}",
"end"
]
| Create zip archivement | [
"Create",
"zip",
"archivement"
]
| fa4962e152811c3fe703c637cf1d95ea2d019393 | https://github.com/kayac/rebi/blob/fa4962e152811c3fe703c637cf1d95ea2d019393/lib/rebi/zip_helper.rb#L57-L110 | train |
liquidm/ext | lib/liquid/configuration.rb | Liquid.Configuration.reload! | def reload!
clear
@mixins.each do |file|
mixin(file)
end
@callbacks.each do |callback|
callback.call(self)
end
end | ruby | def reload!
clear
@mixins.each do |file|
mixin(file)
end
@callbacks.each do |callback|
callback.call(self)
end
end | [
"def",
"reload!",
"clear",
"@mixins",
".",
"each",
"do",
"|",
"file",
"|",
"mixin",
"(",
"file",
")",
"end",
"@callbacks",
".",
"each",
"do",
"|",
"callback",
"|",
"callback",
".",
"call",
"(",
"self",
")",
"end",
"end"
]
| Reload all mixins.
@return [void] | [
"Reload",
"all",
"mixins",
"."
]
| 0b7e16ac361460165ba40211720e20cafca62591 | https://github.com/liquidm/ext/blob/0b7e16ac361460165ba40211720e20cafca62591/lib/liquid/configuration.rb#L121-L131 | train |
liquidm/ext | lib/liquid/logger.rb | Liquid.Logger.called_from | def called_from
location = caller.detect('unknown:0') do |line|
line.match(/\/liquid(-|\/)ext/).nil?
end
file, line, _ = location.split(':')
{ :file => file, :line => line }
end | ruby | def called_from
location = caller.detect('unknown:0') do |line|
line.match(/\/liquid(-|\/)ext/).nil?
end
file, line, _ = location.split(':')
{ :file => file, :line => line }
end | [
"def",
"called_from",
"location",
"=",
"caller",
".",
"detect",
"(",
"'unknown:0'",
")",
"do",
"|",
"line",
"|",
"line",
".",
"match",
"(",
"/",
"\\/",
"\\/",
"/",
")",
".",
"nil?",
"end",
"file",
",",
"line",
",",
"_",
"=",
"location",
".",
"split",
"(",
"':'",
")",
"{",
":file",
"=>",
"file",
",",
":line",
"=>",
"line",
"}",
"end"
]
| Return the first callee outside the liquid-ext gem | [
"Return",
"the",
"first",
"callee",
"outside",
"the",
"liquid",
"-",
"ext",
"gem"
]
| 0b7e16ac361460165ba40211720e20cafca62591 | https://github.com/liquidm/ext/blob/0b7e16ac361460165ba40211720e20cafca62591/lib/liquid/logger.rb#L148-L154 | train |
relevance/log_buddy | lib/log_buddy/utils.rb | LogBuddy.Utils.read_line | def read_line(frame)
file, line_number = frame.split(/:/, 2)
line_number = line_number.to_i
lines = File.readlines(file)
lines[line_number - 1]
end | ruby | def read_line(frame)
file, line_number = frame.split(/:/, 2)
line_number = line_number.to_i
lines = File.readlines(file)
lines[line_number - 1]
end | [
"def",
"read_line",
"(",
"frame",
")",
"file",
",",
"line_number",
"=",
"frame",
".",
"split",
"(",
"/",
"/",
",",
"2",
")",
"line_number",
"=",
"line_number",
".",
"to_i",
"lines",
"=",
"File",
".",
"readlines",
"(",
"file",
")",
"lines",
"[",
"line_number",
"-",
"1",
"]",
"end"
]
| Return the calling line | [
"Return",
"the",
"calling",
"line"
]
| 851dc7a5b4246cbce18bbd999b46f9da22eda61c | https://github.com/relevance/log_buddy/blob/851dc7a5b4246cbce18bbd999b46f9da22eda61c/lib/log_buddy/utils.rb#L29-L35 | train |
0exp/symbiont-ruby | lib/symbiont/public_trigger.rb | Symbiont.PublicTrigger.method | def method(method_name)
__context__ = __actual_context__(method_name)
# NOTE:
# block is used cuz #__actual_context__can raise
# ::NoMethodError (ContextNoMethodError) too (and we should raise it)
begin
__context__.method(method_name)
rescue ::NoMethodError
# NOTE:
# this situation is caused when the context object does not respond
# to #method method (BasicObject instances for example). We can extract
# method objects via it's singleton class.
__context_singleton__ = __extract_singleton_class__(__context__)
__context_singleton__.public_instance_method(method_name).bind(__context__)
end
end | ruby | def method(method_name)
__context__ = __actual_context__(method_name)
# NOTE:
# block is used cuz #__actual_context__can raise
# ::NoMethodError (ContextNoMethodError) too (and we should raise it)
begin
__context__.method(method_name)
rescue ::NoMethodError
# NOTE:
# this situation is caused when the context object does not respond
# to #method method (BasicObject instances for example). We can extract
# method objects via it's singleton class.
__context_singleton__ = __extract_singleton_class__(__context__)
__context_singleton__.public_instance_method(method_name).bind(__context__)
end
end | [
"def",
"method",
"(",
"method_name",
")",
"__context__",
"=",
"__actual_context__",
"(",
"method_name",
")",
"begin",
"__context__",
".",
"method",
"(",
"method_name",
")",
"rescue",
"::",
"NoMethodError",
"__context_singleton__",
"=",
"__extract_singleton_class__",
"(",
"__context__",
")",
"__context_singleton__",
".",
"public_instance_method",
"(",
"method_name",
")",
".",
"bind",
"(",
"__context__",
")",
"end",
"end"
]
| Returns a corresponding public method object of the actual context.
@param method_name [String,Symbol] Method name
@raise [::NameError]
@raise [Symbiont::Trigger::ContextNoMethodError, ::NoMethodError]
@return [Method]
@see [Symbiont::Trigger#method]
@api private
@since 0.5.0 | [
"Returns",
"a",
"corresponding",
"public",
"method",
"object",
"of",
"the",
"actual",
"context",
"."
]
| a514a9a145fda118f2947ed5d82986fb2e18896d | https://github.com/0exp/symbiont-ruby/blob/a514a9a145fda118f2947ed5d82986fb2e18896d/lib/symbiont/public_trigger.rb#L53-L70 | train |
0exp/symbiont-ruby | lib/symbiont/isolator.rb | Symbiont.Isolator.public_method | def public_method(method_name, *required_contexts, direction: default_direction)
public_trigger(*required_contexts, direction: direction).method(method_name)
end | ruby | def public_method(method_name, *required_contexts, direction: default_direction)
public_trigger(*required_contexts, direction: direction).method(method_name)
end | [
"def",
"public_method",
"(",
"method_name",
",",
"*",
"required_contexts",
",",
"direction",
":",
"default_direction",
")",
"public_trigger",
"(",
"*",
"required_contexts",
",",
"direction",
":",
"direction",
")",
".",
"method",
"(",
"method_name",
")",
"end"
]
| Gets the method object taken from the context that can respond to it.
Considers only public methods.
@param method_name [Symbol,String] A name of required method.
@param required_contexts [Array<Object>]
A set of objects that should be used as the main context series for method resolving
algorithm.
@param direction [Array<Symbol>]
An array of symbols that represents the direction of contexts.
@return [Method]
@see Symbiont::PublicTrigger
@see Symbiont::Trigger#method
@api public
@since 0.3.0 | [
"Gets",
"the",
"method",
"object",
"taken",
"from",
"the",
"context",
"that",
"can",
"respond",
"to",
"it",
".",
"Considers",
"only",
"public",
"methods",
"."
]
| a514a9a145fda118f2947ed5d82986fb2e18896d | https://github.com/0exp/symbiont-ruby/blob/a514a9a145fda118f2947ed5d82986fb2e18896d/lib/symbiont/isolator.rb#L107-L109 | train |
0exp/symbiont-ruby | lib/symbiont/isolator.rb | Symbiont.Isolator.private_method | def private_method(method_name, *required_contexts, direction: default_direction)
private_trigger(*required_contexts, direction: direction).method(method_name)
end | ruby | def private_method(method_name, *required_contexts, direction: default_direction)
private_trigger(*required_contexts, direction: direction).method(method_name)
end | [
"def",
"private_method",
"(",
"method_name",
",",
"*",
"required_contexts",
",",
"direction",
":",
"default_direction",
")",
"private_trigger",
"(",
"*",
"required_contexts",
",",
"direction",
":",
"direction",
")",
".",
"method",
"(",
"method_name",
")",
"end"
]
| Gets the method object taken from the context that can respond to it.
Considers private methods and public methods.
@param method_name [Symbol,String] A name of required method.
@param required_contexts [Array<Object>]
A set of objects that should be used as the main context series for method resolving
algorithm.
@param direction [Array<Symbol>]
An array of symbols that represents the direction of contexts.
@return [Method]
@see Symbiont::PrivateTrigger
@see Symbiont::Trigger#method
@api public
@since 0.3.0 | [
"Gets",
"the",
"method",
"object",
"taken",
"from",
"the",
"context",
"that",
"can",
"respond",
"to",
"it",
".",
"Considers",
"private",
"methods",
"and",
"public",
"methods",
"."
]
| a514a9a145fda118f2947ed5d82986fb2e18896d | https://github.com/0exp/symbiont-ruby/blob/a514a9a145fda118f2947ed5d82986fb2e18896d/lib/symbiont/isolator.rb#L127-L129 | train |
0exp/symbiont-ruby | lib/symbiont/isolator.rb | Symbiont.Isolator.public_trigger | def public_trigger(*required_contexts, direction: default_direction)
PublicTrigger.new(*required_contexts, context_direction: direction, &closure)
end | ruby | def public_trigger(*required_contexts, direction: default_direction)
PublicTrigger.new(*required_contexts, context_direction: direction, &closure)
end | [
"def",
"public_trigger",
"(",
"*",
"required_contexts",
",",
"direction",
":",
"default_direction",
")",
"PublicTrigger",
".",
"new",
"(",
"*",
"required_contexts",
",",
"context_direction",
":",
"direction",
",",
"&",
"closure",
")",
"end"
]
| Factory method that instantiates a public trigger with the desired execution context,
the direction of method dispatching and the closure that needs to be performed.
@param required_contexts [Array<Object>]
A set of objects that should be used as the main context series for method resolving
algorithm.
@param direction [Array<Symbol>]
An array of symbols that represents the direction of contexts. Possible values:
- Symbiont::IOK
- Symbiont::OIK
- Symbiont::OKI
- Symbiont::IKO
- Symbiont::KOI
- Symbiont::KIO
@return [Symbiont::PublicTrigger]
@see Symbiont::PublicTrigger
@see Symbiont::Trigger
@api private
@since 0.3.0 | [
"Factory",
"method",
"that",
"instantiates",
"a",
"public",
"trigger",
"with",
"the",
"desired",
"execution",
"context",
"the",
"direction",
"of",
"method",
"dispatching",
"and",
"the",
"closure",
"that",
"needs",
"to",
"be",
"performed",
"."
]
| a514a9a145fda118f2947ed5d82986fb2e18896d | https://github.com/0exp/symbiont-ruby/blob/a514a9a145fda118f2947ed5d82986fb2e18896d/lib/symbiont/isolator.rb#L155-L157 | train |
0exp/symbiont-ruby | lib/symbiont/isolator.rb | Symbiont.Isolator.private_trigger | def private_trigger(*required_contexts, direction: default_direction)
PrivateTrigger.new(*required_contexts, context_direction: direction, &closure)
end | ruby | def private_trigger(*required_contexts, direction: default_direction)
PrivateTrigger.new(*required_contexts, context_direction: direction, &closure)
end | [
"def",
"private_trigger",
"(",
"*",
"required_contexts",
",",
"direction",
":",
"default_direction",
")",
"PrivateTrigger",
".",
"new",
"(",
"*",
"required_contexts",
",",
"context_direction",
":",
"direction",
",",
"&",
"closure",
")",
"end"
]
| Factory method that instantiates a private trigger with the desired execution context,
the direction of method dispatching and the closure that needs to be performed.
@param required_contexts [Array<Object>]
A set of objects that should be used as the main context series for method resolving
algorithm.
@param direction [Array<Symbol>]
An array of symbols that represents the direction of contexts. Possible values:
- Symbiont::IOK
- Symbiont::OIK
- Symbiont::OKI
- Symbiont::IKO
- Symbiont::KOI
- Symbiont::KIO
@return [Symbiont::PrivateTrigger]
@see Symbiont::PrivateTrigger
@see Symbiont::Trigger
@api private
@since 0.3.0 | [
"Factory",
"method",
"that",
"instantiates",
"a",
"private",
"trigger",
"with",
"the",
"desired",
"execution",
"context",
"the",
"direction",
"of",
"method",
"dispatching",
"and",
"the",
"closure",
"that",
"needs",
"to",
"be",
"performed",
"."
]
| a514a9a145fda118f2947ed5d82986fb2e18896d | https://github.com/0exp/symbiont-ruby/blob/a514a9a145fda118f2947ed5d82986fb2e18896d/lib/symbiont/isolator.rb#L181-L183 | train |
kennyp/potracer | lib/potracer.rb | Potracer.Trace.trace | def trace(bitmap = nil, params = nil, &block)
if block_given?
do_trace(bitmap || @bitmap, params || @params, &block)
else
do_trace(bitmap || @bitmap, params || @params)
end
end | ruby | def trace(bitmap = nil, params = nil, &block)
if block_given?
do_trace(bitmap || @bitmap, params || @params, &block)
else
do_trace(bitmap || @bitmap, params || @params)
end
end | [
"def",
"trace",
"(",
"bitmap",
"=",
"nil",
",",
"params",
"=",
"nil",
",",
"&",
"block",
")",
"if",
"block_given?",
"do_trace",
"(",
"bitmap",
"||",
"@bitmap",
",",
"params",
"||",
"@params",
",",
"&",
"block",
")",
"else",
"do_trace",
"(",
"bitmap",
"||",
"@bitmap",
",",
"params",
"||",
"@params",
")",
"end",
"end"
]
| Trace the given +bitmap+
==== Attributes
* +bitmap+ - an instance of Potracer::Bitmap. If not given the +@bitmap+
is used.
* +params+ - an instance of Potracer::Params. If not given +@params+ is
used.
* +block+ - optional block called to report trace progress | [
"Trace",
"the",
"given",
"+",
"bitmap",
"+"
]
| b67d3ff6a1ae672ccc6701fa5245fa532b461ef3 | https://github.com/kennyp/potracer/blob/b67d3ff6a1ae672ccc6701fa5245fa532b461ef3/lib/potracer.rb#L23-L29 | train |
nedap/railjet | lib/railjet/context.rb | Railjet.Context.method_missing | def method_missing(name, *args, &block)
getter_name = name[0..-2]
if name =~ /^[a-z]+=$/ && !respond_to?(getter_name)
define_accessor(getter_name, args.first)
else
super
end
end | ruby | def method_missing(name, *args, &block)
getter_name = name[0..-2]
if name =~ /^[a-z]+=$/ && !respond_to?(getter_name)
define_accessor(getter_name, args.first)
else
super
end
end | [
"def",
"method_missing",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"getter_name",
"=",
"name",
"[",
"0",
"..",
"-",
"2",
"]",
"if",
"name",
"=~",
"/",
"/",
"&&",
"!",
"respond_to?",
"(",
"getter_name",
")",
"define_accessor",
"(",
"getter_name",
",",
"args",
".",
"first",
")",
"else",
"super",
"end",
"end"
]
| New values can be assigned to context on-the-fly,
but it's not possible to change anything. | [
"New",
"values",
"can",
"be",
"assigned",
"to",
"context",
"on",
"-",
"the",
"-",
"fly",
"but",
"it",
"s",
"not",
"possible",
"to",
"change",
"anything",
"."
]
| 38fbf1619eee78af6ae01f9339fdee8881fabbf4 | https://github.com/nedap/railjet/blob/38fbf1619eee78af6ae01f9339fdee8881fabbf4/lib/railjet/context.rb#L9-L17 | train |
lukebayes/project-sprouts | lib/sprout/executable/session.rb | Sprout::Executable.Session.handle_user_input | def handle_user_input
while true
begin
break if !wait_for_prompt
input = $stdin.gets.chomp!
execute_action(input, true)
rescue SignalException => e
return false
end
end
wait
end | ruby | def handle_user_input
while true
begin
break if !wait_for_prompt
input = $stdin.gets.chomp!
execute_action(input, true)
rescue SignalException => e
return false
end
end
wait
end | [
"def",
"handle_user_input",
"while",
"true",
"begin",
"break",
"if",
"!",
"wait_for_prompt",
"input",
"=",
"$stdin",
".",
"gets",
".",
"chomp!",
"execute_action",
"(",
"input",
",",
"true",
")",
"rescue",
"SignalException",
"=>",
"e",
"return",
"false",
"end",
"end",
"wait",
"end"
]
| Expose the running process to manual
input on the terminal, and write stdout
back to the user. | [
"Expose",
"the",
"running",
"process",
"to",
"manual",
"input",
"on",
"the",
"terminal",
"and",
"write",
"stdout",
"back",
"to",
"the",
"user",
"."
]
| 6882d7309d617e35350749df84fac5e7d9c5e843 | https://github.com/lukebayes/project-sprouts/blob/6882d7309d617e35350749df84fac5e7d9c5e843/lib/sprout/executable/session.rb#L225-L236 | train |
lukebayes/project-sprouts | lib/sprout/executable/session.rb | Sprout::Executable.Session.execute_action | def execute_action action, silence=false
action = action.strip
if wait_for_prompt
stdout.puts(action) unless silence
@prompted = false
process_runner.puts action
end
end | ruby | def execute_action action, silence=false
action = action.strip
if wait_for_prompt
stdout.puts(action) unless silence
@prompted = false
process_runner.puts action
end
end | [
"def",
"execute_action",
"action",
",",
"silence",
"=",
"false",
"action",
"=",
"action",
".",
"strip",
"if",
"wait_for_prompt",
"stdout",
".",
"puts",
"(",
"action",
")",
"unless",
"silence",
"@prompted",
"=",
"false",
"process_runner",
".",
"puts",
"action",
"end",
"end"
]
| Execute a single action. | [
"Execute",
"a",
"single",
"action",
"."
]
| 6882d7309d617e35350749df84fac5e7d9c5e843 | https://github.com/lukebayes/project-sprouts/blob/6882d7309d617e35350749df84fac5e7d9c5e843/lib/sprout/executable/session.rb#L304-L311 | train |
alphagov/govuk_message_queue_consumer | lib/govuk_message_queue_consumer/consumer.rb | GovukMessageQueueConsumer.Consumer.run | def run(subscribe_opts: {})
@rabbitmq_connection.start
subscribe_opts = { block: true, manual_ack: true}.merge(subscribe_opts)
queue.subscribe(subscribe_opts) do |delivery_info, headers, payload|
begin
message = Message.new(payload, headers, delivery_info)
@statsd_client.increment("#{@queue_name}.started")
message_consumer.process(message)
@statsd_client.increment("#{@queue_name}.#{message.status}")
rescue Exception => e
@statsd_client.increment("#{@queue_name}.uncaught_exception")
GovukError.notify(e) if defined?(GovukError)
@logger.error "Uncaught exception in processor: \n\n #{e.class}: #{e.message}\n\n#{e.backtrace.join("\n")}"
exit(1) # Ensure rabbitmq requeues outstanding messages
end
end
end | ruby | def run(subscribe_opts: {})
@rabbitmq_connection.start
subscribe_opts = { block: true, manual_ack: true}.merge(subscribe_opts)
queue.subscribe(subscribe_opts) do |delivery_info, headers, payload|
begin
message = Message.new(payload, headers, delivery_info)
@statsd_client.increment("#{@queue_name}.started")
message_consumer.process(message)
@statsd_client.increment("#{@queue_name}.#{message.status}")
rescue Exception => e
@statsd_client.increment("#{@queue_name}.uncaught_exception")
GovukError.notify(e) if defined?(GovukError)
@logger.error "Uncaught exception in processor: \n\n #{e.class}: #{e.message}\n\n#{e.backtrace.join("\n")}"
exit(1) # Ensure rabbitmq requeues outstanding messages
end
end
end | [
"def",
"run",
"(",
"subscribe_opts",
":",
"{",
"}",
")",
"@rabbitmq_connection",
".",
"start",
"subscribe_opts",
"=",
"{",
"block",
":",
"true",
",",
"manual_ack",
":",
"true",
"}",
".",
"merge",
"(",
"subscribe_opts",
")",
"queue",
".",
"subscribe",
"(",
"subscribe_opts",
")",
"do",
"|",
"delivery_info",
",",
"headers",
",",
"payload",
"|",
"begin",
"message",
"=",
"Message",
".",
"new",
"(",
"payload",
",",
"headers",
",",
"delivery_info",
")",
"@statsd_client",
".",
"increment",
"(",
"\"#{@queue_name}.started\"",
")",
"message_consumer",
".",
"process",
"(",
"message",
")",
"@statsd_client",
".",
"increment",
"(",
"\"#{@queue_name}.#{message.status}\"",
")",
"rescue",
"Exception",
"=>",
"e",
"@statsd_client",
".",
"increment",
"(",
"\"#{@queue_name}.uncaught_exception\"",
")",
"GovukError",
".",
"notify",
"(",
"e",
")",
"if",
"defined?",
"(",
"GovukError",
")",
"@logger",
".",
"error",
"\"Uncaught exception in processor: \\n\\n #{e.class}: #{e.message}\\n\\n#{e.backtrace.join(\"\\n\")}\"",
"exit",
"(",
"1",
")",
"end",
"end",
"end"
]
| Create a new consumer
@param queue_name [String] Your queue name. This is specific to your application,
and should already exist and have a binding via puppet
@param processor [Object] An object that responds to `process`
@param rabbitmq_connection [Object] A Bunny connection object derived from `Bunny.new`
@param statsd_client [Statsd] An instance of the Statsd class
@param logger [Object] A Logger object for emitting errors (to stderr by default) | [
"Create",
"a",
"new",
"consumer"
]
| c944ed6273e2c4505a6826ad187a1fa496182a13 | https://github.com/alphagov/govuk_message_queue_consumer/blob/c944ed6273e2c4505a6826ad187a1fa496182a13/lib/govuk_message_queue_consumer/consumer.rb#L29-L46 | train |
lukebayes/project-sprouts | lib/sprout/process_runner.rb | Sprout.ProcessRunner.update_status | def update_status sig=0
pid_int = Integer("#{ @pid }")
begin
Process::kill sig, pid_int
true
rescue Errno::ESRCH
false
end
end | ruby | def update_status sig=0
pid_int = Integer("#{ @pid }")
begin
Process::kill sig, pid_int
true
rescue Errno::ESRCH
false
end
end | [
"def",
"update_status",
"sig",
"=",
"0",
"pid_int",
"=",
"Integer",
"(",
"\"#{ @pid }\"",
")",
"begin",
"Process",
"::",
"kill",
"sig",
",",
"pid_int",
"true",
"rescue",
"Errno",
"::",
"ESRCH",
"false",
"end",
"end"
]
| Send an update signal to the process.
@param sig [Integer] The signal to send, default 0 (or no action requested) | [
"Send",
"an",
"update",
"signal",
"to",
"the",
"process",
"."
]
| 6882d7309d617e35350749df84fac5e7d9c5e843 | https://github.com/lukebayes/project-sprouts/blob/6882d7309d617e35350749df84fac5e7d9c5e843/lib/sprout/process_runner.rb#L93-L101 | train |
xuanxu/random_sources | lib/providers/hot_bits.rb | RandomSources.HotBits.bytes | def bytes(num=10)
num = [[2048, num.to_i].min , 0].max
numbers = []
response = REXML::Document.new( open("https://www.fourmilab.ch/cgi-bin/Hotbits?fmt=xml&nbytes=#{num}"))
status = REXML::XPath.first( response, "//status")
case status.attributes['result'].to_i
when 200
data = REXML::XPath.first( response, "//random-data" ).text.split
data.each{|byte| numbers << byte.hex}
when 503
raise StandardError.new "#{status.text}"
end
numbers
end | ruby | def bytes(num=10)
num = [[2048, num.to_i].min , 0].max
numbers = []
response = REXML::Document.new( open("https://www.fourmilab.ch/cgi-bin/Hotbits?fmt=xml&nbytes=#{num}"))
status = REXML::XPath.first( response, "//status")
case status.attributes['result'].to_i
when 200
data = REXML::XPath.first( response, "//random-data" ).text.split
data.each{|byte| numbers << byte.hex}
when 503
raise StandardError.new "#{status.text}"
end
numbers
end | [
"def",
"bytes",
"(",
"num",
"=",
"10",
")",
"num",
"=",
"[",
"[",
"2048",
",",
"num",
".",
"to_i",
"]",
".",
"min",
",",
"0",
"]",
".",
"max",
"numbers",
"=",
"[",
"]",
"response",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"open",
"(",
"\"https://www.fourmilab.ch/cgi-bin/Hotbits?fmt=xml&nbytes=#{num}\"",
")",
")",
"status",
"=",
"REXML",
"::",
"XPath",
".",
"first",
"(",
"response",
",",
"\"//status\"",
")",
"case",
"status",
".",
"attributes",
"[",
"'result'",
"]",
".",
"to_i",
"when",
"200",
"data",
"=",
"REXML",
"::",
"XPath",
".",
"first",
"(",
"response",
",",
"\"//random-data\"",
")",
".",
"text",
".",
"split",
"data",
".",
"each",
"{",
"|",
"byte",
"|",
"numbers",
"<<",
"byte",
".",
"hex",
"}",
"when",
"503",
"raise",
"StandardError",
".",
"new",
"\"#{status.text}\"",
"end",
"numbers",
"end"
]
| Random bytes generator.
It returns an Array of integers with values between 0 and 255
It receives the number of random bytes to generate (max 2048, default 10) | [
"Random",
"bytes",
"generator",
"."
]
| 8fb43ea50e97191bc5d68b634887b72752f6d63e | https://github.com/xuanxu/random_sources/blob/8fb43ea50e97191bc5d68b634887b72752f6d63e/lib/providers/hot_bits.rb#L31-L46 | train |
lukebayes/project-sprouts | lib/sprout/system/unix_system.rb | Sprout::System.UnixSystem.should_repair_executable | def should_repair_executable path
return (File.exists?(path) && !File.directory?(path) && File.read(path).match(/^\#\!\/bin\/sh/))
end | ruby | def should_repair_executable path
return (File.exists?(path) && !File.directory?(path) && File.read(path).match(/^\#\!\/bin\/sh/))
end | [
"def",
"should_repair_executable",
"path",
"return",
"(",
"File",
".",
"exists?",
"(",
"path",
")",
"&&",
"!",
"File",
".",
"directory?",
"(",
"path",
")",
"&&",
"File",
".",
"read",
"(",
"path",
")",
".",
"match",
"(",
"/",
"\\#",
"\\!",
"\\/",
"\\/",
"/",
")",
")",
"end"
]
| Determine if we should call +repair_executable+
for the file at the provided +path+ String.
Will this corrupt binaries? Yes... Yes. it. will.
This also fails on UTF-8 files since Ruby's regex
appears to choke on UTF-8?? | [
"Determine",
"if",
"we",
"should",
"call",
"+",
"repair_executable",
"+",
"for",
"the",
"file",
"at",
"the",
"provided",
"+",
"path",
"+",
"String",
"."
]
| 6882d7309d617e35350749df84fac5e7d9c5e843 | https://github.com/lukebayes/project-sprouts/blob/6882d7309d617e35350749df84fac5e7d9c5e843/lib/sprout/system/unix_system.rb#L69-L71 | train |
xuanxu/random_sources | lib/providers/random_org.rb | RandomSources.RandomOrg.integers | def integers(options = {})
url_params = { max: clean(options[:max]) || 100,
min: clean(options[:min]) || 1,
num: clean(options[:num]) || 10,
base: clean(options[:base]) || 10,
rnd: 'new',
format: 'plain',
col: 1
}
numbers=[]
check_for_http_errors{
response=open("#{@website}integers/?max=#{url_params[:max]}&min=#{url_params[:min]}&base=#{url_params[:base]}&col=#{url_params[:col]}&rnd=#{url_params[:rnd]}&format=#{url_params[:format]}&num=#{url_params[:num]}")
response.each_line{|line| numbers << line.to_i}
}
numbers
end | ruby | def integers(options = {})
url_params = { max: clean(options[:max]) || 100,
min: clean(options[:min]) || 1,
num: clean(options[:num]) || 10,
base: clean(options[:base]) || 10,
rnd: 'new',
format: 'plain',
col: 1
}
numbers=[]
check_for_http_errors{
response=open("#{@website}integers/?max=#{url_params[:max]}&min=#{url_params[:min]}&base=#{url_params[:base]}&col=#{url_params[:col]}&rnd=#{url_params[:rnd]}&format=#{url_params[:format]}&num=#{url_params[:num]}")
response.each_line{|line| numbers << line.to_i}
}
numbers
end | [
"def",
"integers",
"(",
"options",
"=",
"{",
"}",
")",
"url_params",
"=",
"{",
"max",
":",
"clean",
"(",
"options",
"[",
":max",
"]",
")",
"||",
"100",
",",
"min",
":",
"clean",
"(",
"options",
"[",
":min",
"]",
")",
"||",
"1",
",",
"num",
":",
"clean",
"(",
"options",
"[",
":num",
"]",
")",
"||",
"10",
",",
"base",
":",
"clean",
"(",
"options",
"[",
":base",
"]",
")",
"||",
"10",
",",
"rnd",
":",
"'new'",
",",
"format",
":",
"'plain'",
",",
"col",
":",
"1",
"}",
"numbers",
"=",
"[",
"]",
"check_for_http_errors",
"{",
"response",
"=",
"open",
"(",
"\"#{@website}integers/?max=#{url_params[:max]}&min=#{url_params[:min]}&base=#{url_params[:base]}&col=#{url_params[:col]}&rnd=#{url_params[:rnd]}&format=#{url_params[:format]}&num=#{url_params[:num]}\"",
")",
"response",
".",
"each_line",
"{",
"|",
"line",
"|",
"numbers",
"<<",
"line",
".",
"to_i",
"}",
"}",
"numbers",
"end"
]
| Random Integers Generator.
Configuration options:
* <tt>:num</tt> - The number of integers requested. Posibles values: [1,1e4]. Default: 10
* <tt>:min</tt> - The smallest value allowed for each integer. Posibles values: [-1e9,1e9]. Default: 1
* <tt>:max</tt> - The smallest value allowed for each integer. Posibles values: [-1e9,1e9]. Default: 100
* <tt>:base</tt> - The base that will be used to print the numbers. Posibles values: 2, 8, 10, 16 (binary, octal, decimal or hexadecimal). Default: 10
It returns an Array of integers with the size indicated by <tt>:num</tt>
integers(num: 15, max: 2, min: 200, base: 8) #=> array of 15 base 8 numbers between 2 and 200
integers(num: 4, max: 33) #=> [31, 25, 28, 6] | [
"Random",
"Integers",
"Generator",
"."
]
| 8fb43ea50e97191bc5d68b634887b72752f6d63e | https://github.com/xuanxu/random_sources/blob/8fb43ea50e97191bc5d68b634887b72752f6d63e/lib/providers/random_org.rb#L36-L54 | train |
xuanxu/random_sources | lib/providers/random_org.rb | RandomSources.RandomOrg.sequence | def sequence(min, max)
url_params = { max: clean(max) || 10,
min: clean(min) || 1,
rnd: 'new',
format: 'plain',
col: 1
}
sequence_numbers=[]
check_for_http_errors{
response=open("#{@website}sequences/?max=#{url_params[:max]}&min=#{url_params[:min]}&col=#{url_params[:col]}&rnd=#{url_params[:rnd]}&format=#{url_params[:format]}")
response.each_line{|line| sequence_numbers << line.to_i}
}
sequence_numbers
end | ruby | def sequence(min, max)
url_params = { max: clean(max) || 10,
min: clean(min) || 1,
rnd: 'new',
format: 'plain',
col: 1
}
sequence_numbers=[]
check_for_http_errors{
response=open("#{@website}sequences/?max=#{url_params[:max]}&min=#{url_params[:min]}&col=#{url_params[:col]}&rnd=#{url_params[:rnd]}&format=#{url_params[:format]}")
response.each_line{|line| sequence_numbers << line.to_i}
}
sequence_numbers
end | [
"def",
"sequence",
"(",
"min",
",",
"max",
")",
"url_params",
"=",
"{",
"max",
":",
"clean",
"(",
"max",
")",
"||",
"10",
",",
"min",
":",
"clean",
"(",
"min",
")",
"||",
"1",
",",
"rnd",
":",
"'new'",
",",
"format",
":",
"'plain'",
",",
"col",
":",
"1",
"}",
"sequence_numbers",
"=",
"[",
"]",
"check_for_http_errors",
"{",
"response",
"=",
"open",
"(",
"\"#{@website}sequences/?max=#{url_params[:max]}&min=#{url_params[:min]}&col=#{url_params[:col]}&rnd=#{url_params[:rnd]}&format=#{url_params[:format]}\"",
")",
"response",
".",
"each_line",
"{",
"|",
"line",
"|",
"sequence_numbers",
"<<",
"line",
".",
"to_i",
"}",
"}",
"sequence_numbers",
"end"
]
| The Sequence Generator
It will randomize a given interval of integers, i.e., arrange them in random order.
It needs two params:
* <tt>min</tt> - The lower bound of the interval (inclusive). Posibles values: [-1e9,1e9]
* <tt>max</tt> - The upper bound of the interval (inclusive). Posibles values: [-1e9,1e9]
The length of the sequence (the largest minus the smallest value plus 1) can be no greater than 10,000.
It returns an Array of all the integers of the given interval arranged randomly
sequence(2, 15) #=> [13, 2, 10, 4, 9, 15 ,12, 3, 5, 7, 6, 14, 8, 11] | [
"The",
"Sequence",
"Generator"
]
| 8fb43ea50e97191bc5d68b634887b72752f6d63e | https://github.com/xuanxu/random_sources/blob/8fb43ea50e97191bc5d68b634887b72752f6d63e/lib/providers/random_org.rb#L69-L84 | train |
xuanxu/random_sources | lib/providers/random_org.rb | RandomSources.RandomOrg.strings | def strings(options = {})
url_params = { num: clean(options[:num]) || 10,
len: clean(options[:len]) || 8,
digits: check_on_off(options[:digits]) || 'on',
unique: check_on_off(options[:unique]) || 'on',
upperalpha: check_on_off(options[:upperalpha]) || 'on',
loweralpha: check_on_off(options[:loweralpha]) || 'on',
rnd: 'new',
format: 'plain'
}
strings=[]
check_for_http_errors{
response=open("#{@website}strings/?num=#{url_params[:num]}&len=#{url_params[:len]}&digits=#{url_params[:digits]}&unique=#{url_params[:unique]}&upperalpha=#{url_params[:upperalpha]}&loweralpha=#{url_params[:loweralpha]}&rnd=#{url_params[:rnd]}&format=#{url_params[:format]}")
response.each_line{|line| strings << line.strip}
}
strings
end | ruby | def strings(options = {})
url_params = { num: clean(options[:num]) || 10,
len: clean(options[:len]) || 8,
digits: check_on_off(options[:digits]) || 'on',
unique: check_on_off(options[:unique]) || 'on',
upperalpha: check_on_off(options[:upperalpha]) || 'on',
loweralpha: check_on_off(options[:loweralpha]) || 'on',
rnd: 'new',
format: 'plain'
}
strings=[]
check_for_http_errors{
response=open("#{@website}strings/?num=#{url_params[:num]}&len=#{url_params[:len]}&digits=#{url_params[:digits]}&unique=#{url_params[:unique]}&upperalpha=#{url_params[:upperalpha]}&loweralpha=#{url_params[:loweralpha]}&rnd=#{url_params[:rnd]}&format=#{url_params[:format]}")
response.each_line{|line| strings << line.strip}
}
strings
end | [
"def",
"strings",
"(",
"options",
"=",
"{",
"}",
")",
"url_params",
"=",
"{",
"num",
":",
"clean",
"(",
"options",
"[",
":num",
"]",
")",
"||",
"10",
",",
"len",
":",
"clean",
"(",
"options",
"[",
":len",
"]",
")",
"||",
"8",
",",
"digits",
":",
"check_on_off",
"(",
"options",
"[",
":digits",
"]",
")",
"||",
"'on'",
",",
"unique",
":",
"check_on_off",
"(",
"options",
"[",
":unique",
"]",
")",
"||",
"'on'",
",",
"upperalpha",
":",
"check_on_off",
"(",
"options",
"[",
":upperalpha",
"]",
")",
"||",
"'on'",
",",
"loweralpha",
":",
"check_on_off",
"(",
"options",
"[",
":loweralpha",
"]",
")",
"||",
"'on'",
",",
"rnd",
":",
"'new'",
",",
"format",
":",
"'plain'",
"}",
"strings",
"=",
"[",
"]",
"check_for_http_errors",
"{",
"response",
"=",
"open",
"(",
"\"#{@website}strings/?num=#{url_params[:num]}&len=#{url_params[:len]}&digits=#{url_params[:digits]}&unique=#{url_params[:unique]}&upperalpha=#{url_params[:upperalpha]}&loweralpha=#{url_params[:loweralpha]}&rnd=#{url_params[:rnd]}&format=#{url_params[:format]}\"",
")",
"response",
".",
"each_line",
"{",
"|",
"line",
"|",
"strings",
"<<",
"line",
".",
"strip",
"}",
"}",
"strings",
"end"
]
| Random Strings Generator.
It will generate truly random strings of various length and character compositions.
Configuration options:
* <tt>:num</tt> - The number of strings requested. Posibles values: [1,1e4]. Default: 10
* <tt>:len</tt> - The length of the strings. All the strings produced will have the same length. Posibles values: [1,20]. Default: 8
* <tt>:digits</tt> - Determines whether digits (0-9) are allowed to occur in the strings. Posibles values: ['on', 'off']. Default: on
* <tt>:upperalpha</tt> - Determines whether uppercase alphabetic characters (A-Z) are allowed to occur in the strings. Posibles values: ['on', 'off']. Default: on
* <tt>:loweralpha</tt> - Determines lowercase alphabetic characters (a-z) are allowed to occur in the strings. Posibles values: ['on', 'off']. Default: on
* <tt>:unique</tt> - Determines whether the strings picked should be unique (as a series of raffle tickets drawn from a hat) or not (as a series of die rolls).
If unique is set to on, then there is the additional constraint that the number of strings requested (num) must be less than or equal to the number of strings
that exist with the selected length and characters. Posibles values: ['on', 'off']. Default: on
It returns an Array of Strings of the size indicated with <tt>:num</tt>
strings(num: 15, len: 2, digits: 'off', upperalpha: 'off') #=> array of 15 strings of size 2 composed by diggits and lowercase letters with no repetition.
strings(num: 4, len: 10) #=> ["iloqQz2nGa", "D2mgs12kD6", "yMe1eDsinJ", "ZQPaEol6xr"] | [
"Random",
"Strings",
"Generator",
"."
]
| 8fb43ea50e97191bc5d68b634887b72752f6d63e | https://github.com/xuanxu/random_sources/blob/8fb43ea50e97191bc5d68b634887b72752f6d63e/lib/providers/random_org.rb#L104-L123 | train |
lukebayes/project-sprouts | lib/sprout/file_target.rb | Sprout.FileTarget.add_library | def add_library name, path
if path.is_a?(Array)
path = path.collect { |p| expand_local_path(p) }
else
path = expand_local_path path
end
library = Sprout::Library.new( :name => name, :path => path, :file_target => self )
libraries << library
library
end | ruby | def add_library name, path
if path.is_a?(Array)
path = path.collect { |p| expand_local_path(p) }
else
path = expand_local_path path
end
library = Sprout::Library.new( :name => name, :path => path, :file_target => self )
libraries << library
library
end | [
"def",
"add_library",
"name",
",",
"path",
"if",
"path",
".",
"is_a?",
"(",
"Array",
")",
"path",
"=",
"path",
".",
"collect",
"{",
"|",
"p",
"|",
"expand_local_path",
"(",
"p",
")",
"}",
"else",
"path",
"=",
"expand_local_path",
"path",
"end",
"library",
"=",
"Sprout",
"::",
"Library",
".",
"new",
"(",
":name",
"=>",
"name",
",",
":path",
"=>",
"path",
",",
":file_target",
"=>",
"self",
")",
"libraries",
"<<",
"library",
"library",
"end"
]
| Add a library to the package.
@return [Sprout::Library] The newly created library that was added.
@param name [Symbol] Name that will be used to retrieve this library on +load+.
@param path [File, Path, Array] File or files that will be associated with
this library and copied into the target project library folder when loaded.
(If the path is a directory, all files forward of that directory will be included.) | [
"Add",
"a",
"library",
"to",
"the",
"package",
"."
]
| 6882d7309d617e35350749df84fac5e7d9c5e843 | https://github.com/lukebayes/project-sprouts/blob/6882d7309d617e35350749df84fac5e7d9c5e843/lib/sprout/file_target.rb#L46-L55 | train |
lukebayes/project-sprouts | lib/sprout/file_target.rb | Sprout.FileTarget.add_executable | def add_executable name, path
path = expand_local_path path
executables << OpenStruct.new( :name => name, :path => path, :file_target => self )
end | ruby | def add_executable name, path
path = expand_local_path path
executables << OpenStruct.new( :name => name, :path => path, :file_target => self )
end | [
"def",
"add_executable",
"name",
",",
"path",
"path",
"=",
"expand_local_path",
"path",
"executables",
"<<",
"OpenStruct",
".",
"new",
"(",
":name",
"=>",
"name",
",",
":path",
"=>",
"path",
",",
":file_target",
"=>",
"self",
")",
"end"
]
| Add an executable to the RubyGem package.
@param name [Symbol] that will be used to retrieve this executable later.
@param path [File] relative path to the executable that will be associated
with this name. | [
"Add",
"an",
"executable",
"to",
"the",
"RubyGem",
"package",
"."
]
| 6882d7309d617e35350749df84fac5e7d9c5e843 | https://github.com/lukebayes/project-sprouts/blob/6882d7309d617e35350749df84fac5e7d9c5e843/lib/sprout/file_target.rb#L64-L67 | train |
lukebayes/project-sprouts | lib/sprout/system/base_system.rb | Sprout::System.BaseSystem.execute | def execute(tool, options='')
Sprout.stdout.puts("#{tool} #{options}")
runner = get_and_execute_process_runner(tool, options)
error = runner.read_err
result = runner.read
if(result.size > 0)
Sprout.stdout.puts result
end
if(error.size > 0)
raise Sprout::Errors::ExecutionError.new("[ERROR] #{error}")
end
result || error
end | ruby | def execute(tool, options='')
Sprout.stdout.puts("#{tool} #{options}")
runner = get_and_execute_process_runner(tool, options)
error = runner.read_err
result = runner.read
if(result.size > 0)
Sprout.stdout.puts result
end
if(error.size > 0)
raise Sprout::Errors::ExecutionError.new("[ERROR] #{error}")
end
result || error
end | [
"def",
"execute",
"(",
"tool",
",",
"options",
"=",
"''",
")",
"Sprout",
".",
"stdout",
".",
"puts",
"(",
"\"#{tool} #{options}\"",
")",
"runner",
"=",
"get_and_execute_process_runner",
"(",
"tool",
",",
"options",
")",
"error",
"=",
"runner",
".",
"read_err",
"result",
"=",
"runner",
".",
"read",
"if",
"(",
"result",
".",
"size",
">",
"0",
")",
"Sprout",
".",
"stdout",
".",
"puts",
"result",
"end",
"if",
"(",
"error",
".",
"size",
">",
"0",
")",
"raise",
"Sprout",
"::",
"Errors",
"::",
"ExecutionError",
".",
"new",
"(",
"\"[ERROR] #{error}\"",
")",
"end",
"result",
"||",
"error",
"end"
]
| Creates a new process, executes the command
and returns whatever the process wrote to stdout, or stderr.
Raises a +Sprout::Errors::ExecutionError+ if the process writes to stderr | [
"Creates",
"a",
"new",
"process",
"executes",
"the",
"command",
"and",
"returns",
"whatever",
"the",
"process",
"wrote",
"to",
"stdout",
"or",
"stderr",
"."
]
| 6882d7309d617e35350749df84fac5e7d9c5e843 | https://github.com/lukebayes/project-sprouts/blob/6882d7309d617e35350749df84fac5e7d9c5e843/lib/sprout/system/base_system.rb#L70-L85 | train |
lukebayes/project-sprouts | lib/sprout/system/base_system.rb | Sprout::System.BaseSystem.execute_thread | def execute_thread tool, options='', prompt=nil, &block
t = Thread.new do
Thread.current.abort_on_exception = true
runner = execute_silent(tool, options)
Thread.current['runner'] = runner
out = read_from runner.r, prompt, &block
err = read_from runner.e, prompt, &block
out.join && err.kill
end
# Wait for the runner to be created
# before returning a nil reference
# that never gets populated...
while t['runner'].nil? do
sleep(0.1)
end
if !t.alive?
raise Sprout::Errors::UsageError.new(t['runner'].read_err)
end
t
end | ruby | def execute_thread tool, options='', prompt=nil, &block
t = Thread.new do
Thread.current.abort_on_exception = true
runner = execute_silent(tool, options)
Thread.current['runner'] = runner
out = read_from runner.r, prompt, &block
err = read_from runner.e, prompt, &block
out.join && err.kill
end
# Wait for the runner to be created
# before returning a nil reference
# that never gets populated...
while t['runner'].nil? do
sleep(0.1)
end
if !t.alive?
raise Sprout::Errors::UsageError.new(t['runner'].read_err)
end
t
end | [
"def",
"execute_thread",
"tool",
",",
"options",
"=",
"''",
",",
"prompt",
"=",
"nil",
",",
"&",
"block",
"t",
"=",
"Thread",
".",
"new",
"do",
"Thread",
".",
"current",
".",
"abort_on_exception",
"=",
"true",
"runner",
"=",
"execute_silent",
"(",
"tool",
",",
"options",
")",
"Thread",
".",
"current",
"[",
"'runner'",
"]",
"=",
"runner",
"out",
"=",
"read_from",
"runner",
".",
"r",
",",
"prompt",
",",
"&",
"block",
"err",
"=",
"read_from",
"runner",
".",
"e",
",",
"prompt",
",",
"&",
"block",
"out",
".",
"join",
"&&",
"err",
".",
"kill",
"end",
"while",
"t",
"[",
"'runner'",
"]",
".",
"nil?",
"do",
"sleep",
"(",
"0.1",
")",
"end",
"if",
"!",
"t",
".",
"alive?",
"raise",
"Sprout",
"::",
"Errors",
"::",
"UsageError",
".",
"new",
"(",
"t",
"[",
"'runner'",
"]",
".",
"read_err",
")",
"end",
"t",
"end"
]
| Execute a new process in a separate thread and yield whatever output
is written to its stderr and stdout.
@return [Sprout::ProcessRunner]
@param tool [File] Path to the executable.
@param options [String] The command line options that the executable accepts.
@param prompt [Regex] The prompt that will trigger the listener block to be called.
@yield [String] Message that was received from the process, called when #prompt is encountered. | [
"Execute",
"a",
"new",
"process",
"in",
"a",
"separate",
"thread",
"and",
"yield",
"whatever",
"output",
"is",
"written",
"to",
"its",
"stderr",
"and",
"stdout",
"."
]
| 6882d7309d617e35350749df84fac5e7d9c5e843 | https://github.com/lukebayes/project-sprouts/blob/6882d7309d617e35350749df84fac5e7d9c5e843/lib/sprout/system/base_system.rb#L107-L129 | train |
lukebayes/project-sprouts | lib/sprout/system/base_system.rb | Sprout::System.BaseSystem.get_and_execute_process_runner | def get_and_execute_process_runner tool, options=nil
runner = get_process_runner
runner.execute_open4 clean_path(tool), options
runner
end | ruby | def get_and_execute_process_runner tool, options=nil
runner = get_process_runner
runner.execute_open4 clean_path(tool), options
runner
end | [
"def",
"get_and_execute_process_runner",
"tool",
",",
"options",
"=",
"nil",
"runner",
"=",
"get_process_runner",
"runner",
".",
"execute_open4",
"clean_path",
"(",
"tool",
")",
",",
"options",
"runner",
"end"
]
| Get a process runner and execute the provided +executable+,
with the provided +options+.
+executable+ String path to the external executable file.
+options+ String commandline options to send to the +executable+. | [
"Get",
"a",
"process",
"runner",
"and",
"execute",
"the",
"provided",
"+",
"executable",
"+",
"with",
"the",
"provided",
"+",
"options",
"+",
"."
]
| 6882d7309d617e35350749df84fac5e7d9c5e843 | https://github.com/lukebayes/project-sprouts/blob/6882d7309d617e35350749df84fac5e7d9c5e843/lib/sprout/system/base_system.rb#L255-L259 | train |
lukebayes/project-sprouts | lib/sprout/system/win_system.rb | Sprout::System.WinSystem.get_and_execute_process_runner | def get_and_execute_process_runner tool, options=nil
tool = clean_path find_tool(tool)
runner = get_process_runner
runner.execute_win32 tool, options
runner
end | ruby | def get_and_execute_process_runner tool, options=nil
tool = clean_path find_tool(tool)
runner = get_process_runner
runner.execute_win32 tool, options
runner
end | [
"def",
"get_and_execute_process_runner",
"tool",
",",
"options",
"=",
"nil",
"tool",
"=",
"clean_path",
"find_tool",
"(",
"tool",
")",
"runner",
"=",
"get_process_runner",
"runner",
".",
"execute_win32",
"tool",
",",
"options",
"runner",
"end"
]
| Gets the process runner and calls
platform-specific execute method | [
"Gets",
"the",
"process",
"runner",
"and",
"calls",
"platform",
"-",
"specific",
"execute",
"method"
]
| 6882d7309d617e35350749df84fac5e7d9c5e843 | https://github.com/lukebayes/project-sprouts/blob/6882d7309d617e35350749df84fac5e7d9c5e843/lib/sprout/system/win_system.rb#L55-L60 | train |
cheef/shell-spinner | lib/shell-spinner.rb | ShellSpinner.Runner.build_new_exception | def build_new_exception e
e.class.new(e.message)
rescue
Exception.new e.message
end | ruby | def build_new_exception e
e.class.new(e.message)
rescue
Exception.new e.message
end | [
"def",
"build_new_exception",
"e",
"e",
".",
"class",
".",
"new",
"(",
"e",
".",
"message",
")",
"rescue",
"Exception",
".",
"new",
"e",
".",
"message",
"end"
]
| Needs for cases when custom exceptions needs a several required arguments | [
"Needs",
"for",
"cases",
"when",
"custom",
"exceptions",
"needs",
"a",
"several",
"required",
"arguments"
]
| 4693953da0c714eb839ef5793f0124a080c49bc3 | https://github.com/cheef/shell-spinner/blob/4693953da0c714eb839ef5793f0124a080c49bc3/lib/shell-spinner.rb#L70-L74 | train |
akerl/githubstats | lib/githubstats.rb | GithubStats.User.streak | def streak
return [] if streaks.empty?
streaks.last.last.date >= Date.today - 1 ? streaks.last : []
end | ruby | def streak
return [] if streaks.empty?
streaks.last.last.date >= Date.today - 1 ? streaks.last : []
end | [
"def",
"streak",
"return",
"[",
"]",
"if",
"streaks",
".",
"empty?",
"streaks",
".",
"last",
".",
"last",
".",
"date",
">=",
"Date",
".",
"today",
"-",
"1",
"?",
"streaks",
".",
"last",
":",
"[",
"]",
"end"
]
| Set a custom streaks value that takes into account GitHub,
which makes available streak data for longer than a year | [
"Set",
"a",
"custom",
"streaks",
"value",
"that",
"takes",
"into",
"account",
"GitHub",
"which",
"makes",
"available",
"streak",
"data",
"for",
"longer",
"than",
"a",
"year"
]
| 39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2 | https://github.com/akerl/githubstats/blob/39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2/lib/githubstats.rb#L69-L72 | train |
akerl/githubstats | lib/githubstats.rb | GithubStats.User.guess_user | def guess_user(names = [])
names << Rugged::Config.global['github.user'] if USE_RUGGED
names << ENV['USER']
names.find { |name| name } || (raise 'Failed to guess username')
end | ruby | def guess_user(names = [])
names << Rugged::Config.global['github.user'] if USE_RUGGED
names << ENV['USER']
names.find { |name| name } || (raise 'Failed to guess username')
end | [
"def",
"guess_user",
"(",
"names",
"=",
"[",
"]",
")",
"names",
"<<",
"Rugged",
"::",
"Config",
".",
"global",
"[",
"'github.user'",
"]",
"if",
"USE_RUGGED",
"names",
"<<",
"ENV",
"[",
"'USER'",
"]",
"names",
".",
"find",
"{",
"|",
"name",
"|",
"name",
"}",
"||",
"(",
"raise",
"'Failed to guess username'",
")",
"end"
]
| Guesses the user's name based on system environment | [
"Guesses",
"the",
"user",
"s",
"name",
"based",
"on",
"system",
"environment"
]
| 39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2 | https://github.com/akerl/githubstats/blob/39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2/lib/githubstats.rb#L109-L113 | train |
akerl/githubstats | lib/githubstats.rb | GithubStats.User.real_streak_rewind | def real_streak_rewind(partial_streak)
new_data = download(partial_streak.first.date - 1)
old_data = partial_streak.map(&:to_a)
new_stats = GithubStats::Data.new(new_data + old_data)
partial_streak = new_stats.streaks.last
return partial_streak if partial_streak.first.date != new_stats.start_date
real_streak_rewind partial_streak
end | ruby | def real_streak_rewind(partial_streak)
new_data = download(partial_streak.first.date - 1)
old_data = partial_streak.map(&:to_a)
new_stats = GithubStats::Data.new(new_data + old_data)
partial_streak = new_stats.streaks.last
return partial_streak if partial_streak.first.date != new_stats.start_date
real_streak_rewind partial_streak
end | [
"def",
"real_streak_rewind",
"(",
"partial_streak",
")",
"new_data",
"=",
"download",
"(",
"partial_streak",
".",
"first",
".",
"date",
"-",
"1",
")",
"old_data",
"=",
"partial_streak",
".",
"map",
"(",
"&",
":to_a",
")",
"new_stats",
"=",
"GithubStats",
"::",
"Data",
".",
"new",
"(",
"new_data",
"+",
"old_data",
")",
"partial_streak",
"=",
"new_stats",
".",
"streaks",
".",
"last",
"return",
"partial_streak",
"if",
"partial_streak",
".",
"first",
".",
"date",
"!=",
"new_stats",
".",
"start_date",
"real_streak_rewind",
"partial_streak",
"end"
]
| Set a custom longest_streak that takes into account GitHub's
historical records | [
"Set",
"a",
"custom",
"longest_streak",
"that",
"takes",
"into",
"account",
"GitHub",
"s",
"historical",
"records"
]
| 39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2 | https://github.com/akerl/githubstats/blob/39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2/lib/githubstats.rb#L127-L134 | train |
akerl/githubstats | lib/githubstats.rb | GithubStats.User.download | def download(to_date = nil)
url = to_date ? @url + "?to=#{to_date.strftime('%Y-%m-%d')}" : @url
res = Curl::Easy.perform(url)
code = res.response_code
raise("Failed loading data from GitHub: #{url} #{code}") if code != 200
html = Nokogiri::HTML(res.body_str)
html.css('.day').map do |x|
x.attributes.values_at('data-date', 'data-count').map(&:value)
end
end | ruby | def download(to_date = nil)
url = to_date ? @url + "?to=#{to_date.strftime('%Y-%m-%d')}" : @url
res = Curl::Easy.perform(url)
code = res.response_code
raise("Failed loading data from GitHub: #{url} #{code}") if code != 200
html = Nokogiri::HTML(res.body_str)
html.css('.day').map do |x|
x.attributes.values_at('data-date', 'data-count').map(&:value)
end
end | [
"def",
"download",
"(",
"to_date",
"=",
"nil",
")",
"url",
"=",
"to_date",
"?",
"@url",
"+",
"\"?to=#{to_date.strftime('%Y-%m-%d')}\"",
":",
"@url",
"res",
"=",
"Curl",
"::",
"Easy",
".",
"perform",
"(",
"url",
")",
"code",
"=",
"res",
".",
"response_code",
"raise",
"(",
"\"Failed loading data from GitHub: #{url} #{code}\"",
")",
"if",
"code",
"!=",
"200",
"html",
"=",
"Nokogiri",
"::",
"HTML",
"(",
"res",
".",
"body_str",
")",
"html",
".",
"css",
"(",
"'.day'",
")",
".",
"map",
"do",
"|",
"x",
"|",
"x",
".",
"attributes",
".",
"values_at",
"(",
"'data-date'",
",",
"'data-count'",
")",
".",
"map",
"(",
"&",
":value",
")",
"end",
"end"
]
| Downloads new data from Github | [
"Downloads",
"new",
"data",
"from",
"Github"
]
| 39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2 | https://github.com/akerl/githubstats/blob/39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2/lib/githubstats.rb#L143-L152 | train |
airslie/renalware-core | app/models/renalware/patient.rb | Renalware.Patient.to_s | def to_s(format = :default)
title_suffix = " (#{title})" if has_title?
formatted_name = "#{family_name.upcase}, #{given_name}#{title_suffix}"
formatted_nhs_number = " (#{nhs_number})" if nhs_number.present?
case format
when :default then formatted_name
when :long then "#{formatted_name}#{formatted_nhs_number}"
else full_name
end
end | ruby | def to_s(format = :default)
title_suffix = " (#{title})" if has_title?
formatted_name = "#{family_name.upcase}, #{given_name}#{title_suffix}"
formatted_nhs_number = " (#{nhs_number})" if nhs_number.present?
case format
when :default then formatted_name
when :long then "#{formatted_name}#{formatted_nhs_number}"
else full_name
end
end | [
"def",
"to_s",
"(",
"format",
"=",
":default",
")",
"title_suffix",
"=",
"\" (#{title})\"",
"if",
"has_title?",
"formatted_name",
"=",
"\"#{family_name.upcase}, #{given_name}#{title_suffix}\"",
"formatted_nhs_number",
"=",
"\" (#{nhs_number})\"",
"if",
"nhs_number",
".",
"present?",
"case",
"format",
"when",
":default",
"then",
"formatted_name",
"when",
":long",
"then",
"\"#{formatted_name}#{formatted_nhs_number}\"",
"else",
"full_name",
"end",
"end"
]
| Overrides Personable mixin | [
"Overrides",
"Personable",
"mixin"
]
| 07f20ed4071fc88666590c43a848e7413d5e384b | https://github.com/airslie/renalware-core/blob/07f20ed4071fc88666590c43a848e7413d5e384b/app/models/renalware/patient.rb#L120-L129 | train |
auser/poolparty | lib/cloud_providers/connections.rb | CloudProviders.Connections.ssh_cleanup_known_hosts! | def ssh_cleanup_known_hosts!(hosts=[host, public_ip])
hosts = [hosts] unless hosts.respond_to? :each
hosts.compact.each do |name|
system_run "ssh-keygen -R %s" % name
end
end | ruby | def ssh_cleanup_known_hosts!(hosts=[host, public_ip])
hosts = [hosts] unless hosts.respond_to? :each
hosts.compact.each do |name|
system_run "ssh-keygen -R %s" % name
end
end | [
"def",
"ssh_cleanup_known_hosts!",
"(",
"hosts",
"=",
"[",
"host",
",",
"public_ip",
"]",
")",
"hosts",
"=",
"[",
"hosts",
"]",
"unless",
"hosts",
".",
"respond_to?",
":each",
"hosts",
".",
"compact",
".",
"each",
"do",
"|",
"name",
"|",
"system_run",
"\"ssh-keygen -R %s\"",
"%",
"name",
"end",
"end"
]
| remove hostname and corresponding from known_hosts file. Avoids warning when reusing elastic_ip, and
less likely, if amazone reassigns ip. By default removes both dns_name and ip | [
"remove",
"hostname",
"and",
"corresponding",
"from",
"known_hosts",
"file",
".",
"Avoids",
"warning",
"when",
"reusing",
"elastic_ip",
"and",
"less",
"likely",
"if",
"amazone",
"reassigns",
"ip",
".",
"By",
"default",
"removes",
"both",
"dns_name",
"and",
"ip"
]
| 8b4af051833addd84f4282bcedbdffa814d8e033 | https://github.com/auser/poolparty/blob/8b4af051833addd84f4282bcedbdffa814d8e033/lib/cloud_providers/connections.rb#L83-L88 | train |
akerl/githubstats | lib/githubstats/data.rb | GithubStats.Data.to_h | def to_h
@raw.reduce(Hash.new(0)) do |acc, elem|
acc.merge(elem.date => elem.score)
end
end | ruby | def to_h
@raw.reduce(Hash.new(0)) do |acc, elem|
acc.merge(elem.date => elem.score)
end
end | [
"def",
"to_h",
"@raw",
".",
"reduce",
"(",
"Hash",
".",
"new",
"(",
"0",
")",
")",
"do",
"|",
"acc",
",",
"elem",
"|",
"acc",
".",
"merge",
"(",
"elem",
".",
"date",
"=>",
"elem",
".",
"score",
")",
"end",
"end"
]
| Create a data object and turn on caching
The data as a hash where the keys are dates and values are scores | [
"Create",
"a",
"data",
"object",
"and",
"turn",
"on",
"caching"
]
| 39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2 | https://github.com/akerl/githubstats/blob/39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2/lib/githubstats/data.rb#L45-L49 | train |
akerl/githubstats | lib/githubstats/data.rb | GithubStats.Data.streaks | def streaks
streaks = @raw.each_with_object(Array.new(1, [])) do |point, acc|
point.score.zero? ? acc << [] : acc.last << point
end
streaks.reject!(&:empty?)
streaks
end | ruby | def streaks
streaks = @raw.each_with_object(Array.new(1, [])) do |point, acc|
point.score.zero? ? acc << [] : acc.last << point
end
streaks.reject!(&:empty?)
streaks
end | [
"def",
"streaks",
"streaks",
"=",
"@raw",
".",
"each_with_object",
"(",
"Array",
".",
"new",
"(",
"1",
",",
"[",
"]",
")",
")",
"do",
"|",
"point",
",",
"acc",
"|",
"point",
".",
"score",
".",
"zero?",
"?",
"acc",
"<<",
"[",
"]",
":",
"acc",
".",
"last",
"<<",
"point",
"end",
"streaks",
".",
"reject!",
"(",
"&",
":empty?",
")",
"streaks",
"end"
]
| All streaks for a user | [
"All",
"streaks",
"for",
"a",
"user"
]
| 39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2 | https://github.com/akerl/githubstats/blob/39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2/lib/githubstats/data.rb#L88-L94 | train |
akerl/githubstats | lib/githubstats/data.rb | GithubStats.Data.outliers | def outliers
return [] if scores.uniq.size < 5
scores.select { |x| ((mean - x) / std_var).abs > GITHUB_MAGIC }.uniq
end | ruby | def outliers
return [] if scores.uniq.size < 5
scores.select { |x| ((mean - x) / std_var).abs > GITHUB_MAGIC }.uniq
end | [
"def",
"outliers",
"return",
"[",
"]",
"if",
"scores",
".",
"uniq",
".",
"size",
"<",
"5",
"scores",
".",
"select",
"{",
"|",
"x",
"|",
"(",
"(",
"mean",
"-",
"x",
")",
"/",
"std_var",
")",
".",
"abs",
">",
"GITHUB_MAGIC",
"}",
".",
"uniq",
"end"
]
| Outliers of the set | [
"Outliers",
"of",
"the",
"set"
]
| 39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2 | https://github.com/akerl/githubstats/blob/39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2/lib/githubstats/data.rb#L139-L142 | train |
akerl/githubstats | lib/githubstats/data.rb | GithubStats.Data.quartiles | def quartiles
quartiles = Array.new(5) { [] }
@raw.each_with_object(quartiles) do |elem, acc|
acc[quartile(elem.score)] << elem
end
end | ruby | def quartiles
quartiles = Array.new(5) { [] }
@raw.each_with_object(quartiles) do |elem, acc|
acc[quartile(elem.score)] << elem
end
end | [
"def",
"quartiles",
"quartiles",
"=",
"Array",
".",
"new",
"(",
"5",
")",
"{",
"[",
"]",
"}",
"@raw",
".",
"each_with_object",
"(",
"quartiles",
")",
"do",
"|",
"elem",
",",
"acc",
"|",
"acc",
"[",
"quartile",
"(",
"elem",
".",
"score",
")",
"]",
"<<",
"elem",
"end",
"end"
]
| Return the list split into quartiles | [
"Return",
"the",
"list",
"split",
"into",
"quartiles"
]
| 39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2 | https://github.com/akerl/githubstats/blob/39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2/lib/githubstats/data.rb#L172-L177 | train |
akerl/githubstats | lib/githubstats/data.rb | GithubStats.Data.quartile | def quartile(score)
return nil if score < 0 || score > max.score
quartile_boundaries.count { |bound| score > bound }
end | ruby | def quartile(score)
return nil if score < 0 || score > max.score
quartile_boundaries.count { |bound| score > bound }
end | [
"def",
"quartile",
"(",
"score",
")",
"return",
"nil",
"if",
"score",
"<",
"0",
"||",
"score",
">",
"max",
".",
"score",
"quartile_boundaries",
".",
"count",
"{",
"|",
"bound",
"|",
"score",
">",
"bound",
"}",
"end"
]
| Return the quartile of a given score | [
"Return",
"the",
"quartile",
"of",
"a",
"given",
"score"
]
| 39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2 | https://github.com/akerl/githubstats/blob/39ac2383a6e7b83e36ea5f8ac67a0fdb74f4f5c2/lib/githubstats/data.rb#L182-L185 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.