repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.analysis
def analysis @analysis ||= Hash.new do |h, time| time = time.to_sym times = @times[time] h[time] = MoreMath::Sequence.new(times) end end
ruby
def analysis @analysis ||= Hash.new do |h, time| time = time.to_sym times = @times[time] h[time] = MoreMath::Sequence.new(times) end end
[ "def", "analysis", "@analysis", "||=", "Hash", ".", "new", "do", "|", "h", ",", "time", "|", "time", "=", "time", ".", "to_sym", "times", "=", "@times", "[", "time", "]", "h", "[", "time", "]", "=", "MoreMath", "::", "Sequence", ".", "new", "(", "times", ")", "end", "end" ]
Returns a Hash of Sequence object for all of TIMES's time keys.
[ "Returns", "a", "Hash", "of", "Sequence", "object", "for", "all", "of", "TIMES", "s", "time", "keys", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L181-L187
train
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.cover?
def cover?(other) time = self.case.compare_time.to_sym analysis[time].cover?(other.analysis[time], self.case.covering.alpha_level.abs) end
ruby
def cover?(other) time = self.case.compare_time.to_sym analysis[time].cover?(other.analysis[time], self.case.covering.alpha_level.abs) end
[ "def", "cover?", "(", "other", ")", "time", "=", "self", ".", "case", ".", "compare_time", ".", "to_sym", "analysis", "[", "time", "]", ".", "cover?", "(", "other", ".", "analysis", "[", "time", "]", ",", "self", ".", "case", ".", "covering", ".", "alpha_level", ".", "abs", ")", "end" ]
Return true, if other's mean value is indistinguishable from this object's mean after filtering out the noise from the measurements with a Welch's t-Test. This mean's that differences in the mean of both clocks might not inidicate a real performance difference and may be caused by chance.
[ "Return", "true", "if", "other", "s", "mean", "value", "is", "indistinguishable", "from", "this", "object", "s", "mean", "after", "filtering", "out", "the", "noise", "from", "the", "measurements", "with", "a", "Welch", "s", "t", "-", "Test", ".", "This", "mean", "s", "that", "differences", "in", "the", "mean", "of", "both", "clocks", "might", "not", "inidicate", "a", "real", "performance", "difference", "and", "may", "be", "caused", "by", "chance", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L194-L197
train
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.to_a
def to_a if @repeat >= 1 (::Bullshit::Clock::ALL_COLUMNS).map do |t| analysis[t].elements end.transpose else [] end end
ruby
def to_a if @repeat >= 1 (::Bullshit::Clock::ALL_COLUMNS).map do |t| analysis[t].elements end.transpose else [] end end
[ "def", "to_a", "if", "@repeat", ">=", "1", "(", "::", "Bullshit", "::", "Clock", "::", "ALL_COLUMNS", ")", ".", "map", "do", "|", "t", "|", "analysis", "[", "t", "]", ".", "elements", "end", ".", "transpose", "else", "[", "]", "end", "end" ]
Returns the measurements as an array of arrays.
[ "Returns", "the", "measurements", "as", "an", "array", "of", "arrays", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L205-L213
train
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.take_time
def take_time @time, times = Time.now, Process.times user_time = times.utime + times.cutime # user time of this process and its children system_time = times.stime + times.cstime # system time of this process and its children total_time = user_time + system_time # total time of this process and its children [ @time.to_f, total_time, user_time, system_time ] end
ruby
def take_time @time, times = Time.now, Process.times user_time = times.utime + times.cutime # user time of this process and its children system_time = times.stime + times.cstime # system time of this process and its children total_time = user_time + system_time # total time of this process and its children [ @time.to_f, total_time, user_time, system_time ] end
[ "def", "take_time", "@time", ",", "times", "=", "Time", ".", "now", ",", "Process", ".", "times", "user_time", "=", "times", ".", "utime", "+", "times", ".", "cutime", "system_time", "=", "times", ".", "stime", "+", "times", ".", "cstime", "total_time", "=", "user_time", "+", "system_time", "[", "@time", ".", "to_f", ",", "total_time", ",", "user_time", ",", "system_time", "]", "end" ]
Takes the times an returns an array, consisting of the times in the order of enumerated in the TIMES constant.
[ "Takes", "the", "times", "an", "returns", "an", "array", "consisting", "of", "the", "times", "in", "the", "order", "of", "enumerated", "in", "the", "TIMES", "constant", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L217-L223
train
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.measure
def measure before = take_time yield after = take_time @repeat += 1 @times[:repeat] << @repeat @times[:scatter] << @scatter bs = self.case.batch_size.abs if bs and bs > 1 TIMES.each_with_index { |t, i| @times[t] << (after[i] - before[i]) / bs } else TIMES.each_with_index { |t, i| @times[t] << after[i] - before[i] } end @analysis = nil end
ruby
def measure before = take_time yield after = take_time @repeat += 1 @times[:repeat] << @repeat @times[:scatter] << @scatter bs = self.case.batch_size.abs if bs and bs > 1 TIMES.each_with_index { |t, i| @times[t] << (after[i] - before[i]) / bs } else TIMES.each_with_index { |t, i| @times[t] << after[i] - before[i] } end @analysis = nil end
[ "def", "measure", "before", "=", "take_time", "yield", "after", "=", "take_time", "@repeat", "+=", "1", "@times", "[", ":repeat", "]", "<<", "@repeat", "@times", "[", ":scatter", "]", "<<", "@scatter", "bs", "=", "self", ".", "case", ".", "batch_size", ".", "abs", "if", "bs", "and", "bs", ">", "1", "TIMES", ".", "each_with_index", "{", "|", "t", ",", "i", "|", "@times", "[", "t", "]", "<<", "(", "after", "[", "i", "]", "-", "before", "[", "i", "]", ")", "/", "bs", "}", "else", "TIMES", ".", "each_with_index", "{", "|", "t", ",", "i", "|", "@times", "[", "t", "]", "<<", "after", "[", "i", "]", "-", "before", "[", "i", "]", "}", "end", "@analysis", "=", "nil", "end" ]
Take a single measurement. This method should be called with the code to benchmark in a block.
[ "Take", "a", "single", "measurement", ".", "This", "method", "should", "be", "called", "with", "the", "code", "to", "benchmark", "in", "a", "block", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L232-L246
train
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.detect_autocorrelation
def detect_autocorrelation(time) analysis[time.to_sym].detect_autocorrelation( self.case.autocorrelation.max_lags.to_i, self.case.autocorrelation.alpha_level.abs) end
ruby
def detect_autocorrelation(time) analysis[time.to_sym].detect_autocorrelation( self.case.autocorrelation.max_lags.to_i, self.case.autocorrelation.alpha_level.abs) end
[ "def", "detect_autocorrelation", "(", "time", ")", "analysis", "[", "time", ".", "to_sym", "]", ".", "detect_autocorrelation", "(", "self", ".", "case", ".", "autocorrelation", ".", "max_lags", ".", "to_i", ",", "self", ".", "case", ".", "autocorrelation", ".", "alpha_level", ".", "abs", ")", "end" ]
Returns the q value for the Ljung-Box statistic of this +time+'s analysis.detect_autocorrelation method.
[ "Returns", "the", "q", "value", "for", "the", "Ljung", "-", "Box", "statistic", "of", "this", "+", "time", "+", "s", "analysis", ".", "detect_autocorrelation", "method", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L282-L286
train
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.autocorrelation_plot
def autocorrelation_plot(time) r = autocorrelation time start = @times[:repeat].first ende = (start + r.size) (start...ende).to_a.zip(r) end
ruby
def autocorrelation_plot(time) r = autocorrelation time start = @times[:repeat].first ende = (start + r.size) (start...ende).to_a.zip(r) end
[ "def", "autocorrelation_plot", "(", "time", ")", "r", "=", "autocorrelation", "time", "start", "=", "@times", "[", ":repeat", "]", ".", "first", "ende", "=", "(", "start", "+", "r", ".", "size", ")", "(", "start", "...", "ende", ")", ".", "to_a", ".", "zip", "(", "r", ")", "end" ]
Returns the arrays for the autocorrelation plot, the first array for the numbers of lag measured, the second for the autocorrelation value.
[ "Returns", "the", "arrays", "for", "the", "autocorrelation", "plot", "the", "first", "array", "for", "the", "numbers", "of", "lag", "measured", "the", "second", "for", "the", "autocorrelation", "value", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L365-L370
train
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.truncate_data
def truncate_data(offset) for t in ALL_COLUMNS times = @times[t] @times[t] = @times[t][offset, times.size] @repeat = @times[t].size end @analysis = nil self end
ruby
def truncate_data(offset) for t in ALL_COLUMNS times = @times[t] @times[t] = @times[t][offset, times.size] @repeat = @times[t].size end @analysis = nil self end
[ "def", "truncate_data", "(", "offset", ")", "for", "t", "in", "ALL_COLUMNS", "times", "=", "@times", "[", "t", "]", "@times", "[", "t", "]", "=", "@times", "[", "t", "]", "[", "offset", ",", "times", ".", "size", "]", "@repeat", "=", "@times", "[", "t", "]", ".", "size", "end", "@analysis", "=", "nil", "self", "end" ]
Truncate the measurements stored in this clock starting from the integer +offset+.
[ "Truncate", "the", "measurements", "stored", "in", "this", "clock", "starting", "from", "the", "integer", "+", "offset", "+", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L379-L387
train
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.find_truncation_offset
def find_truncation_offset truncation = self.case.truncate_data slope_angle = self.case.truncate_data.slope_angle.abs time = self.case.compare_time.to_sym ms = analysis[time].elements.reverse offset = ms.size - 1 @slopes = [] ModuleFunctions.array_window(ms, truncation.window_size) do |data| lr = LinearRegression.new(data) a = lr.a @slopes << [ offset, a ] a.abs > slope_angle and break offset -= 1 end offset < 0 ? 0 : offset end
ruby
def find_truncation_offset truncation = self.case.truncate_data slope_angle = self.case.truncate_data.slope_angle.abs time = self.case.compare_time.to_sym ms = analysis[time].elements.reverse offset = ms.size - 1 @slopes = [] ModuleFunctions.array_window(ms, truncation.window_size) do |data| lr = LinearRegression.new(data) a = lr.a @slopes << [ offset, a ] a.abs > slope_angle and break offset -= 1 end offset < 0 ? 0 : offset end
[ "def", "find_truncation_offset", "truncation", "=", "self", ".", "case", ".", "truncate_data", "slope_angle", "=", "self", ".", "case", ".", "truncate_data", ".", "slope_angle", ".", "abs", "time", "=", "self", ".", "case", ".", "compare_time", ".", "to_sym", "ms", "=", "analysis", "[", "time", "]", ".", "elements", ".", "reverse", "offset", "=", "ms", ".", "size", "-", "1", "@slopes", "=", "[", "]", "ModuleFunctions", ".", "array_window", "(", "ms", ",", "truncation", ".", "window_size", ")", "do", "|", "data", "|", "lr", "=", "LinearRegression", ".", "new", "(", "data", ")", "a", "=", "lr", ".", "a", "@slopes", "<<", "[", "offset", ",", "a", "]", "a", ".", "abs", ">", "slope_angle", "and", "break", "offset", "-=", "1", "end", "offset", "<", "0", "?", "0", ":", "offset", "end" ]
Find an offset from the start of the measurements in this clock to truncate the initial data until a stable state has been reached and return it as an integer.
[ "Find", "an", "offset", "from", "the", "start", "of", "the", "measurements", "in", "this", "clock", "to", "truncate", "the", "initial", "data", "until", "a", "stable", "state", "has", "been", "reached", "and", "return", "it", "as", "an", "integer", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L392-L407
train
flori/bullshit
lib/bullshit.rb
Bullshit.CaseMethod.load
def load(fp = file_path) self.clock = self.case.class.clock.new self $DEBUG and warn "Loading '#{fp}' into clock." File.open(fp, 'r') do |f| f.each do |line| line.chomp! line =~ /^\s*#/ and next clock << line.split(/\t/) end end self rescue Errno::ENOENT end
ruby
def load(fp = file_path) self.clock = self.case.class.clock.new self $DEBUG and warn "Loading '#{fp}' into clock." File.open(fp, 'r') do |f| f.each do |line| line.chomp! line =~ /^\s*#/ and next clock << line.split(/\t/) end end self rescue Errno::ENOENT end
[ "def", "load", "(", "fp", "=", "file_path", ")", "self", ".", "clock", "=", "self", ".", "case", ".", "class", ".", "clock", ".", "new", "self", "$DEBUG", "and", "warn", "\"Loading '#{fp}' into clock.\"", "File", ".", "open", "(", "fp", ",", "'r'", ")", "do", "|", "f", "|", "f", ".", "each", "do", "|", "line", "|", "line", ".", "chomp!", "line", "=~", "/", "\\s", "/", "and", "next", "clock", "<<", "line", ".", "split", "(", "/", "\\t", "/", ")", "end", "end", "self", "rescue", "Errno", "::", "ENOENT", "end" ]
Load the data of file +fp+ into this clock.
[ "Load", "the", "data", "of", "file", "+", "fp", "+", "into", "this", "clock", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L481-L493
train
flori/bullshit
lib/bullshit.rb
Bullshit.Case.longest_name
def longest_name bmethods.empty? and return 0 bmethods.map { |x| x.short_name.size }.max end
ruby
def longest_name bmethods.empty? and return 0 bmethods.map { |x| x.short_name.size }.max end
[ "def", "longest_name", "bmethods", ".", "empty?", "and", "return", "0", "bmethods", ".", "map", "{", "|", "x", "|", "x", ".", "short_name", ".", "size", "}", ".", "max", "end" ]
Return the length of the longest_name of all these methods' names.
[ "Return", "the", "length", "of", "the", "longest_name", "of", "all", "these", "methods", "names", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L745-L748
train
flori/bullshit
lib/bullshit.rb
Bullshit.Case.pre_run
def pre_run(bc_method) setup_name = bc_method.setup_name if respond_to? setup_name $DEBUG and warn "Calling #{setup_name}." __send__(setup_name) end self.class.output.puts "#{bc_method.long_name}:" end
ruby
def pre_run(bc_method) setup_name = bc_method.setup_name if respond_to? setup_name $DEBUG and warn "Calling #{setup_name}." __send__(setup_name) end self.class.output.puts "#{bc_method.long_name}:" end
[ "def", "pre_run", "(", "bc_method", ")", "setup_name", "=", "bc_method", ".", "setup_name", "if", "respond_to?", "setup_name", "$DEBUG", "and", "warn", "\"Calling #{setup_name}.\"", "__send__", "(", "setup_name", ")", "end", "self", ".", "class", ".", "output", ".", "puts", "\"#{bc_method.long_name}:\"", "end" ]
Output before +bc_method+ is run.
[ "Output", "before", "+", "bc_method", "+", "is", "run", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L885-L892
train
flori/bullshit
lib/bullshit.rb
Bullshit.Case.run_method
def run_method(bc_method) pre_run bc_method clock = self.class.clock.__send__(self.class.clock_method, bc_method) do __send__(bc_method.name) end bc_method.clock = clock post_run bc_method clock end
ruby
def run_method(bc_method) pre_run bc_method clock = self.class.clock.__send__(self.class.clock_method, bc_method) do __send__(bc_method.name) end bc_method.clock = clock post_run bc_method clock end
[ "def", "run_method", "(", "bc_method", ")", "pre_run", "bc_method", "clock", "=", "self", ".", "class", ".", "clock", ".", "__send__", "(", "self", ".", "class", ".", "clock_method", ",", "bc_method", ")", "do", "__send__", "(", "bc_method", ".", "name", ")", "end", "bc_method", ".", "clock", "=", "clock", "post_run", "bc_method", "clock", "end" ]
Run only pre_run and post_run methods. Yield to the block, if one was given.
[ "Run", "only", "pre_run", "and", "post_run", "methods", ".", "Yield", "to", "the", "block", "if", "one", "was", "given", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L896-L904
train
flori/bullshit
lib/bullshit.rb
Bullshit.Case.post_run
def post_run(bc_method) teardown_name = bc_method.teardown_name if respond_to? teardown_name $DEBUG and warn "Calling #{teardown_name}." __send__(bc_method.teardown_name) end end
ruby
def post_run(bc_method) teardown_name = bc_method.teardown_name if respond_to? teardown_name $DEBUG and warn "Calling #{teardown_name}." __send__(bc_method.teardown_name) end end
[ "def", "post_run", "(", "bc_method", ")", "teardown_name", "=", "bc_method", ".", "teardown_name", "if", "respond_to?", "teardown_name", "$DEBUG", "and", "warn", "\"Calling #{teardown_name}.\"", "__send__", "(", "bc_method", ".", "teardown_name", ")", "end", "end" ]
Output after +bc_method+ is run.
[ "Output", "after", "+", "bc_method", "+", "is", "run", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L913-L919
train
flori/bullshit
lib/bullshit.rb
Bullshit.Comparison.output_filename
def output_filename(name) path = File.expand_path(name, output_dir) output File.new(path, 'a+') end
ruby
def output_filename(name) path = File.expand_path(name, output_dir) output File.new(path, 'a+') end
[ "def", "output_filename", "(", "name", ")", "path", "=", "File", ".", "expand_path", "(", "name", ",", "output_dir", ")", "output", "File", ".", "new", "(", "path", ",", "'a+'", ")", "end" ]
Output results to the file named +name+.
[ "Output", "results", "to", "the", "file", "named", "+", "name", "+", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L1162-L1165
train
SebastianSzturo/inaho
lib/inaho/dictionary.rb
Inaho.Dictionary.validate
def validate errors = [] schema_path = File.expand_path("../../../vendor/AppleDictionarySchema.rng", __FILE__) schema = Nokogiri::XML::RelaxNG(File.open(schema_path)) schema.validate(Nokogiri::XML(self.to_xml)).each do |error| errors << error end if errors.size > 0 return errors else return true end end
ruby
def validate errors = [] schema_path = File.expand_path("../../../vendor/AppleDictionarySchema.rng", __FILE__) schema = Nokogiri::XML::RelaxNG(File.open(schema_path)) schema.validate(Nokogiri::XML(self.to_xml)).each do |error| errors << error end if errors.size > 0 return errors else return true end end
[ "def", "validate", "errors", "=", "[", "]", "schema_path", "=", "File", ".", "expand_path", "(", "\"../../../vendor/AppleDictionarySchema.rng\"", ",", "__FILE__", ")", "schema", "=", "Nokogiri", "::", "XML", "::", "RelaxNG", "(", "File", ".", "open", "(", "schema_path", ")", ")", "schema", ".", "validate", "(", "Nokogiri", "::", "XML", "(", "self", ".", "to_xml", ")", ")", ".", "each", "do", "|", "error", "|", "errors", "<<", "error", "end", "if", "errors", ".", "size", ">", "0", "return", "errors", "else", "return", "true", "end", "end" ]
Validate Dictionary xml with Apple's RelaxNG schema. Returns true if xml is valid. Returns List of Nokogiri::XML::SyntaxError objects if xml is not valid.
[ "Validate", "Dictionary", "xml", "with", "Apple", "s", "RelaxNG", "schema", "." ]
e3664bc59aa90197258d715a9032c18f82b84ebd
https://github.com/SebastianSzturo/inaho/blob/e3664bc59aa90197258d715a9032c18f82b84ebd/lib/inaho/dictionary.rb#L33-L47
train
SebastianSzturo/inaho
lib/inaho/dictionary.rb
Inaho.Dictionary.to_xml
def to_xml xml = "" xml << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" xml << "<d:dictionary xmlns=\"http://www.w3.org/1999/xhtml\" " xml << "xmlns:d=\"http://www.apple.com/DTDs/DictionaryService-1.0.rng\">\n" @entries.each do |entry| next if entry.to_xml.nil? xml << entry.to_xml end xml << "</d:dictionary>" return xml end
ruby
def to_xml xml = "" xml << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" xml << "<d:dictionary xmlns=\"http://www.w3.org/1999/xhtml\" " xml << "xmlns:d=\"http://www.apple.com/DTDs/DictionaryService-1.0.rng\">\n" @entries.each do |entry| next if entry.to_xml.nil? xml << entry.to_xml end xml << "</d:dictionary>" return xml end
[ "def", "to_xml", "xml", "=", "\"\"", "xml", "<<", "\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"", "xml", "<<", "\"<d:dictionary xmlns=\\\"http://www.w3.org/1999/xhtml\\\" \"", "xml", "<<", "\"xmlns:d=\\\"http://www.apple.com/DTDs/DictionaryService-1.0.rng\\\">\\n\"", "@entries", ".", "each", "do", "|", "entry", "|", "next", "if", "entry", ".", "to_xml", ".", "nil?", "xml", "<<", "entry", ".", "to_xml", "end", "xml", "<<", "\"</d:dictionary>\"", "return", "xml", "end" ]
Generates xml for Dictionary and Entry objects. Returns String.
[ "Generates", "xml", "for", "Dictionary", "and", "Entry", "objects", "." ]
e3664bc59aa90197258d715a9032c18f82b84ebd
https://github.com/SebastianSzturo/inaho/blob/e3664bc59aa90197258d715a9032c18f82b84ebd/lib/inaho/dictionary.rb#L52-L65
train
wilddima/stribog
lib/stribog/create_hash.rb
Stribog.CreateHash.return_hash
def return_hash(final_vector) case digest_length when 512 create_digest(final_vector) when 256 create_digest(vector_from_array(final_vector[0..31])) else raise ArgumentError, "digest length must be equal to 256 or 512, not #{digest_length}" end end
ruby
def return_hash(final_vector) case digest_length when 512 create_digest(final_vector) when 256 create_digest(vector_from_array(final_vector[0..31])) else raise ArgumentError, "digest length must be equal to 256 or 512, not #{digest_length}" end end
[ "def", "return_hash", "(", "final_vector", ")", "case", "digest_length", "when", "512", "create_digest", "(", "final_vector", ")", "when", "256", "create_digest", "(", "vector_from_array", "(", "final_vector", "[", "0", "..", "31", "]", ")", ")", "else", "raise", "ArgumentError", ",", "\"digest length must be equal to 256 or 512, not #{digest_length}\"", "end", "end" ]
Method, which return digest, dependent on them length
[ "Method", "which", "return", "digest", "dependent", "on", "them", "length" ]
696e0d4f18f5c210a0fa9e20af49bbb55c29ad72
https://github.com/wilddima/stribog/blob/696e0d4f18f5c210a0fa9e20af49bbb55c29ad72/lib/stribog/create_hash.rb#L58-L68
train
robertwahler/repo_manager
lib/repo_manager/actions/base_action.rb
RepoManager.BaseAction.parse_options
def parse_options(parser_configuration = {}) raise_on_invalid_option = parser_configuration.has_key?(:raise_on_invalid_option) ? parser_configuration[:raise_on_invalid_option] : true parse_base_options = parser_configuration.has_key?(:parse_base_options) ? parser_configuration[:parse_base_options] : true logger.debug "parsing args: #{@args.inspect}, raise_on_invalid_option: #{raise_on_invalid_option}, parse_base_options: #{parse_base_options}" @option_parser ||= OptionParser.new option_parser.banner = help + "\n\nOptions:" if parse_base_options option_parser.on("--template [NAME]", "Use a template to render output. (default=default.slim)") do |t| options[:template] = t.nil? ? "default.slim" : t @template = options[:template] end option_parser.on("--output FILENAME", "Render output directly to a file") do |f| options[:output] = f @output = options[:output] end option_parser.on("--force", "Overwrite file output without prompting") do |f| options[:force] = f end option_parser.on("-r", "--repos a1,a2,a3", "--asset a1,a2,a3", "--filter a1,a2,a3", Array, "List of regex asset name filters") do |list| options[:filter] = list end # NOTE: OptionParser will add short options, there is no way to stop '-m' from being the same as '--match' option_parser.on("--match [MODE]", "Asset filter match mode. MODE=ALL (default), FIRST, EXACT, or ONE (fails if more than 1 match)") do |m| options[:match] = m || "ALL" options[:match].upcase! unless ["ALL", "FIRST", "EXACT", "ONE"].include?(options[:match]) puts "invalid match mode option: #{options[:match]}" exit 1 end end end # allow decendants to add options yield option_parser if block_given? # reprocess args for known options, see binary wrapper for first pass # (first pass doesn't know about action specific options), find all # action options that may come after the action/subcommand (options # before subcommand have already been processed) and its args logger.debug "args before reprocessing: #{@args.inspect}" begin option_parser.order!(@args) rescue OptionParser::InvalidOption => e if raise_on_invalid_option puts "option error: #{e}" puts option_parser exit 1 else # parse and consume until we hit an unknown option (not arg), put it back so it # can be shifted into the new array e.recover(@args) end end logger.debug "args before unknown collection: #{@args.inspect}" unknown_args = [] while unknown_arg = @args.shift logger.debug "unknown_arg: #{unknown_arg.inspect}" unknown_args << unknown_arg begin # consume options and stop at an arg option_parser.order!(@args) rescue OptionParser::InvalidOption => e if raise_on_invalid_option puts "option error: #{e}" puts option_parser exit 1 else # parse and consume until we hit an unknown option (not arg), put it back so it # can be shifted into the new array e.recover(@args) end end end logger.debug "args after unknown collection: #{@args.inspect}" @args = unknown_args.dup logger.debug "args after reprocessing: #{@args.inspect}" logger.debug "configuration after reprocessing: #{@configuration.inspect}" logger.debug "options after reprocessing: #{@options.inspect}" option_parser end
ruby
def parse_options(parser_configuration = {}) raise_on_invalid_option = parser_configuration.has_key?(:raise_on_invalid_option) ? parser_configuration[:raise_on_invalid_option] : true parse_base_options = parser_configuration.has_key?(:parse_base_options) ? parser_configuration[:parse_base_options] : true logger.debug "parsing args: #{@args.inspect}, raise_on_invalid_option: #{raise_on_invalid_option}, parse_base_options: #{parse_base_options}" @option_parser ||= OptionParser.new option_parser.banner = help + "\n\nOptions:" if parse_base_options option_parser.on("--template [NAME]", "Use a template to render output. (default=default.slim)") do |t| options[:template] = t.nil? ? "default.slim" : t @template = options[:template] end option_parser.on("--output FILENAME", "Render output directly to a file") do |f| options[:output] = f @output = options[:output] end option_parser.on("--force", "Overwrite file output without prompting") do |f| options[:force] = f end option_parser.on("-r", "--repos a1,a2,a3", "--asset a1,a2,a3", "--filter a1,a2,a3", Array, "List of regex asset name filters") do |list| options[:filter] = list end # NOTE: OptionParser will add short options, there is no way to stop '-m' from being the same as '--match' option_parser.on("--match [MODE]", "Asset filter match mode. MODE=ALL (default), FIRST, EXACT, or ONE (fails if more than 1 match)") do |m| options[:match] = m || "ALL" options[:match].upcase! unless ["ALL", "FIRST", "EXACT", "ONE"].include?(options[:match]) puts "invalid match mode option: #{options[:match]}" exit 1 end end end # allow decendants to add options yield option_parser if block_given? # reprocess args for known options, see binary wrapper for first pass # (first pass doesn't know about action specific options), find all # action options that may come after the action/subcommand (options # before subcommand have already been processed) and its args logger.debug "args before reprocessing: #{@args.inspect}" begin option_parser.order!(@args) rescue OptionParser::InvalidOption => e if raise_on_invalid_option puts "option error: #{e}" puts option_parser exit 1 else # parse and consume until we hit an unknown option (not arg), put it back so it # can be shifted into the new array e.recover(@args) end end logger.debug "args before unknown collection: #{@args.inspect}" unknown_args = [] while unknown_arg = @args.shift logger.debug "unknown_arg: #{unknown_arg.inspect}" unknown_args << unknown_arg begin # consume options and stop at an arg option_parser.order!(@args) rescue OptionParser::InvalidOption => e if raise_on_invalid_option puts "option error: #{e}" puts option_parser exit 1 else # parse and consume until we hit an unknown option (not arg), put it back so it # can be shifted into the new array e.recover(@args) end end end logger.debug "args after unknown collection: #{@args.inspect}" @args = unknown_args.dup logger.debug "args after reprocessing: #{@args.inspect}" logger.debug "configuration after reprocessing: #{@configuration.inspect}" logger.debug "options after reprocessing: #{@options.inspect}" option_parser end
[ "def", "parse_options", "(", "parser_configuration", "=", "{", "}", ")", "raise_on_invalid_option", "=", "parser_configuration", ".", "has_key?", "(", ":raise_on_invalid_option", ")", "?", "parser_configuration", "[", ":raise_on_invalid_option", "]", ":", "true", "parse_base_options", "=", "parser_configuration", ".", "has_key?", "(", ":parse_base_options", ")", "?", "parser_configuration", "[", ":parse_base_options", "]", ":", "true", "logger", ".", "debug", "\"parsing args: #{@args.inspect}, raise_on_invalid_option: #{raise_on_invalid_option}, parse_base_options: #{parse_base_options}\"", "@option_parser", "||=", "OptionParser", ".", "new", "option_parser", ".", "banner", "=", "help", "+", "\"\\n\\nOptions:\"", "if", "parse_base_options", "option_parser", ".", "on", "(", "\"--template [NAME]\"", ",", "\"Use a template to render output. (default=default.slim)\"", ")", "do", "|", "t", "|", "options", "[", ":template", "]", "=", "t", ".", "nil?", "?", "\"default.slim\"", ":", "t", "@template", "=", "options", "[", ":template", "]", "end", "option_parser", ".", "on", "(", "\"--output FILENAME\"", ",", "\"Render output directly to a file\"", ")", "do", "|", "f", "|", "options", "[", ":output", "]", "=", "f", "@output", "=", "options", "[", ":output", "]", "end", "option_parser", ".", "on", "(", "\"--force\"", ",", "\"Overwrite file output without prompting\"", ")", "do", "|", "f", "|", "options", "[", ":force", "]", "=", "f", "end", "option_parser", ".", "on", "(", "\"-r\"", ",", "\"--repos a1,a2,a3\"", ",", "\"--asset a1,a2,a3\"", ",", "\"--filter a1,a2,a3\"", ",", "Array", ",", "\"List of regex asset name filters\"", ")", "do", "|", "list", "|", "options", "[", ":filter", "]", "=", "list", "end", "option_parser", ".", "on", "(", "\"--match [MODE]\"", ",", "\"Asset filter match mode. MODE=ALL (default), FIRST, EXACT, or ONE (fails if more than 1 match)\"", ")", "do", "|", "m", "|", "options", "[", ":match", "]", "=", "m", "||", "\"ALL\"", "options", "[", ":match", "]", ".", "upcase!", "unless", "[", "\"ALL\"", ",", "\"FIRST\"", ",", "\"EXACT\"", ",", "\"ONE\"", "]", ".", "include?", "(", "options", "[", ":match", "]", ")", "puts", "\"invalid match mode option: #{options[:match]}\"", "exit", "1", "end", "end", "end", "yield", "option_parser", "if", "block_given?", "logger", ".", "debug", "\"args before reprocessing: #{@args.inspect}\"", "begin", "option_parser", ".", "order!", "(", "@args", ")", "rescue", "OptionParser", "::", "InvalidOption", "=>", "e", "if", "raise_on_invalid_option", "puts", "\"option error: #{e}\"", "puts", "option_parser", "exit", "1", "else", "e", ".", "recover", "(", "@args", ")", "end", "end", "logger", ".", "debug", "\"args before unknown collection: #{@args.inspect}\"", "unknown_args", "=", "[", "]", "while", "unknown_arg", "=", "@args", ".", "shift", "logger", ".", "debug", "\"unknown_arg: #{unknown_arg.inspect}\"", "unknown_args", "<<", "unknown_arg", "begin", "option_parser", ".", "order!", "(", "@args", ")", "rescue", "OptionParser", "::", "InvalidOption", "=>", "e", "if", "raise_on_invalid_option", "puts", "\"option error: #{e}\"", "puts", "option_parser", "exit", "1", "else", "e", ".", "recover", "(", "@args", ")", "end", "end", "end", "logger", ".", "debug", "\"args after unknown collection: #{@args.inspect}\"", "@args", "=", "unknown_args", ".", "dup", "logger", ".", "debug", "\"args after reprocessing: #{@args.inspect}\"", "logger", ".", "debug", "\"configuration after reprocessing: #{@configuration.inspect}\"", "logger", ".", "debug", "\"options after reprocessing: #{@options.inspect}\"", "option_parser", "end" ]
Parse generic action options for all decendant actions @return [OptionParser] for use by decendant actions
[ "Parse", "generic", "action", "options", "for", "all", "decendant", "actions" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/actions/base_action.rb#L47-L136
train
robertwahler/repo_manager
lib/repo_manager/actions/base_action.rb
RepoManager.BaseAction.asset_options
def asset_options # include all base action options result = options.deep_clone # anything left on the command line should be filters as all options have # been consumed, for pass through options, filters must be ignored by overwritting them filters = args.dup filters += result[:filter] if result[:filter] result = result.merge(:filter => filters) unless filters.empty? # asset type to create type = result[:type] || asset_type result = result.merge(:type => type) # optional key: :assets_folder, absolute path or relative to config file if :base_folder is specified result = result.merge(:assets_folder => configuration[:folders][:assets]) if configuration[:folders] # optional key: :base_folder is the folder that contains the main config file result = result.merge(:base_folder => File.dirname(configuration[:configuration_filename])) if configuration[:configuration_filename] result end
ruby
def asset_options # include all base action options result = options.deep_clone # anything left on the command line should be filters as all options have # been consumed, for pass through options, filters must be ignored by overwritting them filters = args.dup filters += result[:filter] if result[:filter] result = result.merge(:filter => filters) unless filters.empty? # asset type to create type = result[:type] || asset_type result = result.merge(:type => type) # optional key: :assets_folder, absolute path or relative to config file if :base_folder is specified result = result.merge(:assets_folder => configuration[:folders][:assets]) if configuration[:folders] # optional key: :base_folder is the folder that contains the main config file result = result.merge(:base_folder => File.dirname(configuration[:configuration_filename])) if configuration[:configuration_filename] result end
[ "def", "asset_options", "result", "=", "options", ".", "deep_clone", "filters", "=", "args", ".", "dup", "filters", "+=", "result", "[", ":filter", "]", "if", "result", "[", ":filter", "]", "result", "=", "result", ".", "merge", "(", ":filter", "=>", "filters", ")", "unless", "filters", ".", "empty?", "type", "=", "result", "[", ":type", "]", "||", "asset_type", "result", "=", "result", ".", "merge", "(", ":type", "=>", "type", ")", "result", "=", "result", ".", "merge", "(", ":assets_folder", "=>", "configuration", "[", ":folders", "]", "[", ":assets", "]", ")", "if", "configuration", "[", ":folders", "]", "result", "=", "result", ".", "merge", "(", ":base_folder", "=>", "File", ".", "dirname", "(", "configuration", "[", ":configuration_filename", "]", ")", ")", "if", "configuration", "[", ":configuration_filename", "]", "result", "end" ]
asset options separated from assets to make it easier to override assets
[ "asset", "options", "separated", "from", "assets", "to", "make", "it", "easier", "to", "override", "assets" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/actions/base_action.rb#L185-L206
train
robertwahler/repo_manager
lib/repo_manager/actions/base_action.rb
RepoManager.BaseAction.render
def render(view_options=configuration) logger.debug "rendering" result = "" if template logger.debug "rendering with template : #{template}" view = AppView.new(items, view_options) view.template = template result = view.render else items.each_with_index do |item, index| result += "\n" unless index == 0 result += item.name.green + ":\n" if item.respond_to?(:attributes) attributes = item.attributes.deep_clone result += attributes.recursively_stringify_keys!.to_conf.gsub(/\s+$/, '') # strip trailing whitespace from YAML result += "\n" end end end result end
ruby
def render(view_options=configuration) logger.debug "rendering" result = "" if template logger.debug "rendering with template : #{template}" view = AppView.new(items, view_options) view.template = template result = view.render else items.each_with_index do |item, index| result += "\n" unless index == 0 result += item.name.green + ":\n" if item.respond_to?(:attributes) attributes = item.attributes.deep_clone result += attributes.recursively_stringify_keys!.to_conf.gsub(/\s+$/, '') # strip trailing whitespace from YAML result += "\n" end end end result end
[ "def", "render", "(", "view_options", "=", "configuration", ")", "logger", ".", "debug", "\"rendering\"", "result", "=", "\"\"", "if", "template", "logger", ".", "debug", "\"rendering with template : #{template}\"", "view", "=", "AppView", ".", "new", "(", "items", ",", "view_options", ")", "view", ".", "template", "=", "template", "result", "=", "view", ".", "render", "else", "items", ".", "each_with_index", "do", "|", "item", ",", "index", "|", "result", "+=", "\"\\n\"", "unless", "index", "==", "0", "result", "+=", "item", ".", "name", ".", "green", "+", "\":\\n\"", "if", "item", ".", "respond_to?", "(", ":attributes", ")", "attributes", "=", "item", ".", "attributes", ".", "deep_clone", "result", "+=", "attributes", ".", "recursively_stringify_keys!", ".", "to_conf", ".", "gsub", "(", "/", "\\s", "/", ",", "''", ")", "result", "+=", "\"\\n\"", "end", "end", "end", "result", "end" ]
Render items result to a string @return [String] suitable for displaying on STDOUT or writing to a file
[ "Render", "items", "result", "to", "a", "string" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/actions/base_action.rb#L218-L238
train
Yellowen/site_framework
lib/site_framework/middleware.rb
SiteFramework.Middleware.call
def call(env) # Create a method called domain which will return the current domain # name Rails.application.send :define_singleton_method, 'domain_name' do env['SERVER_NAME'] end # Create `fetch_domain` method on `Rails.application` # only if it didn't already define. unless Rails.application.respond_to? :fetch_domain Rails.application.send :define_singleton_method, 'fetch_domain' do if defined? ActiveRecord Domain.find_by(nam: Rails.application.domain_name) elsif defined? Mongoid Site.where('domains.name' => Rails.application.domain_name).domains.first end end end Rails.application.send :define_singleton_method, 'site' do site = nil unless Rails.application.domain.nil? site = Rails.application.domain.site end site end Rails.application @app.call(env) end
ruby
def call(env) # Create a method called domain which will return the current domain # name Rails.application.send :define_singleton_method, 'domain_name' do env['SERVER_NAME'] end # Create `fetch_domain` method on `Rails.application` # only if it didn't already define. unless Rails.application.respond_to? :fetch_domain Rails.application.send :define_singleton_method, 'fetch_domain' do if defined? ActiveRecord Domain.find_by(nam: Rails.application.domain_name) elsif defined? Mongoid Site.where('domains.name' => Rails.application.domain_name).domains.first end end end Rails.application.send :define_singleton_method, 'site' do site = nil unless Rails.application.domain.nil? site = Rails.application.domain.site end site end Rails.application @app.call(env) end
[ "def", "call", "(", "env", ")", "Rails", ".", "application", ".", "send", ":define_singleton_method", ",", "'domain_name'", "do", "env", "[", "'SERVER_NAME'", "]", "end", "unless", "Rails", ".", "application", ".", "respond_to?", ":fetch_domain", "Rails", ".", "application", ".", "send", ":define_singleton_method", ",", "'fetch_domain'", "do", "if", "defined?", "ActiveRecord", "Domain", ".", "find_by", "(", "nam", ":", "Rails", ".", "application", ".", "domain_name", ")", "elsif", "defined?", "Mongoid", "Site", ".", "where", "(", "'domains.name'", "=>", "Rails", ".", "application", ".", "domain_name", ")", ".", "domains", ".", "first", "end", "end", "end", "Rails", ".", "application", ".", "send", ":define_singleton_method", ",", "'site'", "do", "site", "=", "nil", "unless", "Rails", ".", "application", ".", "domain", ".", "nil?", "site", "=", "Rails", ".", "application", ".", "domain", ".", "site", "end", "site", "end", "Rails", ".", "application", "@app", ".", "call", "(", "env", ")", "end" ]
Middleware initializer method which gets the `app` from previous middleware
[ "Middleware", "initializer", "method", "which", "gets", "the", "app", "from", "previous", "middleware" ]
d4b1067c37c09c802aa4e1d5588ffdd3631f6395
https://github.com/Yellowen/site_framework/blob/d4b1067c37c09c802aa4e1d5588ffdd3631f6395/lib/site_framework/middleware.rb#L13-L42
train
janlelis/fresh
lib/ripl/fresh.rb
Ripl.Fresh.loop_eval
def loop_eval(input) if input == '' @command_mode = :system and return end case @command_mode when :system # generate ruby code to execute the command if !@result_storage ruby_command_code = "_ = system '#{ input }'\n" else temp_file = "/tmp/ripl-fresh_#{ rand 12345678901234567890 }" ruby_command_code = "_ = system '#{ input } 2>&1', :out => '#{ temp_file }'\n" # assign result to result storage variable case @result_operator when '=>', '=>>' result_literal = "[]" formatted_result = "File.read('#{ temp_file }').split($/)" operator = @result_operator == '=>>' ? '+=' : '=' when '~>', '~>>' result_literal = "''" formatted_result = "File.read('#{ temp_file }')" operator = @result_operator == '~>>' ? '<<' : '=' end ruby_command_code << %Q% #{ @result_storage } ||= #{ result_literal } #{ @result_storage } #{ operator } #{ formatted_result } FileUtils.rm '#{ temp_file }' % end # ruby_command_code << "raise( SystemCallError.new $?.exitstatus ) if !_\n" # easy auto indent ruby_command_code << "if !_ raise( SystemCallError.new $?.exitstatus ) end;" super @input = ruby_command_code when :mixed # call the ruby method, but with shell style arguments TODO more shell like (e.g. "") method_name, *args = *input.split super @input = "#{ method_name }(*#{ args })" else # good old :ruby super end end
ruby
def loop_eval(input) if input == '' @command_mode = :system and return end case @command_mode when :system # generate ruby code to execute the command if !@result_storage ruby_command_code = "_ = system '#{ input }'\n" else temp_file = "/tmp/ripl-fresh_#{ rand 12345678901234567890 }" ruby_command_code = "_ = system '#{ input } 2>&1', :out => '#{ temp_file }'\n" # assign result to result storage variable case @result_operator when '=>', '=>>' result_literal = "[]" formatted_result = "File.read('#{ temp_file }').split($/)" operator = @result_operator == '=>>' ? '+=' : '=' when '~>', '~>>' result_literal = "''" formatted_result = "File.read('#{ temp_file }')" operator = @result_operator == '~>>' ? '<<' : '=' end ruby_command_code << %Q% #{ @result_storage } ||= #{ result_literal } #{ @result_storage } #{ operator } #{ formatted_result } FileUtils.rm '#{ temp_file }' % end # ruby_command_code << "raise( SystemCallError.new $?.exitstatus ) if !_\n" # easy auto indent ruby_command_code << "if !_ raise( SystemCallError.new $?.exitstatus ) end;" super @input = ruby_command_code when :mixed # call the ruby method, but with shell style arguments TODO more shell like (e.g. "") method_name, *args = *input.split super @input = "#{ method_name }(*#{ args })" else # good old :ruby super end end
[ "def", "loop_eval", "(", "input", ")", "if", "input", "==", "''", "@command_mode", "=", ":system", "and", "return", "end", "case", "@command_mode", "when", ":system", "if", "!", "@result_storage", "ruby_command_code", "=", "\"_ = system '#{ input }'\\n\"", "else", "temp_file", "=", "\"/tmp/ripl-fresh_#{ rand 12345678901234567890 }\"", "ruby_command_code", "=", "\"_ = system '#{ input } 2>&1', :out => '#{ temp_file }'\\n\"", "case", "@result_operator", "when", "'=>'", ",", "'=>>'", "result_literal", "=", "\"[]\"", "formatted_result", "=", "\"File.read('#{ temp_file }').split($/)\"", "operator", "=", "@result_operator", "==", "'=>>'", "?", "'+='", ":", "'='", "when", "'~>'", ",", "'~>>'", "result_literal", "=", "\"''\"", "formatted_result", "=", "\"File.read('#{ temp_file }')\"", "operator", "=", "@result_operator", "==", "'~>>'", "?", "'<<'", ":", "'='", "end", "ruby_command_code", "<<", "%Q% #{ @result_storage } ||= #{ result_literal } #{ @result_storage } #{ operator } #{ formatted_result } FileUtils.rm '#{ temp_file }' %", "end", "ruby_command_code", "<<", "\"if !_ raise( SystemCallError.new $?.exitstatus ) end;\"", "super", "@input", "=", "ruby_command_code", "when", ":mixed", "method_name", ",", "*", "args", "=", "*", "input", ".", "split", "super", "@input", "=", "\"#{ method_name }(*#{ args })\"", "else", "super", "end", "end" ]
get result (depending on @command_mode)
[ "get", "result", "(", "depending", "on" ]
5bd2417232cf035f28b8ee16c212da162f2770a5
https://github.com/janlelis/fresh/blob/5bd2417232cf035f28b8ee16c212da162f2770a5/lib/ripl/fresh.rb#L60-L105
train
fcheung/corefoundation
lib/corefoundation/data.rb
CF.Data.to_s
def to_s ptr = CF.CFDataGetBytePtr(self) if CF::String::HAS_ENCODING ptr.read_string(CF.CFDataGetLength(self)).force_encoding(Encoding::ASCII_8BIT) else ptr.read_string(CF.CFDataGetLength(self)) end end
ruby
def to_s ptr = CF.CFDataGetBytePtr(self) if CF::String::HAS_ENCODING ptr.read_string(CF.CFDataGetLength(self)).force_encoding(Encoding::ASCII_8BIT) else ptr.read_string(CF.CFDataGetLength(self)) end end
[ "def", "to_s", "ptr", "=", "CF", ".", "CFDataGetBytePtr", "(", "self", ")", "if", "CF", "::", "String", "::", "HAS_ENCODING", "ptr", ".", "read_string", "(", "CF", ".", "CFDataGetLength", "(", "self", ")", ")", ".", "force_encoding", "(", "Encoding", "::", "ASCII_8BIT", ")", "else", "ptr", ".", "read_string", "(", "CF", ".", "CFDataGetLength", "(", "self", ")", ")", "end", "end" ]
Creates a ruby string from the wrapped data. The encoding will always be ASCII_8BIT @return [String]
[ "Creates", "a", "ruby", "string", "from", "the", "wrapped", "data", ".", "The", "encoding", "will", "always", "be", "ASCII_8BIT" ]
a5c766359e74f873902d916e9fb051ec7fdedbb9
https://github.com/fcheung/corefoundation/blob/a5c766359e74f873902d916e9fb051ec7fdedbb9/lib/corefoundation/data.rb#L24-L31
train
rakeoe/rakeoe
lib/rakeoe/toolchain.rb
RakeOE.Toolchain.set_build_vars
def set_build_vars warning_flags = ' -W -Wall' if 'release' == @config.release optimization_flags = " #{@config.optimization_release} -DRELEASE" else optimization_flags = " #{@config.optimization_dbg} -g" end # we could make these also arrays of source directories ... @settings['APP_SRC_DIR'] = 'src/app' @settings['LIB_SRC_DIR'] = 'src/lib' # derived settings @settings['BUILD_DIR'] = "#{build_dir}" @settings['LIB_OUT'] = "#{@settings['BUILD_DIR']}/libs" @settings['APP_OUT'] = "#{@settings['BUILD_DIR']}/apps" unless @settings['OECORE_TARGET_SYSROOT'].nil? || @settings['OECORE_TARGET_SYSROOT'].empty? @settings['SYS_LFLAGS'] = "-L#{@settings['OECORE_TARGET_SYSROOT']}/lib -L#{@settings['OECORE_TARGET_SYSROOT']}/usr/lib" end # set LD_LIBRARY_PATH @settings['LD_LIBRARY_PATH'] = @settings['LIB_OUT'] # standard settings @settings['CXXFLAGS'] += warning_flags + optimization_flags + " #{@config.language_std_cpp}" @settings['CFLAGS'] += warning_flags + optimization_flags + " #{@config.language_std_c}" if @settings['PRJ_TYPE'] == 'SOLIB' @settings['CXXFLAGS'] += ' -fPIC' @settings['CFLAGS'] += ' -fPIC' end # !! don't change order of the following string components without care !! @settings['LDFLAGS'] = @settings['LDFLAGS'] + " -L #{@settings['LIB_OUT']} #{@settings['SYS_LFLAGS']} -Wl,--no-as-needed -Wl,--start-group" end
ruby
def set_build_vars warning_flags = ' -W -Wall' if 'release' == @config.release optimization_flags = " #{@config.optimization_release} -DRELEASE" else optimization_flags = " #{@config.optimization_dbg} -g" end # we could make these also arrays of source directories ... @settings['APP_SRC_DIR'] = 'src/app' @settings['LIB_SRC_DIR'] = 'src/lib' # derived settings @settings['BUILD_DIR'] = "#{build_dir}" @settings['LIB_OUT'] = "#{@settings['BUILD_DIR']}/libs" @settings['APP_OUT'] = "#{@settings['BUILD_DIR']}/apps" unless @settings['OECORE_TARGET_SYSROOT'].nil? || @settings['OECORE_TARGET_SYSROOT'].empty? @settings['SYS_LFLAGS'] = "-L#{@settings['OECORE_TARGET_SYSROOT']}/lib -L#{@settings['OECORE_TARGET_SYSROOT']}/usr/lib" end # set LD_LIBRARY_PATH @settings['LD_LIBRARY_PATH'] = @settings['LIB_OUT'] # standard settings @settings['CXXFLAGS'] += warning_flags + optimization_flags + " #{@config.language_std_cpp}" @settings['CFLAGS'] += warning_flags + optimization_flags + " #{@config.language_std_c}" if @settings['PRJ_TYPE'] == 'SOLIB' @settings['CXXFLAGS'] += ' -fPIC' @settings['CFLAGS'] += ' -fPIC' end # !! don't change order of the following string components without care !! @settings['LDFLAGS'] = @settings['LDFLAGS'] + " -L #{@settings['LIB_OUT']} #{@settings['SYS_LFLAGS']} -Wl,--no-as-needed -Wl,--start-group" end
[ "def", "set_build_vars", "warning_flags", "=", "' -W -Wall'", "if", "'release'", "==", "@config", ".", "release", "optimization_flags", "=", "\" #{@config.optimization_release} -DRELEASE\"", "else", "optimization_flags", "=", "\" #{@config.optimization_dbg} -g\"", "end", "@settings", "[", "'APP_SRC_DIR'", "]", "=", "'src/app'", "@settings", "[", "'LIB_SRC_DIR'", "]", "=", "'src/lib'", "@settings", "[", "'BUILD_DIR'", "]", "=", "\"#{build_dir}\"", "@settings", "[", "'LIB_OUT'", "]", "=", "\"#{@settings['BUILD_DIR']}/libs\"", "@settings", "[", "'APP_OUT'", "]", "=", "\"#{@settings['BUILD_DIR']}/apps\"", "unless", "@settings", "[", "'OECORE_TARGET_SYSROOT'", "]", ".", "nil?", "||", "@settings", "[", "'OECORE_TARGET_SYSROOT'", "]", ".", "empty?", "@settings", "[", "'SYS_LFLAGS'", "]", "=", "\"-L#{@settings['OECORE_TARGET_SYSROOT']}/lib -L#{@settings['OECORE_TARGET_SYSROOT']}/usr/lib\"", "end", "@settings", "[", "'LD_LIBRARY_PATH'", "]", "=", "@settings", "[", "'LIB_OUT'", "]", "@settings", "[", "'CXXFLAGS'", "]", "+=", "warning_flags", "+", "optimization_flags", "+", "\" #{@config.language_std_cpp}\"", "@settings", "[", "'CFLAGS'", "]", "+=", "warning_flags", "+", "optimization_flags", "+", "\" #{@config.language_std_c}\"", "if", "@settings", "[", "'PRJ_TYPE'", "]", "==", "'SOLIB'", "@settings", "[", "'CXXFLAGS'", "]", "+=", "' -fPIC'", "@settings", "[", "'CFLAGS'", "]", "+=", "' -fPIC'", "end", "@settings", "[", "'LDFLAGS'", "]", "=", "@settings", "[", "'LDFLAGS'", "]", "+", "\" -L #{@settings['LIB_OUT']} #{@settings['SYS_LFLAGS']} -Wl,--no-as-needed -Wl,--start-group\"", "end" ]
Set common build variables
[ "Set", "common", "build", "variables" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/toolchain.rb#L188-L220
train
rakeoe/rakeoe
lib/rakeoe/toolchain.rb
RakeOE.Toolchain.reduce_libs_to_bare_minimum
def reduce_libs_to_bare_minimum(libs) rv = libs.clone lib_entries = RakeOE::PrjFileCache.get_lib_entries(libs) lib_entries.each_pair do |lib, entry| rv.delete(lib) unless RakeOE::PrjFileCache.project_entry_buildable?(entry, @target) end rv end
ruby
def reduce_libs_to_bare_minimum(libs) rv = libs.clone lib_entries = RakeOE::PrjFileCache.get_lib_entries(libs) lib_entries.each_pair do |lib, entry| rv.delete(lib) unless RakeOE::PrjFileCache.project_entry_buildable?(entry, @target) end rv end
[ "def", "reduce_libs_to_bare_minimum", "(", "libs", ")", "rv", "=", "libs", ".", "clone", "lib_entries", "=", "RakeOE", "::", "PrjFileCache", ".", "get_lib_entries", "(", "libs", ")", "lib_entries", ".", "each_pair", "do", "|", "lib", ",", "entry", "|", "rv", ".", "delete", "(", "lib", ")", "unless", "RakeOE", "::", "PrjFileCache", ".", "project_entry_buildable?", "(", "entry", ",", "@target", ")", "end", "rv", "end" ]
Reduces the given list of libraries to bare minimum, i.e. the minimum needed for actual platform @libs list of libraries @return reduced list of libraries
[ "Reduces", "the", "given", "list", "of", "libraries", "to", "bare", "minimum", "i", ".", "e", ".", "the", "minimum", "needed", "for", "actual", "platform" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/toolchain.rb#L322-L329
train
rakeoe/rakeoe
lib/rakeoe/toolchain.rb
RakeOE.Toolchain.libs_for_binary
def libs_for_binary(a_binary, visited=[]) return [] if visited.include?(a_binary) visited << a_binary pre = Rake::Task[a_binary].prerequisites rv = [] pre.each do |p| next if (File.extname(p) != '.a') && (File.extname(p) != '.so') next if p =~ /\-app\.a/ rv << File.basename(p).gsub(/(\.a|\.so|^lib)/, '') rv += libs_for_binary(p, visited) # Recursive call end reduce_libs_to_bare_minimum(rv.uniq) end
ruby
def libs_for_binary(a_binary, visited=[]) return [] if visited.include?(a_binary) visited << a_binary pre = Rake::Task[a_binary].prerequisites rv = [] pre.each do |p| next if (File.extname(p) != '.a') && (File.extname(p) != '.so') next if p =~ /\-app\.a/ rv << File.basename(p).gsub(/(\.a|\.so|^lib)/, '') rv += libs_for_binary(p, visited) # Recursive call end reduce_libs_to_bare_minimum(rv.uniq) end
[ "def", "libs_for_binary", "(", "a_binary", ",", "visited", "=", "[", "]", ")", "return", "[", "]", "if", "visited", ".", "include?", "(", "a_binary", ")", "visited", "<<", "a_binary", "pre", "=", "Rake", "::", "Task", "[", "a_binary", "]", ".", "prerequisites", "rv", "=", "[", "]", "pre", ".", "each", "do", "|", "p", "|", "next", "if", "(", "File", ".", "extname", "(", "p", ")", "!=", "'.a'", ")", "&&", "(", "File", ".", "extname", "(", "p", ")", "!=", "'.so'", ")", "next", "if", "p", "=~", "/", "\\-", "\\.", "/", "rv", "<<", "File", ".", "basename", "(", "p", ")", ".", "gsub", "(", "/", "\\.", "\\.", "/", ",", "''", ")", "rv", "+=", "libs_for_binary", "(", "p", ",", "visited", ")", "end", "reduce_libs_to_bare_minimum", "(", "rv", ".", "uniq", ")", "end" ]
Return array of library prerequisites for given file
[ "Return", "array", "of", "library", "prerequisites", "for", "given", "file" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/toolchain.rb#L333-L348
train
rakeoe/rakeoe
lib/rakeoe/toolchain.rb
RakeOE.Toolchain.obj
def obj(params = {}) extension = File.extname(params[:source]) object = params[:object] source = params[:source] incs = compiler_incs_for(params[:includes]) + " #{@settings['LIB_INC']}" case when cpp_source_extensions.include?(extension) flags = @settings['CXXFLAGS'] + ' ' + params[:settings]['ADD_CXXFLAGS'] compiler = "#{@settings['CXX']} -x c++ " when c_source_extensions.include?(extension) flags = @settings['CFLAGS'] + ' ' + params[:settings]['ADD_CFLAGS'] compiler = "#{@settings['CC']} -x c " when as_source_extensions.include?(extension) flags = '' compiler = "#{@settings['AS']}" else raise "unsupported source file extension (#{extension}) for creating object!" end sh "#{compiler} #{flags} #{incs} -c #{source} -o #{object}" end
ruby
def obj(params = {}) extension = File.extname(params[:source]) object = params[:object] source = params[:source] incs = compiler_incs_for(params[:includes]) + " #{@settings['LIB_INC']}" case when cpp_source_extensions.include?(extension) flags = @settings['CXXFLAGS'] + ' ' + params[:settings]['ADD_CXXFLAGS'] compiler = "#{@settings['CXX']} -x c++ " when c_source_extensions.include?(extension) flags = @settings['CFLAGS'] + ' ' + params[:settings]['ADD_CFLAGS'] compiler = "#{@settings['CC']} -x c " when as_source_extensions.include?(extension) flags = '' compiler = "#{@settings['AS']}" else raise "unsupported source file extension (#{extension}) for creating object!" end sh "#{compiler} #{flags} #{incs} -c #{source} -o #{object}" end
[ "def", "obj", "(", "params", "=", "{", "}", ")", "extension", "=", "File", ".", "extname", "(", "params", "[", ":source", "]", ")", "object", "=", "params", "[", ":object", "]", "source", "=", "params", "[", ":source", "]", "incs", "=", "compiler_incs_for", "(", "params", "[", ":includes", "]", ")", "+", "\" #{@settings['LIB_INC']}\"", "case", "when", "cpp_source_extensions", ".", "include?", "(", "extension", ")", "flags", "=", "@settings", "[", "'CXXFLAGS'", "]", "+", "' '", "+", "params", "[", ":settings", "]", "[", "'ADD_CXXFLAGS'", "]", "compiler", "=", "\"#{@settings['CXX']} -x c++ \"", "when", "c_source_extensions", ".", "include?", "(", "extension", ")", "flags", "=", "@settings", "[", "'CFLAGS'", "]", "+", "' '", "+", "params", "[", ":settings", "]", "[", "'ADD_CFLAGS'", "]", "compiler", "=", "\"#{@settings['CC']} -x c \"", "when", "as_source_extensions", ".", "include?", "(", "extension", ")", "flags", "=", "''", "compiler", "=", "\"#{@settings['AS']}\"", "else", "raise", "\"unsupported source file extension (#{extension}) for creating object!\"", "end", "sh", "\"#{compiler} #{flags} #{incs} -c #{source} -o #{object}\"", "end" ]
Creates compilation object @param [Hash] params @option params [String] :source source filename with path @option params [String] :object object filename path @option params [Hash] :settings project specific settings @option params [Array] :includes include paths used
[ "Creates", "compilation", "object" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/toolchain.rb#L403-L423
train
fogonthedowns/rubychem
lib/rubychem/equation.rb
RubyChem.Equation.solve_equivalent_fractions
def solve_equivalent_fractions last = 0 array = Array.new @reduced_row_echelon_form.each do |x| array = last.gcdlcm(x.last.denominator) last = x.last.denominator end array.max end
ruby
def solve_equivalent_fractions last = 0 array = Array.new @reduced_row_echelon_form.each do |x| array = last.gcdlcm(x.last.denominator) last = x.last.denominator end array.max end
[ "def", "solve_equivalent_fractions", "last", "=", "0", "array", "=", "Array", ".", "new", "@reduced_row_echelon_form", ".", "each", "do", "|", "x", "|", "array", "=", "last", ".", "gcdlcm", "(", "x", ".", "last", ".", "denominator", ")", "last", "=", "x", ".", "last", ".", "denominator", "end", "array", ".", "max", "end" ]
from the reduced row echelon form we are left with a set of equivalent fractions to transform into a whole number we do this by using the gcdlcm method
[ "from", "the", "reduced", "row", "echelon", "form", "we", "are", "left", "with", "a", "set", "of", "equivalent", "fractions", "to", "transform", "into", "a", "whole", "number", "we", "do", "this", "by", "using", "the", "gcdlcm", "method" ]
7750e29465538b7c67f5a41a5cae6b7f74a7faac
https://github.com/fogonthedowns/rubychem/blob/7750e29465538b7c67f5a41a5cae6b7f74a7faac/lib/rubychem/equation.rb#L158-L166
train
fogonthedowns/rubychem
lib/rubychem/equation.rb
RubyChem.Equation.apply_solved_equivalent_fractions_to_fraction
def apply_solved_equivalent_fractions_to_fraction int = self.solve_equivalent_fractions answer = [] @reduced_row_echelon_form.each do |row| answer << row.last * int end answer << int count = 0 @balanced = Hash.new @left_system_of_equations.each do |x,v| answer[count] @left_system_of_equations[x] = answer[count].to_i.abs unless answer[count].nil? count += 1 end @right_system_of_equations.each do |x,v| answer[count] @right_system_of_equations[x] = answer[count].to_i.abs unless answer[count].nil? count += 1 end answer @balanced = {left:@left_system_of_equations,right:@right_system_of_equations} self.balanced_string.gsub(/([\D^])1([\D$])/, '\1\2') # or (/1(?!\d)/,"") end
ruby
def apply_solved_equivalent_fractions_to_fraction int = self.solve_equivalent_fractions answer = [] @reduced_row_echelon_form.each do |row| answer << row.last * int end answer << int count = 0 @balanced = Hash.new @left_system_of_equations.each do |x,v| answer[count] @left_system_of_equations[x] = answer[count].to_i.abs unless answer[count].nil? count += 1 end @right_system_of_equations.each do |x,v| answer[count] @right_system_of_equations[x] = answer[count].to_i.abs unless answer[count].nil? count += 1 end answer @balanced = {left:@left_system_of_equations,right:@right_system_of_equations} self.balanced_string.gsub(/([\D^])1([\D$])/, '\1\2') # or (/1(?!\d)/,"") end
[ "def", "apply_solved_equivalent_fractions_to_fraction", "int", "=", "self", ".", "solve_equivalent_fractions", "answer", "=", "[", "]", "@reduced_row_echelon_form", ".", "each", "do", "|", "row", "|", "answer", "<<", "row", ".", "last", "*", "int", "end", "answer", "<<", "int", "count", "=", "0", "@balanced", "=", "Hash", ".", "new", "@left_system_of_equations", ".", "each", "do", "|", "x", ",", "v", "|", "answer", "[", "count", "]", "@left_system_of_equations", "[", "x", "]", "=", "answer", "[", "count", "]", ".", "to_i", ".", "abs", "unless", "answer", "[", "count", "]", ".", "nil?", "count", "+=", "1", "end", "@right_system_of_equations", ".", "each", "do", "|", "x", ",", "v", "|", "answer", "[", "count", "]", "@right_system_of_equations", "[", "x", "]", "=", "answer", "[", "count", "]", ".", "to_i", ".", "abs", "unless", "answer", "[", "count", "]", ".", "nil?", "count", "+=", "1", "end", "answer", "@balanced", "=", "{", "left", ":", "@left_system_of_equations", ",", "right", ":", "@right_system_of_equations", "}", "self", ".", "balanced_string", ".", "gsub", "(", "/", "\\D", "\\D", "/", ",", "'\\1\\2'", ")", "end" ]
Now that we have the whole number from solve_equivalent_fractions we must apply that to each of the fractions to solve for the balanced equation
[ "Now", "that", "we", "have", "the", "whole", "number", "from", "solve_equivalent_fractions", "we", "must", "apply", "that", "to", "each", "of", "the", "fractions", "to", "solve", "for", "the", "balanced", "equation" ]
7750e29465538b7c67f5a41a5cae6b7f74a7faac
https://github.com/fogonthedowns/rubychem/blob/7750e29465538b7c67f5a41a5cae6b7f74a7faac/lib/rubychem/equation.rb#L172-L194
train
fogonthedowns/rubychem
lib/rubychem/equation.rb
RubyChem.Equation.reduced_row_echelon_form
def reduced_row_echelon_form(ary) lead = 0 rows = ary.size cols = ary[0].size rary = convert_to_rational(ary) # use rational arithmetic catch :done do rows.times do |r| throw :done if cols <= lead i = r while rary[i][lead] == 0 i += 1 if rows == i i = r lead += 1 throw :done if cols == lead end end # swap rows i and r rary[i], rary[r] = rary[r], rary[i] # normalize row r v = rary[r][lead] rary[r].collect! {|x| x /= v} # reduce other rows rows.times do |i| next if i == r v = rary[i][lead] rary[i].each_index {|j| rary[i][j] -= v * rary[r][j]} end lead += 1 end end rary end
ruby
def reduced_row_echelon_form(ary) lead = 0 rows = ary.size cols = ary[0].size rary = convert_to_rational(ary) # use rational arithmetic catch :done do rows.times do |r| throw :done if cols <= lead i = r while rary[i][lead] == 0 i += 1 if rows == i i = r lead += 1 throw :done if cols == lead end end # swap rows i and r rary[i], rary[r] = rary[r], rary[i] # normalize row r v = rary[r][lead] rary[r].collect! {|x| x /= v} # reduce other rows rows.times do |i| next if i == r v = rary[i][lead] rary[i].each_index {|j| rary[i][j] -= v * rary[r][j]} end lead += 1 end end rary end
[ "def", "reduced_row_echelon_form", "(", "ary", ")", "lead", "=", "0", "rows", "=", "ary", ".", "size", "cols", "=", "ary", "[", "0", "]", ".", "size", "rary", "=", "convert_to_rational", "(", "ary", ")", "catch", ":done", "do", "rows", ".", "times", "do", "|", "r", "|", "throw", ":done", "if", "cols", "<=", "lead", "i", "=", "r", "while", "rary", "[", "i", "]", "[", "lead", "]", "==", "0", "i", "+=", "1", "if", "rows", "==", "i", "i", "=", "r", "lead", "+=", "1", "throw", ":done", "if", "cols", "==", "lead", "end", "end", "rary", "[", "i", "]", ",", "rary", "[", "r", "]", "=", "rary", "[", "r", "]", ",", "rary", "[", "i", "]", "v", "=", "rary", "[", "r", "]", "[", "lead", "]", "rary", "[", "r", "]", ".", "collect!", "{", "|", "x", "|", "x", "/=", "v", "}", "rows", ".", "times", "do", "|", "i", "|", "next", "if", "i", "==", "r", "v", "=", "rary", "[", "i", "]", "[", "lead", "]", "rary", "[", "i", "]", ".", "each_index", "{", "|", "j", "|", "rary", "[", "i", "]", "[", "j", "]", "-=", "v", "*", "rary", "[", "r", "]", "[", "j", "]", "}", "end", "lead", "+=", "1", "end", "end", "rary", "end" ]
returns an 2-D array where each element is a Rational
[ "returns", "an", "2", "-", "D", "array", "where", "each", "element", "is", "a", "Rational" ]
7750e29465538b7c67f5a41a5cae6b7f74a7faac
https://github.com/fogonthedowns/rubychem/blob/7750e29465538b7c67f5a41a5cae6b7f74a7faac/lib/rubychem/equation.rb#L207-L239
train
wvanbergen/http_status_exceptions
lib/http_status_exceptions.rb
HTTPStatus.ControllerAddition.http_status_exception
def http_status_exception(exception) @exception = exception render_options = {:template => exception.template, :status => exception.status} render_options[:layout] = exception.template_layout if exception.template_layout render(render_options) rescue ActionView::MissingTemplate head(exception.status) end
ruby
def http_status_exception(exception) @exception = exception render_options = {:template => exception.template, :status => exception.status} render_options[:layout] = exception.template_layout if exception.template_layout render(render_options) rescue ActionView::MissingTemplate head(exception.status) end
[ "def", "http_status_exception", "(", "exception", ")", "@exception", "=", "exception", "render_options", "=", "{", ":template", "=>", "exception", ".", "template", ",", ":status", "=>", "exception", ".", "status", "}", "render_options", "[", ":layout", "]", "=", "exception", ".", "template_layout", "if", "exception", ".", "template_layout", "render", "(", "render_options", ")", "rescue", "ActionView", "::", "MissingTemplate", "head", "(", "exception", ".", "status", ")", "end" ]
The default handler for raised HTTP status exceptions. It will render a template if available, or respond with an empty response with the HTTP status corresponding to the exception. You can override this method in your <tt>ApplicationController</tt> to handle the exceptions yourself. <tt>exception</tt>:: The HTTP status exception to handle.
[ "The", "default", "handler", "for", "raised", "HTTP", "status", "exceptions", ".", "It", "will", "render", "a", "template", "if", "available", "or", "respond", "with", "an", "empty", "response", "with", "the", "HTTP", "status", "corresponding", "to", "the", "exception", "." ]
8b88105f4784d03cb16cb4d36efb161394d02a2d
https://github.com/wvanbergen/http_status_exceptions/blob/8b88105f4784d03cb16cb4d36efb161394d02a2d/lib/http_status_exceptions.rb#L138-L145
train
rocky/rbx-trepanning
app/eventbuffer.rb
Trace.EventBuffer.append
def append(event, frame, arg) item = EventStruct.new(event, arg, frame) @pos = self.succ_pos @marks.shift if @marks[0] == @pos @buf[@pos] = item @size += 1 unless @maxsize && @size == @maxsize end
ruby
def append(event, frame, arg) item = EventStruct.new(event, arg, frame) @pos = self.succ_pos @marks.shift if @marks[0] == @pos @buf[@pos] = item @size += 1 unless @maxsize && @size == @maxsize end
[ "def", "append", "(", "event", ",", "frame", ",", "arg", ")", "item", "=", "EventStruct", ".", "new", "(", "event", ",", "arg", ",", "frame", ")", "@pos", "=", "self", ".", "succ_pos", "@marks", ".", "shift", "if", "@marks", "[", "0", "]", "==", "@pos", "@buf", "[", "@pos", "]", "=", "item", "@size", "+=", "1", "unless", "@maxsize", "&&", "@size", "==", "@maxsize", "end" ]
Add a new event dropping off old events if that was declared marks are also dropped if buffer has a limit.
[ "Add", "a", "new", "event", "dropping", "off", "old", "events", "if", "that", "was", "declared", "marks", "are", "also", "dropped", "if", "buffer", "has", "a", "limit", "." ]
192e5d3b8236f0c1094f7ba3a6b5d2c42ed43fc1
https://github.com/rocky/rbx-trepanning/blob/192e5d3b8236f0c1094f7ba3a6b5d2c42ed43fc1/app/eventbuffer.rb#L25-L31
train
ivanzotov/constructor
pages/app/models/constructor_pages/template.rb
ConstructorPages.Template.check_code_name
def check_code_name(cname) [cname.pluralize, cname.singularize].each {|name| return false if root.descendants.map{|t| t.code_name unless t.code_name == cname}.include?(name)} true end
ruby
def check_code_name(cname) [cname.pluralize, cname.singularize].each {|name| return false if root.descendants.map{|t| t.code_name unless t.code_name == cname}.include?(name)} true end
[ "def", "check_code_name", "(", "cname", ")", "[", "cname", ".", "pluralize", ",", "cname", ".", "singularize", "]", ".", "each", "{", "|", "name", "|", "return", "false", "if", "root", ".", "descendants", ".", "map", "{", "|", "t", "|", "t", ".", "code_name", "unless", "t", ".", "code_name", "==", "cname", "}", ".", "include?", "(", "name", ")", "}", "true", "end" ]
Check if there is code_name in same branch
[ "Check", "if", "there", "is", "code_name", "in", "same", "branch" ]
1d52fb5b642200a6993f5a630e6934bccbcbf4e8
https://github.com/ivanzotov/constructor/blob/1d52fb5b642200a6993f5a630e6934bccbcbf4e8/pages/app/models/constructor_pages/template.rb#L39-L43
train
aelogica/express_templates
lib/express_templates/renderer.rb
ExpressTemplates.Renderer.render
def render context=nil, template_or_src=nil, &block compiled_template = compile(template_or_src, &block) context.instance_eval compiled_template end
ruby
def render context=nil, template_or_src=nil, &block compiled_template = compile(template_or_src, &block) context.instance_eval compiled_template end
[ "def", "render", "context", "=", "nil", ",", "template_or_src", "=", "nil", ",", "&", "block", "compiled_template", "=", "compile", "(", "template_or_src", ",", "&", "block", ")", "context", ".", "instance_eval", "compiled_template", "end" ]
render accepts source or block, evaluates the resulting string of ruby in the context provided
[ "render", "accepts", "source", "or", "block", "evaluates", "the", "resulting", "string", "of", "ruby", "in", "the", "context", "provided" ]
d5d447357e737c9220ca0025feb9e6f8f6249b5b
https://github.com/aelogica/express_templates/blob/d5d447357e737c9220ca0025feb9e6f8f6249b5b/lib/express_templates/renderer.rb#L4-L7
train
robertwahler/repo_manager
lib/repo_manager/settings.rb
RepoManager.Settings.configure
def configure(options) # config file default options configuration = { :options => { :verbose => false, :color => 'AUTO', :short => false, :unmodified => 'HIDE', :match => 'ALL', :list => 'ALL' }, :commands => [ 'diff', 'grep', 'log', 'ls-files', 'show', 'status' ] } # set default config if not given on command line config = options[:config] if config.nil? config = [ File.join(@working_dir, "repo.conf"), File.join(@working_dir, ".repo.conf"), File.join(@working_dir, "repo_manager", "repo.conf"), File.join(@working_dir, ".repo_manager", "repo.conf"), File.join(@working_dir, "config", "repo.conf"), File.expand_path(File.join("~", ".repo.conf")), File.expand_path(File.join("~", "repo.conf")), File.expand_path(File.join("~", "repo_manager", "repo.conf")), File.expand_path(File.join("~", ".repo_manager", "repo.conf")) ].detect { |filename| File.exists?(filename) } end if config && File.exists?(config) # load options from the config file, overwriting hard-coded defaults logger.debug "reading configuration file: #{config}" config_contents = YAML.load(ERB.new(File.open(config, "rb").read).result) configuration.merge!(config_contents.symbolize_keys!) if config_contents && config_contents.is_a?(Hash) else # user specified a config file?, no error if user did not specify config file raise "config file not found" if options[:config] end # store the original full config filename for later use configuration[:configuration_filename] = config configuration.recursively_symbolize_keys! # the command line options override options read from the config file configuration[:options].merge!(options) configuration end
ruby
def configure(options) # config file default options configuration = { :options => { :verbose => false, :color => 'AUTO', :short => false, :unmodified => 'HIDE', :match => 'ALL', :list => 'ALL' }, :commands => [ 'diff', 'grep', 'log', 'ls-files', 'show', 'status' ] } # set default config if not given on command line config = options[:config] if config.nil? config = [ File.join(@working_dir, "repo.conf"), File.join(@working_dir, ".repo.conf"), File.join(@working_dir, "repo_manager", "repo.conf"), File.join(@working_dir, ".repo_manager", "repo.conf"), File.join(@working_dir, "config", "repo.conf"), File.expand_path(File.join("~", ".repo.conf")), File.expand_path(File.join("~", "repo.conf")), File.expand_path(File.join("~", "repo_manager", "repo.conf")), File.expand_path(File.join("~", ".repo_manager", "repo.conf")) ].detect { |filename| File.exists?(filename) } end if config && File.exists?(config) # load options from the config file, overwriting hard-coded defaults logger.debug "reading configuration file: #{config}" config_contents = YAML.load(ERB.new(File.open(config, "rb").read).result) configuration.merge!(config_contents.symbolize_keys!) if config_contents && config_contents.is_a?(Hash) else # user specified a config file?, no error if user did not specify config file raise "config file not found" if options[:config] end # store the original full config filename for later use configuration[:configuration_filename] = config configuration.recursively_symbolize_keys! # the command line options override options read from the config file configuration[:options].merge!(options) configuration end
[ "def", "configure", "(", "options", ")", "configuration", "=", "{", ":options", "=>", "{", ":verbose", "=>", "false", ",", ":color", "=>", "'AUTO'", ",", ":short", "=>", "false", ",", ":unmodified", "=>", "'HIDE'", ",", ":match", "=>", "'ALL'", ",", ":list", "=>", "'ALL'", "}", ",", ":commands", "=>", "[", "'diff'", ",", "'grep'", ",", "'log'", ",", "'ls-files'", ",", "'show'", ",", "'status'", "]", "}", "config", "=", "options", "[", ":config", "]", "if", "config", ".", "nil?", "config", "=", "[", "File", ".", "join", "(", "@working_dir", ",", "\"repo.conf\"", ")", ",", "File", ".", "join", "(", "@working_dir", ",", "\".repo.conf\"", ")", ",", "File", ".", "join", "(", "@working_dir", ",", "\"repo_manager\"", ",", "\"repo.conf\"", ")", ",", "File", ".", "join", "(", "@working_dir", ",", "\".repo_manager\"", ",", "\"repo.conf\"", ")", ",", "File", ".", "join", "(", "@working_dir", ",", "\"config\"", ",", "\"repo.conf\"", ")", ",", "File", ".", "expand_path", "(", "File", ".", "join", "(", "\"~\"", ",", "\".repo.conf\"", ")", ")", ",", "File", ".", "expand_path", "(", "File", ".", "join", "(", "\"~\"", ",", "\"repo.conf\"", ")", ")", ",", "File", ".", "expand_path", "(", "File", ".", "join", "(", "\"~\"", ",", "\"repo_manager\"", ",", "\"repo.conf\"", ")", ")", ",", "File", ".", "expand_path", "(", "File", ".", "join", "(", "\"~\"", ",", "\".repo_manager\"", ",", "\"repo.conf\"", ")", ")", "]", ".", "detect", "{", "|", "filename", "|", "File", ".", "exists?", "(", "filename", ")", "}", "end", "if", "config", "&&", "File", ".", "exists?", "(", "config", ")", "logger", ".", "debug", "\"reading configuration file: #{config}\"", "config_contents", "=", "YAML", ".", "load", "(", "ERB", ".", "new", "(", "File", ".", "open", "(", "config", ",", "\"rb\"", ")", ".", "read", ")", ".", "result", ")", "configuration", ".", "merge!", "(", "config_contents", ".", "symbolize_keys!", ")", "if", "config_contents", "&&", "config_contents", ".", "is_a?", "(", "Hash", ")", "else", "raise", "\"config file not found\"", "if", "options", "[", ":config", "]", "end", "configuration", "[", ":configuration_filename", "]", "=", "config", "configuration", ".", "recursively_symbolize_keys!", "configuration", "[", ":options", "]", ".", "merge!", "(", "options", ")", "configuration", "end" ]
read options from YAML config
[ "read", "options", "from", "YAML", "config" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/settings.rb#L38-L94
train
eprothro/cassie
lib/cassie/statements/execution/batched_fetching.rb
Cassie::Statements::Execution.BatchedFetching.fetch_in_batches
def fetch_in_batches(opts={}) opts[:batch_size] ||= 1000 # spawn the new query as soon as the enumerable is created # rather than waiting until the firt iteration is executed. # The client could mutate the object between these moments, # however we don't want to spawn twice if a block isn't passed. paged_query = opts.delete(:_paged_query) || self.clone return to_enum(:fetch_in_batches, opts.merge(_paged_query: paged_query)) unless block_given? # use Cassandra internal paging # but clone the query to isolate it # and allow all paging queries # to execute within a Cassie::Query # for use of other features, like logging # # note: stateless page size is independent from limit paged_query.stateless_page_size = opts[:batch_size] paged_query.paging_state = nil loop do # done if the previous result was the last page break if paged_query.result && paged_query.result.last_page? raise page_size_changed_error(opts[:batch_size]) if opts[:batch_size] != paged_query.stateless_page_size batch = paged_query.fetch paged_query.paging_state = paged_query.result.paging_state yield batch end end
ruby
def fetch_in_batches(opts={}) opts[:batch_size] ||= 1000 # spawn the new query as soon as the enumerable is created # rather than waiting until the firt iteration is executed. # The client could mutate the object between these moments, # however we don't want to spawn twice if a block isn't passed. paged_query = opts.delete(:_paged_query) || self.clone return to_enum(:fetch_in_batches, opts.merge(_paged_query: paged_query)) unless block_given? # use Cassandra internal paging # but clone the query to isolate it # and allow all paging queries # to execute within a Cassie::Query # for use of other features, like logging # # note: stateless page size is independent from limit paged_query.stateless_page_size = opts[:batch_size] paged_query.paging_state = nil loop do # done if the previous result was the last page break if paged_query.result && paged_query.result.last_page? raise page_size_changed_error(opts[:batch_size]) if opts[:batch_size] != paged_query.stateless_page_size batch = paged_query.fetch paged_query.paging_state = paged_query.result.paging_state yield batch end end
[ "def", "fetch_in_batches", "(", "opts", "=", "{", "}", ")", "opts", "[", ":batch_size", "]", "||=", "1000", "paged_query", "=", "opts", ".", "delete", "(", ":_paged_query", ")", "||", "self", ".", "clone", "return", "to_enum", "(", ":fetch_in_batches", ",", "opts", ".", "merge", "(", "_paged_query", ":", "paged_query", ")", ")", "unless", "block_given?", "paged_query", ".", "stateless_page_size", "=", "opts", "[", ":batch_size", "]", "paged_query", ".", "paging_state", "=", "nil", "loop", "do", "break", "if", "paged_query", ".", "result", "&&", "paged_query", ".", "result", ".", "last_page?", "raise", "page_size_changed_error", "(", "opts", "[", ":batch_size", "]", ")", "if", "opts", "[", ":batch_size", "]", "!=", "paged_query", ".", "stateless_page_size", "batch", "=", "paged_query", ".", "fetch", "paged_query", ".", "paging_state", "=", "paged_query", ".", "result", ".", "paging_state", "yield", "batch", "end", "end" ]
Yields each batch of records that was found by the options as an array. If you do not provide a block to find_in_batches, it will return an Enumerator for chaining with other methods. query.fetch_in_batches do |records| puts "max score in group: #{records.max{ |a, b| a.score <=> b.score }}" end "max score in group: 26" ==== Options * <tt>:batch_size</tt> - Specifies the size of the batch. Default to 1000. NOTE: Any limit specified on the query will affect the batched set. Cassandra internal paging is used for batching.
[ "Yields", "each", "batch", "of", "records", "that", "was", "found", "by", "the", "options", "as", "an", "array", "." ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/statements/execution/batched_fetching.rb#L50-L81
train
tmobaird/GuideboxWrapper
lib/GuideboxWrapper/guidebox_movie.rb
GuideboxWrapper.GuideboxMovie.search_for
def search_for(name) url = build_query(name) url += '/fuzzy/web' data = @client.query(url) sleep(1) data["results"] end
ruby
def search_for(name) url = build_query(name) url += '/fuzzy/web' data = @client.query(url) sleep(1) data["results"] end
[ "def", "search_for", "(", "name", ")", "url", "=", "build_query", "(", "name", ")", "url", "+=", "'/fuzzy/web'", "data", "=", "@client", ".", "query", "(", "url", ")", "sleep", "(", "1", ")", "data", "[", "\"results\"", "]", "end" ]
Search for show
[ "Search", "for", "show" ]
431d541141c21620b640dcffee6cf23b3d5ca616
https://github.com/tmobaird/GuideboxWrapper/blob/431d541141c21620b640dcffee6cf23b3d5ca616/lib/GuideboxWrapper/guidebox_movie.rb#L8-L14
train
pwnieexpress/snapi
lib/snapi/argument.rb
Snapi.Argument.valid_input?
def valid_input?(input) case @attributes[:type] when :boolean [true,false].include?(input) when :enum raise MissingValuesError unless @attributes[:values] raise InvalidValuesError unless @attributes[:values].class == Array @attributes[:values].include?(input) when :string format = @attributes[:format] || :anything Validator.valid_input?(format, input) when :number [Integer, Fixnum].include?(input.class) when :timestamp # TODO timestamp pending # raise PendingBranchError true else false end end
ruby
def valid_input?(input) case @attributes[:type] when :boolean [true,false].include?(input) when :enum raise MissingValuesError unless @attributes[:values] raise InvalidValuesError unless @attributes[:values].class == Array @attributes[:values].include?(input) when :string format = @attributes[:format] || :anything Validator.valid_input?(format, input) when :number [Integer, Fixnum].include?(input.class) when :timestamp # TODO timestamp pending # raise PendingBranchError true else false end end
[ "def", "valid_input?", "(", "input", ")", "case", "@attributes", "[", ":type", "]", "when", ":boolean", "[", "true", ",", "false", "]", ".", "include?", "(", "input", ")", "when", ":enum", "raise", "MissingValuesError", "unless", "@attributes", "[", ":values", "]", "raise", "InvalidValuesError", "unless", "@attributes", "[", ":values", "]", ".", "class", "==", "Array", "@attributes", "[", ":values", "]", ".", "include?", "(", "input", ")", "when", ":string", "format", "=", "@attributes", "[", ":format", "]", "||", ":anything", "Validator", ".", "valid_input?", "(", "format", ",", "input", ")", "when", ":number", "[", "Integer", ",", "Fixnum", "]", ".", "include?", "(", "input", ".", "class", ")", "when", ":timestamp", "true", "else", "false", "end", "end" ]
Check if a value provided will suffice for the way this argument is defined. @param input, Just about anything... @returns Boolean. true if valid
[ "Check", "if", "a", "value", "provided", "will", "suffice", "for", "the", "way", "this", "argument", "is", "defined", "." ]
3c2a6fe454721945e4e58b8b496d3c20ada55df7
https://github.com/pwnieexpress/snapi/blob/3c2a6fe454721945e4e58b8b496d3c20ada55df7/lib/snapi/argument.rb#L139-L159
train
eprothro/cassie
lib/cassie/statements/execution/fetching.rb
Cassie::Statements::Execution.Fetching.fetch
def fetch(args={}) args.each do |k, v| setter = "#{k}=" send(setter, v) if respond_to? setter end execute result end
ruby
def fetch(args={}) args.each do |k, v| setter = "#{k}=" send(setter, v) if respond_to? setter end execute result end
[ "def", "fetch", "(", "args", "=", "{", "}", ")", "args", ".", "each", "do", "|", "k", ",", "v", "|", "setter", "=", "\"#{k}=\"", "send", "(", "setter", ",", "v", ")", "if", "respond_to?", "setter", "end", "execute", "result", "end" ]
Returns array of rows or empty array query.fetch(id: 1) => [{id: 1, name: 'eprothro'}]
[ "Returns", "array", "of", "rows", "or", "empty", "array" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/statements/execution/fetching.rb#L19-L27
train
fcheung/corefoundation
lib/corefoundation/base.rb
CF.Base.inspect
def inspect cf = CF::String.new(CF.CFCopyDescription(self)) cf.to_s.tap {cf.release} end
ruby
def inspect cf = CF::String.new(CF.CFCopyDescription(self)) cf.to_s.tap {cf.release} end
[ "def", "inspect", "cf", "=", "CF", "::", "String", ".", "new", "(", "CF", ".", "CFCopyDescription", "(", "self", ")", ")", "cf", ".", "to_s", ".", "tap", "{", "cf", ".", "release", "}", "end" ]
Returns a ruby string containing the output of CFCopyDescription for the wrapped object @return [String]
[ "Returns", "a", "ruby", "string", "containing", "the", "output", "of", "CFCopyDescription", "for", "the", "wrapped", "object" ]
a5c766359e74f873902d916e9fb051ec7fdedbb9
https://github.com/fcheung/corefoundation/blob/a5c766359e74f873902d916e9fb051ec7fdedbb9/lib/corefoundation/base.rb#L146-L149
train
fcheung/corefoundation
lib/corefoundation/base.rb
CF.Base.equals?
def equals?(other) if other.is_a?(CF::Base) @ptr.address == other.to_ptr.address else false end end
ruby
def equals?(other) if other.is_a?(CF::Base) @ptr.address == other.to_ptr.address else false end end
[ "def", "equals?", "(", "other", ")", "if", "other", ".", "is_a?", "(", "CF", "::", "Base", ")", "@ptr", ".", "address", "==", "other", ".", "to_ptr", ".", "address", "else", "false", "end", "end" ]
Uses CFHash to return a hash code @return [Integer] eql? (and ==) are implemented using CFEqual equals? is defined as returning true if the wrapped pointer is the same
[ "Uses", "CFHash", "to", "return", "a", "hash", "code" ]
a5c766359e74f873902d916e9fb051ec7fdedbb9
https://github.com/fcheung/corefoundation/blob/a5c766359e74f873902d916e9fb051ec7fdedbb9/lib/corefoundation/base.rb#L172-L178
train
bachya/cliutils
lib/cliutils/pretty_io.rb
CLIUtils.PrettyIO.color_chart
def color_chart [0, 1, 4, 5, 7].each do |attr| puts '----------------------------------------------------------------' puts "ESC[#{attr};Foreground;Background" 30.upto(37) do |fg| 40.upto(47) do |bg| print "\033[#{attr};#{fg};#{bg}m #{fg};#{bg} " end puts "\033[0m" end end end
ruby
def color_chart [0, 1, 4, 5, 7].each do |attr| puts '----------------------------------------------------------------' puts "ESC[#{attr};Foreground;Background" 30.upto(37) do |fg| 40.upto(47) do |bg| print "\033[#{attr};#{fg};#{bg}m #{fg};#{bg} " end puts "\033[0m" end end end
[ "def", "color_chart", "[", "0", ",", "1", ",", "4", ",", "5", ",", "7", "]", ".", "each", "do", "|", "attr", "|", "puts", "'----------------------------------------------------------------'", "puts", "\"ESC[#{attr};Foreground;Background\"", "30", ".", "upto", "(", "37", ")", "do", "|", "fg", "|", "40", ".", "upto", "(", "47", ")", "do", "|", "bg", "|", "print", "\"\\033[#{attr};#{fg};#{bg}m #{fg};#{bg} \"", "end", "puts", "\"\\033[0m\"", "end", "end", "end" ]
Displays a chart of all the possible ANSI foreground and background color combinations. @return [void]
[ "Displays", "a", "chart", "of", "all", "the", "possible", "ANSI", "foreground", "and", "background", "color", "combinations", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/pretty_io.rb#L28-L39
train
lml/lev
lib/lev/handler.rb
Lev.Handler.validate_paramified_params
def validate_paramified_params self.class.paramify_methods.each do |method| params = send(method) transfer_errors_from(params, TermMapper.scope(params.group)) if !params.valid? end end
ruby
def validate_paramified_params self.class.paramify_methods.each do |method| params = send(method) transfer_errors_from(params, TermMapper.scope(params.group)) if !params.valid? end end
[ "def", "validate_paramified_params", "self", ".", "class", ".", "paramify_methods", ".", "each", "do", "|", "method", "|", "params", "=", "send", "(", "method", ")", "transfer_errors_from", "(", "params", ",", "TermMapper", ".", "scope", "(", "params", ".", "group", ")", ")", "if", "!", "params", ".", "valid?", "end", "end" ]
Helper method to validate paramified params and to transfer any errors into the handler.
[ "Helper", "method", "to", "validate", "paramified", "params", "and", "to", "transfer", "any", "errors", "into", "the", "handler", "." ]
ce39ac122796974dafb24ee61428540dacf34371
https://github.com/lml/lev/blob/ce39ac122796974dafb24ee61428540dacf34371/lib/lev/handler.rb#L222-L227
train
GenieBelt/gb-dispatch
lib/gb_dispatch/queue.rb
GBDispatch.Queue.perform_after
def perform_after(time, block=nil) task = Concurrent::ScheduledTask.new(time) do block = ->(){ yield } unless block self.async.perform_now block end task.execute task end
ruby
def perform_after(time, block=nil) task = Concurrent::ScheduledTask.new(time) do block = ->(){ yield } unless block self.async.perform_now block end task.execute task end
[ "def", "perform_after", "(", "time", ",", "block", "=", "nil", ")", "task", "=", "Concurrent", "::", "ScheduledTask", ".", "new", "(", "time", ")", "do", "block", "=", "->", "(", ")", "{", "yield", "}", "unless", "block", "self", ".", "async", ".", "perform_now", "block", "end", "task", ".", "execute", "task", "end" ]
Perform block after given period @param time [Fixnum] @param block [Proc] @yield if there is no block given it yield without param. @return [Concurrent::ScheduledTask]
[ "Perform", "block", "after", "given", "period" ]
6ee932de9b397b96c82271478db1bf5933449e94
https://github.com/GenieBelt/gb-dispatch/blob/6ee932de9b397b96c82271478db1bf5933449e94/lib/gb_dispatch/queue.rb#L57-L64
train
ktemkin/ruby-ise
lib/ise/preference_file.rb
ISE.PreferenceFile.set_by_path
def set_by_path(path, value, target=@ini) #Split the path into its components. keys = path.split('/') #Traverse the path, creating any "folders" necessary along the way. until keys.one? target[keys.first] = {} unless target[keys.first].is_a?(Hash) target = target[keys.shift] end #And finally, place the value into the appropriate "leaf". target[keys.shift] = value end
ruby
def set_by_path(path, value, target=@ini) #Split the path into its components. keys = path.split('/') #Traverse the path, creating any "folders" necessary along the way. until keys.one? target[keys.first] = {} unless target[keys.first].is_a?(Hash) target = target[keys.shift] end #And finally, place the value into the appropriate "leaf". target[keys.shift] = value end
[ "def", "set_by_path", "(", "path", ",", "value", ",", "target", "=", "@ini", ")", "keys", "=", "path", ".", "split", "(", "'/'", ")", "until", "keys", ".", "one?", "target", "[", "keys", ".", "first", "]", "=", "{", "}", "unless", "target", "[", "keys", ".", "first", "]", ".", "is_a?", "(", "Hash", ")", "target", "=", "target", "[", "keys", ".", "shift", "]", "end", "target", "[", "keys", ".", "shift", "]", "=", "value", "end" ]
Sets the value of a key in a hash-of-hashes via a unix-style path. path: The path to the target key, in a unix-style path structure. See example below. value: The value to put into the key. target: The hash to operate on. If target isn't provided, we work with the base INI. Example: set_by_path('foo/bar/tab', 3, a) would set a[foo][bar][tab] = 3; setting foo and bar to
[ "Sets", "the", "value", "of", "a", "key", "in", "a", "hash", "-", "of", "-", "hashes", "via", "a", "unix", "-", "style", "path", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/preference_file.rb#L46-L60
train
ktemkin/ruby-ise
lib/ise/preference_file.rb
ISE.PreferenceFile.get_by_path
def get_by_path(path, target=@ini) #Split the path into its components... keys = path.split('/') #And traverse the hasn until we've fully navigated the path. target = target[keys.shift] until keys.empty? #Returns the final value. target end
ruby
def get_by_path(path, target=@ini) #Split the path into its components... keys = path.split('/') #And traverse the hasn until we've fully navigated the path. target = target[keys.shift] until keys.empty? #Returns the final value. target end
[ "def", "get_by_path", "(", "path", ",", "target", "=", "@ini", ")", "keys", "=", "path", ".", "split", "(", "'/'", ")", "target", "=", "target", "[", "keys", ".", "shift", "]", "until", "keys", ".", "empty?", "target", "end" ]
Gets the value of a key in a hash-of-hashes via a unix-style path. path: The path to the target key, in a unix-style path structure. See example below. target: The hash to operate on. If target isn't provided, we work with the base INI. Example: set_by_path('foo/bar/tab', 3, a) would set a[foo][bar][tab] = 3; setting foo and bar to
[ "Gets", "the", "value", "of", "a", "key", "in", "a", "hash", "-", "of", "-", "hashes", "via", "a", "unix", "-", "style", "path", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/preference_file.rb#L74-L85
train
ktemkin/ruby-ise
lib/ise/preference_file.rb
ISE.PreferenceFile.process_property
def process_property(property, value) value.chomp! #If either the property or value are empty (or contain invalid whitespace), #abort. return if property.empty? and value.empty? return if value.sub!(%r/\\\s*\z/, '') #Strip any leading/trailing characters. property.strip! value.strip! #Raise an error if we have an invalid property name. parse_error if property.empty? #Parse ISE's value into a path. set_by_path(CGI::unescape(property), unescape_value(value.dup), current_section) #And continue processing the property and value. property.slice!(0, property.length) value.slice!(0, value.length) #Return nil. nil end
ruby
def process_property(property, value) value.chomp! #If either the property or value are empty (or contain invalid whitespace), #abort. return if property.empty? and value.empty? return if value.sub!(%r/\\\s*\z/, '') #Strip any leading/trailing characters. property.strip! value.strip! #Raise an error if we have an invalid property name. parse_error if property.empty? #Parse ISE's value into a path. set_by_path(CGI::unescape(property), unescape_value(value.dup), current_section) #And continue processing the property and value. property.slice!(0, property.length) value.slice!(0, value.length) #Return nil. nil end
[ "def", "process_property", "(", "property", ",", "value", ")", "value", ".", "chomp!", "return", "if", "property", ".", "empty?", "and", "value", ".", "empty?", "return", "if", "value", ".", "sub!", "(", "%r/", "\\\\", "\\s", "\\z", "/", ",", "''", ")", "property", ".", "strip!", "value", ".", "strip!", "parse_error", "if", "property", ".", "empty?", "set_by_path", "(", "CGI", "::", "unescape", "(", "property", ")", ",", "unescape_value", "(", "value", ".", "dup", ")", ",", "current_section", ")", "property", ".", "slice!", "(", "0", ",", "property", ".", "length", ")", "value", ".", "slice!", "(", "0", ",", "value", ".", "length", ")", "nil", "end" ]
Processes a given name-value pair, adding them to the current INI database. Code taken from the 'inifile' gem.
[ "Processes", "a", "given", "name", "-", "value", "pair", "adding", "them", "to", "the", "current", "INI", "database", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/preference_file.rb#L93-L119
train
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.init?
def init?(path = Dir.pwd) begin MiniGit.new(path) rescue Exception return false end true end
ruby
def init?(path = Dir.pwd) begin MiniGit.new(path) rescue Exception return false end true end
[ "def", "init?", "(", "path", "=", "Dir", ".", "pwd", ")", "begin", "MiniGit", ".", "new", "(", "path", ")", "rescue", "Exception", "return", "false", "end", "true", "end" ]
Check if a git directory has been initialized
[ "Check", "if", "a", "git", "directory", "has", "been", "initialized" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L40-L47
train
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.commits?
def commits?(path) res = false Dir.chdir(path) do _stdout, _stderr, exit_status = Open3.capture3( "git rev-parse HEAD" ) res = (exit_status.to_i.zero?) end res end
ruby
def commits?(path) res = false Dir.chdir(path) do _stdout, _stderr, exit_status = Open3.capture3( "git rev-parse HEAD" ) res = (exit_status.to_i.zero?) end res end
[ "def", "commits?", "(", "path", ")", "res", "=", "false", "Dir", ".", "chdir", "(", "path", ")", "do", "_stdout", ",", "_stderr", ",", "exit_status", "=", "Open3", ".", "capture3", "(", "\"git rev-parse HEAD\"", ")", "res", "=", "(", "exit_status", ".", "to_i", ".", "zero?", ")", "end", "res", "end" ]
Check if the repositories already holds some commits
[ "Check", "if", "the", "repositories", "already", "holds", "some", "commits" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L50-L57
train
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.command?
def command?(cmd) cg = MiniGit::Capturing.new cmd_list = cg.help :a => true # typical run: # usage: git [--version] [--help] [-C <path>] [-c name=value] # [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path] # [-p|--paginate|--no-pager] [--no-replace-objects] [--bare] # [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>] # <command> [<args>] # # available git commands in '/usr/local/Cellar/git/1.8.5.2/libexec/git-core' # # add [...] \ # [...] | The part we are interested in, delimited by '\n\n' sequence # [...] / # # 'git help -a' and 'git help -g' lists available subcommands and some # concept guides. See 'git help <command>' or 'git help <concept>' # to read about a specific subcommand or concept l = cmd_list.split("\n\n") l.shift # useless first part #ap l subl = l.each_index.select { |i| l[i] =~ /^\s\s+/ } # find sublines that starts with at least two whitespaces #ap subl return false if subl.empty? subl.any? { |i| l[i].split.include?(cmd) } end
ruby
def command?(cmd) cg = MiniGit::Capturing.new cmd_list = cg.help :a => true # typical run: # usage: git [--version] [--help] [-C <path>] [-c name=value] # [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path] # [-p|--paginate|--no-pager] [--no-replace-objects] [--bare] # [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>] # <command> [<args>] # # available git commands in '/usr/local/Cellar/git/1.8.5.2/libexec/git-core' # # add [...] \ # [...] | The part we are interested in, delimited by '\n\n' sequence # [...] / # # 'git help -a' and 'git help -g' lists available subcommands and some # concept guides. See 'git help <command>' or 'git help <concept>' # to read about a specific subcommand or concept l = cmd_list.split("\n\n") l.shift # useless first part #ap l subl = l.each_index.select { |i| l[i] =~ /^\s\s+/ } # find sublines that starts with at least two whitespaces #ap subl return false if subl.empty? subl.any? { |i| l[i].split.include?(cmd) } end
[ "def", "command?", "(", "cmd", ")", "cg", "=", "MiniGit", "::", "Capturing", ".", "new", "cmd_list", "=", "cg", ".", "help", ":a", "=>", "true", "l", "=", "cmd_list", ".", "split", "(", "\"\\n\\n\"", ")", "l", ".", "shift", "subl", "=", "l", ".", "each_index", ".", "select", "{", "|", "i", "|", "l", "[", "i", "]", "=~", "/", "\\s", "\\s", "/", "}", "return", "false", "if", "subl", ".", "empty?", "subl", ".", "any?", "{", "|", "i", "|", "l", "[", "i", "]", ".", "split", ".", "include?", "(", "cmd", ")", "}", "end" ]
Check the availability of a given git command
[ "Check", "the", "availability", "of", "a", "given", "git", "command" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L60-L86
train
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.init
def init(path = Dir.pwd, _options = {}) # FIXME: for travis test: ensure the global git configurations # 'user.email' and 'user.name' are set [ 'user.name', 'user.email' ].each do |userconf| next unless MiniGit[userconf].nil? warn "The Git global configuration '#{userconf}' is not set so" warn "you should *seriously* consider setting them by running\n\t git config --global #{userconf} 'your_#{userconf.sub(/\./, '_')}'" default_val = ENV['USER'] default_val += '@domain.org' if userconf =~ /email/ warn "Now putting a default value '#{default_val}' you could change later on" run %( git config --global #{userconf} "#{default_val}" ) #MiniGit[userconf] = default_val end exit_status = 1 Dir.mkdir( path ) unless Dir.exist?( path ) Dir.chdir( path ) do execute "git init" unless FalkorLib.config.debug exit_status = $?.to_i end # #puts "#init #{path}" # Dir.chdir( "#{path}" ) do # %x[ pwd && git init ] unless FalkorLib.config.debug # end exit_status end
ruby
def init(path = Dir.pwd, _options = {}) # FIXME: for travis test: ensure the global git configurations # 'user.email' and 'user.name' are set [ 'user.name', 'user.email' ].each do |userconf| next unless MiniGit[userconf].nil? warn "The Git global configuration '#{userconf}' is not set so" warn "you should *seriously* consider setting them by running\n\t git config --global #{userconf} 'your_#{userconf.sub(/\./, '_')}'" default_val = ENV['USER'] default_val += '@domain.org' if userconf =~ /email/ warn "Now putting a default value '#{default_val}' you could change later on" run %( git config --global #{userconf} "#{default_val}" ) #MiniGit[userconf] = default_val end exit_status = 1 Dir.mkdir( path ) unless Dir.exist?( path ) Dir.chdir( path ) do execute "git init" unless FalkorLib.config.debug exit_status = $?.to_i end # #puts "#init #{path}" # Dir.chdir( "#{path}" ) do # %x[ pwd && git init ] unless FalkorLib.config.debug # end exit_status end
[ "def", "init", "(", "path", "=", "Dir", ".", "pwd", ",", "_options", "=", "{", "}", ")", "[", "'user.name'", ",", "'user.email'", "]", ".", "each", "do", "|", "userconf", "|", "next", "unless", "MiniGit", "[", "userconf", "]", ".", "nil?", "warn", "\"The Git global configuration '#{userconf}' is not set so\"", "warn", "\"you should *seriously* consider setting them by running\\n\\t git config --global #{userconf} 'your_#{userconf.sub(/\\./, '_')}'\"", "default_val", "=", "ENV", "[", "'USER'", "]", "default_val", "+=", "'@domain.org'", "if", "userconf", "=~", "/", "/", "warn", "\"Now putting a default value '#{default_val}' you could change later on\"", "run", "%( git config --global #{userconf} \"#{default_val}\" )", "end", "exit_status", "=", "1", "Dir", ".", "mkdir", "(", "path", ")", "unless", "Dir", ".", "exist?", "(", "path", ")", "Dir", ".", "chdir", "(", "path", ")", "do", "execute", "\"git init\"", "unless", "FalkorLib", ".", "config", ".", "debug", "exit_status", "=", "$?", ".", "to_i", "end", "exit_status", "end" ]
Initialize a git repository
[ "Initialize", "a", "git", "repository" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L91-L117
train
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.create_branch
def create_branch(branch, path = Dir.pwd) #ap method(__method__).parameters.map { |arg| arg[1] } g = MiniGit.new(path) error "not yet any commit performed -- You shall do one" unless commits?(path) g.branch branch.to_s end
ruby
def create_branch(branch, path = Dir.pwd) #ap method(__method__).parameters.map { |arg| arg[1] } g = MiniGit.new(path) error "not yet any commit performed -- You shall do one" unless commits?(path) g.branch branch.to_s end
[ "def", "create_branch", "(", "branch", ",", "path", "=", "Dir", ".", "pwd", ")", "g", "=", "MiniGit", ".", "new", "(", "path", ")", "error", "\"not yet any commit performed -- You shall do one\"", "unless", "commits?", "(", "path", ")", "g", ".", "branch", "branch", ".", "to_s", "end" ]
Create a new branch
[ "Create", "a", "new", "branch" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L132-L137
train
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.delete_branch
def delete_branch(branch, path = Dir.pwd, opts = { :force => false }) g = MiniGit.new(path) error "'#{branch}' is not a valid existing branch" unless list_branch(path).include?( branch ) g.branch ((opts[:force]) ? :D : :d) => branch.to_s end
ruby
def delete_branch(branch, path = Dir.pwd, opts = { :force => false }) g = MiniGit.new(path) error "'#{branch}' is not a valid existing branch" unless list_branch(path).include?( branch ) g.branch ((opts[:force]) ? :D : :d) => branch.to_s end
[ "def", "delete_branch", "(", "branch", ",", "path", "=", "Dir", ".", "pwd", ",", "opts", "=", "{", ":force", "=>", "false", "}", ")", "g", "=", "MiniGit", ".", "new", "(", "path", ")", "error", "\"'#{branch}' is not a valid existing branch\"", "unless", "list_branch", "(", "path", ")", ".", "include?", "(", "branch", ")", "g", ".", "branch", "(", "(", "opts", "[", ":force", "]", ")", "?", ":D", ":", ":d", ")", "=>", "branch", ".", "to_s", "end" ]
Delete a branch.
[ "Delete", "a", "branch", "." ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L140-L144
train
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.grab
def grab(branch, path = Dir.pwd, remote = 'origin') exit_status = 1 error "no branch provided" if branch.nil? #remotes = FalkorLib::Git.remotes(path) branches = FalkorLib::Git.list_branch(path) if branches.include? "remotes/#{remote}/#{branch}" info "Grab the branch '#{remote}/#{branch}'" exit_status = execute_in_dir(FalkorLib::Git.rootdir( path ), "git branch --track #{branch} #{remote}/#{branch}") else warning "the remote branch '#{remote}/#{branch}' cannot be found" end exit_status end
ruby
def grab(branch, path = Dir.pwd, remote = 'origin') exit_status = 1 error "no branch provided" if branch.nil? #remotes = FalkorLib::Git.remotes(path) branches = FalkorLib::Git.list_branch(path) if branches.include? "remotes/#{remote}/#{branch}" info "Grab the branch '#{remote}/#{branch}'" exit_status = execute_in_dir(FalkorLib::Git.rootdir( path ), "git branch --track #{branch} #{remote}/#{branch}") else warning "the remote branch '#{remote}/#{branch}' cannot be found" end exit_status end
[ "def", "grab", "(", "branch", ",", "path", "=", "Dir", ".", "pwd", ",", "remote", "=", "'origin'", ")", "exit_status", "=", "1", "error", "\"no branch provided\"", "if", "branch", ".", "nil?", "branches", "=", "FalkorLib", "::", "Git", ".", "list_branch", "(", "path", ")", "if", "branches", ".", "include?", "\"remotes/#{remote}/#{branch}\"", "info", "\"Grab the branch '#{remote}/#{branch}'\"", "exit_status", "=", "execute_in_dir", "(", "FalkorLib", "::", "Git", ".", "rootdir", "(", "path", ")", ",", "\"git branch --track #{branch} #{remote}/#{branch}\"", ")", "else", "warning", "\"the remote branch '#{remote}/#{branch}' cannot be found\"", "end", "exit_status", "end" ]
Grab a remote branch
[ "Grab", "a", "remote", "branch" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L199-L211
train
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.publish
def publish(branch, path = Dir.pwd, remote = 'origin') exit_status = 1 error "no branch provided" if branch.nil? #remotes = FalkorLib::Git.remotes(path) branches = FalkorLib::Git.list_branch(path) Dir.chdir(FalkorLib::Git.rootdir( path ) ) do if branches.include? "remotes/#{remote}/#{branch}" warning "the remote branch '#{remote}/#{branch}' already exists" else info "Publish the branch '#{branch}' on the remote '#{remote}'" exit_status = run %( git push #{remote} #{branch}:refs/heads/#{branch} git fetch #{remote} git branch -u #{remote}/#{branch} #{branch} ) end end exit_status end
ruby
def publish(branch, path = Dir.pwd, remote = 'origin') exit_status = 1 error "no branch provided" if branch.nil? #remotes = FalkorLib::Git.remotes(path) branches = FalkorLib::Git.list_branch(path) Dir.chdir(FalkorLib::Git.rootdir( path ) ) do if branches.include? "remotes/#{remote}/#{branch}" warning "the remote branch '#{remote}/#{branch}' already exists" else info "Publish the branch '#{branch}' on the remote '#{remote}'" exit_status = run %( git push #{remote} #{branch}:refs/heads/#{branch} git fetch #{remote} git branch -u #{remote}/#{branch} #{branch} ) end end exit_status end
[ "def", "publish", "(", "branch", ",", "path", "=", "Dir", ".", "pwd", ",", "remote", "=", "'origin'", ")", "exit_status", "=", "1", "error", "\"no branch provided\"", "if", "branch", ".", "nil?", "branches", "=", "FalkorLib", "::", "Git", ".", "list_branch", "(", "path", ")", "Dir", ".", "chdir", "(", "FalkorLib", "::", "Git", ".", "rootdir", "(", "path", ")", ")", "do", "if", "branches", ".", "include?", "\"remotes/#{remote}/#{branch}\"", "warning", "\"the remote branch '#{remote}/#{branch}' already exists\"", "else", "info", "\"Publish the branch '#{branch}' on the remote '#{remote}'\"", "exit_status", "=", "run", "%( git push #{remote} #{branch}:refs/heads/#{branch} git fetch #{remote} git branch -u #{remote}/#{branch} #{branch} )", "end", "end", "exit_status", "end" ]
Publish a branch on the remote
[ "Publish", "a", "branch", "on", "the", "remote" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L214-L232
train
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.list_files
def list_files(path = Dir.pwd) g = MiniGit.new(path) g.capturing.ls_files.split end
ruby
def list_files(path = Dir.pwd) g = MiniGit.new(path) g.capturing.ls_files.split end
[ "def", "list_files", "(", "path", "=", "Dir", ".", "pwd", ")", "g", "=", "MiniGit", ".", "new", "(", "path", ")", "g", ".", "capturing", ".", "ls_files", ".", "split", "end" ]
List the files currently under version
[ "List", "the", "files", "currently", "under", "version" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L235-L238
train
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.last_tag_commit
def last_tag_commit(path = Dir.pwd) res = "" g = MiniGit.new(path) unless (g.capturing.tag :list => true).empty? # git rev-list --tags --max-count=1 res = (g.capturing.rev_list :tags => true, :max_count => 1).chomp end res end
ruby
def last_tag_commit(path = Dir.pwd) res = "" g = MiniGit.new(path) unless (g.capturing.tag :list => true).empty? # git rev-list --tags --max-count=1 res = (g.capturing.rev_list :tags => true, :max_count => 1).chomp end res end
[ "def", "last_tag_commit", "(", "path", "=", "Dir", ".", "pwd", ")", "res", "=", "\"\"", "g", "=", "MiniGit", ".", "new", "(", "path", ")", "unless", "(", "g", ".", "capturing", ".", "tag", ":list", "=>", "true", ")", ".", "empty?", "res", "=", "(", "g", ".", "capturing", ".", "rev_list", ":tags", "=>", "true", ",", ":max_count", "=>", "1", ")", ".", "chomp", "end", "res", "end" ]
list_tag Get the last tag commit, or nil if no tag can be found
[ "list_tag", "Get", "the", "last", "tag", "commit", "or", "nil", "if", "no", "tag", "can", "be", "found" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L282-L290
train
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.remotes
def remotes(path = Dir.pwd) g = MiniGit.new(path) g.capturing.remote.split end
ruby
def remotes(path = Dir.pwd) g = MiniGit.new(path) g.capturing.remote.split end
[ "def", "remotes", "(", "path", "=", "Dir", ".", "pwd", ")", "g", "=", "MiniGit", ".", "new", "(", "path", ")", "g", ".", "capturing", ".", "remote", ".", "split", "end" ]
tag List of Git remotes
[ "tag", "List", "of", "Git", "remotes" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L303-L306
train
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.subtree_init?
def subtree_init?(path = Dir.pwd) res = true FalkorLib.config.git[:subtrees].keys.each do |dir| res &&= File.directory?(File.join(path, dir)) end res end
ruby
def subtree_init?(path = Dir.pwd) res = true FalkorLib.config.git[:subtrees].keys.each do |dir| res &&= File.directory?(File.join(path, dir)) end res end
[ "def", "subtree_init?", "(", "path", "=", "Dir", ".", "pwd", ")", "res", "=", "true", "FalkorLib", ".", "config", ".", "git", "[", ":subtrees", "]", ".", "keys", ".", "each", "do", "|", "dir", "|", "res", "&&=", "File", ".", "directory?", "(", "File", ".", "join", "(", "path", ",", "dir", ")", ")", "end", "res", "end" ]
Check if the subtrees have been initialized. Actually based on a naive check of sub-directory existence
[ "Check", "if", "the", "subtrees", "have", "been", "initialized", ".", "Actually", "based", "on", "a", "naive", "check", "of", "sub", "-", "directory", "existence" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L414-L420
train
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.subtree_up
def subtree_up(path = Dir.pwd) error "Unable to pull subtree(s): Dirty Git repository" if FalkorLib::Git.dirty?( path ) exit_status = 0 git_root_dir = rootdir(path) Dir.chdir(git_root_dir) do FalkorLib.config.git[:subtrees].each do |dir, conf| next if conf[:url].nil? #url = conf[:url] remote = dir.gsub(/\//, '-') branch = (conf[:branch].nil?) ? 'master' : conf[:branch] remotes = FalkorLib::Git.remotes info "Pulling changes into subtree '#{dir}' using remote '#{remote}/#{branch}'" raise IOError, "The git remote '#{remote}' is not configured" unless remotes.include?( remote ) info "\t\\__ fetching remote '#{remotes.join(',')}'" FalkorLib::Git.fetch( git_root_dir ) raise IOError, "The git subtree directory '#{dir}' does not exists" unless File.directory?( File.join(git_root_dir, dir) ) info "\t\\__ pulling changes" exit_status = execute "git subtree pull --prefix #{dir} --squash #{remote} #{branch}" #exit_status = puts "git subtree pull --prefix #{dir} --squash #{remote} #{branch}" end end exit_status end
ruby
def subtree_up(path = Dir.pwd) error "Unable to pull subtree(s): Dirty Git repository" if FalkorLib::Git.dirty?( path ) exit_status = 0 git_root_dir = rootdir(path) Dir.chdir(git_root_dir) do FalkorLib.config.git[:subtrees].each do |dir, conf| next if conf[:url].nil? #url = conf[:url] remote = dir.gsub(/\//, '-') branch = (conf[:branch].nil?) ? 'master' : conf[:branch] remotes = FalkorLib::Git.remotes info "Pulling changes into subtree '#{dir}' using remote '#{remote}/#{branch}'" raise IOError, "The git remote '#{remote}' is not configured" unless remotes.include?( remote ) info "\t\\__ fetching remote '#{remotes.join(',')}'" FalkorLib::Git.fetch( git_root_dir ) raise IOError, "The git subtree directory '#{dir}' does not exists" unless File.directory?( File.join(git_root_dir, dir) ) info "\t\\__ pulling changes" exit_status = execute "git subtree pull --prefix #{dir} --squash #{remote} #{branch}" #exit_status = puts "git subtree pull --prefix #{dir} --squash #{remote} #{branch}" end end exit_status end
[ "def", "subtree_up", "(", "path", "=", "Dir", ".", "pwd", ")", "error", "\"Unable to pull subtree(s): Dirty Git repository\"", "if", "FalkorLib", "::", "Git", ".", "dirty?", "(", "path", ")", "exit_status", "=", "0", "git_root_dir", "=", "rootdir", "(", "path", ")", "Dir", ".", "chdir", "(", "git_root_dir", ")", "do", "FalkorLib", ".", "config", ".", "git", "[", ":subtrees", "]", ".", "each", "do", "|", "dir", ",", "conf", "|", "next", "if", "conf", "[", ":url", "]", ".", "nil?", "remote", "=", "dir", ".", "gsub", "(", "/", "\\/", "/", ",", "'-'", ")", "branch", "=", "(", "conf", "[", ":branch", "]", ".", "nil?", ")", "?", "'master'", ":", "conf", "[", ":branch", "]", "remotes", "=", "FalkorLib", "::", "Git", ".", "remotes", "info", "\"Pulling changes into subtree '#{dir}' using remote '#{remote}/#{branch}'\"", "raise", "IOError", ",", "\"The git remote '#{remote}' is not configured\"", "unless", "remotes", ".", "include?", "(", "remote", ")", "info", "\"\\t\\\\__ fetching remote '#{remotes.join(',')}'\"", "FalkorLib", "::", "Git", ".", "fetch", "(", "git_root_dir", ")", "raise", "IOError", ",", "\"The git subtree directory '#{dir}' does not exists\"", "unless", "File", ".", "directory?", "(", "File", ".", "join", "(", "git_root_dir", ",", "dir", ")", ")", "info", "\"\\t\\\\__ pulling changes\"", "exit_status", "=", "execute", "\"git subtree pull --prefix #{dir} --squash #{remote} #{branch}\"", "end", "end", "exit_status", "end" ]
Pull the latest changes, assuming the git repository is not dirty
[ "Pull", "the", "latest", "changes", "assuming", "the", "git", "repository", "is", "not", "dirty" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L449-L471
train
devs-ruby/devs
lib/devs/schedulers/calendar_queue.rb
DEVS.CalendarQueue.local_init
def local_init(bucket_count, bucket_width, start_priority) @width = bucket_width old = @buckets @buckets = if @cached_buckets == nil Array.new(bucket_count) { [] } else n = @cached_buckets.size if bucket_count < n # shrink the array @cached_buckets.slice!(bucket_count, n) else # expand the array @cached_buckets.fill(n, bucket_count - n) { [] } end @cached_buckets end @cached_buckets = old @last_priority = start_priority i = start_priority / bucket_width # virtual bucket @last_bucket = (i % bucket_count).to_i @bucket_top = (i+1) * bucket_width + 0.5 * bucket_width # set up queue size change thresholds @shrink_threshold = bucket_count / 2 - 2 @expand_threshold = 2 * bucket_count end
ruby
def local_init(bucket_count, bucket_width, start_priority) @width = bucket_width old = @buckets @buckets = if @cached_buckets == nil Array.new(bucket_count) { [] } else n = @cached_buckets.size if bucket_count < n # shrink the array @cached_buckets.slice!(bucket_count, n) else # expand the array @cached_buckets.fill(n, bucket_count - n) { [] } end @cached_buckets end @cached_buckets = old @last_priority = start_priority i = start_priority / bucket_width # virtual bucket @last_bucket = (i % bucket_count).to_i @bucket_top = (i+1) * bucket_width + 0.5 * bucket_width # set up queue size change thresholds @shrink_threshold = bucket_count / 2 - 2 @expand_threshold = 2 * bucket_count end
[ "def", "local_init", "(", "bucket_count", ",", "bucket_width", ",", "start_priority", ")", "@width", "=", "bucket_width", "old", "=", "@buckets", "@buckets", "=", "if", "@cached_buckets", "==", "nil", "Array", ".", "new", "(", "bucket_count", ")", "{", "[", "]", "}", "else", "n", "=", "@cached_buckets", ".", "size", "if", "bucket_count", "<", "n", "@cached_buckets", ".", "slice!", "(", "bucket_count", ",", "n", ")", "else", "@cached_buckets", ".", "fill", "(", "n", ",", "bucket_count", "-", "n", ")", "{", "[", "]", "}", "end", "@cached_buckets", "end", "@cached_buckets", "=", "old", "@last_priority", "=", "start_priority", "i", "=", "start_priority", "/", "bucket_width", "@last_bucket", "=", "(", "i", "%", "bucket_count", ")", ".", "to_i", "@bucket_top", "=", "(", "i", "+", "1", ")", "*", "bucket_width", "+", "0.5", "*", "bucket_width", "@shrink_threshold", "=", "bucket_count", "/", "2", "-", "2", "@expand_threshold", "=", "2", "*", "bucket_count", "end" ]
Initializes a bucket array within
[ "Initializes", "a", "bucket", "array", "within" ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/schedulers/calendar_queue.rb#L231-L257
train
devs-ruby/devs
lib/devs/schedulers/calendar_queue.rb
DEVS.CalendarQueue.resize
def resize(new_size) return unless @resize_enabled bucket_width = new_width # find new bucket width local_init(new_size, bucket_width, @last_priority) i = 0 while i < @cached_buckets.size bucket = @cached_buckets[i] @size -= bucket.size while obj = bucket.pop self << obj end i += 1 end end
ruby
def resize(new_size) return unless @resize_enabled bucket_width = new_width # find new bucket width local_init(new_size, bucket_width, @last_priority) i = 0 while i < @cached_buckets.size bucket = @cached_buckets[i] @size -= bucket.size while obj = bucket.pop self << obj end i += 1 end end
[ "def", "resize", "(", "new_size", ")", "return", "unless", "@resize_enabled", "bucket_width", "=", "new_width", "local_init", "(", "new_size", ",", "bucket_width", ",", "@last_priority", ")", "i", "=", "0", "while", "i", "<", "@cached_buckets", ".", "size", "bucket", "=", "@cached_buckets", "[", "i", "]", "@size", "-=", "bucket", ".", "size", "while", "obj", "=", "bucket", ".", "pop", "self", "<<", "obj", "end", "i", "+=", "1", "end", "end" ]
Resize buckets to new_size.
[ "Resize", "buckets", "to", "new_size", "." ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/schedulers/calendar_queue.rb#L260-L275
train
devs-ruby/devs
lib/devs/schedulers/calendar_queue.rb
DEVS.CalendarQueue.new_width
def new_width # decides how many queue elements to sample return 1.0 if @size < 2 n = if @size <= 5 @size else 5 + (@size / 10).to_i end n = 25 if n > 25 # record variables tmp_last_bucket = @last_bucket tmp_last_priority = @last_priority tmp_bucket_top = @bucket_top # dequeue n events from the queue and record their priorities with # resize_enabled set to false. @resize_enabled = false tmp = Array.new(n) average = 0.0 i = 0 while i < n # dequeue events to get a test sample tmp[i] = self.pop # and sum up the differences in time average += tmp[i].time_next - tmp[i-1].time_next if i > 0 i += 1 end # calculate average separation of sampled events average = average / (n-1).to_f # put the first sample back onto the queue self << tmp[0] # recalculate average using only separations smaller than twice the # original average new_average = 0.0 j = 0 i = 1 while i < n sub = tmp[i].time_next - tmp[i-1].time_next if sub < average * 2.0 new_average += sub j += 1 end # put the remaining samples back onto the queue self << tmp[i] i += 1 end new_average = new_average / j.to_f # restore variables @resize_enabled = true @last_bucket = tmp_last_bucket @last_priority = tmp_last_priority @bucket_top = tmp_bucket_top # this is the new width if new_average > 0.0 new_average * 3.0 elsif average > 0.0 average * 2.0 else 1.0 end end
ruby
def new_width # decides how many queue elements to sample return 1.0 if @size < 2 n = if @size <= 5 @size else 5 + (@size / 10).to_i end n = 25 if n > 25 # record variables tmp_last_bucket = @last_bucket tmp_last_priority = @last_priority tmp_bucket_top = @bucket_top # dequeue n events from the queue and record their priorities with # resize_enabled set to false. @resize_enabled = false tmp = Array.new(n) average = 0.0 i = 0 while i < n # dequeue events to get a test sample tmp[i] = self.pop # and sum up the differences in time average += tmp[i].time_next - tmp[i-1].time_next if i > 0 i += 1 end # calculate average separation of sampled events average = average / (n-1).to_f # put the first sample back onto the queue self << tmp[0] # recalculate average using only separations smaller than twice the # original average new_average = 0.0 j = 0 i = 1 while i < n sub = tmp[i].time_next - tmp[i-1].time_next if sub < average * 2.0 new_average += sub j += 1 end # put the remaining samples back onto the queue self << tmp[i] i += 1 end new_average = new_average / j.to_f # restore variables @resize_enabled = true @last_bucket = tmp_last_bucket @last_priority = tmp_last_priority @bucket_top = tmp_bucket_top # this is the new width if new_average > 0.0 new_average * 3.0 elsif average > 0.0 average * 2.0 else 1.0 end end
[ "def", "new_width", "return", "1.0", "if", "@size", "<", "2", "n", "=", "if", "@size", "<=", "5", "@size", "else", "5", "+", "(", "@size", "/", "10", ")", ".", "to_i", "end", "n", "=", "25", "if", "n", ">", "25", "tmp_last_bucket", "=", "@last_bucket", "tmp_last_priority", "=", "@last_priority", "tmp_bucket_top", "=", "@bucket_top", "@resize_enabled", "=", "false", "tmp", "=", "Array", ".", "new", "(", "n", ")", "average", "=", "0.0", "i", "=", "0", "while", "i", "<", "n", "tmp", "[", "i", "]", "=", "self", ".", "pop", "average", "+=", "tmp", "[", "i", "]", ".", "time_next", "-", "tmp", "[", "i", "-", "1", "]", ".", "time_next", "if", "i", ">", "0", "i", "+=", "1", "end", "average", "=", "average", "/", "(", "n", "-", "1", ")", ".", "to_f", "self", "<<", "tmp", "[", "0", "]", "new_average", "=", "0.0", "j", "=", "0", "i", "=", "1", "while", "i", "<", "n", "sub", "=", "tmp", "[", "i", "]", ".", "time_next", "-", "tmp", "[", "i", "-", "1", "]", ".", "time_next", "if", "sub", "<", "average", "*", "2.0", "new_average", "+=", "sub", "j", "+=", "1", "end", "self", "<<", "tmp", "[", "i", "]", "i", "+=", "1", "end", "new_average", "=", "new_average", "/", "j", ".", "to_f", "@resize_enabled", "=", "true", "@last_bucket", "=", "tmp_last_bucket", "@last_priority", "=", "tmp_last_priority", "@bucket_top", "=", "tmp_bucket_top", "if", "new_average", ">", "0.0", "new_average", "*", "3.0", "elsif", "average", ">", "0.0", "average", "*", "2.0", "else", "1.0", "end", "end" ]
Calculates the width to use for buckets
[ "Calculates", "the", "width", "to", "use", "for", "buckets" ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/schedulers/calendar_queue.rb#L278-L344
train
devs-ruby/devs
lib/devs/simulation.rb
DEVS.Simulation.transition_stats
def transition_stats if done? @transition_stats ||= ( stats = {} hierarchy = @processor.children.dup i = 0 while i < hierarchy.size child = hierarchy[i] if child.model.coupled? hierarchy.concat(child.children) else stats[child.model.name] = child.transition_stats end i+=1 end total = Hash.new(0) stats.values.each { |h| h.each { |k, v| total[k] += v }} stats[:TOTAL] = total stats ) end end
ruby
def transition_stats if done? @transition_stats ||= ( stats = {} hierarchy = @processor.children.dup i = 0 while i < hierarchy.size child = hierarchy[i] if child.model.coupled? hierarchy.concat(child.children) else stats[child.model.name] = child.transition_stats end i+=1 end total = Hash.new(0) stats.values.each { |h| h.each { |k, v| total[k] += v }} stats[:TOTAL] = total stats ) end end
[ "def", "transition_stats", "if", "done?", "@transition_stats", "||=", "(", "stats", "=", "{", "}", "hierarchy", "=", "@processor", ".", "children", ".", "dup", "i", "=", "0", "while", "i", "<", "hierarchy", ".", "size", "child", "=", "hierarchy", "[", "i", "]", "if", "child", ".", "model", ".", "coupled?", "hierarchy", ".", "concat", "(", "child", ".", "children", ")", "else", "stats", "[", "child", ".", "model", ".", "name", "]", "=", "child", ".", "transition_stats", "end", "i", "+=", "1", "end", "total", "=", "Hash", ".", "new", "(", "0", ")", "stats", ".", "values", ".", "each", "{", "|", "h", "|", "h", ".", "each", "{", "|", "k", ",", "v", "|", "total", "[", "k", "]", "+=", "v", "}", "}", "stats", "[", ":TOTAL", "]", "=", "total", "stats", ")", "end", "end" ]
Returns the number of transitions per model along with the total @return [Hash<Symbol, Fixnum>]
[ "Returns", "the", "number", "of", "transitions", "per", "model", "along", "with", "the", "total" ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/simulation.rb#L163-L184
train
robertwahler/repo_manager
lib/repo_manager/views/base_view.rb
RepoManager.BaseView.partial
def partial(filename) filename = partial_path(filename) raise "unable to find partial file: #{filename}" unless File.exists?(filename) contents = File.open(filename, "rb") {|f| f.read} # TODO: detect template EOL and match it to the partial's EOL # force unix eol contents.gsub!(/\r\n/, "\n") if contents.match("\r\n") contents end
ruby
def partial(filename) filename = partial_path(filename) raise "unable to find partial file: #{filename}" unless File.exists?(filename) contents = File.open(filename, "rb") {|f| f.read} # TODO: detect template EOL and match it to the partial's EOL # force unix eol contents.gsub!(/\r\n/, "\n") if contents.match("\r\n") contents end
[ "def", "partial", "(", "filename", ")", "filename", "=", "partial_path", "(", "filename", ")", "raise", "\"unable to find partial file: #{filename}\"", "unless", "File", ".", "exists?", "(", "filename", ")", "contents", "=", "File", ".", "open", "(", "filename", ",", "\"rb\"", ")", "{", "|", "f", "|", "f", ".", "read", "}", "contents", ".", "gsub!", "(", "/", "\\r", "\\n", "/", ",", "\"\\n\"", ")", "if", "contents", ".", "match", "(", "\"\\r\\n\"", ")", "contents", "end" ]
render a partial filename: unless absolute, it will be relative to the main template @example slim escapes HTML, use '==' head == render 'mystyle.css' @return [String] of non-escaped textual content
[ "render", "a", "partial" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/views/base_view.rb#L86-L94
train
robertwahler/repo_manager
lib/repo_manager/views/base_view.rb
RepoManager.BaseView.partial_path
def partial_path(filename) return filename if filename.nil? || Pathname.new(filename).absolute? # try relative to template if template base_folder = File.dirname(template) filename = File.expand_path(File.join(base_folder, filename)) return filename if File.exists?(filename) end # try relative to PWD filename = File.expand_path(File.join(FileUtils.pwd, filename)) return filename if File.exists?(filename) # try built in template folder filename = File.expand_path(File.join('../templates', filename), __FILE__) end
ruby
def partial_path(filename) return filename if filename.nil? || Pathname.new(filename).absolute? # try relative to template if template base_folder = File.dirname(template) filename = File.expand_path(File.join(base_folder, filename)) return filename if File.exists?(filename) end # try relative to PWD filename = File.expand_path(File.join(FileUtils.pwd, filename)) return filename if File.exists?(filename) # try built in template folder filename = File.expand_path(File.join('../templates', filename), __FILE__) end
[ "def", "partial_path", "(", "filename", ")", "return", "filename", "if", "filename", ".", "nil?", "||", "Pathname", ".", "new", "(", "filename", ")", ".", "absolute?", "if", "template", "base_folder", "=", "File", ".", "dirname", "(", "template", ")", "filename", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "base_folder", ",", "filename", ")", ")", "return", "filename", "if", "File", ".", "exists?", "(", "filename", ")", "end", "filename", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "FileUtils", ".", "pwd", ",", "filename", ")", ")", "return", "filename", "if", "File", ".", "exists?", "(", "filename", ")", "filename", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "'../templates'", ",", "filename", ")", ",", "__FILE__", ")", "end" ]
full expanded path to the given partial
[ "full", "expanded", "path", "to", "the", "given", "partial" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/views/base_view.rb#L118-L134
train
abarrak/network-client
lib/network/client.rb
Network.Client.set_logger
def set_logger @logger = if block_given? yield elsif defined?(Rails) Rails.logger else logger = Logger.new(STDOUT) logger.level = Logger::DEBUG logger end end
ruby
def set_logger @logger = if block_given? yield elsif defined?(Rails) Rails.logger else logger = Logger.new(STDOUT) logger.level = Logger::DEBUG logger end end
[ "def", "set_logger", "@logger", "=", "if", "block_given?", "yield", "elsif", "defined?", "(", "Rails", ")", "Rails", ".", "logger", "else", "logger", "=", "Logger", ".", "new", "(", "STDOUT", ")", "logger", ".", "level", "=", "Logger", "::", "DEBUG", "logger", "end", "end" ]
Sets the client logger object. Execution is yielded to passed +block+ to set, customize, and returning a logger instance. == Returns: +logger+ instance variable.
[ "Sets", "the", "client", "logger", "object", ".", "Execution", "is", "yielded", "to", "passed", "+", "block", "+", "to", "set", "customize", "and", "returning", "a", "logger", "instance", "." ]
4cf898be318bb4df056f82d405ba9ce09d3f59ac
https://github.com/abarrak/network-client/blob/4cf898be318bb4df056f82d405ba9ce09d3f59ac/lib/network/client.rb#L168-L178
train
pwnieexpress/snapi
lib/snapi/validator.rb
Snapi.Validator.valid_input?
def valid_input?(key,string) raise InvalidFormatError unless valid_regex_format?(key) boolarray = validation_regex[key].map do |regxp| (string =~ regxp) == 0 ? true : false end return true if boolarray.include?(true) false end
ruby
def valid_input?(key,string) raise InvalidFormatError unless valid_regex_format?(key) boolarray = validation_regex[key].map do |regxp| (string =~ regxp) == 0 ? true : false end return true if boolarray.include?(true) false end
[ "def", "valid_input?", "(", "key", ",", "string", ")", "raise", "InvalidFormatError", "unless", "valid_regex_format?", "(", "key", ")", "boolarray", "=", "validation_regex", "[", "key", "]", ".", "map", "do", "|", "regxp", "|", "(", "string", "=~", "regxp", ")", "==", "0", "?", "true", ":", "false", "end", "return", "true", "if", "boolarray", ".", "include?", "(", "true", ")", "false", "end" ]
Core method of the module which attempts to check if a provided string matches any of the regex's as identified by the key @params key, Symbol key which maps to one of the keys in the validation_regex method below @params string, String to check @returns Boolean, true if string checks out
[ "Core", "method", "of", "the", "module", "which", "attempts", "to", "check", "if", "a", "provided", "string", "matches", "any", "of", "the", "regex", "s", "as", "identified", "by", "the", "key" ]
3c2a6fe454721945e4e58b8b496d3c20ada55df7
https://github.com/pwnieexpress/snapi/blob/3c2a6fe454721945e4e58b8b496d3c20ada55df7/lib/snapi/validator.rb#L14-L23
train
pwnieexpress/snapi
lib/snapi/validator.rb
Snapi.Validator.validation_regex
def validation_regex { :address => [HOSTNAME_REGEX, DOMAIN_REGEX, IP_V4_REGEX, IP_V6_REGEX], :anything => [/.*/], :bool => [TRUEFALSE_REGEX], :command => [SIMPLE_COMMAND_REGEX], :gsm_adapter => [ADAPTER_REGEX], :hostname => [HOSTNAME_REGEX], :interface => [INTERFACE_REGEX], :ip => [IP_V4_REGEX, IP_V6_REGEX], :ipv6 => [IP_V6_REGEX], :ipv4 => [IP_V4_REGEX], :json => [JsonValidator], :mac => [MAC_REGEX], :snapi_function_name => [SNAPI_FUNCTION_NAME], :on_off => [ON_OFF_REGEX], :port => [PORT_REGEX], :uri => [URI_REGEX], } end
ruby
def validation_regex { :address => [HOSTNAME_REGEX, DOMAIN_REGEX, IP_V4_REGEX, IP_V6_REGEX], :anything => [/.*/], :bool => [TRUEFALSE_REGEX], :command => [SIMPLE_COMMAND_REGEX], :gsm_adapter => [ADAPTER_REGEX], :hostname => [HOSTNAME_REGEX], :interface => [INTERFACE_REGEX], :ip => [IP_V4_REGEX, IP_V6_REGEX], :ipv6 => [IP_V6_REGEX], :ipv4 => [IP_V4_REGEX], :json => [JsonValidator], :mac => [MAC_REGEX], :snapi_function_name => [SNAPI_FUNCTION_NAME], :on_off => [ON_OFF_REGEX], :port => [PORT_REGEX], :uri => [URI_REGEX], } end
[ "def", "validation_regex", "{", ":address", "=>", "[", "HOSTNAME_REGEX", ",", "DOMAIN_REGEX", ",", "IP_V4_REGEX", ",", "IP_V6_REGEX", "]", ",", ":anything", "=>", "[", "/", "/", "]", ",", ":bool", "=>", "[", "TRUEFALSE_REGEX", "]", ",", ":command", "=>", "[", "SIMPLE_COMMAND_REGEX", "]", ",", ":gsm_adapter", "=>", "[", "ADAPTER_REGEX", "]", ",", ":hostname", "=>", "[", "HOSTNAME_REGEX", "]", ",", ":interface", "=>", "[", "INTERFACE_REGEX", "]", ",", ":ip", "=>", "[", "IP_V4_REGEX", ",", "IP_V6_REGEX", "]", ",", ":ipv6", "=>", "[", "IP_V6_REGEX", "]", ",", ":ipv4", "=>", "[", "IP_V4_REGEX", "]", ",", ":json", "=>", "[", "JsonValidator", "]", ",", ":mac", "=>", "[", "MAC_REGEX", "]", ",", ":snapi_function_name", "=>", "[", "SNAPI_FUNCTION_NAME", "]", ",", ":on_off", "=>", "[", "ON_OFF_REGEX", "]", ",", ":port", "=>", "[", "PORT_REGEX", "]", ",", ":uri", "=>", "[", "URI_REGEX", "]", ",", "}", "end" ]
A helper dictionary which returns and array of valid Regexp patterns in exchange for a valid key @returns Hash, dictionary of symbols and Regexp arrays
[ "A", "helper", "dictionary", "which", "returns", "and", "array", "of", "valid", "Regexp", "patterns", "in", "exchange", "for", "a", "valid", "key" ]
3c2a6fe454721945e4e58b8b496d3c20ada55df7
https://github.com/pwnieexpress/snapi/blob/3c2a6fe454721945e4e58b8b496d3c20ada55df7/lib/snapi/validator.rb#L45-L64
train
robertwahler/repo_manager
lib/repo_manager/tasks/task_manager.rb
RepoManager.TaskManager.load_tasks
def load_tasks return if @loaded # By convention, the '*_helper.rb' files are helpers and need to be loaded first. Load # them into the Thor::Sandbox namespace Dir.glob( File.join(File.dirname(__FILE__), '**', '*.rb') ).each do |task| if task.match(/_helper\.rb$/) #logger.debug "load_thorfile helper: #{task}" ::Thor::Util.load_thorfile task end end # Now load the thor files Dir.glob( File.join(File.dirname(__FILE__), '**', '*.rb') ).each do |task| unless task.match(/_helper\.rb$/) #logger.debug "load_thorfile: #{task}" ::Thor::Util.load_thorfile task end end # load user tasks if user_tasks_folder Dir.glob( File.join([user_tasks_folder, '**', '*.{rb,thor}']) ).each { |task| ::Thor::Util.load_thorfile task if task.match(/_helper\.rb$/) } Dir.glob( File.join([user_tasks_folder, '**', '*.{rb,thor}']) ).each { |task| ::Thor::Util.load_thorfile task unless task.match(/_helper\.rb$/) } end @loaded = true end
ruby
def load_tasks return if @loaded # By convention, the '*_helper.rb' files are helpers and need to be loaded first. Load # them into the Thor::Sandbox namespace Dir.glob( File.join(File.dirname(__FILE__), '**', '*.rb') ).each do |task| if task.match(/_helper\.rb$/) #logger.debug "load_thorfile helper: #{task}" ::Thor::Util.load_thorfile task end end # Now load the thor files Dir.glob( File.join(File.dirname(__FILE__), '**', '*.rb') ).each do |task| unless task.match(/_helper\.rb$/) #logger.debug "load_thorfile: #{task}" ::Thor::Util.load_thorfile task end end # load user tasks if user_tasks_folder Dir.glob( File.join([user_tasks_folder, '**', '*.{rb,thor}']) ).each { |task| ::Thor::Util.load_thorfile task if task.match(/_helper\.rb$/) } Dir.glob( File.join([user_tasks_folder, '**', '*.{rb,thor}']) ).each { |task| ::Thor::Util.load_thorfile task unless task.match(/_helper\.rb$/) } end @loaded = true end
[ "def", "load_tasks", "return", "if", "@loaded", "Dir", ".", "glob", "(", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'**'", ",", "'*.rb'", ")", ")", ".", "each", "do", "|", "task", "|", "if", "task", ".", "match", "(", "/", "\\.", "/", ")", "::", "Thor", "::", "Util", ".", "load_thorfile", "task", "end", "end", "Dir", ".", "glob", "(", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'**'", ",", "'*.rb'", ")", ")", ".", "each", "do", "|", "task", "|", "unless", "task", ".", "match", "(", "/", "\\.", "/", ")", "::", "Thor", "::", "Util", ".", "load_thorfile", "task", "end", "end", "if", "user_tasks_folder", "Dir", ".", "glob", "(", "File", ".", "join", "(", "[", "user_tasks_folder", ",", "'**'", ",", "'*.{rb,thor}'", "]", ")", ")", ".", "each", "{", "|", "task", "|", "::", "Thor", "::", "Util", ".", "load_thorfile", "task", "if", "task", ".", "match", "(", "/", "\\.", "/", ")", "}", "Dir", ".", "glob", "(", "File", ".", "join", "(", "[", "user_tasks_folder", ",", "'**'", ",", "'*.{rb,thor}'", "]", ")", ")", ".", "each", "{", "|", "task", "|", "::", "Thor", "::", "Util", ".", "load_thorfile", "task", "unless", "task", ".", "match", "(", "/", "\\.", "/", ")", "}", "end", "@loaded", "=", "true", "end" ]
load all the tasks in this gem plus the user's own repo_manager task folder NOTE: doesn't load any default tasks or non-RepoManager tasks
[ "load", "all", "the", "tasks", "in", "this", "gem", "plus", "the", "user", "s", "own", "repo_manager", "task", "folder" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/tasks/task_manager.rb#L72-L99
train
robertwahler/repo_manager
lib/repo_manager/tasks/task_manager.rb
RepoManager.TaskManager.task_help
def task_help(name) load_tasks klass, task = find_by_namespace(name) # set '$thor_runner' to true to display full namespace $thor_runner = true klass.task_help(shell , task) end
ruby
def task_help(name) load_tasks klass, task = find_by_namespace(name) # set '$thor_runner' to true to display full namespace $thor_runner = true klass.task_help(shell , task) end
[ "def", "task_help", "(", "name", ")", "load_tasks", "klass", ",", "task", "=", "find_by_namespace", "(", "name", ")", "$thor_runner", "=", "true", "klass", ".", "task_help", "(", "shell", ",", "task", ")", "end" ]
display help for the given task
[ "display", "help", "for", "the", "given", "task" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/tasks/task_manager.rb#L135-L144
train
robertwahler/repo_manager
lib/repo_manager/tasks/task_manager.rb
RepoManager.TaskManager.list_tasks
def list_tasks load_tasks # set '$thor_runner' to true to display full namespace $thor_runner = true list = [] #Thor.printable_tasks(all = true, subcommand = true) Thor::Base.subclasses.each do |klass| list += klass.printable_tasks(false) unless klass == Thor end list.sort!{ |a,b| a[0] <=> b[0] } title = "repo_manager tasks" shell.say shell.set_color(title, :blue, bold=true) shell.say "-" * title.size shell.print_table(list, :ident => 2, :truncate => true) end
ruby
def list_tasks load_tasks # set '$thor_runner' to true to display full namespace $thor_runner = true list = [] #Thor.printable_tasks(all = true, subcommand = true) Thor::Base.subclasses.each do |klass| list += klass.printable_tasks(false) unless klass == Thor end list.sort!{ |a,b| a[0] <=> b[0] } title = "repo_manager tasks" shell.say shell.set_color(title, :blue, bold=true) shell.say "-" * title.size shell.print_table(list, :ident => 2, :truncate => true) end
[ "def", "list_tasks", "load_tasks", "$thor_runner", "=", "true", "list", "=", "[", "]", "Thor", "::", "Base", ".", "subclasses", ".", "each", "do", "|", "klass", "|", "list", "+=", "klass", ".", "printable_tasks", "(", "false", ")", "unless", "klass", "==", "Thor", "end", "list", ".", "sort!", "{", "|", "a", ",", "b", "|", "a", "[", "0", "]", "<=>", "b", "[", "0", "]", "}", "title", "=", "\"repo_manager tasks\"", "shell", ".", "say", "shell", ".", "set_color", "(", "title", ",", ":blue", ",", "bold", "=", "true", ")", "shell", ".", "say", "\"-\"", "*", "title", ".", "size", "shell", ".", "print_table", "(", "list", ",", ":ident", "=>", "2", ",", ":truncate", "=>", "true", ")", "end" ]
display a list of tasks for user display
[ "display", "a", "list", "of", "tasks", "for", "user", "display" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/tasks/task_manager.rb#L147-L163
train
robertwahler/repo_manager
lib/repo_manager/tasks/task_manager.rb
RepoManager.TaskManager.list_bare_tasks
def list_bare_tasks load_tasks Thor::Base.subclasses.each do |klass| unless klass == Thor klass.tasks.each do |t| puts "#{klass.namespace}:#{t[0]}" end end end end
ruby
def list_bare_tasks load_tasks Thor::Base.subclasses.each do |klass| unless klass == Thor klass.tasks.each do |t| puts "#{klass.namespace}:#{t[0]}" end end end end
[ "def", "list_bare_tasks", "load_tasks", "Thor", "::", "Base", ".", "subclasses", ".", "each", "do", "|", "klass", "|", "unless", "klass", "==", "Thor", "klass", ".", "tasks", ".", "each", "do", "|", "t", "|", "puts", "\"#{klass.namespace}:#{t[0]}\"", "end", "end", "end", "end" ]
display a list of tasks for CLI completion
[ "display", "a", "list", "of", "tasks", "for", "CLI", "completion" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/tasks/task_manager.rb#L166-L176
train
tmobaird/GuideboxWrapper
lib/GuideboxWrapper/guidebox_tv.rb
GuideboxWrapper.GuideboxTv.search_for_by_provider
def search_for_by_provider(name, provider) url = build_query(name) url += '/fuzzy/' + provider + "/web" data = @client.query(url) data["results"] end
ruby
def search_for_by_provider(name, provider) url = build_query(name) url += '/fuzzy/' + provider + "/web" data = @client.query(url) data["results"] end
[ "def", "search_for_by_provider", "(", "name", ",", "provider", ")", "url", "=", "build_query", "(", "name", ")", "url", "+=", "'/fuzzy/'", "+", "provider", "+", "\"/web\"", "data", "=", "@client", ".", "query", "(", "url", ")", "data", "[", "\"results\"", "]", "end" ]
Search by provider
[ "Search", "by", "provider" ]
431d541141c21620b640dcffee6cf23b3d5ca616
https://github.com/tmobaird/GuideboxWrapper/blob/431d541141c21620b640dcffee6cf23b3d5ca616/lib/GuideboxWrapper/guidebox_tv.rb#L17-L22
train
tmobaird/GuideboxWrapper
lib/GuideboxWrapper/guidebox_tv.rb
GuideboxWrapper.GuideboxTv.search_by_db_id
def search_by_db_id(id, type) url = @base_url url += "/search/id/" case type when "tvdb" url += "tvdb/" url += id.to_s when "themoviedb" url += "themoviedb/" url += id.to_s when "imdb" url += "imdb/" url += id else puts "That id type does not exist" return end @client.query(url) end
ruby
def search_by_db_id(id, type) url = @base_url url += "/search/id/" case type when "tvdb" url += "tvdb/" url += id.to_s when "themoviedb" url += "themoviedb/" url += id.to_s when "imdb" url += "imdb/" url += id else puts "That id type does not exist" return end @client.query(url) end
[ "def", "search_by_db_id", "(", "id", ",", "type", ")", "url", "=", "@base_url", "url", "+=", "\"/search/id/\"", "case", "type", "when", "\"tvdb\"", "url", "+=", "\"tvdb/\"", "url", "+=", "id", ".", "to_s", "when", "\"themoviedb\"", "url", "+=", "\"themoviedb/\"", "url", "+=", "id", ".", "to_s", "when", "\"imdb\"", "url", "+=", "\"imdb/\"", "url", "+=", "id", "else", "puts", "\"That id type does not exist\"", "return", "end", "@client", ".", "query", "(", "url", ")", "end" ]
Search for show by external db id
[ "Search", "for", "show", "by", "external", "db", "id" ]
431d541141c21620b640dcffee6cf23b3d5ca616
https://github.com/tmobaird/GuideboxWrapper/blob/431d541141c21620b640dcffee6cf23b3d5ca616/lib/GuideboxWrapper/guidebox_tv.rb#L25-L43
train
tmobaird/GuideboxWrapper
lib/GuideboxWrapper/guidebox_tv.rb
GuideboxWrapper.GuideboxTv.show_information
def show_information(name) id = self.search_for(name).first["id"] url = @base_url url += "/show/" + id.to_s @client.query(url) end
ruby
def show_information(name) id = self.search_for(name).first["id"] url = @base_url url += "/show/" + id.to_s @client.query(url) end
[ "def", "show_information", "(", "name", ")", "id", "=", "self", ".", "search_for", "(", "name", ")", ".", "first", "[", "\"id\"", "]", "url", "=", "@base_url", "url", "+=", "\"/show/\"", "+", "id", ".", "to_s", "@client", ".", "query", "(", "url", ")", "end" ]
Get all tv show info
[ "Get", "all", "tv", "show", "info" ]
431d541141c21620b640dcffee6cf23b3d5ca616
https://github.com/tmobaird/GuideboxWrapper/blob/431d541141c21620b640dcffee6cf23b3d5ca616/lib/GuideboxWrapper/guidebox_tv.rb#L66-L71
train
devs-ruby/devs
lib/devs/coordinator.rb
DEVS.Coordinator.min_time_next
def min_time_next tn = DEVS::INFINITY if (obj = @scheduler.peek) tn = obj.time_next end tn end
ruby
def min_time_next tn = DEVS::INFINITY if (obj = @scheduler.peek) tn = obj.time_next end tn end
[ "def", "min_time_next", "tn", "=", "DEVS", "::", "INFINITY", "if", "(", "obj", "=", "@scheduler", ".", "peek", ")", "tn", "=", "obj", ".", "time_next", "end", "tn", "end" ]
Returns the minimum time next in all children @return [Numeric] the min time next
[ "Returns", "the", "minimum", "time", "next", "in", "all", "children" ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/coordinator.rb#L53-L59
train
devs-ruby/devs
lib/devs/coordinator.rb
DEVS.Coordinator.max_time_last
def max_time_last max = 0 i = 0 while i < @children.size tl = @children[i].time_last max = tl if tl > max i += 1 end max end
ruby
def max_time_last max = 0 i = 0 while i < @children.size tl = @children[i].time_last max = tl if tl > max i += 1 end max end
[ "def", "max_time_last", "max", "=", "0", "i", "=", "0", "while", "i", "<", "@children", ".", "size", "tl", "=", "@children", "[", "i", "]", ".", "time_last", "max", "=", "tl", "if", "tl", ">", "max", "i", "+=", "1", "end", "max", "end" ]
Returns the maximum time last in all children @return [Numeric] the max time last
[ "Returns", "the", "maximum", "time", "last", "in", "all", "children" ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/coordinator.rb#L64-L73
train
mynyml/rack-accept-media-types
lib/rack/accept_media_types.rb
Rack.AcceptMediaTypes.order
def order(types) #:nodoc: types.map {|type| AcceptMediaType.new(type) }.reverse.sort.reverse.select {|type| type.valid? }.map {|type| type.range } end
ruby
def order(types) #:nodoc: types.map {|type| AcceptMediaType.new(type) }.reverse.sort.reverse.select {|type| type.valid? }.map {|type| type.range } end
[ "def", "order", "(", "types", ")", "types", ".", "map", "{", "|", "type", "|", "AcceptMediaType", ".", "new", "(", "type", ")", "}", ".", "reverse", ".", "sort", ".", "reverse", ".", "select", "{", "|", "type", "|", "type", ".", "valid?", "}", ".", "map", "{", "|", "type", "|", "type", ".", "range", "}", "end" ]
Order media types by quality values, remove invalid types, and return media ranges.
[ "Order", "media", "types", "by", "quality", "values", "remove", "invalid", "types", "and", "return", "media", "ranges", "." ]
3d0f38882a466cc72043fd6f6e735b7f255e4b0d
https://github.com/mynyml/rack-accept-media-types/blob/3d0f38882a466cc72043fd6f6e735b7f255e4b0d/lib/rack/accept_media_types.rb#L80-L82
train
lml/lev
lib/lev/better_active_model_errors.rb
Lev.BetterActiveModelErrors.set
def set(key, value) types[key.to_sym] = (value == [] ? [] : (value.is_a?(Symbol) ? value : nil)) messages[key.to_sym] = value end
ruby
def set(key, value) types[key.to_sym] = (value == [] ? [] : (value.is_a?(Symbol) ? value : nil)) messages[key.to_sym] = value end
[ "def", "set", "(", "key", ",", "value", ")", "types", "[", "key", ".", "to_sym", "]", "=", "(", "value", "==", "[", "]", "?", "[", "]", ":", "(", "value", ".", "is_a?", "(", "Symbol", ")", "?", "value", ":", "nil", ")", ")", "messages", "[", "key", ".", "to_sym", "]", "=", "value", "end" ]
Set messages for +key+ to +value+
[ "Set", "messages", "for", "+", "key", "+", "to", "+", "value", "+" ]
ce39ac122796974dafb24ee61428540dacf34371
https://github.com/lml/lev/blob/ce39ac122796974dafb24ee61428540dacf34371/lib/lev/better_active_model_errors.rb#L122-L125
train
lml/lev
lib/lev/better_active_model_errors.rb
Lev.BetterActiveModelErrors.delete
def delete(key) key = key.to_sym types.delete(key) messages.delete(key) end
ruby
def delete(key) key = key.to_sym types.delete(key) messages.delete(key) end
[ "def", "delete", "(", "key", ")", "key", "=", "key", ".", "to_sym", "types", ".", "delete", "(", "key", ")", "messages", ".", "delete", "(", "key", ")", "end" ]
Delete messages for +key+
[ "Delete", "messages", "for", "+", "key", "+" ]
ce39ac122796974dafb24ee61428540dacf34371
https://github.com/lml/lev/blob/ce39ac122796974dafb24ee61428540dacf34371/lib/lev/better_active_model_errors.rb#L128-L132
train
lml/lev
lib/lev/better_active_model_errors.rb
Lev.BetterActiveModelErrors.empty?
def empty? all? { |k, v| v && v.empty? && !v.is_a?(String) } end
ruby
def empty? all? { |k, v| v && v.empty? && !v.is_a?(String) } end
[ "def", "empty?", "all?", "{", "|", "k", ",", "v", "|", "v", "&&", "v", ".", "empty?", "&&", "!", "v", ".", "is_a?", "(", "String", ")", "}", "end" ]
Returns true if no errors are found, false otherwise. If the error message is a string it can be empty.
[ "Returns", "true", "if", "no", "errors", "are", "found", "false", "otherwise", ".", "If", "the", "error", "message", "is", "a", "string", "it", "can", "be", "empty", "." ]
ce39ac122796974dafb24ee61428540dacf34371
https://github.com/lml/lev/blob/ce39ac122796974dafb24ee61428540dacf34371/lib/lev/better_active_model_errors.rb#L219-L221
train
lml/lev
lib/lev/better_active_model_errors.rb
Lev.BetterActiveModelErrors.add_on_empty
def add_on_empty(attributes, options = {}) [attributes].flatten.each do |attribute| value = @base.send(:read_attribute_for_validation, attribute) is_empty = value.respond_to?(:empty?) ? value.empty? : false add(attribute, :empty, options) if value.nil? || is_empty end end
ruby
def add_on_empty(attributes, options = {}) [attributes].flatten.each do |attribute| value = @base.send(:read_attribute_for_validation, attribute) is_empty = value.respond_to?(:empty?) ? value.empty? : false add(attribute, :empty, options) if value.nil? || is_empty end end
[ "def", "add_on_empty", "(", "attributes", ",", "options", "=", "{", "}", ")", "[", "attributes", "]", ".", "flatten", ".", "each", "do", "|", "attribute", "|", "value", "=", "@base", ".", "send", "(", ":read_attribute_for_validation", ",", "attribute", ")", "is_empty", "=", "value", ".", "respond_to?", "(", ":empty?", ")", "?", "value", ".", "empty?", ":", "false", "add", "(", "attribute", ",", ":empty", ",", "options", ")", "if", "value", ".", "nil?", "||", "is_empty", "end", "end" ]
Will add an error message to each of the attributes in +attributes+ that is empty.
[ "Will", "add", "an", "error", "message", "to", "each", "of", "the", "attributes", "in", "+", "attributes", "+", "that", "is", "empty", "." ]
ce39ac122796974dafb24ee61428540dacf34371
https://github.com/lml/lev/blob/ce39ac122796974dafb24ee61428540dacf34371/lib/lev/better_active_model_errors.rb#L269-L275
train
chills42/guard-inch
lib/guard/inch.rb
Guard.Inch.start
def start message = 'Guard::Inch is running' message << ' in pedantic mode' if options[:pedantic] message << ' and inspecting private fields' if options[:private] ::Guard::UI.info message run_all if options[:all_on_start] end
ruby
def start message = 'Guard::Inch is running' message << ' in pedantic mode' if options[:pedantic] message << ' and inspecting private fields' if options[:private] ::Guard::UI.info message run_all if options[:all_on_start] end
[ "def", "start", "message", "=", "'Guard::Inch is running'", "message", "<<", "' in pedantic mode'", "if", "options", "[", ":pedantic", "]", "message", "<<", "' and inspecting private fields'", "if", "options", "[", ":private", "]", "::", "Guard", "::", "UI", ".", "info", "message", "run_all", "if", "options", "[", ":all_on_start", "]", "end" ]
configure a new instance of the plugin @param [Hash] options the guard plugin options On start, display a message and optionally run the documentation lint
[ "configure", "a", "new", "instance", "of", "the", "plugin" ]
5f8427996797e5c2100b7a1abb36fedf696b725c
https://github.com/chills42/guard-inch/blob/5f8427996797e5c2100b7a1abb36fedf696b725c/lib/guard/inch.rb#L19-L25
train
ivanzotov/constructor
pages/app/models/constructor_pages/page.rb
ConstructorPages.Page.update_fields_values
def update_fields_values(params) params || return fields.each {|f| f.find_or_create_type_object(self).tap {|t| t || next params[f.code_name.to_sym].tap {|v| v && t.value = v} t.save }} end
ruby
def update_fields_values(params) params || return fields.each {|f| f.find_or_create_type_object(self).tap {|t| t || next params[f.code_name.to_sym].tap {|v| v && t.value = v} t.save }} end
[ "def", "update_fields_values", "(", "params", ")", "params", "||", "return", "fields", ".", "each", "{", "|", "f", "|", "f", ".", "find_or_create_type_object", "(", "self", ")", ".", "tap", "{", "|", "t", "|", "t", "||", "next", "params", "[", "f", ".", "code_name", ".", "to_sym", "]", ".", "tap", "{", "|", "v", "|", "v", "&&", "t", ".", "value", "=", "v", "}", "t", ".", "save", "}", "}", "end" ]
Update all fields values with given params. @param params should looks like <tt>{price: 500, content: 'Hello'}</tt>
[ "Update", "all", "fields", "values", "with", "given", "params", "." ]
1d52fb5b642200a6993f5a630e6934bccbcbf4e8
https://github.com/ivanzotov/constructor/blob/1d52fb5b642200a6993f5a630e6934bccbcbf4e8/pages/app/models/constructor_pages/page.rb#L133-L139
train
ivanzotov/constructor
pages/app/models/constructor_pages/page.rb
ConstructorPages.Page.find_page_in_branch
def find_page_in_branch(cname) Template.find_by(code_name: cname.singularize).tap {|t| t || return (descendants.where(template_id: t.id) if cname == cname.pluralize).tap {|r| r ||= [] return r.empty? ? ancestors.find_by(template_id: t.id) : r}} end
ruby
def find_page_in_branch(cname) Template.find_by(code_name: cname.singularize).tap {|t| t || return (descendants.where(template_id: t.id) if cname == cname.pluralize).tap {|r| r ||= [] return r.empty? ? ancestors.find_by(template_id: t.id) : r}} end
[ "def", "find_page_in_branch", "(", "cname", ")", "Template", ".", "find_by", "(", "code_name", ":", "cname", ".", "singularize", ")", ".", "tap", "{", "|", "t", "|", "t", "||", "return", "(", "descendants", ".", "where", "(", "template_id", ":", "t", ".", "id", ")", "if", "cname", "==", "cname", ".", "pluralize", ")", ".", "tap", "{", "|", "r", "|", "r", "||=", "[", "]", "return", "r", ".", "empty?", "?", "ancestors", ".", "find_by", "(", "template_id", ":", "t", ".", "id", ")", ":", "r", "}", "}", "end" ]
Search page by template code_name in same branch of pages and templates. It allows to call page.category.brand.series.model etc. Return one page if founded in ancestors, and return array of pages if founded in descendants It determines if code_name is singular or nor @param cname template code name
[ "Search", "page", "by", "template", "code_name", "in", "same", "branch", "of", "pages", "and", "templates", ".", "It", "allows", "to", "call", "page", ".", "category", ".", "brand", ".", "series", ".", "model", "etc", "." ]
1d52fb5b642200a6993f5a630e6934bccbcbf4e8
https://github.com/ivanzotov/constructor/blob/1d52fb5b642200a6993f5a630e6934bccbcbf4e8/pages/app/models/constructor_pages/page.rb#L155-L159
train
ivanzotov/constructor
pages/app/models/constructor_pages/page.rb
ConstructorPages.Page.as_json
def as_json(options = {}) {name: self.name, title: self.title}.merge(options).tap do |options| fields.each {|f| options.merge!({f.code_name.to_sym => f.get_value_for(self)})} end end
ruby
def as_json(options = {}) {name: self.name, title: self.title}.merge(options).tap do |options| fields.each {|f| options.merge!({f.code_name.to_sym => f.get_value_for(self)})} end end
[ "def", "as_json", "(", "options", "=", "{", "}", ")", "{", "name", ":", "self", ".", "name", ",", "title", ":", "self", ".", "title", "}", ".", "merge", "(", "options", ")", ".", "tap", "do", "|", "options", "|", "fields", ".", "each", "{", "|", "f", "|", "options", ".", "merge!", "(", "{", "f", ".", "code_name", ".", "to_sym", "=>", "f", ".", "get_value_for", "(", "self", ")", "}", ")", "}", "end", "end" ]
Returns page hash attributes with fields. Default attributes are name and title. Options param allows to add more. @param options default merge name and title page attributes
[ "Returns", "page", "hash", "attributes", "with", "fields", "." ]
1d52fb5b642200a6993f5a630e6934bccbcbf4e8
https://github.com/ivanzotov/constructor/blob/1d52fb5b642200a6993f5a630e6934bccbcbf4e8/pages/app/models/constructor_pages/page.rb#L177-L181
train
stve/tophat
lib/tophat/meta.rb
TopHat.MetaHelper.meta_tag
def meta_tag(options, open=false, escape=true) tag(:meta, options, open, escape) end
ruby
def meta_tag(options, open=false, escape=true) tag(:meta, options, open, escape) end
[ "def", "meta_tag", "(", "options", ",", "open", "=", "false", ",", "escape", "=", "true", ")", "tag", "(", ":meta", ",", "options", ",", "open", ",", "escape", ")", "end" ]
Meta Tag helper
[ "Meta", "Tag", "helper" ]
c49a7ec029604f0fa2b64af29a72fb07f317f242
https://github.com/stve/tophat/blob/c49a7ec029604f0fa2b64af29a72fb07f317f242/lib/tophat/meta.rb#L5-L7
train
postmodern/ffi-bit_masks
lib/ffi/bit_masks.rb
FFI.BitMasks.bit_mask
def bit_mask(name,flags,type=:uint) bit_mask = BitMask.new(flags,type) typedef(bit_mask,name) return bit_mask end
ruby
def bit_mask(name,flags,type=:uint) bit_mask = BitMask.new(flags,type) typedef(bit_mask,name) return bit_mask end
[ "def", "bit_mask", "(", "name", ",", "flags", ",", "type", "=", ":uint", ")", "bit_mask", "=", "BitMask", ".", "new", "(", "flags", ",", "type", ")", "typedef", "(", "bit_mask", ",", "name", ")", "return", "bit_mask", "end" ]
Defines a new bitmask. @param [Symbol] name The name of the bitmask. @param [Hash{Symbol => Integer}] flags The flags and their masks. @param [Symbol] type The underlying type. @return [BitMask] The new bitmask.
[ "Defines", "a", "new", "bitmask", "." ]
dc34c2f99f9cc9a5629de8ccee87a97a182e0fa8
https://github.com/postmodern/ffi-bit_masks/blob/dc34c2f99f9cc9a5629de8ccee87a97a182e0fa8/lib/ffi/bit_masks.rb#L24-L29
train
eprothro/cassie
lib/cassie/schema/migrator.rb
Cassie::Schema.Migrator.build_up_commands
def build_up_commands local_versions.select{ |v| v > current_version && v <= target_version } .map{ |v| ApplyCommand.new(v) } end
ruby
def build_up_commands local_versions.select{ |v| v > current_version && v <= target_version } .map{ |v| ApplyCommand.new(v) } end
[ "def", "build_up_commands", "local_versions", ".", "select", "{", "|", "v", "|", "v", ">", "current_version", "&&", "v", "<=", "target_version", "}", ".", "map", "{", "|", "v", "|", "ApplyCommand", ".", "new", "(", "v", ")", "}", "end" ]
install all local versions since current a (current) | b | c | d (target) | e
[ "install", "all", "local", "versions", "since", "current" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/migrator.rb#L73-L76
train
eprothro/cassie
lib/cassie/schema/migrator.rb
Cassie::Schema.Migrator.build_down_commands
def build_down_commands rollbacks = rollback_versions.map{ |v| RollbackCommand.new(v) } missing = missing_versions_before(rollbacks.last.version).map{ |v| ApplyCommand.new(v) } rollbacks + missing end
ruby
def build_down_commands rollbacks = rollback_versions.map{ |v| RollbackCommand.new(v) } missing = missing_versions_before(rollbacks.last.version).map{ |v| ApplyCommand.new(v) } rollbacks + missing end
[ "def", "build_down_commands", "rollbacks", "=", "rollback_versions", ".", "map", "{", "|", "v", "|", "RollbackCommand", ".", "new", "(", "v", ")", "}", "missing", "=", "missing_versions_before", "(", "rollbacks", ".", "last", ".", "version", ")", ".", "map", "{", "|", "v", "|", "ApplyCommand", ".", "new", "(", "v", ")", "}", "rollbacks", "+", "missing", "end" ]
rollback all versions applied past the target and apply missing versions to get to target 0 | a (target) (not applied) | b | c | d (current) | e
[ "rollback", "all", "versions", "applied", "past", "the", "target", "and", "apply", "missing", "versions", "to", "get", "to", "target" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/migrator.rb#L82-L86
train
eprothro/cassie
lib/cassie/schema/migrator.rb
Cassie::Schema.Migrator.missing_versions_before
def missing_versions_before(last_rollback) return [] unless last_rollback rollback_index = applied_versions.index(last_rollback) stop = if rollback_index == applied_versions.length - 1 # rolled back to oldest version, a rollback # would put us in a versionless state. # Any versions up to target should be applied Version.new('0') else applied_versions[rollback_index + 1] end return [] if stop == target_version local_versions.select{ |v| v > stop && v <= target_version } end
ruby
def missing_versions_before(last_rollback) return [] unless last_rollback rollback_index = applied_versions.index(last_rollback) stop = if rollback_index == applied_versions.length - 1 # rolled back to oldest version, a rollback # would put us in a versionless state. # Any versions up to target should be applied Version.new('0') else applied_versions[rollback_index + 1] end return [] if stop == target_version local_versions.select{ |v| v > stop && v <= target_version } end
[ "def", "missing_versions_before", "(", "last_rollback", ")", "return", "[", "]", "unless", "last_rollback", "rollback_index", "=", "applied_versions", ".", "index", "(", "last_rollback", ")", "stop", "=", "if", "rollback_index", "==", "applied_versions", ".", "length", "-", "1", "Version", ".", "new", "(", "'0'", ")", "else", "applied_versions", "[", "rollback_index", "+", "1", "]", "end", "return", "[", "]", "if", "stop", "==", "target_version", "local_versions", ".", "select", "{", "|", "v", "|", "v", ">", "stop", "&&", "v", "<=", "target_version", "}", "end" ]
versions that are not applied yet but need to get applied to get up the target version | 0 (stop) | a (target) | b | c
[ "versions", "that", "are", "not", "applied", "yet", "but", "need", "to", "get", "applied", "to", "get", "up", "the", "target", "version" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/migrator.rb#L99-L116
train
nulldef/ciesta
lib/ciesta/class_methods.rb
Ciesta.ClassMethods.field
def field(name, **options) name = name.to_sym definitions[name] = options proxy.instance_eval do define_method(name) { fields[name] } define_method("#{name}=") { |value| fields[name] = value } end end
ruby
def field(name, **options) name = name.to_sym definitions[name] = options proxy.instance_eval do define_method(name) { fields[name] } define_method("#{name}=") { |value| fields[name] = value } end end
[ "def", "field", "(", "name", ",", "**", "options", ")", "name", "=", "name", ".", "to_sym", "definitions", "[", "name", "]", "=", "options", "proxy", ".", "instance_eval", "do", "define_method", "(", "name", ")", "{", "fields", "[", "name", "]", "}", "define_method", "(", "\"#{name}=\"", ")", "{", "|", "value", "|", "fields", "[", "name", "]", "=", "value", "}", "end", "end" ]
Declare new form field @param [Symbol] name Field name @param [Hash] options Options @option (see Ciesta::Field)
[ "Declare", "new", "form", "field" ]
07352988e687c0778fce8cae001fc2876480da32
https://github.com/nulldef/ciesta/blob/07352988e687c0778fce8cae001fc2876480da32/lib/ciesta/class_methods.rb#L10-L17
train
CDLUC3/resync
lib/resync/shared/base_change_list.rb
Resync.BaseChangeList.changes
def changes(of_type: nil, in_range: nil) resources.select do |r| is_of_type = of_type ? r.change == of_type : true is_in_range = in_range ? in_range.cover?(r.modified_time) : true is_of_type && is_in_range end end
ruby
def changes(of_type: nil, in_range: nil) resources.select do |r| is_of_type = of_type ? r.change == of_type : true is_in_range = in_range ? in_range.cover?(r.modified_time) : true is_of_type && is_in_range end end
[ "def", "changes", "(", "of_type", ":", "nil", ",", "in_range", ":", "nil", ")", "resources", ".", "select", "do", "|", "r", "|", "is_of_type", "=", "of_type", "?", "r", ".", "change", "==", "of_type", ":", "true", "is_in_range", "=", "in_range", "?", "in_range", ".", "cover?", "(", "r", ".", "modified_time", ")", ":", "true", "is_of_type", "&&", "is_in_range", "end", "end" ]
Filters the list of changes by change type, modification time, or both. @param of_type [Types::Change] the change type @param in_range [Range<Time>] the range of modification times @return [Array<Resource>] the matching changes, or all changes if neither +of_type+ nor +in_range+ is specified.
[ "Filters", "the", "list", "of", "changes", "by", "change", "type", "modification", "time", "or", "both", "." ]
f59a1f77f3c378180ee9ebcc42b325372f1e7a31
https://github.com/CDLUC3/resync/blob/f59a1f77f3c378180ee9ebcc42b325372f1e7a31/lib/resync/shared/base_change_list.rb#L11-L17
train
ohler55/opee
lib/opee/actor.rb
Opee.Actor.on_idle
def on_idle(op, *args) @idle_mutex.synchronize { @idle.insert(0, Act.new(op, args)) } @loop.wakeup() if RUNNING == @state end
ruby
def on_idle(op, *args) @idle_mutex.synchronize { @idle.insert(0, Act.new(op, args)) } @loop.wakeup() if RUNNING == @state end
[ "def", "on_idle", "(", "op", ",", "*", "args", ")", "@idle_mutex", ".", "synchronize", "{", "@idle", ".", "insert", "(", "0", ",", "Act", ".", "new", "(", "op", ",", "args", ")", ")", "}", "@loop", ".", "wakeup", "(", ")", "if", "RUNNING", "==", "@state", "end" ]
Queues an operation and arguments to be called when the Actor is has no other requests to process. @param [Symbol] op method to queue for the Actor @param [Array] args arguments to the op method
[ "Queues", "an", "operation", "and", "arguments", "to", "be", "called", "when", "the", "Actor", "is", "has", "no", "other", "requests", "to", "process", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/actor.rb#L153-L158
train
ohler55/opee
lib/opee/actor.rb
Opee.Actor.method_missing
def method_missing(m, *args, &blk) raise NoMethodError.new("undefined method '#{m}' for #{self.class}", m, args) unless respond_to?(m, true) ask(m, *args) end
ruby
def method_missing(m, *args, &blk) raise NoMethodError.new("undefined method '#{m}' for #{self.class}", m, args) unless respond_to?(m, true) ask(m, *args) end
[ "def", "method_missing", "(", "m", ",", "*", "args", ",", "&", "blk", ")", "raise", "NoMethodError", ".", "new", "(", "\"undefined method '#{m}' for #{self.class}\"", ",", "m", ",", "args", ")", "unless", "respond_to?", "(", "m", ",", "true", ")", "ask", "(", "m", ",", "*", "args", ")", "end" ]
When an attempt is made to call a private method of the Actor it is places on the processing queue. Other methods cause a NoMethodError to be raised as it normally would. @param [Symbol] m method to queue for the Actor @param [Array] args arguments to the op method @param [Proc] blk ignored
[ "When", "an", "attempt", "is", "made", "to", "call", "a", "private", "method", "of", "the", "Actor", "it", "is", "places", "on", "the", "processing", "queue", ".", "Other", "methods", "cause", "a", "NoMethodError", "to", "be", "raised", "as", "it", "normally", "would", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/actor.rb#L177-L180
train
fulldecent/structured-acceptance-test
implementations/ruby/lib/stat.rb
StatModule.Stat.findings=
def findings=(findings) raise TypeException unless findings.is_a?(Array) findings.each { |item| raise TypeException unless item.is_a?(StatModule::Finding) raise DuplicateElementException if @findings.include?(item) @findings.push(item) } end
ruby
def findings=(findings) raise TypeException unless findings.is_a?(Array) findings.each { |item| raise TypeException unless item.is_a?(StatModule::Finding) raise DuplicateElementException if @findings.include?(item) @findings.push(item) } end
[ "def", "findings", "=", "(", "findings", ")", "raise", "TypeException", "unless", "findings", ".", "is_a?", "(", "Array", ")", "findings", ".", "each", "{", "|", "item", "|", "raise", "TypeException", "unless", "item", ".", "is_a?", "(", "StatModule", "::", "Finding", ")", "raise", "DuplicateElementException", "if", "@findings", ".", "include?", "(", "item", ")", "@findings", ".", "push", "(", "item", ")", "}", "end" ]
Initialize new Stat object Params: +process+:: StatModule::Process, required +hash+:: Hash, can be null Set array of findings Params: +findings+:: Array of StatModule::Finding
[ "Initialize", "new", "Stat", "object" ]
9766f4863a8bcfdf6ac50a7aa36cce0314481118
https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/stat.rb#L43-L50
train
fulldecent/structured-acceptance-test
implementations/ruby/lib/stat.rb
StatModule.Stat.print_header
def print_header @finding_print_index = 0 hash = {} hash['statVersion'] = @statVersion hash['process'] = @process hash['findings'] = [] result = hash.to_json result = result[0..result.length - 3] puts(result) puts $stdout.flush end
ruby
def print_header @finding_print_index = 0 hash = {} hash['statVersion'] = @statVersion hash['process'] = @process hash['findings'] = [] result = hash.to_json result = result[0..result.length - 3] puts(result) puts $stdout.flush end
[ "def", "print_header", "@finding_print_index", "=", "0", "hash", "=", "{", "}", "hash", "[", "'statVersion'", "]", "=", "@statVersion", "hash", "[", "'process'", "]", "=", "@process", "hash", "[", "'findings'", "]", "=", "[", "]", "result", "=", "hash", ".", "to_json", "result", "=", "result", "[", "0", "..", "result", ".", "length", "-", "3", "]", "puts", "(", "result", ")", "puts", "$stdout", ".", "flush", "end" ]
Prints header of STAT object in json format Header contains statVersion, process and optional array of findings
[ "Prints", "header", "of", "STAT", "object", "in", "json", "format", "Header", "contains", "statVersion", "process", "and", "optional", "array", "of", "findings" ]
9766f4863a8bcfdf6ac50a7aa36cce0314481118
https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/stat.rb#L77-L88
train
fulldecent/structured-acceptance-test
implementations/ruby/lib/stat.rb
StatModule.Stat.print_finding
def print_finding if @finding_print_index < @findings.length result = @findings[@finding_print_index].to_json result += ',' unless @finding_print_index >= @findings.length - 1 puts result puts $stdout.flush @finding_print_index += 1 else raise IndexOutOfBoundException end end
ruby
def print_finding if @finding_print_index < @findings.length result = @findings[@finding_print_index].to_json result += ',' unless @finding_print_index >= @findings.length - 1 puts result puts $stdout.flush @finding_print_index += 1 else raise IndexOutOfBoundException end end
[ "def", "print_finding", "if", "@finding_print_index", "<", "@findings", ".", "length", "result", "=", "@findings", "[", "@finding_print_index", "]", ".", "to_json", "result", "+=", "','", "unless", "@finding_print_index", ">=", "@findings", ".", "length", "-", "1", "puts", "result", "puts", "$stdout", ".", "flush", "@finding_print_index", "+=", "1", "else", "raise", "IndexOutOfBoundException", "end", "end" ]
Prints one finding in json format.
[ "Prints", "one", "finding", "in", "json", "format", "." ]
9766f4863a8bcfdf6ac50a7aa36cce0314481118
https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/stat.rb#L92-L103
train