id
int32 0
24.9k
| 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
|
---|---|---|---|---|---|---|---|---|---|---|---|
23,300 | localytics/humidifier | lib/humidifier/stack.rb | Humidifier.Stack.add | def add(name, resource, attributes = {})
resources[name] = resource
resource.update_attributes(attributes) if attributes.any?
resource
end | ruby | def add(name, resource, attributes = {})
resources[name] = resource
resource.update_attributes(attributes) if attributes.any?
resource
end | [
"def",
"add",
"(",
"name",
",",
"resource",
",",
"attributes",
"=",
"{",
"}",
")",
"resources",
"[",
"name",
"]",
"=",
"resource",
"resource",
".",
"update_attributes",
"(",
"attributes",
")",
"if",
"attributes",
".",
"any?",
"resource",
"end"
] | Add a resource to the stack and optionally set its attributes | [
"Add",
"a",
"resource",
"to",
"the",
"stack",
"and",
"optionally",
"set",
"its",
"attributes"
] | 143c2fd9a411278988e8b40bd7598ac80f419c20 | https://github.com/localytics/humidifier/blob/143c2fd9a411278988e8b40bd7598ac80f419c20/lib/humidifier/stack.rb#L32-L36 |
23,301 | localytics/humidifier | lib/humidifier/stack.rb | Humidifier.Stack.to_cf | def to_cf(serializer = :json)
resources = static_resources.merge(enumerable_resources)
case serializer
when :json then JSON.pretty_generate(resources)
when :yaml then YAML.dump(resources)
end
end | ruby | def to_cf(serializer = :json)
resources = static_resources.merge(enumerable_resources)
case serializer
when :json then JSON.pretty_generate(resources)
when :yaml then YAML.dump(resources)
end
end | [
"def",
"to_cf",
"(",
"serializer",
"=",
":json",
")",
"resources",
"=",
"static_resources",
".",
"merge",
"(",
"enumerable_resources",
")",
"case",
"serializer",
"when",
":json",
"then",
"JSON",
".",
"pretty_generate",
"(",
"resources",
")",
"when",
":yaml",
"then",
"YAML",
".",
"dump",
"(",
"resources",
")",
"end",
"end"
] | A string representation of the stack that's valid for CFN | [
"A",
"string",
"representation",
"of",
"the",
"stack",
"that",
"s",
"valid",
"for",
"CFN"
] | 143c2fd9a411278988e8b40bd7598ac80f419c20 | https://github.com/localytics/humidifier/blob/143c2fd9a411278988e8b40bd7598ac80f419c20/lib/humidifier/stack.rb#L45-L52 |
23,302 | grange-insurance/cuke_slicer | lib/cuke_slicer/slicer.rb | CukeSlicer.Slicer.slice | def slice(target, filters = {}, format, &block)
validate_target(target)
validate_filters(filters)
validate_format(format)
begin
target = File.directory?(target) ? CukeModeler::Directory.new(target) : CukeModeler::FeatureFile.new(target)
rescue => e
if e.message =~ /lexing|parsing/i
raise(ArgumentError, "A syntax or lexing problem was encountered while trying to parse #{target}")
else
raise e
end
end
if target.is_a?(CukeModeler::Directory)
sliced_tests = DirectoryExtractor.new.extract(target, filters, format, &block)
else
sliced_tests = FileExtractor.new.extract(target, filters, format, &block)
end
sliced_tests
end | ruby | def slice(target, filters = {}, format, &block)
validate_target(target)
validate_filters(filters)
validate_format(format)
begin
target = File.directory?(target) ? CukeModeler::Directory.new(target) : CukeModeler::FeatureFile.new(target)
rescue => e
if e.message =~ /lexing|parsing/i
raise(ArgumentError, "A syntax or lexing problem was encountered while trying to parse #{target}")
else
raise e
end
end
if target.is_a?(CukeModeler::Directory)
sliced_tests = DirectoryExtractor.new.extract(target, filters, format, &block)
else
sliced_tests = FileExtractor.new.extract(target, filters, format, &block)
end
sliced_tests
end | [
"def",
"slice",
"(",
"target",
",",
"filters",
"=",
"{",
"}",
",",
"format",
",",
"&",
"block",
")",
"validate_target",
"(",
"target",
")",
"validate_filters",
"(",
"filters",
")",
"validate_format",
"(",
"format",
")",
"begin",
"target",
"=",
"File",
".",
"directory?",
"(",
"target",
")",
"?",
"CukeModeler",
"::",
"Directory",
".",
"new",
"(",
"target",
")",
":",
"CukeModeler",
"::",
"FeatureFile",
".",
"new",
"(",
"target",
")",
"rescue",
"=>",
"e",
"if",
"e",
".",
"message",
"=~",
"/",
"/i",
"raise",
"(",
"ArgumentError",
",",
"\"A syntax or lexing problem was encountered while trying to parse #{target}\"",
")",
"else",
"raise",
"e",
"end",
"end",
"if",
"target",
".",
"is_a?",
"(",
"CukeModeler",
"::",
"Directory",
")",
"sliced_tests",
"=",
"DirectoryExtractor",
".",
"new",
".",
"extract",
"(",
"target",
",",
"filters",
",",
"format",
",",
"block",
")",
"else",
"sliced_tests",
"=",
"FileExtractor",
".",
"new",
".",
"extract",
"(",
"target",
",",
"filters",
",",
"format",
",",
"block",
")",
"end",
"sliced_tests",
"end"
] | Slices up the given location into individual test cases.
The location chosen for slicing can be a file or directory path. Optional filters can be provided in order to
ignore certain kinds of test cases. See #known_filters for the available option types. Most options are either a
string or regular expression, although arrays of the same can be given instead if more than one filter is desired.
A block can be provided as a filter which can allow for maximal filtering flexibility. Note, however, that this
exposes the underlying modeling objects and knowledge of how they work is then required to make good use of the
filter.
Finally, the test cases can be provided as a collection of file:line strings or as a collection of the object
types used to represent test cases by the underlying modeling library.
@param target [String] the location that will be sliced up
@param filters [Hash] the filters that will be applied to the sliced test cases
@param format [Symbol] the type of output: :file_line or :test_object | [
"Slices",
"up",
"the",
"given",
"location",
"into",
"individual",
"test",
"cases",
"."
] | 8a31914fae2458c26ec268d9b2c0ea554a7c510c | https://github.com/grange-insurance/cuke_slicer/blob/8a31914fae2458c26ec268d9b2c0ea554a7c510c/lib/cuke_slicer/slicer.rb#L27-L50 |
23,303 | iiif-prezi/osullivan | lib/iiif/ordered_hash.rb | IIIF.OrderedHash.insert | def insert(index, key, value)
tmp = IIIF::OrderedHash.new
index = self.length + 1 + index if index < 0
if index < 0
m = "Index #{index} is too small for current length (#{length})"
raise IndexError, m
end
if index > 0
i=0
self.each do |k,v|
tmp[k] = v
self.delete(k)
i+=1
break if i == index
end
end
tmp[key] = value
tmp.merge!(self) # copy the remaining to tmp
self.clear # start over...
self.merge!(tmp) # now put them all back
self
end | ruby | def insert(index, key, value)
tmp = IIIF::OrderedHash.new
index = self.length + 1 + index if index < 0
if index < 0
m = "Index #{index} is too small for current length (#{length})"
raise IndexError, m
end
if index > 0
i=0
self.each do |k,v|
tmp[k] = v
self.delete(k)
i+=1
break if i == index
end
end
tmp[key] = value
tmp.merge!(self) # copy the remaining to tmp
self.clear # start over...
self.merge!(tmp) # now put them all back
self
end | [
"def",
"insert",
"(",
"index",
",",
"key",
",",
"value",
")",
"tmp",
"=",
"IIIF",
"::",
"OrderedHash",
".",
"new",
"index",
"=",
"self",
".",
"length",
"+",
"1",
"+",
"index",
"if",
"index",
"<",
"0",
"if",
"index",
"<",
"0",
"m",
"=",
"\"Index #{index} is too small for current length (#{length})\"",
"raise",
"IndexError",
",",
"m",
"end",
"if",
"index",
">",
"0",
"i",
"=",
"0",
"self",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"tmp",
"[",
"k",
"]",
"=",
"v",
"self",
".",
"delete",
"(",
"k",
")",
"i",
"+=",
"1",
"break",
"if",
"i",
"==",
"index",
"end",
"end",
"tmp",
"[",
"key",
"]",
"=",
"value",
"tmp",
".",
"merge!",
"(",
"self",
")",
"# copy the remaining to tmp",
"self",
".",
"clear",
"# start over...",
"self",
".",
"merge!",
"(",
"tmp",
")",
"# now put them all back",
"self",
"end"
] | Insert a new key and value at the suppplied index.
Note that this is slightly different from Array#insert in that new
entries must be added one at a time, i.e. insert(n, k, v, k, v...) is
not supported.
@param [Integer] index
@param [Object] key
@param [Object] value | [
"Insert",
"a",
"new",
"key",
"and",
"value",
"at",
"the",
"suppplied",
"index",
"."
] | d659b736a19ea6283761cf417dcad78470da0978 | https://github.com/iiif-prezi/osullivan/blob/d659b736a19ea6283761cf417dcad78470da0978/lib/iiif/ordered_hash.rb#L15-L36 |
23,304 | iiif-prezi/osullivan | lib/iiif/ordered_hash.rb | IIIF.OrderedHash.remove_empties | def remove_empties
self.keys.each do |key|
if (self[key].kind_of?(Array) && self[key].empty?) || self[key].nil?
self.delete(key)
end
end
end | ruby | def remove_empties
self.keys.each do |key|
if (self[key].kind_of?(Array) && self[key].empty?) || self[key].nil?
self.delete(key)
end
end
end | [
"def",
"remove_empties",
"self",
".",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"if",
"(",
"self",
"[",
"key",
"]",
".",
"kind_of?",
"(",
"Array",
")",
"&&",
"self",
"[",
"key",
"]",
".",
"empty?",
")",
"||",
"self",
"[",
"key",
"]",
".",
"nil?",
"self",
".",
"delete",
"(",
"key",
")",
"end",
"end",
"end"
] | Delete any keys that are empty arrays | [
"Delete",
"any",
"keys",
"that",
"are",
"empty",
"arrays"
] | d659b736a19ea6283761cf417dcad78470da0978 | https://github.com/iiif-prezi/osullivan/blob/d659b736a19ea6283761cf417dcad78470da0978/lib/iiif/ordered_hash.rb#L79-L85 |
23,305 | iiif-prezi/osullivan | lib/iiif/ordered_hash.rb | IIIF.OrderedHash.camelize_keys | def camelize_keys
self.keys.each_with_index do |key, i|
if key != key.camelize(:lower)
self.insert(i, key.camelize(:lower), self[key])
self.delete(key)
end
end
self
end | ruby | def camelize_keys
self.keys.each_with_index do |key, i|
if key != key.camelize(:lower)
self.insert(i, key.camelize(:lower), self[key])
self.delete(key)
end
end
self
end | [
"def",
"camelize_keys",
"self",
".",
"keys",
".",
"each_with_index",
"do",
"|",
"key",
",",
"i",
"|",
"if",
"key",
"!=",
"key",
".",
"camelize",
"(",
":lower",
")",
"self",
".",
"insert",
"(",
"i",
",",
"key",
".",
"camelize",
"(",
":lower",
")",
",",
"self",
"[",
"key",
"]",
")",
"self",
".",
"delete",
"(",
"key",
")",
"end",
"end",
"self",
"end"
] | Covert snake_case keys to camelCase | [
"Covert",
"snake_case",
"keys",
"to",
"camelCase"
] | d659b736a19ea6283761cf417dcad78470da0978 | https://github.com/iiif-prezi/osullivan/blob/d659b736a19ea6283761cf417dcad78470da0978/lib/iiif/ordered_hash.rb#L88-L96 |
23,306 | iiif-prezi/osullivan | lib/iiif/ordered_hash.rb | IIIF.OrderedHash.snakeize_keys | def snakeize_keys
self.keys.each_with_index do |key, i|
if key != key.underscore
self.insert(i, key.underscore, self[key])
self.delete(key)
end
end
self
end | ruby | def snakeize_keys
self.keys.each_with_index do |key, i|
if key != key.underscore
self.insert(i, key.underscore, self[key])
self.delete(key)
end
end
self
end | [
"def",
"snakeize_keys",
"self",
".",
"keys",
".",
"each_with_index",
"do",
"|",
"key",
",",
"i",
"|",
"if",
"key",
"!=",
"key",
".",
"underscore",
"self",
".",
"insert",
"(",
"i",
",",
"key",
".",
"underscore",
",",
"self",
"[",
"key",
"]",
")",
"self",
".",
"delete",
"(",
"key",
")",
"end",
"end",
"self",
"end"
] | Covert camelCase keys to snake_case | [
"Covert",
"camelCase",
"keys",
"to",
"snake_case"
] | d659b736a19ea6283761cf417dcad78470da0978 | https://github.com/iiif-prezi/osullivan/blob/d659b736a19ea6283761cf417dcad78470da0978/lib/iiif/ordered_hash.rb#L99-L107 |
23,307 | salesking/king_dtaus | lib/king_dta/dtazv.rb | KingDta.Dtazv.add_z | def add_z(bookings)
data3 = '0256'
data3 += 'Z'
sum = 0
bookings.each do |b|
sum += b.value.divmod(100)[0]
end
data3 += '%015i' % sum
data3 += '%015i' % bookings.count
data3 += '%0221s' % ''
raise "DTAUS: Längenfehler Z (#{data3.size} <> 256)\n" if data3.size != 256
dta_string << data3
end | ruby | def add_z(bookings)
data3 = '0256'
data3 += 'Z'
sum = 0
bookings.each do |b|
sum += b.value.divmod(100)[0]
end
data3 += '%015i' % sum
data3 += '%015i' % bookings.count
data3 += '%0221s' % ''
raise "DTAUS: Längenfehler Z (#{data3.size} <> 256)\n" if data3.size != 256
dta_string << data3
end | [
"def",
"add_z",
"(",
"bookings",
")",
"data3",
"=",
"'0256'",
"data3",
"+=",
"'Z'",
"sum",
"=",
"0",
"bookings",
".",
"each",
"do",
"|",
"b",
"|",
"sum",
"+=",
"b",
".",
"value",
".",
"divmod",
"(",
"100",
")",
"[",
"0",
"]",
"end",
"data3",
"+=",
"'%015i'",
"%",
"sum",
"data3",
"+=",
"'%015i'",
"%",
"bookings",
".",
"count",
"data3",
"+=",
"'%0221s'",
"%",
"''",
"raise",
"\"DTAUS: Längenfehler Z (#{data3.size} <> 256)\\n\" ",
"f ",
"ata3.",
"s",
"ize ",
"= ",
"56",
"dta_string",
"<<",
"data3",
"end"
] | THE MAGICAL Z SEGMENT | [
"THE",
"MAGICAL",
"Z",
"SEGMENT"
] | 84a72f2f0476b6fae5253aa7a139cfc639eace08 | https://github.com/salesking/king_dtaus/blob/84a72f2f0476b6fae5253aa7a139cfc639eace08/lib/king_dta/dtazv.rb#L275-L287 |
23,308 | iiif-prezi/osullivan | lib/iiif/hash_behaviours.rb | IIIF.HashBehaviours.select | def select
new_instance = self.class.new
if block_given?
@data.each { |k,v| new_instance.data[k] = v if yield(k,v) }
end
return new_instance
end | ruby | def select
new_instance = self.class.new
if block_given?
@data.each { |k,v| new_instance.data[k] = v if yield(k,v) }
end
return new_instance
end | [
"def",
"select",
"new_instance",
"=",
"self",
".",
"class",
".",
"new",
"if",
"block_given?",
"@data",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"new_instance",
".",
"data",
"[",
"k",
"]",
"=",
"v",
"if",
"yield",
"(",
"k",
",",
"v",
")",
"}",
"end",
"return",
"new_instance",
"end"
] | Returns a new instance consisting of entries for which the block returns
true. Not that an enumerator is not available for the OrderedHash'
implementation | [
"Returns",
"a",
"new",
"instance",
"consisting",
"of",
"entries",
"for",
"which",
"the",
"block",
"returns",
"true",
".",
"Not",
"that",
"an",
"enumerator",
"is",
"not",
"available",
"for",
"the",
"OrderedHash",
"implementation"
] | d659b736a19ea6283761cf417dcad78470da0978 | https://github.com/iiif-prezi/osullivan/blob/d659b736a19ea6283761cf417dcad78470da0978/lib/iiif/hash_behaviours.rb#L123-L129 |
23,309 | salesking/king_dtaus | lib/king_dta/account.rb | KingDta.Account.bank_account_number= | def bank_account_number=(number)
raise ArgumentError.new('Bank account number cannot be nil') if number.nil?
nr_str = "#{number}".gsub(/\s/,'')
raise ArgumentError.new('Bank account number too long, max 10 allowed') if nr_str.length > 10
raise ArgumentError.new('Bank account number cannot be 0') if nr_str == '0'
@bank_account_number = nr_str.to_i
end | ruby | def bank_account_number=(number)
raise ArgumentError.new('Bank account number cannot be nil') if number.nil?
nr_str = "#{number}".gsub(/\s/,'')
raise ArgumentError.new('Bank account number too long, max 10 allowed') if nr_str.length > 10
raise ArgumentError.new('Bank account number cannot be 0') if nr_str == '0'
@bank_account_number = nr_str.to_i
end | [
"def",
"bank_account_number",
"=",
"(",
"number",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"'Bank account number cannot be nil'",
")",
"if",
"number",
".",
"nil?",
"nr_str",
"=",
"\"#{number}\"",
".",
"gsub",
"(",
"/",
"\\s",
"/",
",",
"''",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"'Bank account number too long, max 10 allowed'",
")",
"if",
"nr_str",
".",
"length",
">",
"10",
"raise",
"ArgumentError",
".",
"new",
"(",
"'Bank account number cannot be 0'",
")",
"if",
"nr_str",
"==",
"'0'",
"@bank_account_number",
"=",
"nr_str",
".",
"to_i",
"end"
] | Cast given account number to integer. Strips spaces and leading zeros
from the bank account number.
DTA relies on integers for checksums and field values.
@param [String|Integer] number | [
"Cast",
"given",
"account",
"number",
"to",
"integer",
".",
"Strips",
"spaces",
"and",
"leading",
"zeros",
"from",
"the",
"bank",
"account",
"number",
".",
"DTA",
"relies",
"on",
"integers",
"for",
"checksums",
"and",
"field",
"values",
"."
] | 84a72f2f0476b6fae5253aa7a139cfc639eace08 | https://github.com/salesking/king_dtaus/blob/84a72f2f0476b6fae5253aa7a139cfc639eace08/lib/king_dta/account.rb#L49-L56 |
23,310 | ssoroka/scheduler_daemon | lib/scheduler_daemon/base.rb | Scheduler.Base.time | def time
if Time.respond_to?(:zone) && Time.zone
self.class.send(:define_method, :time) { Time.zone.now.to_s }
else
self.class.send(:define_method, :time) { Time.now.to_s }
end
time
end | ruby | def time
if Time.respond_to?(:zone) && Time.zone
self.class.send(:define_method, :time) { Time.zone.now.to_s }
else
self.class.send(:define_method, :time) { Time.now.to_s }
end
time
end | [
"def",
"time",
"if",
"Time",
".",
"respond_to?",
"(",
":zone",
")",
"&&",
"Time",
".",
"zone",
"self",
".",
"class",
".",
"send",
"(",
":define_method",
",",
":time",
")",
"{",
"Time",
".",
"zone",
".",
"now",
".",
"to_s",
"}",
"else",
"self",
".",
"class",
".",
"send",
"(",
":define_method",
",",
":time",
")",
"{",
"Time",
".",
"now",
".",
"to_s",
"}",
"end",
"time",
"end"
] | time redefines itself with a faster implementation, since it gets called a lot. | [
"time",
"redefines",
"itself",
"with",
"a",
"faster",
"implementation",
"since",
"it",
"gets",
"called",
"a",
"lot",
"."
] | dc52046eb0002ba8529a3f6cc8cea3f327020020 | https://github.com/ssoroka/scheduler_daemon/blob/dc52046eb0002ba8529a3f6cc8cea3f327020020/lib/scheduler_daemon/base.rb#L69-L76 |
23,311 | bmuller/bandit | lib/bandit/storage/redis.rb | Bandit.RedisStorage.init | def init(key, value)
with_failure_grace(value) {
@redis.set(key, value) if get(key, nil).nil?
}
end | ruby | def init(key, value)
with_failure_grace(value) {
@redis.set(key, value) if get(key, nil).nil?
}
end | [
"def",
"init",
"(",
"key",
",",
"value",
")",
"with_failure_grace",
"(",
"value",
")",
"{",
"@redis",
".",
"set",
"(",
"key",
",",
"value",
")",
"if",
"get",
"(",
"key",
",",
"nil",
")",
".",
"nil?",
"}",
"end"
] | initialize key if not set | [
"initialize",
"key",
"if",
"not",
"set"
] | 4c2528adee6ed761b3298f5b8889819ed9e04483 | https://github.com/bmuller/bandit/blob/4c2528adee6ed761b3298f5b8889819ed9e04483/lib/bandit/storage/redis.rb#L28-L32 |
23,312 | bmuller/bandit | lib/bandit/storage/redis.rb | Bandit.RedisStorage.get | def get(key, default=0)
with_failure_grace(default) {
val = @redis.get(key)
return default if val.nil?
val.numeric? ? val.to_i : val
}
end | ruby | def get(key, default=0)
with_failure_grace(default) {
val = @redis.get(key)
return default if val.nil?
val.numeric? ? val.to_i : val
}
end | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"0",
")",
"with_failure_grace",
"(",
"default",
")",
"{",
"val",
"=",
"@redis",
".",
"get",
"(",
"key",
")",
"return",
"default",
"if",
"val",
".",
"nil?",
"val",
".",
"numeric?",
"?",
"val",
".",
"to_i",
":",
"val",
"}",
"end"
] | get key if exists, otherwise 0 | [
"get",
"key",
"if",
"exists",
"otherwise",
"0"
] | 4c2528adee6ed761b3298f5b8889819ed9e04483 | https://github.com/bmuller/bandit/blob/4c2528adee6ed761b3298f5b8889819ed9e04483/lib/bandit/storage/redis.rb#L35-L41 |
23,313 | bmuller/bandit | lib/bandit/extensions/view_concerns.rb | Bandit.ViewConcerns.bandit_session_choose | def bandit_session_choose(exp)
name = "bandit_#{exp}".intern
# choose url param with preference
value = params[name].nil? ? cookies.signed[name] : params[name]
# choose with default, and set cookie
cookies.signed[name] = Bandit.get_experiment(exp).choose(value)
end | ruby | def bandit_session_choose(exp)
name = "bandit_#{exp}".intern
# choose url param with preference
value = params[name].nil? ? cookies.signed[name] : params[name]
# choose with default, and set cookie
cookies.signed[name] = Bandit.get_experiment(exp).choose(value)
end | [
"def",
"bandit_session_choose",
"(",
"exp",
")",
"name",
"=",
"\"bandit_#{exp}\"",
".",
"intern",
"# choose url param with preference",
"value",
"=",
"params",
"[",
"name",
"]",
".",
"nil?",
"?",
"cookies",
".",
"signed",
"[",
"name",
"]",
":",
"params",
"[",
"name",
"]",
"# choose with default, and set cookie",
"cookies",
".",
"signed",
"[",
"name",
"]",
"=",
"Bandit",
".",
"get_experiment",
"(",
"exp",
")",
".",
"choose",
"(",
"value",
")",
"end"
] | stick to one alternative for the entire browser session | [
"stick",
"to",
"one",
"alternative",
"for",
"the",
"entire",
"browser",
"session"
] | 4c2528adee6ed761b3298f5b8889819ed9e04483 | https://github.com/bmuller/bandit/blob/4c2528adee6ed761b3298f5b8889819ed9e04483/lib/bandit/extensions/view_concerns.rb#L18-L24 |
23,314 | bmuller/bandit | lib/bandit/extensions/view_concerns.rb | Bandit.ViewConcerns.bandit_sticky_choose | def bandit_sticky_choose(exp)
name = "bandit_#{exp}".intern
# choose url param with preference
value = params[name].nil? ? cookies.signed[name] : params[name]
# sticky choice may outlast a given alternative
alternative = if Bandit.get_experiment(exp).alternatives.include?(value)
value
else
Bandit.get_experiment(exp).choose(value)
end
# re-set cookie
cookies.permanent.signed[name] = alternative
end | ruby | def bandit_sticky_choose(exp)
name = "bandit_#{exp}".intern
# choose url param with preference
value = params[name].nil? ? cookies.signed[name] : params[name]
# sticky choice may outlast a given alternative
alternative = if Bandit.get_experiment(exp).alternatives.include?(value)
value
else
Bandit.get_experiment(exp).choose(value)
end
# re-set cookie
cookies.permanent.signed[name] = alternative
end | [
"def",
"bandit_sticky_choose",
"(",
"exp",
")",
"name",
"=",
"\"bandit_#{exp}\"",
".",
"intern",
"# choose url param with preference",
"value",
"=",
"params",
"[",
"name",
"]",
".",
"nil?",
"?",
"cookies",
".",
"signed",
"[",
"name",
"]",
":",
"params",
"[",
"name",
"]",
"# sticky choice may outlast a given alternative",
"alternative",
"=",
"if",
"Bandit",
".",
"get_experiment",
"(",
"exp",
")",
".",
"alternatives",
".",
"include?",
"(",
"value",
")",
"value",
"else",
"Bandit",
".",
"get_experiment",
"(",
"exp",
")",
".",
"choose",
"(",
"value",
")",
"end",
"# re-set cookie",
"cookies",
".",
"permanent",
".",
"signed",
"[",
"name",
"]",
"=",
"alternative",
"end"
] | stick to one alternative until user deletes cookies or changes browser | [
"stick",
"to",
"one",
"alternative",
"until",
"user",
"deletes",
"cookies",
"or",
"changes",
"browser"
] | 4c2528adee6ed761b3298f5b8889819ed9e04483 | https://github.com/bmuller/bandit/blob/4c2528adee6ed761b3298f5b8889819ed9e04483/lib/bandit/extensions/view_concerns.rb#L27-L39 |
23,315 | shinesolutions/ruby_aem | lib/ruby_aem.rb | RubyAem.Aem.sanitise_conf | def sanitise_conf(conf)
conf[:username] ||= 'admin'
conf[:password] ||= 'admin'
conf[:protocol] ||= 'http'
conf[:host] ||= 'localhost'
conf[:port] ||= 4502
conf[:timeout] ||= 300
# handle custom configuration value being passed as a String
# e.g. when the values are passed via environment variables
conf[:port] = conf[:port].to_i
conf[:timeout] = conf[:timeout].to_i
conf[:verify_ssl] = conf[:verify_ssl] == 'true' if conf[:verify_ssl].is_a? String
conf[:debug] = conf[:debug] == 'true' if conf[:debug].is_a? String
end | ruby | def sanitise_conf(conf)
conf[:username] ||= 'admin'
conf[:password] ||= 'admin'
conf[:protocol] ||= 'http'
conf[:host] ||= 'localhost'
conf[:port] ||= 4502
conf[:timeout] ||= 300
# handle custom configuration value being passed as a String
# e.g. when the values are passed via environment variables
conf[:port] = conf[:port].to_i
conf[:timeout] = conf[:timeout].to_i
conf[:verify_ssl] = conf[:verify_ssl] == 'true' if conf[:verify_ssl].is_a? String
conf[:debug] = conf[:debug] == 'true' if conf[:debug].is_a? String
end | [
"def",
"sanitise_conf",
"(",
"conf",
")",
"conf",
"[",
":username",
"]",
"||=",
"'admin'",
"conf",
"[",
":password",
"]",
"||=",
"'admin'",
"conf",
"[",
":protocol",
"]",
"||=",
"'http'",
"conf",
"[",
":host",
"]",
"||=",
"'localhost'",
"conf",
"[",
":port",
"]",
"||=",
"4502",
"conf",
"[",
":timeout",
"]",
"||=",
"300",
"# handle custom configuration value being passed as a String",
"# e.g. when the values are passed via environment variables",
"conf",
"[",
":port",
"]",
"=",
"conf",
"[",
":port",
"]",
".",
"to_i",
"conf",
"[",
":timeout",
"]",
"=",
"conf",
"[",
":timeout",
"]",
".",
"to_i",
"conf",
"[",
":verify_ssl",
"]",
"=",
"conf",
"[",
":verify_ssl",
"]",
"==",
"'true'",
"if",
"conf",
"[",
":verify_ssl",
"]",
".",
"is_a?",
"String",
"conf",
"[",
":debug",
"]",
"=",
"conf",
"[",
":debug",
"]",
"==",
"'true'",
"if",
"conf",
"[",
":debug",
"]",
".",
"is_a?",
"String",
"end"
] | Initialise a Ruby AEM instance.
@param conf configuration hash of the following configuration values:
- username: username used to authenticate to AEM instance, default: 'admin'
- password: password used to authenticate to AEM instance, default: 'admin'
- protocol: AEM instance protocol (http or https), default: 'http'
- host: AEM instance host name, default: 'localhost'
- port: AEM instance port, default: 4502
- timeout: connection timeout in seconds, default: 300 seconds
- debug: if true, then additional debug messages will be included, default: false
@return new RubyAem::Aem instance
Set default configuration values and handle numeric/boolean String values | [
"Initialise",
"a",
"Ruby",
"AEM",
"instance",
"."
] | 96e9d491486f09e044ea5d05c433e53a37a08120 | https://github.com/shinesolutions/ruby_aem/blob/96e9d491486f09e044ea5d05c433e53a37a08120/lib/ruby_aem.rb#L82-L95 |
23,316 | shinesolutions/ruby_aem | lib/ruby_aem.rb | RubyAem.Aem.config_property | def config_property(name, type, value)
RubyAem::Resources::ConfigProperty.new(@client, name, type, value)
end | ruby | def config_property(name, type, value)
RubyAem::Resources::ConfigProperty.new(@client, name, type, value)
end | [
"def",
"config_property",
"(",
"name",
",",
"type",
",",
"value",
")",
"RubyAem",
"::",
"Resources",
"::",
"ConfigProperty",
".",
"new",
"(",
"@client",
",",
"name",
",",
"type",
",",
"value",
")",
"end"
] | Create a config property instance.
@param name the property's name
@param type the property's type, e.g. Boolean
@param value the property's value, e.g. true
@return new RubyAem::Resources::ConfigProperty instance | [
"Create",
"a",
"config",
"property",
"instance",
"."
] | 96e9d491486f09e044ea5d05c433e53a37a08120 | https://github.com/shinesolutions/ruby_aem/blob/96e9d491486f09e044ea5d05c433e53a37a08120/lib/ruby_aem.rb#L136-L138 |
23,317 | shinesolutions/ruby_aem | lib/ruby_aem.rb | RubyAem.Aem.package | def package(group_name, package_name, package_version)
RubyAem::Resources::Package.new(@client, group_name, package_name, package_version)
end | ruby | def package(group_name, package_name, package_version)
RubyAem::Resources::Package.new(@client, group_name, package_name, package_version)
end | [
"def",
"package",
"(",
"group_name",
",",
"package_name",
",",
"package_version",
")",
"RubyAem",
"::",
"Resources",
"::",
"Package",
".",
"new",
"(",
"@client",
",",
"group_name",
",",
"package_name",
",",
"package_version",
")",
"end"
] | Create a package instance.
@param group_name the group name of the package, e.g. somepackagegroup
@param package_name the name of the package, e.g. somepackage
@param package_version the version of the package, e.g. 1.2.3
@return new RubyAem::Resources::Package instance | [
"Create",
"a",
"package",
"instance",
"."
] | 96e9d491486f09e044ea5d05c433e53a37a08120 | https://github.com/shinesolutions/ruby_aem/blob/96e9d491486f09e044ea5d05c433e53a37a08120/lib/ruby_aem.rb#L180-L182 |
23,318 | bmuller/bandit | lib/bandit/storage/base.rb | Bandit.BaseStorage.part_key | def part_key(exp, alt, date_hour=nil)
parts = [ "participants", exp.name, alt ]
parts += [ date_hour.date, date_hour.hour ] unless date_hour.nil?
make_key parts
end | ruby | def part_key(exp, alt, date_hour=nil)
parts = [ "participants", exp.name, alt ]
parts += [ date_hour.date, date_hour.hour ] unless date_hour.nil?
make_key parts
end | [
"def",
"part_key",
"(",
"exp",
",",
"alt",
",",
"date_hour",
"=",
"nil",
")",
"parts",
"=",
"[",
"\"participants\"",
",",
"exp",
".",
"name",
",",
"alt",
"]",
"parts",
"+=",
"[",
"date_hour",
".",
"date",
",",
"date_hour",
".",
"hour",
"]",
"unless",
"date_hour",
".",
"nil?",
"make_key",
"parts",
"end"
] | if date_hour is nil, create key for total
otherwise, create key for hourly based | [
"if",
"date_hour",
"is",
"nil",
"create",
"key",
"for",
"total",
"otherwise",
"create",
"key",
"for",
"hourly",
"based"
] | 4c2528adee6ed761b3298f5b8889819ed9e04483 | https://github.com/bmuller/bandit/blob/4c2528adee6ed761b3298f5b8889819ed9e04483/lib/bandit/storage/base.rb#L105-L109 |
23,319 | notEthan/oauthenticator | lib/oauthenticator/rack_authenticator.rb | OAuthenticator.RackAuthenticator.unauthenticated_response | def unauthenticated_response(errors)
# default to a blank realm, I suppose
realm = @options[:realm] || ''
response_headers = {"WWW-Authenticate" => %Q(OAuth realm="#{realm}"), 'Content-Type' => 'application/json'}
body = {'errors' => errors}
error_message = begin
error_values = errors.values.inject([], &:+)
if error_values.size <= 1
error_values.first
else
# sentencify with periods
error_values.map { |v| v =~ /\.\s*\z/ ? v : v + '.' }.join(' ')
end
end
body['error_message'] = error_message if error_message
[401, response_headers, [JSON.pretty_generate(body)]]
end | ruby | def unauthenticated_response(errors)
# default to a blank realm, I suppose
realm = @options[:realm] || ''
response_headers = {"WWW-Authenticate" => %Q(OAuth realm="#{realm}"), 'Content-Type' => 'application/json'}
body = {'errors' => errors}
error_message = begin
error_values = errors.values.inject([], &:+)
if error_values.size <= 1
error_values.first
else
# sentencify with periods
error_values.map { |v| v =~ /\.\s*\z/ ? v : v + '.' }.join(' ')
end
end
body['error_message'] = error_message if error_message
[401, response_headers, [JSON.pretty_generate(body)]]
end | [
"def",
"unauthenticated_response",
"(",
"errors",
")",
"# default to a blank realm, I suppose",
"realm",
"=",
"@options",
"[",
":realm",
"]",
"||",
"''",
"response_headers",
"=",
"{",
"\"WWW-Authenticate\"",
"=>",
"%Q(OAuth realm=\"#{realm}\")",
",",
"'Content-Type'",
"=>",
"'application/json'",
"}",
"body",
"=",
"{",
"'errors'",
"=>",
"errors",
"}",
"error_message",
"=",
"begin",
"error_values",
"=",
"errors",
".",
"values",
".",
"inject",
"(",
"[",
"]",
",",
":+",
")",
"if",
"error_values",
".",
"size",
"<=",
"1",
"error_values",
".",
"first",
"else",
"# sentencify with periods ",
"error_values",
".",
"map",
"{",
"|",
"v",
"|",
"v",
"=~",
"/",
"\\.",
"\\s",
"\\z",
"/",
"?",
"v",
":",
"v",
"+",
"'.'",
"}",
".",
"join",
"(",
"' '",
")",
"end",
"end",
"body",
"[",
"'error_message'",
"]",
"=",
"error_message",
"if",
"error_message",
"[",
"401",
",",
"response_headers",
",",
"[",
"JSON",
".",
"pretty_generate",
"(",
"body",
")",
"]",
"]",
"end"
] | the response for an unauthenticated request. the argument will be a hash with the key 'errors', whose
value is a hash with string keys indicating attributes with errors, and values being arrays of strings
indicating error messages on the attribute key. | [
"the",
"response",
"for",
"an",
"unauthenticated",
"request",
".",
"the",
"argument",
"will",
"be",
"a",
"hash",
"with",
"the",
"key",
"errors",
"whose",
"value",
"is",
"a",
"hash",
"with",
"string",
"keys",
"indicating",
"attributes",
"with",
"errors",
"and",
"values",
"being",
"arrays",
"of",
"strings",
"indicating",
"error",
"messages",
"on",
"the",
"attribute",
"key",
"."
] | f462501e4d3e79086855ad5c6f95104de3c2ec07 | https://github.com/notEthan/oauthenticator/blob/f462501e4d3e79086855ad5c6f95104de3c2ec07/lib/oauthenticator/rack_authenticator.rb#L65-L83 |
23,320 | bmuller/bandit | lib/bandit/extensions/controller_concerns.rb | Bandit.ControllerConcerns.bandit_simple_convert! | def bandit_simple_convert!(exp, alt, count=1)
Bandit.get_experiment(exp).convert!(alt, count)
end | ruby | def bandit_simple_convert!(exp, alt, count=1)
Bandit.get_experiment(exp).convert!(alt, count)
end | [
"def",
"bandit_simple_convert!",
"(",
"exp",
",",
"alt",
",",
"count",
"=",
"1",
")",
"Bandit",
".",
"get_experiment",
"(",
"exp",
")",
".",
"convert!",
"(",
"alt",
",",
"count",
")",
"end"
] | look mum, no cookies | [
"look",
"mum",
"no",
"cookies"
] | 4c2528adee6ed761b3298f5b8889819ed9e04483 | https://github.com/bmuller/bandit/blob/4c2528adee6ed761b3298f5b8889819ed9e04483/lib/bandit/extensions/controller_concerns.rb#L13-L15 |
23,321 | bmuller/bandit | lib/bandit/extensions/controller_concerns.rb | Bandit.ControllerConcerns.bandit_session_convert! | def bandit_session_convert!(exp, alt=nil, count=1)
cookiename = "bandit_#{exp}".intern
cookiename_converted = "bandit_#{exp}_converted".intern
alt ||= cookies.signed[cookiename]
unless alt.nil? or cookies.signed[cookiename_converted]
Bandit.get_experiment(exp).convert!(alt, count)
cookies.delete(cookiename)
end
end | ruby | def bandit_session_convert!(exp, alt=nil, count=1)
cookiename = "bandit_#{exp}".intern
cookiename_converted = "bandit_#{exp}_converted".intern
alt ||= cookies.signed[cookiename]
unless alt.nil? or cookies.signed[cookiename_converted]
Bandit.get_experiment(exp).convert!(alt, count)
cookies.delete(cookiename)
end
end | [
"def",
"bandit_session_convert!",
"(",
"exp",
",",
"alt",
"=",
"nil",
",",
"count",
"=",
"1",
")",
"cookiename",
"=",
"\"bandit_#{exp}\"",
".",
"intern",
"cookiename_converted",
"=",
"\"bandit_#{exp}_converted\"",
".",
"intern",
"alt",
"||=",
"cookies",
".",
"signed",
"[",
"cookiename",
"]",
"unless",
"alt",
".",
"nil?",
"or",
"cookies",
".",
"signed",
"[",
"cookiename_converted",
"]",
"Bandit",
".",
"get_experiment",
"(",
"exp",
")",
".",
"convert!",
"(",
"alt",
",",
"count",
")",
"cookies",
".",
"delete",
"(",
"cookiename",
")",
"end",
"end"
] | expects a session cookie, deletes it, will convert again | [
"expects",
"a",
"session",
"cookie",
"deletes",
"it",
"will",
"convert",
"again"
] | 4c2528adee6ed761b3298f5b8889819ed9e04483 | https://github.com/bmuller/bandit/blob/4c2528adee6ed761b3298f5b8889819ed9e04483/lib/bandit/extensions/controller_concerns.rb#L18-L26 |
23,322 | bmuller/bandit | lib/bandit/extensions/controller_concerns.rb | Bandit.ControllerConcerns.bandit_sticky_convert! | def bandit_sticky_convert!(exp, alt=nil, count=1)
cookiename = "bandit_#{exp}".intern
cookiename_converted = "bandit_#{exp}_converted".intern
alt ||= cookies.signed[cookiename]
unless alt.nil? or cookies.signed[cookiename_converted]
cookies.permanent.signed[cookiename_converted] = "true"
Bandit.get_experiment(exp).convert!(alt, count)
end
end | ruby | def bandit_sticky_convert!(exp, alt=nil, count=1)
cookiename = "bandit_#{exp}".intern
cookiename_converted = "bandit_#{exp}_converted".intern
alt ||= cookies.signed[cookiename]
unless alt.nil? or cookies.signed[cookiename_converted]
cookies.permanent.signed[cookiename_converted] = "true"
Bandit.get_experiment(exp).convert!(alt, count)
end
end | [
"def",
"bandit_sticky_convert!",
"(",
"exp",
",",
"alt",
"=",
"nil",
",",
"count",
"=",
"1",
")",
"cookiename",
"=",
"\"bandit_#{exp}\"",
".",
"intern",
"cookiename_converted",
"=",
"\"bandit_#{exp}_converted\"",
".",
"intern",
"alt",
"||=",
"cookies",
".",
"signed",
"[",
"cookiename",
"]",
"unless",
"alt",
".",
"nil?",
"or",
"cookies",
".",
"signed",
"[",
"cookiename_converted",
"]",
"cookies",
".",
"permanent",
".",
"signed",
"[",
"cookiename_converted",
"]",
"=",
"\"true\"",
"Bandit",
".",
"get_experiment",
"(",
"exp",
")",
".",
"convert!",
"(",
"alt",
",",
"count",
")",
"end",
"end"
] | creates a _converted cookie, prevents multiple conversions | [
"creates",
"a",
"_converted",
"cookie",
"prevents",
"multiple",
"conversions"
] | 4c2528adee6ed761b3298f5b8889819ed9e04483 | https://github.com/bmuller/bandit/blob/4c2528adee6ed761b3298f5b8889819ed9e04483/lib/bandit/extensions/controller_concerns.rb#L29-L37 |
23,323 | david942j/rbelftools | lib/elftools/dynamic.rb | ELFTools.Dynamic.each_tags | def each_tags(&block)
return enum_for(:each_tags) unless block_given?
arr = []
0.step do |i|
tag = tag_at(i).tap(&block)
arr << tag
break if tag.header.d_tag == ELFTools::Constants::DT_NULL
end
arr
end | ruby | def each_tags(&block)
return enum_for(:each_tags) unless block_given?
arr = []
0.step do |i|
tag = tag_at(i).tap(&block)
arr << tag
break if tag.header.d_tag == ELFTools::Constants::DT_NULL
end
arr
end | [
"def",
"each_tags",
"(",
"&",
"block",
")",
"return",
"enum_for",
"(",
":each_tags",
")",
"unless",
"block_given?",
"arr",
"=",
"[",
"]",
"0",
".",
"step",
"do",
"|",
"i",
"|",
"tag",
"=",
"tag_at",
"(",
"i",
")",
".",
"tap",
"(",
"block",
")",
"arr",
"<<",
"tag",
"break",
"if",
"tag",
".",
"header",
".",
"d_tag",
"==",
"ELFTools",
"::",
"Constants",
"::",
"DT_NULL",
"end",
"arr",
"end"
] | Iterate all tags.
@note
This method assume the following methods already exist:
header
tag_start
@yieldparam [ELFTools::Dynamic::Tag] tag
@return [Enumerator<ELFTools::Dynamic::Tag>, Array<ELFTools::Dynamic::Tag>]
If block is not given, an enumerator will be returned.
Otherwise, return array of tags. | [
"Iterate",
"all",
"tags",
"."
] | 9a453ac31d72eae3b8b99d5dbd361c101577d58e | https://github.com/david942j/rbelftools/blob/9a453ac31d72eae3b8b99d5dbd361c101577d58e/lib/elftools/dynamic.rb#L19-L29 |
23,324 | david942j/rbelftools | lib/elftools/dynamic.rb | ELFTools.Dynamic.tag_at | def tag_at(n)
return if n < 0
@tag_at_map ||= {}
return @tag_at_map[n] if @tag_at_map[n]
dyn = Structs::ELF_Dyn.new(endian: endian)
dyn.elf_class = header.elf_class
stream.pos = tag_start + n * dyn.num_bytes
dyn.offset = stream.pos
@tag_at_map[n] = Tag.new(dyn.read(stream), stream, method(:str_offset))
end | ruby | def tag_at(n)
return if n < 0
@tag_at_map ||= {}
return @tag_at_map[n] if @tag_at_map[n]
dyn = Structs::ELF_Dyn.new(endian: endian)
dyn.elf_class = header.elf_class
stream.pos = tag_start + n * dyn.num_bytes
dyn.offset = stream.pos
@tag_at_map[n] = Tag.new(dyn.read(stream), stream, method(:str_offset))
end | [
"def",
"tag_at",
"(",
"n",
")",
"return",
"if",
"n",
"<",
"0",
"@tag_at_map",
"||=",
"{",
"}",
"return",
"@tag_at_map",
"[",
"n",
"]",
"if",
"@tag_at_map",
"[",
"n",
"]",
"dyn",
"=",
"Structs",
"::",
"ELF_Dyn",
".",
"new",
"(",
"endian",
":",
"endian",
")",
"dyn",
".",
"elf_class",
"=",
"header",
".",
"elf_class",
"stream",
".",
"pos",
"=",
"tag_start",
"+",
"n",
"*",
"dyn",
".",
"num_bytes",
"dyn",
".",
"offset",
"=",
"stream",
".",
"pos",
"@tag_at_map",
"[",
"n",
"]",
"=",
"Tag",
".",
"new",
"(",
"dyn",
".",
"read",
"(",
"stream",
")",
",",
"stream",
",",
"method",
"(",
":str_offset",
")",
")",
"end"
] | Get the +n+-th tag.
Tags are lazy loaded.
@note
This method assume the following methods already exist:
header
tag_start
@note
We cannot do bound checking of +n+ here since the only way to get size
of tags is calling +tags.size+.
@param [Integer] n The index.
@return [ELFTools::Dynamic::Tag] The desired tag. | [
"Get",
"the",
"+",
"n",
"+",
"-",
"th",
"tag",
"."
] | 9a453ac31d72eae3b8b99d5dbd361c101577d58e | https://github.com/david942j/rbelftools/blob/9a453ac31d72eae3b8b99d5dbd361c101577d58e/lib/elftools/dynamic.rb#L91-L102 |
23,325 | david942j/rbelftools | lib/elftools/elf_file.rb | ELFTools.ELFFile.build_id | def build_id
section = section_by_name('.note.gnu.build-id')
return nil if section.nil?
note = section.notes.first
return nil if note.nil?
note.desc.unpack('H*').first
end | ruby | def build_id
section = section_by_name('.note.gnu.build-id')
return nil if section.nil?
note = section.notes.first
return nil if note.nil?
note.desc.unpack('H*').first
end | [
"def",
"build_id",
"section",
"=",
"section_by_name",
"(",
"'.note.gnu.build-id'",
")",
"return",
"nil",
"if",
"section",
".",
"nil?",
"note",
"=",
"section",
".",
"notes",
".",
"first",
"return",
"nil",
"if",
"note",
".",
"nil?",
"note",
".",
"desc",
".",
"unpack",
"(",
"'H*'",
")",
".",
"first",
"end"
] | Return the BuildID of ELF.
@return [String, nil]
BuildID in hex form will be returned.
+nil+ is returned if the .note.gnu.build-id section
is not found.
@example
elf.build_id
#=> '73ab62cb7bc9959ce053c2b711322158708cdc07' | [
"Return",
"the",
"BuildID",
"of",
"ELF",
"."
] | 9a453ac31d72eae3b8b99d5dbd361c101577d58e | https://github.com/david942j/rbelftools/blob/9a453ac31d72eae3b8b99d5dbd361c101577d58e/lib/elftools/elf_file.rb#L50-L58 |
23,326 | david942j/rbelftools | lib/elftools/elf_file.rb | ELFTools.ELFFile.each_sections | def each_sections(&block)
return enum_for(:each_sections) unless block_given?
Array.new(num_sections) do |i|
section_at(i).tap(&block)
end
end | ruby | def each_sections(&block)
return enum_for(:each_sections) unless block_given?
Array.new(num_sections) do |i|
section_at(i).tap(&block)
end
end | [
"def",
"each_sections",
"(",
"&",
"block",
")",
"return",
"enum_for",
"(",
":each_sections",
")",
"unless",
"block_given?",
"Array",
".",
"new",
"(",
"num_sections",
")",
"do",
"|",
"i",
"|",
"section_at",
"(",
"i",
")",
".",
"tap",
"(",
"block",
")",
"end",
"end"
] | Iterate all sections.
All sections are lazy loading, the section
only be created whenever accessing it.
This method is useful for {#section_by_name}
since not all sections need to be created.
@yieldparam [ELFTools::Sections::Section] section A section.
@yieldreturn [void]
@return [Enumerator<ELFTools::Sections::Section>, Array<ELFTools::Sections::Section>]
As +Array#each+, if block is not given, a enumerator will be returned,
otherwise, the whole sections will be returned. | [
"Iterate",
"all",
"sections",
"."
] | 9a453ac31d72eae3b8b99d5dbd361c101577d58e | https://github.com/david942j/rbelftools/blob/9a453ac31d72eae3b8b99d5dbd361c101577d58e/lib/elftools/elf_file.rb#L120-L126 |
23,327 | david942j/rbelftools | lib/elftools/elf_file.rb | ELFTools.ELFFile.sections_by_type | def sections_by_type(type, &block)
type = Util.to_constant(Constants::SHT, type)
Util.select_by_type(each_sections, type, &block)
end | ruby | def sections_by_type(type, &block)
type = Util.to_constant(Constants::SHT, type)
Util.select_by_type(each_sections, type, &block)
end | [
"def",
"sections_by_type",
"(",
"type",
",",
"&",
"block",
")",
"type",
"=",
"Util",
".",
"to_constant",
"(",
"Constants",
"::",
"SHT",
",",
"type",
")",
"Util",
".",
"select_by_type",
"(",
"each_sections",
",",
"type",
",",
"block",
")",
"end"
] | Fetch all sections with specific type.
The available types are listed in {ELFTools::Constants::PT}.
This method accept giving block.
@param [Integer, Symbol, String] type
The type needed, similar format as {#segment_by_type}.
@yieldparam [ELFTools::Sections::Section] section A section in specific type.
@yieldreturn [void]
@return [Array<ELFTools::Sections::section>] The target sections.
@example
elf = ELFTools::ELFFile.new(File.open('spec/files/amd64.elf'))
elf.sections_by_type(:rela)
#=> [#<ELFTools::Sections::RelocationSection:0x00563cd3219970>,
# #<ELFTools::Sections::RelocationSection:0x00563cd3b89d70>] | [
"Fetch",
"all",
"sections",
"with",
"specific",
"type",
"."
] | 9a453ac31d72eae3b8b99d5dbd361c101577d58e | https://github.com/david942j/rbelftools/blob/9a453ac31d72eae3b8b99d5dbd361c101577d58e/lib/elftools/elf_file.rb#L161-L164 |
23,328 | david942j/rbelftools | lib/elftools/elf_file.rb | ELFTools.ELFFile.each_segments | def each_segments(&block)
return enum_for(:each_segments) unless block_given?
Array.new(num_segments) do |i|
segment_at(i).tap(&block)
end
end | ruby | def each_segments(&block)
return enum_for(:each_segments) unless block_given?
Array.new(num_segments) do |i|
segment_at(i).tap(&block)
end
end | [
"def",
"each_segments",
"(",
"&",
"block",
")",
"return",
"enum_for",
"(",
":each_segments",
")",
"unless",
"block_given?",
"Array",
".",
"new",
"(",
"num_segments",
")",
"do",
"|",
"i",
"|",
"segment_at",
"(",
"i",
")",
".",
"tap",
"(",
"block",
")",
"end",
"end"
] | Iterate all segments.
All segments are lazy loading, the segment
only be created whenever accessing it.
This method is useful for {#segment_by_type}
since not all segments need to be created.
@yieldparam [ELFTools::Segments::Segment] segment A segment.
@yieldreturn [void]
@return [Array<ELFTools::Segments::Segment>]
Whole segments will be returned. | [
"Iterate",
"all",
"segments",
"."
] | 9a453ac31d72eae3b8b99d5dbd361c101577d58e | https://github.com/david942j/rbelftools/blob/9a453ac31d72eae3b8b99d5dbd361c101577d58e/lib/elftools/elf_file.rb#L193-L199 |
23,329 | david942j/rbelftools | lib/elftools/elf_file.rb | ELFTools.ELFFile.segments_by_type | def segments_by_type(type, &block)
type = Util.to_constant(Constants::PT, type)
Util.select_by_type(each_segments, type, &block)
end | ruby | def segments_by_type(type, &block)
type = Util.to_constant(Constants::PT, type)
Util.select_by_type(each_segments, type, &block)
end | [
"def",
"segments_by_type",
"(",
"type",
",",
"&",
"block",
")",
"type",
"=",
"Util",
".",
"to_constant",
"(",
"Constants",
"::",
"PT",
",",
"type",
")",
"Util",
".",
"select_by_type",
"(",
"each_segments",
",",
"type",
",",
"block",
")",
"end"
] | Fetch all segments with specific type.
If you want to find only one segment,
use {#segment_by_type} instead.
This method accept giving block.
@param [Integer, Symbol, String] type
The type needed, same format as {#segment_by_type}.
@yieldparam [ELFTools::Segments::Segment] segment A segment in specific type.
@yieldreturn [void]
@return [Array<ELFTools::Segments::Segment>] The target segments. | [
"Fetch",
"all",
"segments",
"with",
"specific",
"type",
"."
] | 9a453ac31d72eae3b8b99d5dbd361c101577d58e | https://github.com/david942j/rbelftools/blob/9a453ac31d72eae3b8b99d5dbd361c101577d58e/lib/elftools/elf_file.rb#L264-L267 |
23,330 | david942j/rbelftools | lib/elftools/elf_file.rb | ELFTools.ELFFile.offset_from_vma | def offset_from_vma(vma, size = 0)
segments_by_type(:load) do |seg|
return seg.vma_to_offset(vma) if seg.vma_in?(vma, size)
end
end | ruby | def offset_from_vma(vma, size = 0)
segments_by_type(:load) do |seg|
return seg.vma_to_offset(vma) if seg.vma_in?(vma, size)
end
end | [
"def",
"offset_from_vma",
"(",
"vma",
",",
"size",
"=",
"0",
")",
"segments_by_type",
"(",
":load",
")",
"do",
"|",
"seg",
"|",
"return",
"seg",
".",
"vma_to_offset",
"(",
"vma",
")",
"if",
"seg",
".",
"vma_in?",
"(",
"vma",
",",
"size",
")",
"end",
"end"
] | Get the offset related to file, given virtual memory address.
This method should work no matter ELF is a PIE or not.
This method refers from (actually equals to) binutils/readelf.c#offset_from_vma.
@param [Integer] vma The virtual address to be queried.
@return [Integer] Related file offset.
@example
elf = ELFTools::ELFFile.new(File.open('/bin/cat'))
elf.offset_from_vma(0x401337)
#=> 4919 # 0x1337 | [
"Get",
"the",
"offset",
"related",
"to",
"file",
"given",
"virtual",
"memory",
"address",
"."
] | 9a453ac31d72eae3b8b99d5dbd361c101577d58e | https://github.com/david942j/rbelftools/blob/9a453ac31d72eae3b8b99d5dbd361c101577d58e/lib/elftools/elf_file.rb#L291-L295 |
23,331 | david942j/rbelftools | lib/elftools/elf_file.rb | ELFTools.ELFFile.patches | def patches
patch = {}
loaded_headers.each do |header|
header.patches.each do |key, val|
patch[key + header.offset] = val
end
end
patch
end | ruby | def patches
patch = {}
loaded_headers.each do |header|
header.patches.each do |key, val|
patch[key + header.offset] = val
end
end
patch
end | [
"def",
"patches",
"patch",
"=",
"{",
"}",
"loaded_headers",
".",
"each",
"do",
"|",
"header",
"|",
"header",
".",
"patches",
".",
"each",
"do",
"|",
"key",
",",
"val",
"|",
"patch",
"[",
"key",
"+",
"header",
".",
"offset",
"]",
"=",
"val",
"end",
"end",
"patch",
"end"
] | The patch status.
@return [Hash{Integer => String}] | [
"The",
"patch",
"status",
"."
] | 9a453ac31d72eae3b8b99d5dbd361c101577d58e | https://github.com/david942j/rbelftools/blob/9a453ac31d72eae3b8b99d5dbd361c101577d58e/lib/elftools/elf_file.rb#L299-L307 |
23,332 | david942j/rbelftools | lib/elftools/elf_file.rb | ELFTools.ELFFile.save | def save(filename)
stream.pos = 0
all = stream.read.force_encoding('ascii-8bit')
patches.each do |pos, val|
all[pos, val.size] = val
end
IO.binwrite(filename, all)
end | ruby | def save(filename)
stream.pos = 0
all = stream.read.force_encoding('ascii-8bit')
patches.each do |pos, val|
all[pos, val.size] = val
end
IO.binwrite(filename, all)
end | [
"def",
"save",
"(",
"filename",
")",
"stream",
".",
"pos",
"=",
"0",
"all",
"=",
"stream",
".",
"read",
".",
"force_encoding",
"(",
"'ascii-8bit'",
")",
"patches",
".",
"each",
"do",
"|",
"pos",
",",
"val",
"|",
"all",
"[",
"pos",
",",
"val",
".",
"size",
"]",
"=",
"val",
"end",
"IO",
".",
"binwrite",
"(",
"filename",
",",
"all",
")",
"end"
] | Apply patches and save as +filename+.
@param [String] filename
@return [void] | [
"Apply",
"patches",
"and",
"save",
"as",
"+",
"filename",
"+",
"."
] | 9a453ac31d72eae3b8b99d5dbd361c101577d58e | https://github.com/david942j/rbelftools/blob/9a453ac31d72eae3b8b99d5dbd361c101577d58e/lib/elftools/elf_file.rb#L313-L320 |
23,333 | david942j/rbelftools | lib/elftools/elf_file.rb | ELFTools.ELFFile.loaded_headers | def loaded_headers
explore = lambda do |obj|
return obj if obj.is_a?(::ELFTools::Structs::ELFStruct)
return obj.map(&explore) if obj.is_a?(Array)
obj.instance_variables.map do |s|
explore.call(obj.instance_variable_get(s))
end
end
explore.call(self).flatten
end | ruby | def loaded_headers
explore = lambda do |obj|
return obj if obj.is_a?(::ELFTools::Structs::ELFStruct)
return obj.map(&explore) if obj.is_a?(Array)
obj.instance_variables.map do |s|
explore.call(obj.instance_variable_get(s))
end
end
explore.call(self).flatten
end | [
"def",
"loaded_headers",
"explore",
"=",
"lambda",
"do",
"|",
"obj",
"|",
"return",
"obj",
"if",
"obj",
".",
"is_a?",
"(",
"::",
"ELFTools",
"::",
"Structs",
"::",
"ELFStruct",
")",
"return",
"obj",
".",
"map",
"(",
"explore",
")",
"if",
"obj",
".",
"is_a?",
"(",
"Array",
")",
"obj",
".",
"instance_variables",
".",
"map",
"do",
"|",
"s",
"|",
"explore",
".",
"call",
"(",
"obj",
".",
"instance_variable_get",
"(",
"s",
")",
")",
"end",
"end",
"explore",
".",
"call",
"(",
"self",
")",
".",
"flatten",
"end"
] | bad idea.. | [
"bad",
"idea",
".."
] | 9a453ac31d72eae3b8b99d5dbd361c101577d58e | https://github.com/david942j/rbelftools/blob/9a453ac31d72eae3b8b99d5dbd361c101577d58e/lib/elftools/elf_file.rb#L325-L335 |
23,334 | cotag/http-parser | lib/http-parser/parser.rb | HttpParser.Parser.parse | def parse(inst, data)
::HttpParser.http_parser_execute(inst, @settings, data, data.length)
return inst.error?
end | ruby | def parse(inst, data)
::HttpParser.http_parser_execute(inst, @settings, data, data.length)
return inst.error?
end | [
"def",
"parse",
"(",
"inst",
",",
"data",
")",
"::",
"HttpParser",
".",
"http_parser_execute",
"(",
"inst",
",",
"@settings",
",",
"data",
",",
"data",
".",
"length",
")",
"return",
"inst",
".",
"error?",
"end"
] | Parses data.
@param [HttpParser::Instance] inst
The state so far of the request / response being processed.
@param [String] data
The data to parse against the instance specified.
@return [Boolean]
Returns true if the data was parsed successfully. | [
"Parses",
"data",
"."
] | 9a202b38945e9ad66ca113947860267411efc6f2 | https://github.com/cotag/http-parser/blob/9a202b38945e9ad66ca113947860267411efc6f2/lib/http-parser/parser.rb#L221-L224 |
23,335 | shinesolutions/ruby_aem | lib/ruby_aem/client.rb | RubyAem.Client.call | def call(clazz, action, call_params)
resource_name = clazz.name.downcase.sub('rubyaem::resources::', '')
resource = @spec[resource_name]
action_spec = resource['actions'][action]
api = @apis[action_spec['api'].to_sym]
operation = action_spec['operation']
params = []
required_params = action_spec['params']['required'] || {}
required_params.each_value { |value|
params.push(value % call_params)
}
params.push({})
optional_params = action_spec['params']['optional'] || {}
optional_params.each { |key, value|
add_optional_param(key, value, params, call_params)
}
base_responses_spec = resource['responses'] || {}
action_responses_spec = action_spec['responses'] || {}
responses_spec = base_responses_spec.merge(action_responses_spec)
begin
method = RubyAem::Swagger.operation_to_method(operation)
data, status_code, headers = api.send("#{method}_with_http_info", *params)
response = RubyAem::Response.new(status_code, data, headers)
rescue SwaggerAemClient::ApiError => err
response = RubyAem::Response.new(err.code, err.response_body, err.response_headers)
end
handle(response, responses_spec, call_params)
end | ruby | def call(clazz, action, call_params)
resource_name = clazz.name.downcase.sub('rubyaem::resources::', '')
resource = @spec[resource_name]
action_spec = resource['actions'][action]
api = @apis[action_spec['api'].to_sym]
operation = action_spec['operation']
params = []
required_params = action_spec['params']['required'] || {}
required_params.each_value { |value|
params.push(value % call_params)
}
params.push({})
optional_params = action_spec['params']['optional'] || {}
optional_params.each { |key, value|
add_optional_param(key, value, params, call_params)
}
base_responses_spec = resource['responses'] || {}
action_responses_spec = action_spec['responses'] || {}
responses_spec = base_responses_spec.merge(action_responses_spec)
begin
method = RubyAem::Swagger.operation_to_method(operation)
data, status_code, headers = api.send("#{method}_with_http_info", *params)
response = RubyAem::Response.new(status_code, data, headers)
rescue SwaggerAemClient::ApiError => err
response = RubyAem::Response.new(err.code, err.response_body, err.response_headers)
end
handle(response, responses_spec, call_params)
end | [
"def",
"call",
"(",
"clazz",
",",
"action",
",",
"call_params",
")",
"resource_name",
"=",
"clazz",
".",
"name",
".",
"downcase",
".",
"sub",
"(",
"'rubyaem::resources::'",
",",
"''",
")",
"resource",
"=",
"@spec",
"[",
"resource_name",
"]",
"action_spec",
"=",
"resource",
"[",
"'actions'",
"]",
"[",
"action",
"]",
"api",
"=",
"@apis",
"[",
"action_spec",
"[",
"'api'",
"]",
".",
"to_sym",
"]",
"operation",
"=",
"action_spec",
"[",
"'operation'",
"]",
"params",
"=",
"[",
"]",
"required_params",
"=",
"action_spec",
"[",
"'params'",
"]",
"[",
"'required'",
"]",
"||",
"{",
"}",
"required_params",
".",
"each_value",
"{",
"|",
"value",
"|",
"params",
".",
"push",
"(",
"value",
"%",
"call_params",
")",
"}",
"params",
".",
"push",
"(",
"{",
"}",
")",
"optional_params",
"=",
"action_spec",
"[",
"'params'",
"]",
"[",
"'optional'",
"]",
"||",
"{",
"}",
"optional_params",
".",
"each",
"{",
"|",
"key",
",",
"value",
"|",
"add_optional_param",
"(",
"key",
",",
"value",
",",
"params",
",",
"call_params",
")",
"}",
"base_responses_spec",
"=",
"resource",
"[",
"'responses'",
"]",
"||",
"{",
"}",
"action_responses_spec",
"=",
"action_spec",
"[",
"'responses'",
"]",
"||",
"{",
"}",
"responses_spec",
"=",
"base_responses_spec",
".",
"merge",
"(",
"action_responses_spec",
")",
"begin",
"method",
"=",
"RubyAem",
"::",
"Swagger",
".",
"operation_to_method",
"(",
"operation",
")",
"data",
",",
"status_code",
",",
"headers",
"=",
"api",
".",
"send",
"(",
"\"#{method}_with_http_info\"",
",",
"params",
")",
"response",
"=",
"RubyAem",
"::",
"Response",
".",
"new",
"(",
"status_code",
",",
"data",
",",
"headers",
")",
"rescue",
"SwaggerAemClient",
"::",
"ApiError",
"=>",
"err",
"response",
"=",
"RubyAem",
"::",
"Response",
".",
"new",
"(",
"err",
".",
"code",
",",
"err",
".",
"response_body",
",",
"err",
".",
"response_headers",
")",
"end",
"handle",
"(",
"response",
",",
"responses_spec",
",",
"call_params",
")",
"end"
] | Initialise a client.
@param apis a hash of Swagger AEM client's API instances
@param spec ruby_aem specification
@return new RubyAem::Client instance
Make an API call using the relevant Swagger AEM API client.
Clazz and action parameters are used to identify the action, API, and params
from ruby_aem specification, alongside the response handlers.
Call parameters are used to construct HTTP request parameters based on the
specification.
@param clazz the class name of the caller resource
@param action the action of the API call
@param call_params API call parameters
@return RubyAem::Result | [
"Initialise",
"a",
"client",
"."
] | 96e9d491486f09e044ea5d05c433e53a37a08120 | https://github.com/shinesolutions/ruby_aem/blob/96e9d491486f09e044ea5d05c433e53a37a08120/lib/ruby_aem/client.rb#L49-L80 |
23,336 | shinesolutions/ruby_aem | lib/ruby_aem/client.rb | RubyAem.Client.add_optional_param | def add_optional_param(key, value, params, call_params)
# if there is no value in optional param spec,
# then only add optional param that is set in call parameters
if !value
params[-1][key.to_sym] = call_params[key.to_sym] if call_params.key? key.to_sym
# if value is provided in optional param spec,
# then apply variable interpolation the same way as required param
elsif value.class == String
case value
when '__FILE_PACKAGE__'
file_path = "#{call_params[:file_path]}/#{call_params[:package_name]}-#{call_params[:package_version]}.zip"
when '__FILE_PLAIN__'
file_path = call_params[:file_path]
when '__FILE_CERTIFICATE__'
file_path = call_params[:file_path_certificate]
when '__FILE_PRIVATE_KEY__'
file_path = call_params[:file_path_private_key]
end
if !file_path.nil?
File.open(file_path.to_s, 'r') { |file|
params[-1][key.to_sym] = file
}
else
params[-1][key.to_sym] = value % call_params
end
else
params[-1][key.to_sym] = value
end
end | ruby | def add_optional_param(key, value, params, call_params)
# if there is no value in optional param spec,
# then only add optional param that is set in call parameters
if !value
params[-1][key.to_sym] = call_params[key.to_sym] if call_params.key? key.to_sym
# if value is provided in optional param spec,
# then apply variable interpolation the same way as required param
elsif value.class == String
case value
when '__FILE_PACKAGE__'
file_path = "#{call_params[:file_path]}/#{call_params[:package_name]}-#{call_params[:package_version]}.zip"
when '__FILE_PLAIN__'
file_path = call_params[:file_path]
when '__FILE_CERTIFICATE__'
file_path = call_params[:file_path_certificate]
when '__FILE_PRIVATE_KEY__'
file_path = call_params[:file_path_private_key]
end
if !file_path.nil?
File.open(file_path.to_s, 'r') { |file|
params[-1][key.to_sym] = file
}
else
params[-1][key.to_sym] = value % call_params
end
else
params[-1][key.to_sym] = value
end
end | [
"def",
"add_optional_param",
"(",
"key",
",",
"value",
",",
"params",
",",
"call_params",
")",
"# if there is no value in optional param spec,",
"# then only add optional param that is set in call parameters",
"if",
"!",
"value",
"params",
"[",
"-",
"1",
"]",
"[",
"key",
".",
"to_sym",
"]",
"=",
"call_params",
"[",
"key",
".",
"to_sym",
"]",
"if",
"call_params",
".",
"key?",
"key",
".",
"to_sym",
"# if value is provided in optional param spec,",
"# then apply variable interpolation the same way as required param",
"elsif",
"value",
".",
"class",
"==",
"String",
"case",
"value",
"when",
"'__FILE_PACKAGE__'",
"file_path",
"=",
"\"#{call_params[:file_path]}/#{call_params[:package_name]}-#{call_params[:package_version]}.zip\"",
"when",
"'__FILE_PLAIN__'",
"file_path",
"=",
"call_params",
"[",
":file_path",
"]",
"when",
"'__FILE_CERTIFICATE__'",
"file_path",
"=",
"call_params",
"[",
":file_path_certificate",
"]",
"when",
"'__FILE_PRIVATE_KEY__'",
"file_path",
"=",
"call_params",
"[",
":file_path_private_key",
"]",
"end",
"if",
"!",
"file_path",
".",
"nil?",
"File",
".",
"open",
"(",
"file_path",
".",
"to_s",
",",
"'r'",
")",
"{",
"|",
"file",
"|",
"params",
"[",
"-",
"1",
"]",
"[",
"key",
".",
"to_sym",
"]",
"=",
"file",
"}",
"else",
"params",
"[",
"-",
"1",
"]",
"[",
"key",
".",
"to_sym",
"]",
"=",
"value",
"%",
"call_params",
"end",
"else",
"params",
"[",
"-",
"1",
"]",
"[",
"key",
".",
"to_sym",
"]",
"=",
"value",
"end",
"end"
] | Add optional param into params list.
@param key optional param key
@param value optional param value
@param params combined list of required and optional parameters
@param call_params API call parameters | [
"Add",
"optional",
"param",
"into",
"params",
"list",
"."
] | 96e9d491486f09e044ea5d05c433e53a37a08120 | https://github.com/shinesolutions/ruby_aem/blob/96e9d491486f09e044ea5d05c433e53a37a08120/lib/ruby_aem/client.rb#L88-L117 |
23,337 | shinesolutions/ruby_aem | lib/ruby_aem/client.rb | RubyAem.Client.handle | def handle(response, responses_spec, call_params)
if responses_spec.key?(response.status_code)
response_spec = responses_spec[response.status_code]
handler = response_spec['handler']
Handlers.send(handler, response, response_spec, call_params)
else
message = "Unexpected response\nstatus code: #{response.status_code}\nheaders: #{response.headers}\nbody: #{response.body}"
result = Result.new(message, response)
raise RubyAem::Error.new(message, result)
end
end | ruby | def handle(response, responses_spec, call_params)
if responses_spec.key?(response.status_code)
response_spec = responses_spec[response.status_code]
handler = response_spec['handler']
Handlers.send(handler, response, response_spec, call_params)
else
message = "Unexpected response\nstatus code: #{response.status_code}\nheaders: #{response.headers}\nbody: #{response.body}"
result = Result.new(message, response)
raise RubyAem::Error.new(message, result)
end
end | [
"def",
"handle",
"(",
"response",
",",
"responses_spec",
",",
"call_params",
")",
"if",
"responses_spec",
".",
"key?",
"(",
"response",
".",
"status_code",
")",
"response_spec",
"=",
"responses_spec",
"[",
"response",
".",
"status_code",
"]",
"handler",
"=",
"response_spec",
"[",
"'handler'",
"]",
"Handlers",
".",
"send",
"(",
"handler",
",",
"response",
",",
"response_spec",
",",
"call_params",
")",
"else",
"message",
"=",
"\"Unexpected response\\nstatus code: #{response.status_code}\\nheaders: #{response.headers}\\nbody: #{response.body}\"",
"result",
"=",
"Result",
".",
"new",
"(",
"message",
",",
"response",
")",
"raise",
"RubyAem",
"::",
"Error",
".",
"new",
"(",
"message",
",",
"result",
")",
"end",
"end"
] | Handle a response based on status code and a given list of response specifications.
If none of the response specifications contains the status code, a failure result
will then be returned.
@param response response containing HTTP status code, body, and headers
@param responses_spec a list of response specifications as configured in conf/spec.yaml
@param call_params API call parameters
@return RubyAem::Result
@raise RubyAem::Error when the response status code is unexpected | [
"Handle",
"a",
"response",
"based",
"on",
"status",
"code",
"and",
"a",
"given",
"list",
"of",
"response",
"specifications",
".",
"If",
"none",
"of",
"the",
"response",
"specifications",
"contains",
"the",
"status",
"code",
"a",
"failure",
"result",
"will",
"then",
"be",
"returned",
"."
] | 96e9d491486f09e044ea5d05c433e53a37a08120 | https://github.com/shinesolutions/ruby_aem/blob/96e9d491486f09e044ea5d05c433e53a37a08120/lib/ruby_aem/client.rb#L128-L138 |
23,338 | daddyz/evercookie | lib/evercookie/controller.rb | Evercookie.EvercookieController.save | def save
if data = session[Evercookie.hash_name_for_get]
if data[:key] && cookies[data[:key]]
session[Evercookie.hash_name_for_saved] =
{ data[:key] => cookies[data[:key]] }
end
end
render nothing: true
end | ruby | def save
if data = session[Evercookie.hash_name_for_get]
if data[:key] && cookies[data[:key]]
session[Evercookie.hash_name_for_saved] =
{ data[:key] => cookies[data[:key]] }
end
end
render nothing: true
end | [
"def",
"save",
"if",
"data",
"=",
"session",
"[",
"Evercookie",
".",
"hash_name_for_get",
"]",
"if",
"data",
"[",
":key",
"]",
"&&",
"cookies",
"[",
"data",
"[",
":key",
"]",
"]",
"session",
"[",
"Evercookie",
".",
"hash_name_for_saved",
"]",
"=",
"{",
"data",
"[",
":key",
"]",
"=>",
"cookies",
"[",
"data",
"[",
":key",
"]",
"]",
"}",
"end",
"end",
"render",
"nothing",
":",
"true",
"end"
] | Saves current evercookie value to session | [
"Saves",
"current",
"evercookie",
"value",
"to",
"session"
] | 887c607e43865caf2ce7c649fc5e531653024cbe | https://github.com/daddyz/evercookie/blob/887c607e43865caf2ce7c649fc5e531653024cbe/lib/evercookie/controller.rb#L60-L68 |
23,339 | daddyz/evercookie | lib/evercookie/controller.rb | Evercookie.EvercookieController.ec_png | def ec_png
if not cookies[Evercookie.cookie_png].present?
render :nothing => true, :status => 304
return true
end
response.headers["Content-Type"] = "image/png"
response.headers["Last-Modified"] = "Wed, 30 Jun 2010 21:36:48 GMT"
response.headers["Expires"] = "Tue, 31 Dec 2030 23:30:45 GMT"
response.headers["Cache-Control"] = "private, max-age=630720000"
render text: get_blob_png, status: 200, content_type: 'image/png'
end | ruby | def ec_png
if not cookies[Evercookie.cookie_png].present?
render :nothing => true, :status => 304
return true
end
response.headers["Content-Type"] = "image/png"
response.headers["Last-Modified"] = "Wed, 30 Jun 2010 21:36:48 GMT"
response.headers["Expires"] = "Tue, 31 Dec 2030 23:30:45 GMT"
response.headers["Cache-Control"] = "private, max-age=630720000"
render text: get_blob_png, status: 200, content_type: 'image/png'
end | [
"def",
"ec_png",
"if",
"not",
"cookies",
"[",
"Evercookie",
".",
"cookie_png",
"]",
".",
"present?",
"render",
":nothing",
"=>",
"true",
",",
":status",
"=>",
"304",
"return",
"true",
"end",
"response",
".",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"\"image/png\"",
"response",
".",
"headers",
"[",
"\"Last-Modified\"",
"]",
"=",
"\"Wed, 30 Jun 2010 21:36:48 GMT\"",
"response",
".",
"headers",
"[",
"\"Expires\"",
"]",
"=",
"\"Tue, 31 Dec 2030 23:30:45 GMT\"",
"response",
".",
"headers",
"[",
"\"Cache-Control\"",
"]",
"=",
"\"private, max-age=630720000\"",
"render",
"text",
":",
"get_blob_png",
",",
"status",
":",
"200",
",",
"content_type",
":",
"'image/png'",
"end"
] | Renders png image with encoded evercookie value in it | [
"Renders",
"png",
"image",
"with",
"encoded",
"evercookie",
"value",
"in",
"it"
] | 887c607e43865caf2ce7c649fc5e531653024cbe | https://github.com/daddyz/evercookie/blob/887c607e43865caf2ce7c649fc5e531653024cbe/lib/evercookie/controller.rb#L71-L83 |
23,340 | daddyz/evercookie | lib/evercookie/controller.rb | Evercookie.EvercookieController.ec_etag | def ec_etag
if not cookies[Evercookie.cookie_etag].present?
render :text => request.headers['If-None-Match'] || '', :status => 304
return true
end
puts "cache value (#{Evercookie.cookie_etag}): #{cookies[Evercookie.cookie_etag]}"
response.headers["Etag"] = cookies[Evercookie.cookie_etag]
render text: cookies[Evercookie.cookie_etag]
end | ruby | def ec_etag
if not cookies[Evercookie.cookie_etag].present?
render :text => request.headers['If-None-Match'] || '', :status => 304
return true
end
puts "cache value (#{Evercookie.cookie_etag}): #{cookies[Evercookie.cookie_etag]}"
response.headers["Etag"] = cookies[Evercookie.cookie_etag]
render text: cookies[Evercookie.cookie_etag]
end | [
"def",
"ec_etag",
"if",
"not",
"cookies",
"[",
"Evercookie",
".",
"cookie_etag",
"]",
".",
"present?",
"render",
":text",
"=>",
"request",
".",
"headers",
"[",
"'If-None-Match'",
"]",
"||",
"''",
",",
":status",
"=>",
"304",
"return",
"true",
"end",
"puts",
"\"cache value (#{Evercookie.cookie_etag}): #{cookies[Evercookie.cookie_etag]}\"",
"response",
".",
"headers",
"[",
"\"Etag\"",
"]",
"=",
"cookies",
"[",
"Evercookie",
".",
"cookie_etag",
"]",
"render",
"text",
":",
"cookies",
"[",
"Evercookie",
".",
"cookie_etag",
"]",
"end"
] | Renders page with etag header for evercookie js script | [
"Renders",
"page",
"with",
"etag",
"header",
"for",
"evercookie",
"js",
"script"
] | 887c607e43865caf2ce7c649fc5e531653024cbe | https://github.com/daddyz/evercookie/blob/887c607e43865caf2ce7c649fc5e531653024cbe/lib/evercookie/controller.rb#L86-L96 |
23,341 | daddyz/evercookie | lib/evercookie/controller.rb | Evercookie.EvercookieController.ec_cache | def ec_cache
if not cookies[Evercookie.cookie_cache].present?
render :nothing => true, :status => 304
return true
end
puts "cache value (#{Evercookie.cookie_cache}): #{cookies[Evercookie.cookie_cache]}"
response.headers["Content-Type"] = "text/html"
response.headers["Last-Modified"] = "Wed, 30 Jun 2010 21:36:48 GMT"
response.headers["Expires"] = "Tue, 31 Dec 2030 23:30:45 GMT"
response.headers["Cache-Control"] = "private, max-age=630720000"
render text: cookies[Evercookie.cookie_cache]
end | ruby | def ec_cache
if not cookies[Evercookie.cookie_cache].present?
render :nothing => true, :status => 304
return true
end
puts "cache value (#{Evercookie.cookie_cache}): #{cookies[Evercookie.cookie_cache]}"
response.headers["Content-Type"] = "text/html"
response.headers["Last-Modified"] = "Wed, 30 Jun 2010 21:36:48 GMT"
response.headers["Expires"] = "Tue, 31 Dec 2030 23:30:45 GMT"
response.headers["Cache-Control"] = "private, max-age=630720000"
render text: cookies[Evercookie.cookie_cache]
end | [
"def",
"ec_cache",
"if",
"not",
"cookies",
"[",
"Evercookie",
".",
"cookie_cache",
"]",
".",
"present?",
"render",
":nothing",
"=>",
"true",
",",
":status",
"=>",
"304",
"return",
"true",
"end",
"puts",
"\"cache value (#{Evercookie.cookie_cache}): #{cookies[Evercookie.cookie_cache]}\"",
"response",
".",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"\"text/html\"",
"response",
".",
"headers",
"[",
"\"Last-Modified\"",
"]",
"=",
"\"Wed, 30 Jun 2010 21:36:48 GMT\"",
"response",
".",
"headers",
"[",
"\"Expires\"",
"]",
"=",
"\"Tue, 31 Dec 2030 23:30:45 GMT\"",
"response",
".",
"headers",
"[",
"\"Cache-Control\"",
"]",
"=",
"\"private, max-age=630720000\"",
"render",
"text",
":",
"cookies",
"[",
"Evercookie",
".",
"cookie_cache",
"]",
"end"
] | Renders page with cache header for evercookie js script | [
"Renders",
"page",
"with",
"cache",
"header",
"for",
"evercookie",
"js",
"script"
] | 887c607e43865caf2ce7c649fc5e531653024cbe | https://github.com/daddyz/evercookie/blob/887c607e43865caf2ce7c649fc5e531653024cbe/lib/evercookie/controller.rb#L99-L113 |
23,342 | david942j/rbelftools | lib/elftools/note.rb | ELFTools.Note.each_notes | def each_notes
return enum_for(:each_notes) unless block_given?
@notes_offset_map ||= {}
cur = note_start
notes = []
while cur < note_start + note_total_size
stream.pos = cur
@notes_offset_map[cur] ||= create_note(cur)
note = @notes_offset_map[cur]
# name and desc size needs to be 4-bytes align
name_size = Util.align(note.header.n_namesz, 2)
desc_size = Util.align(note.header.n_descsz, 2)
cur += SIZE_OF_NHDR + name_size + desc_size
notes << note
yield note
end
notes
end | ruby | def each_notes
return enum_for(:each_notes) unless block_given?
@notes_offset_map ||= {}
cur = note_start
notes = []
while cur < note_start + note_total_size
stream.pos = cur
@notes_offset_map[cur] ||= create_note(cur)
note = @notes_offset_map[cur]
# name and desc size needs to be 4-bytes align
name_size = Util.align(note.header.n_namesz, 2)
desc_size = Util.align(note.header.n_descsz, 2)
cur += SIZE_OF_NHDR + name_size + desc_size
notes << note
yield note
end
notes
end | [
"def",
"each_notes",
"return",
"enum_for",
"(",
":each_notes",
")",
"unless",
"block_given?",
"@notes_offset_map",
"||=",
"{",
"}",
"cur",
"=",
"note_start",
"notes",
"=",
"[",
"]",
"while",
"cur",
"<",
"note_start",
"+",
"note_total_size",
"stream",
".",
"pos",
"=",
"cur",
"@notes_offset_map",
"[",
"cur",
"]",
"||=",
"create_note",
"(",
"cur",
")",
"note",
"=",
"@notes_offset_map",
"[",
"cur",
"]",
"# name and desc size needs to be 4-bytes align",
"name_size",
"=",
"Util",
".",
"align",
"(",
"note",
".",
"header",
".",
"n_namesz",
",",
"2",
")",
"desc_size",
"=",
"Util",
".",
"align",
"(",
"note",
".",
"header",
".",
"n_descsz",
",",
"2",
")",
"cur",
"+=",
"SIZE_OF_NHDR",
"+",
"name_size",
"+",
"desc_size",
"notes",
"<<",
"note",
"yield",
"note",
"end",
"notes",
"end"
] | Iterate all notes in a note section or segment.
Structure of notes are:
+---------------+
| Note 1 header |
+---------------+
| Note 1 name |
+---------------+
| Note 1 desc |
+---------------+
| Note 2 header |
+---------------+
| ... |
+---------------+
@note
This method assume following methods exist:
stream
note_start
note_total_size
@return [Enumerator<ELFTools::Note::Note>, Array<ELFTools::Note::Note>]
If block is not given, an enumerator will be returned.
Otherwise, return the array of notes. | [
"Iterate",
"all",
"notes",
"in",
"a",
"note",
"section",
"or",
"segment",
"."
] | 9a453ac31d72eae3b8b99d5dbd361c101577d58e | https://github.com/david942j/rbelftools/blob/9a453ac31d72eae3b8b99d5dbd361c101577d58e/lib/elftools/note.rb#L42-L60 |
23,343 | notEthan/oauthenticator | lib/oauthenticator/signed_request.rb | OAuthenticator.SignedRequest.config_method_not_implemented | def config_method_not_implemented
caller_name = caller[0].match(%r(in `(.*?)'))[1]
using_middleware = caller.any? { |l| l =~ %r(oauthenticator/rack_authenticator.rb:.*`call') }
message = "method \##{caller_name} must be implemented on a module of oauth config methods, which is " + begin
if using_middleware
"passed to OAuthenticator::RackAuthenticator using the option :config_methods."
else
"included in a subclass of OAuthenticator::SignedRequest, typically by passing it to OAuthenticator::SignedRequest.including_config(your_module)."
end
end + " Please consult the documentation."
raise NotImplementedError, message
end | ruby | def config_method_not_implemented
caller_name = caller[0].match(%r(in `(.*?)'))[1]
using_middleware = caller.any? { |l| l =~ %r(oauthenticator/rack_authenticator.rb:.*`call') }
message = "method \##{caller_name} must be implemented on a module of oauth config methods, which is " + begin
if using_middleware
"passed to OAuthenticator::RackAuthenticator using the option :config_methods."
else
"included in a subclass of OAuthenticator::SignedRequest, typically by passing it to OAuthenticator::SignedRequest.including_config(your_module)."
end
end + " Please consult the documentation."
raise NotImplementedError, message
end | [
"def",
"config_method_not_implemented",
"caller_name",
"=",
"caller",
"[",
"0",
"]",
".",
"match",
"(",
"%r(",
")",
")",
"[",
"1",
"]",
"using_middleware",
"=",
"caller",
".",
"any?",
"{",
"|",
"l",
"|",
"l",
"=~",
"%r(",
")",
"}",
"message",
"=",
"\"method \\##{caller_name} must be implemented on a module of oauth config methods, which is \"",
"+",
"begin",
"if",
"using_middleware",
"\"passed to OAuthenticator::RackAuthenticator using the option :config_methods.\"",
"else",
"\"included in a subclass of OAuthenticator::SignedRequest, typically by passing it to OAuthenticator::SignedRequest.including_config(your_module).\"",
"end",
"end",
"+",
"\" Please consult the documentation.\"",
"raise",
"NotImplementedError",
",",
"message",
"end"
] | raise a nice error message for a method that needs to be implemented on a module of config methods | [
"raise",
"a",
"nice",
"error",
"message",
"for",
"a",
"method",
"that",
"needs",
"to",
"be",
"implemented",
"on",
"a",
"module",
"of",
"config",
"methods"
] | f462501e4d3e79086855ad5c6f95104de3c2ec07 | https://github.com/notEthan/oauthenticator/blob/f462501e4d3e79086855ad5c6f95104de3c2ec07/lib/oauthenticator/signed_request.rb#L245-L256 |
23,344 | cotag/http-parser | lib/http-parser/types.rb | HttpParser.Instance.error | def error
error = (self[:error_upgrade] & 0b1111111)
return nil if error == 0
err = ::HttpParser.err_name(error)[4..-1] # HPE_ is at the start of all these errors
klass = ERRORS[err.to_sym]
err = "#{::HttpParser.err_desc(error)} (#{err})"
return klass.nil? ? Error::UNKNOWN.new(err) : klass.new(err)
end | ruby | def error
error = (self[:error_upgrade] & 0b1111111)
return nil if error == 0
err = ::HttpParser.err_name(error)[4..-1] # HPE_ is at the start of all these errors
klass = ERRORS[err.to_sym]
err = "#{::HttpParser.err_desc(error)} (#{err})"
return klass.nil? ? Error::UNKNOWN.new(err) : klass.new(err)
end | [
"def",
"error",
"error",
"=",
"(",
"self",
"[",
":error_upgrade",
"]",
"&",
"0b1111111",
")",
"return",
"nil",
"if",
"error",
"==",
"0",
"err",
"=",
"::",
"HttpParser",
".",
"err_name",
"(",
"error",
")",
"[",
"4",
"..",
"-",
"1",
"]",
"# HPE_ is at the start of all these errors",
"klass",
"=",
"ERRORS",
"[",
"err",
".",
"to_sym",
"]",
"err",
"=",
"\"#{::HttpParser.err_desc(error)} (#{err})\"",
"return",
"klass",
".",
"nil?",
"?",
"Error",
"::",
"UNKNOWN",
".",
"new",
"(",
"err",
")",
":",
"klass",
".",
"new",
"(",
"err",
")",
"end"
] | Returns the error that occurred during processing.
@return [StandarError]
Returns the error that occurred. | [
"Returns",
"the",
"error",
"that",
"occurred",
"during",
"processing",
"."
] | 9a202b38945e9ad66ca113947860267411efc6f2 | https://github.com/cotag/http-parser/blob/9a202b38945e9ad66ca113947860267411efc6f2/lib/http-parser/types.rb#L241-L249 |
23,345 | notEthan/oauthenticator | lib/oauthenticator/faraday_signer.rb | OAuthenticator.FaradaySigner.call | def call(request_env)
media_type = Rack::Request.new('CONTENT_TYPE' => request_env[:request_headers]['Content-Type']).media_type
request_attributes = {
:request_method => request_env[:method],
:uri => request_env[:url],
:media_type => media_type,
:body => request_env[:body]
}
# the adapter will set the media type to form-encoded when not otherwise specified on
# requests it expects to have a body. see
# Net::HTTPGenericRequest#supply_default_content_type called in #send_request_with_body.
# other adapters do similarly, I think.
if METHODS_WITH_BODIES.include?(request_env[:method].to_s.downcase) && !request_attributes[:media_type]
request_attributes[:media_type] = 'application/x-www-form-urlencoded'
end
oauthenticator_signable_request = OAuthenticator::SignableRequest.new(@options.merge(request_attributes))
request_env[:request_headers]['Authorization'] = oauthenticator_signable_request.authorization
@app.call(request_env)
end | ruby | def call(request_env)
media_type = Rack::Request.new('CONTENT_TYPE' => request_env[:request_headers]['Content-Type']).media_type
request_attributes = {
:request_method => request_env[:method],
:uri => request_env[:url],
:media_type => media_type,
:body => request_env[:body]
}
# the adapter will set the media type to form-encoded when not otherwise specified on
# requests it expects to have a body. see
# Net::HTTPGenericRequest#supply_default_content_type called in #send_request_with_body.
# other adapters do similarly, I think.
if METHODS_WITH_BODIES.include?(request_env[:method].to_s.downcase) && !request_attributes[:media_type]
request_attributes[:media_type] = 'application/x-www-form-urlencoded'
end
oauthenticator_signable_request = OAuthenticator::SignableRequest.new(@options.merge(request_attributes))
request_env[:request_headers]['Authorization'] = oauthenticator_signable_request.authorization
@app.call(request_env)
end | [
"def",
"call",
"(",
"request_env",
")",
"media_type",
"=",
"Rack",
"::",
"Request",
".",
"new",
"(",
"'CONTENT_TYPE'",
"=>",
"request_env",
"[",
":request_headers",
"]",
"[",
"'Content-Type'",
"]",
")",
".",
"media_type",
"request_attributes",
"=",
"{",
":request_method",
"=>",
"request_env",
"[",
":method",
"]",
",",
":uri",
"=>",
"request_env",
"[",
":url",
"]",
",",
":media_type",
"=>",
"media_type",
",",
":body",
"=>",
"request_env",
"[",
":body",
"]",
"}",
"# the adapter will set the media type to form-encoded when not otherwise specified on ",
"# requests it expects to have a body. see ",
"# Net::HTTPGenericRequest#supply_default_content_type called in #send_request_with_body. ",
"# other adapters do similarly, I think. ",
"if",
"METHODS_WITH_BODIES",
".",
"include?",
"(",
"request_env",
"[",
":method",
"]",
".",
"to_s",
".",
"downcase",
")",
"&&",
"!",
"request_attributes",
"[",
":media_type",
"]",
"request_attributes",
"[",
":media_type",
"]",
"=",
"'application/x-www-form-urlencoded'",
"end",
"oauthenticator_signable_request",
"=",
"OAuthenticator",
"::",
"SignableRequest",
".",
"new",
"(",
"@options",
".",
"merge",
"(",
"request_attributes",
")",
")",
"request_env",
"[",
":request_headers",
"]",
"[",
"'Authorization'",
"]",
"=",
"oauthenticator_signable_request",
".",
"authorization",
"@app",
".",
"call",
"(",
"request_env",
")",
"end"
] | do the thing | [
"do",
"the",
"thing"
] | f462501e4d3e79086855ad5c6f95104de3c2ec07 | https://github.com/notEthan/oauthenticator/blob/f462501e4d3e79086855ad5c6f95104de3c2ec07/lib/oauthenticator/faraday_signer.rb#L56-L74 |
23,346 | notEthan/oauthenticator | lib/oauthenticator/signable_request.rb | OAuthenticator.SignableRequest.signature_base | def signature_base
parts = [normalized_request_method, base_string_uri, normalized_request_params_string]
parts.map { |v| OAuthenticator.escape(v) }.join('&')
end | ruby | def signature_base
parts = [normalized_request_method, base_string_uri, normalized_request_params_string]
parts.map { |v| OAuthenticator.escape(v) }.join('&')
end | [
"def",
"signature_base",
"parts",
"=",
"[",
"normalized_request_method",
",",
"base_string_uri",
",",
"normalized_request_params_string",
"]",
"parts",
".",
"map",
"{",
"|",
"v",
"|",
"OAuthenticator",
".",
"escape",
"(",
"v",
")",
"}",
".",
"join",
"(",
"'&'",
")",
"end"
] | signature base string for signing. section 3.4.1
@return [String] | [
"signature",
"base",
"string",
"for",
"signing",
".",
"section",
"3",
".",
"4",
".",
"1"
] | f462501e4d3e79086855ad5c6f95104de3c2ec07 | https://github.com/notEthan/oauthenticator/blob/f462501e4d3e79086855ad5c6f95104de3c2ec07/lib/oauthenticator/signable_request.rb#L170-L173 |
23,347 | notEthan/oauthenticator | lib/oauthenticator/signable_request.rb | OAuthenticator.SignableRequest.base_string_uri | def base_string_uri
Addressable::URI.parse(@attributes['uri'].to_s).tap do |uri|
uri.scheme = uri.scheme.downcase if uri.scheme
uri.host = uri.host.downcase if uri.host
uri.normalize!
uri.fragment = nil
uri.query = nil
end.to_s
end | ruby | def base_string_uri
Addressable::URI.parse(@attributes['uri'].to_s).tap do |uri|
uri.scheme = uri.scheme.downcase if uri.scheme
uri.host = uri.host.downcase if uri.host
uri.normalize!
uri.fragment = nil
uri.query = nil
end.to_s
end | [
"def",
"base_string_uri",
"Addressable",
"::",
"URI",
".",
"parse",
"(",
"@attributes",
"[",
"'uri'",
"]",
".",
"to_s",
")",
".",
"tap",
"do",
"|",
"uri",
"|",
"uri",
".",
"scheme",
"=",
"uri",
".",
"scheme",
".",
"downcase",
"if",
"uri",
".",
"scheme",
"uri",
".",
"host",
"=",
"uri",
".",
"host",
".",
"downcase",
"if",
"uri",
".",
"host",
"uri",
".",
"normalize!",
"uri",
".",
"fragment",
"=",
"nil",
"uri",
".",
"query",
"=",
"nil",
"end",
".",
"to_s",
"end"
] | section 3.4.1.2
@return [String] | [
"section",
"3",
".",
"4",
".",
"1",
".",
"2"
] | f462501e4d3e79086855ad5c6f95104de3c2ec07 | https://github.com/notEthan/oauthenticator/blob/f462501e4d3e79086855ad5c6f95104de3c2ec07/lib/oauthenticator/signable_request.rb#L178-L186 |
23,348 | notEthan/oauthenticator | lib/oauthenticator/signable_request.rb | OAuthenticator.SignableRequest.normalized_request_params_string | def normalized_request_params_string
normalized_request_params.map { |kv| kv.map { |v| OAuthenticator.escape(v) } }.sort.map { |p| p.join('=') }.join('&')
end | ruby | def normalized_request_params_string
normalized_request_params.map { |kv| kv.map { |v| OAuthenticator.escape(v) } }.sort.map { |p| p.join('=') }.join('&')
end | [
"def",
"normalized_request_params_string",
"normalized_request_params",
".",
"map",
"{",
"|",
"kv",
"|",
"kv",
".",
"map",
"{",
"|",
"v",
"|",
"OAuthenticator",
".",
"escape",
"(",
"v",
")",
"}",
"}",
".",
"sort",
".",
"map",
"{",
"|",
"p",
"|",
"p",
".",
"join",
"(",
"'='",
")",
"}",
".",
"join",
"(",
"'&'",
")",
"end"
] | section 3.4.1.3.2
@return [String] | [
"section",
"3",
".",
"4",
".",
"1",
".",
"3",
".",
"2"
] | f462501e4d3e79086855ad5c6f95104de3c2ec07 | https://github.com/notEthan/oauthenticator/blob/f462501e4d3e79086855ad5c6f95104de3c2ec07/lib/oauthenticator/signable_request.rb#L198-L200 |
23,349 | notEthan/oauthenticator | lib/oauthenticator/signable_request.rb | OAuthenticator.SignableRequest.normalized_request_params | def normalized_request_params
query_params + protocol_params.reject { |k,v| %w(realm oauth_signature).include?(k) }.to_a + entity_params
end | ruby | def normalized_request_params
query_params + protocol_params.reject { |k,v| %w(realm oauth_signature).include?(k) }.to_a + entity_params
end | [
"def",
"normalized_request_params",
"query_params",
"+",
"protocol_params",
".",
"reject",
"{",
"|",
"k",
",",
"v",
"|",
"%w(",
"realm",
"oauth_signature",
")",
".",
"include?",
"(",
"k",
")",
"}",
".",
"to_a",
"+",
"entity_params",
"end"
] | section 3.4.1.3
@return [Array<Array<String> (size 2)>] | [
"section",
"3",
".",
"4",
".",
"1",
".",
"3"
] | f462501e4d3e79086855ad5c6f95104de3c2ec07 | https://github.com/notEthan/oauthenticator/blob/f462501e4d3e79086855ad5c6f95104de3c2ec07/lib/oauthenticator/signable_request.rb#L205-L207 |
23,350 | notEthan/oauthenticator | lib/oauthenticator/signable_request.rb | OAuthenticator.SignableRequest.parse_form_encoded | def parse_form_encoded(data)
data.split(/[&;]/).map do |pair|
key, value = pair.split('=', 2).map { |v| CGI::unescape(v) }
[key, value] unless [nil, ''].include?(key)
end.compact
end | ruby | def parse_form_encoded(data)
data.split(/[&;]/).map do |pair|
key, value = pair.split('=', 2).map { |v| CGI::unescape(v) }
[key, value] unless [nil, ''].include?(key)
end.compact
end | [
"def",
"parse_form_encoded",
"(",
"data",
")",
"data",
".",
"split",
"(",
"/",
"/",
")",
".",
"map",
"do",
"|",
"pair",
"|",
"key",
",",
"value",
"=",
"pair",
".",
"split",
"(",
"'='",
",",
"2",
")",
".",
"map",
"{",
"|",
"v",
"|",
"CGI",
"::",
"unescape",
"(",
"v",
")",
"}",
"[",
"key",
",",
"value",
"]",
"unless",
"[",
"nil",
",",
"''",
"]",
".",
"include?",
"(",
"key",
")",
"end",
".",
"compact",
"end"
] | like CGI.parse but it keeps keys without any value. doesn't keep blank keys though.
@return [Array<Array<String, nil> (size 2)>] | [
"like",
"CGI",
".",
"parse",
"but",
"it",
"keeps",
"keys",
"without",
"any",
"value",
".",
"doesn",
"t",
"keep",
"blank",
"keys",
"though",
"."
] | f462501e4d3e79086855ad5c6f95104de3c2ec07 | https://github.com/notEthan/oauthenticator/blob/f462501e4d3e79086855ad5c6f95104de3c2ec07/lib/oauthenticator/signable_request.rb#L236-L241 |
23,351 | notEthan/oauthenticator | lib/oauthenticator/signable_request.rb | OAuthenticator.SignableRequest.read_body | def read_body
body = @attributes['body']
if body.nil?
''
elsif body.is_a?(String)
body
elsif body.respond_to?(:read) && body.respond_to?(:rewind)
body.rewind
body.read.tap do
body.rewind
end
else
raise TypeError, "Body must be a String or something IO-like (responding to #read and #rewind). " +
"got body = #{body.inspect}"
end
end | ruby | def read_body
body = @attributes['body']
if body.nil?
''
elsif body.is_a?(String)
body
elsif body.respond_to?(:read) && body.respond_to?(:rewind)
body.rewind
body.read.tap do
body.rewind
end
else
raise TypeError, "Body must be a String or something IO-like (responding to #read and #rewind). " +
"got body = #{body.inspect}"
end
end | [
"def",
"read_body",
"body",
"=",
"@attributes",
"[",
"'body'",
"]",
"if",
"body",
".",
"nil?",
"''",
"elsif",
"body",
".",
"is_a?",
"(",
"String",
")",
"body",
"elsif",
"body",
".",
"respond_to?",
"(",
":read",
")",
"&&",
"body",
".",
"respond_to?",
"(",
":rewind",
")",
"body",
".",
"rewind",
"body",
".",
"read",
".",
"tap",
"do",
"body",
".",
"rewind",
"end",
"else",
"raise",
"TypeError",
",",
"\"Body must be a String or something IO-like (responding to #read and #rewind). \"",
"+",
"\"got body = #{body.inspect}\"",
"end",
"end"
] | reads the request body, be it String or IO
@return [String] request body | [
"reads",
"the",
"request",
"body",
"be",
"it",
"String",
"or",
"IO"
] | f462501e4d3e79086855ad5c6f95104de3c2ec07 | https://github.com/notEthan/oauthenticator/blob/f462501e4d3e79086855ad5c6f95104de3c2ec07/lib/oauthenticator/signable_request.rb#L253-L268 |
23,352 | notEthan/oauthenticator | lib/oauthenticator/signable_request.rb | OAuthenticator.SignableRequest.rsa_sha1_signature | def rsa_sha1_signature
private_key = OpenSSL::PKey::RSA.new(@attributes['consumer_secret'])
Base64.encode64(private_key.sign(OpenSSL::Digest::SHA1.new, signature_base)).gsub(/\n/, '')
end | ruby | def rsa_sha1_signature
private_key = OpenSSL::PKey::RSA.new(@attributes['consumer_secret'])
Base64.encode64(private_key.sign(OpenSSL::Digest::SHA1.new, signature_base)).gsub(/\n/, '')
end | [
"def",
"rsa_sha1_signature",
"private_key",
"=",
"OpenSSL",
"::",
"PKey",
"::",
"RSA",
".",
"new",
"(",
"@attributes",
"[",
"'consumer_secret'",
"]",
")",
"Base64",
".",
"encode64",
"(",
"private_key",
".",
"sign",
"(",
"OpenSSL",
"::",
"Digest",
"::",
"SHA1",
".",
"new",
",",
"signature_base",
")",
")",
".",
"gsub",
"(",
"/",
"\\n",
"/",
",",
"''",
")",
"end"
] | signature, with method RSA-SHA1. section 3.4.3
@return [String] | [
"signature",
"with",
"method",
"RSA",
"-",
"SHA1",
".",
"section",
"3",
".",
"4",
".",
"3"
] | f462501e4d3e79086855ad5c6f95104de3c2ec07 | https://github.com/notEthan/oauthenticator/blob/f462501e4d3e79086855ad5c6f95104de3c2ec07/lib/oauthenticator/signable_request.rb#L298-L301 |
23,353 | notEthan/oauthenticator | lib/oauthenticator/signable_request.rb | OAuthenticator.SignableRequest.hmac_sha1_signature | def hmac_sha1_signature
# hmac secret is same as plaintext signature
secret = plaintext_signature
Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::SHA1.new, secret, signature_base)).gsub(/\n/, '')
end | ruby | def hmac_sha1_signature
# hmac secret is same as plaintext signature
secret = plaintext_signature
Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::SHA1.new, secret, signature_base)).gsub(/\n/, '')
end | [
"def",
"hmac_sha1_signature",
"# hmac secret is same as plaintext signature ",
"secret",
"=",
"plaintext_signature",
"Base64",
".",
"encode64",
"(",
"OpenSSL",
"::",
"HMAC",
".",
"digest",
"(",
"OpenSSL",
"::",
"Digest",
"::",
"SHA1",
".",
"new",
",",
"secret",
",",
"signature_base",
")",
")",
".",
"gsub",
"(",
"/",
"\\n",
"/",
",",
"''",
")",
"end"
] | signature, with method HMAC-SHA1. section 3.4.2
@return [String] | [
"signature",
"with",
"method",
"HMAC",
"-",
"SHA1",
".",
"section",
"3",
".",
"4",
".",
"2"
] | f462501e4d3e79086855ad5c6f95104de3c2ec07 | https://github.com/notEthan/oauthenticator/blob/f462501e4d3e79086855ad5c6f95104de3c2ec07/lib/oauthenticator/signable_request.rb#L306-L310 |
23,354 | moio/tetra | lib/tetra/facades/bash.rb | Tetra.Bash.bash | def bash(command = nil)
Tempfile.open("tetra-history") do |history_file|
Tempfile.open("tetra-bashrc") do |bashrc_file|
kit = Tetra::Kit.new(@project)
ant_path = kit.find_executable("ant")
ant_in_kit = ant_path != nil
ant_commandline = Tetra::Ant.commandline(@project.full_path, ant_path)
mvn_path = kit.find_executable("mvn")
mvn_in_kit = mvn_path != nil
mvn_commandline = Tetra::Mvn.commandline(@project.full_path, mvn_path)
bashrc_content = Bashrc.new(history_file.path, ant_in_kit, ant_commandline, mvn_in_kit, mvn_commandline).to_s
log.debug "writing bashrc file: #{bashrc_file.path}"
log.debug bashrc_content
bashrc_file.write(bashrc_content)
bashrc_file.flush
if command
run("bash --rcfile #{bashrc_file.path} -i -c '#{command}'")
[command]
else
run_interactive("bash --rcfile #{bashrc_file.path} -i")
history = File.read(history_file)
log.debug "history contents:"
log.debug history
history.split("\n").map(&:strip)
end
end
end
end | ruby | def bash(command = nil)
Tempfile.open("tetra-history") do |history_file|
Tempfile.open("tetra-bashrc") do |bashrc_file|
kit = Tetra::Kit.new(@project)
ant_path = kit.find_executable("ant")
ant_in_kit = ant_path != nil
ant_commandline = Tetra::Ant.commandline(@project.full_path, ant_path)
mvn_path = kit.find_executable("mvn")
mvn_in_kit = mvn_path != nil
mvn_commandline = Tetra::Mvn.commandline(@project.full_path, mvn_path)
bashrc_content = Bashrc.new(history_file.path, ant_in_kit, ant_commandline, mvn_in_kit, mvn_commandline).to_s
log.debug "writing bashrc file: #{bashrc_file.path}"
log.debug bashrc_content
bashrc_file.write(bashrc_content)
bashrc_file.flush
if command
run("bash --rcfile #{bashrc_file.path} -i -c '#{command}'")
[command]
else
run_interactive("bash --rcfile #{bashrc_file.path} -i")
history = File.read(history_file)
log.debug "history contents:"
log.debug history
history.split("\n").map(&:strip)
end
end
end
end | [
"def",
"bash",
"(",
"command",
"=",
"nil",
")",
"Tempfile",
".",
"open",
"(",
"\"tetra-history\"",
")",
"do",
"|",
"history_file",
"|",
"Tempfile",
".",
"open",
"(",
"\"tetra-bashrc\"",
")",
"do",
"|",
"bashrc_file",
"|",
"kit",
"=",
"Tetra",
"::",
"Kit",
".",
"new",
"(",
"@project",
")",
"ant_path",
"=",
"kit",
".",
"find_executable",
"(",
"\"ant\"",
")",
"ant_in_kit",
"=",
"ant_path",
"!=",
"nil",
"ant_commandline",
"=",
"Tetra",
"::",
"Ant",
".",
"commandline",
"(",
"@project",
".",
"full_path",
",",
"ant_path",
")",
"mvn_path",
"=",
"kit",
".",
"find_executable",
"(",
"\"mvn\"",
")",
"mvn_in_kit",
"=",
"mvn_path",
"!=",
"nil",
"mvn_commandline",
"=",
"Tetra",
"::",
"Mvn",
".",
"commandline",
"(",
"@project",
".",
"full_path",
",",
"mvn_path",
")",
"bashrc_content",
"=",
"Bashrc",
".",
"new",
"(",
"history_file",
".",
"path",
",",
"ant_in_kit",
",",
"ant_commandline",
",",
"mvn_in_kit",
",",
"mvn_commandline",
")",
".",
"to_s",
"log",
".",
"debug",
"\"writing bashrc file: #{bashrc_file.path}\"",
"log",
".",
"debug",
"bashrc_content",
"bashrc_file",
".",
"write",
"(",
"bashrc_content",
")",
"bashrc_file",
".",
"flush",
"if",
"command",
"run",
"(",
"\"bash --rcfile #{bashrc_file.path} -i -c '#{command}'\"",
")",
"[",
"command",
"]",
"else",
"run_interactive",
"(",
"\"bash --rcfile #{bashrc_file.path} -i\"",
")",
"history",
"=",
"File",
".",
"read",
"(",
"history_file",
")",
"log",
".",
"debug",
"\"history contents:\"",
"log",
".",
"debug",
"history",
"history",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"map",
"(",
":strip",
")",
"end",
"end",
"end",
"end"
] | runs bash in a subshell, returns list of
commands that were run in the session | [
"runs",
"bash",
"in",
"a",
"subshell",
"returns",
"list",
"of",
"commands",
"that",
"were",
"run",
"in",
"the",
"session"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/facades/bash.rb#L15-L47 |
23,355 | jantman/serverspec-extended-types | lib/serverspec_extended_types/bitlbee.rb | Serverspec.Type.bitlbee | def bitlbee(port, nick, password, use_ssl=false)
Bitlbee.new(port, nick, password, use_ssl)
end | ruby | def bitlbee(port, nick, password, use_ssl=false)
Bitlbee.new(port, nick, password, use_ssl)
end | [
"def",
"bitlbee",
"(",
"port",
",",
"nick",
",",
"password",
",",
"use_ssl",
"=",
"false",
")",
"Bitlbee",
".",
"new",
"(",
"port",
",",
"nick",
",",
"password",
",",
"use_ssl",
")",
"end"
] | Serverspec Type method for Bitlbee
@example
describe bitlbee(6697, 'myuser', 'mypass') do
# tests here
end
@api public
@param port [Integer] the port to connect to
@param nick [String] the nick to connect as
@param password [String] the password for nick
@param use_ssl [Boolean] whether to connect with SSL
@return {Serverspec::Type::Bitlbee} instance | [
"Serverspec",
"Type",
"method",
"for",
"Bitlbee"
] | 28437dcccc403ab71abe8bf481ec4d22d4eed395 | https://github.com/jantman/serverspec-extended-types/blob/28437dcccc403ab71abe8bf481ec4d22d4eed395/lib/serverspec_extended_types/bitlbee.rb#L198-L200 |
23,356 | moio/tetra | lib/tetra/facades/git.rb | Tetra.Git.commit_directories | def commit_directories(directories, message)
log.debug "committing with message: #{message}"
Dir.chdir(@directory) do
directories.each do |directory|
run("git rm -r --cached --ignore-unmatch #{directory}")
run("git add #{directory}")
end
run("git commit --allow-empty -F -", false, message)
end
end | ruby | def commit_directories(directories, message)
log.debug "committing with message: #{message}"
Dir.chdir(@directory) do
directories.each do |directory|
run("git rm -r --cached --ignore-unmatch #{directory}")
run("git add #{directory}")
end
run("git commit --allow-empty -F -", false, message)
end
end | [
"def",
"commit_directories",
"(",
"directories",
",",
"message",
")",
"log",
".",
"debug",
"\"committing with message: #{message}\"",
"Dir",
".",
"chdir",
"(",
"@directory",
")",
"do",
"directories",
".",
"each",
"do",
"|",
"directory",
"|",
"run",
"(",
"\"git rm -r --cached --ignore-unmatch #{directory}\"",
")",
"run",
"(",
"\"git add #{directory}\"",
")",
"end",
"run",
"(",
"\"git commit --allow-empty -F -\"",
",",
"false",
",",
"message",
")",
"end",
"end"
] | adds all files in the specified directories,
removes all files not in the specified directories,
commits with message | [
"adds",
"all",
"files",
"in",
"the",
"specified",
"directories",
"removes",
"all",
"files",
"not",
"in",
"the",
"specified",
"directories",
"commits",
"with",
"message"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/facades/git.rb#L49-L59 |
23,357 | moio/tetra | lib/tetra/facades/git.rb | Tetra.Git.commit_file | def commit_file(path, message)
Dir.chdir(@directory) do
log.debug "committing path #{path} with message: #{message}"
run("git add #{path}")
run("git commit --allow-empty -F -", false, message)
end
end | ruby | def commit_file(path, message)
Dir.chdir(@directory) do
log.debug "committing path #{path} with message: #{message}"
run("git add #{path}")
run("git commit --allow-empty -F -", false, message)
end
end | [
"def",
"commit_file",
"(",
"path",
",",
"message",
")",
"Dir",
".",
"chdir",
"(",
"@directory",
")",
"do",
"log",
".",
"debug",
"\"committing path #{path} with message: #{message}\"",
"run",
"(",
"\"git add #{path}\"",
")",
"run",
"(",
"\"git commit --allow-empty -F -\"",
",",
"false",
",",
"message",
")",
"end",
"end"
] | commits one single file | [
"commits",
"one",
"single",
"file"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/facades/git.rb#L62-L68 |
23,358 | moio/tetra | lib/tetra/facades/git.rb | Tetra.Git.revert_directories | def revert_directories(directories, id)
Dir.chdir(@directory) do
directories.each do |directory|
# reverts added and modified files, both in index and working tree
run("git checkout -f #{id} -- #{directory}")
# compute the list of deleted files
files_in_commit = run("git ls-tree --name-only -r #{id} -- #{directory}").split("\n")
files_in_head = run("git ls-tree --name-only -r HEAD -- #{directory}").split("\n")
files_added_after_head = run("git ls-files -o -- #{directory}").split("\n")
files_to_delete = files_in_head - files_in_commit + files_added_after_head
files_to_delete.each do |file|
FileUtils.rm_rf(file)
end
end
end
end | ruby | def revert_directories(directories, id)
Dir.chdir(@directory) do
directories.each do |directory|
# reverts added and modified files, both in index and working tree
run("git checkout -f #{id} -- #{directory}")
# compute the list of deleted files
files_in_commit = run("git ls-tree --name-only -r #{id} -- #{directory}").split("\n")
files_in_head = run("git ls-tree --name-only -r HEAD -- #{directory}").split("\n")
files_added_after_head = run("git ls-files -o -- #{directory}").split("\n")
files_to_delete = files_in_head - files_in_commit + files_added_after_head
files_to_delete.each do |file|
FileUtils.rm_rf(file)
end
end
end
end | [
"def",
"revert_directories",
"(",
"directories",
",",
"id",
")",
"Dir",
".",
"chdir",
"(",
"@directory",
")",
"do",
"directories",
".",
"each",
"do",
"|",
"directory",
"|",
"# reverts added and modified files, both in index and working tree",
"run",
"(",
"\"git checkout -f #{id} -- #{directory}\"",
")",
"# compute the list of deleted files",
"files_in_commit",
"=",
"run",
"(",
"\"git ls-tree --name-only -r #{id} -- #{directory}\"",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"files_in_head",
"=",
"run",
"(",
"\"git ls-tree --name-only -r HEAD -- #{directory}\"",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"files_added_after_head",
"=",
"run",
"(",
"\"git ls-files -o -- #{directory}\"",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"files_to_delete",
"=",
"files_in_head",
"-",
"files_in_commit",
"+",
"files_added_after_head",
"files_to_delete",
".",
"each",
"do",
"|",
"file",
"|",
"FileUtils",
".",
"rm_rf",
"(",
"file",
")",
"end",
"end",
"end",
"end"
] | reverts multiple directories' contents as per specified id | [
"reverts",
"multiple",
"directories",
"contents",
"as",
"per",
"specified",
"id"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/facades/git.rb#L71-L88 |
23,359 | moio/tetra | lib/tetra/facades/git.rb | Tetra.Git.disable_special_files | def disable_special_files(path)
Dir.chdir(File.join(@directory, path)) do
Find.find(".") do |file|
next unless file =~ /\.git(ignore)?$/
FileUtils.mv(file, "#{file}_disabled_by_tetra")
end
end
end | ruby | def disable_special_files(path)
Dir.chdir(File.join(@directory, path)) do
Find.find(".") do |file|
next unless file =~ /\.git(ignore)?$/
FileUtils.mv(file, "#{file}_disabled_by_tetra")
end
end
end | [
"def",
"disable_special_files",
"(",
"path",
")",
"Dir",
".",
"chdir",
"(",
"File",
".",
"join",
"(",
"@directory",
",",
"path",
")",
")",
"do",
"Find",
".",
"find",
"(",
"\".\"",
")",
"do",
"|",
"file",
"|",
"next",
"unless",
"file",
"=~",
"/",
"\\.",
"/",
"FileUtils",
".",
"mv",
"(",
"file",
",",
"\"#{file}_disabled_by_tetra\"",
")",
"end",
"end",
"end"
] | renames git special files to 'disable' them | [
"renames",
"git",
"special",
"files",
"to",
"disable",
"them"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/facades/git.rb#L99-L107 |
23,360 | moio/tetra | lib/tetra/facades/git.rb | Tetra.Git.merge_with_id | def merge_with_id(path, new_path, id)
Dir.chdir(@directory) do
run("git show #{id}:#{path} > #{path}.old_version")
conflict_count = 0
begin
run("git merge-file #{path} #{path}.old_version #{new_path} \
-L \"newly generated\" \
-L \"previously generated\" \
-L \"user edited\"")
rescue ExecutionFailed => e
if e.status > 0
conflict_count = e.status
else
raise e
end
end
File.delete("#{path}.old_version")
conflict_count
end
end | ruby | def merge_with_id(path, new_path, id)
Dir.chdir(@directory) do
run("git show #{id}:#{path} > #{path}.old_version")
conflict_count = 0
begin
run("git merge-file #{path} #{path}.old_version #{new_path} \
-L \"newly generated\" \
-L \"previously generated\" \
-L \"user edited\"")
rescue ExecutionFailed => e
if e.status > 0
conflict_count = e.status
else
raise e
end
end
File.delete("#{path}.old_version")
conflict_count
end
end | [
"def",
"merge_with_id",
"(",
"path",
",",
"new_path",
",",
"id",
")",
"Dir",
".",
"chdir",
"(",
"@directory",
")",
"do",
"run",
"(",
"\"git show #{id}:#{path} > #{path}.old_version\"",
")",
"conflict_count",
"=",
"0",
"begin",
"run",
"(",
"\"git merge-file #{path} #{path}.old_version #{new_path} \\\n -L \\\"newly generated\\\" \\\n -L \\\"previously generated\\\" \\\n -L \\\"user edited\\\"\"",
")",
"rescue",
"ExecutionFailed",
"=>",
"e",
"if",
"e",
".",
"status",
">",
"0",
"conflict_count",
"=",
"e",
".",
"status",
"else",
"raise",
"e",
"end",
"end",
"File",
".",
"delete",
"(",
"\"#{path}.old_version\"",
")",
"conflict_count",
"end",
"end"
] | 3-way merges the git file at path with the one in new_path
assuming they have a common ancestor at the specified id
returns the conflict count | [
"3",
"-",
"way",
"merges",
"the",
"git",
"file",
"at",
"path",
"with",
"the",
"one",
"in",
"new_path",
"assuming",
"they",
"have",
"a",
"common",
"ancestor",
"at",
"the",
"specified",
"id",
"returns",
"the",
"conflict",
"count"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/facades/git.rb#L112-L132 |
23,361 | moio/tetra | lib/tetra/facades/git.rb | Tetra.Git.changed_files | def changed_files(directory, id)
Dir.chdir(@directory) do
tracked_files = []
begin
tracked_files += run("git diff-index --name-only #{id} -- #{directory}").split
rescue ExecutionFailed => e
raise e if e.status != 1 # status 1 is normal
end
untracked_files = run("git ls-files --exclude-standard --others -- #{directory}").split
tracked_files + untracked_files
end
end | ruby | def changed_files(directory, id)
Dir.chdir(@directory) do
tracked_files = []
begin
tracked_files += run("git diff-index --name-only #{id} -- #{directory}").split
rescue ExecutionFailed => e
raise e if e.status != 1 # status 1 is normal
end
untracked_files = run("git ls-files --exclude-standard --others -- #{directory}").split
tracked_files + untracked_files
end
end | [
"def",
"changed_files",
"(",
"directory",
",",
"id",
")",
"Dir",
".",
"chdir",
"(",
"@directory",
")",
"do",
"tracked_files",
"=",
"[",
"]",
"begin",
"tracked_files",
"+=",
"run",
"(",
"\"git diff-index --name-only #{id} -- #{directory}\"",
")",
".",
"split",
"rescue",
"ExecutionFailed",
"=>",
"e",
"raise",
"e",
"if",
"e",
".",
"status",
"!=",
"1",
"# status 1 is normal",
"end",
"untracked_files",
"=",
"run",
"(",
"\"git ls-files --exclude-standard --others -- #{directory}\"",
")",
".",
"split",
"tracked_files",
"+",
"untracked_files",
"end",
"end"
] | returns the list of files changed from since_id
including changes in the working tree and staging
area | [
"returns",
"the",
"list",
"of",
"files",
"changed",
"from",
"since_id",
"including",
"changes",
"in",
"the",
"working",
"tree",
"and",
"staging",
"area"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/facades/git.rb#L137-L149 |
23,362 | moio/tetra | lib/tetra/facades/git.rb | Tetra.Git.archive | def archive(directory, id, destination_path)
Dir.chdir(@directory) do
FileUtils.mkdir_p(File.dirname(destination_path))
run("git archive --format=tar #{id} -- #{directory} | xz -9e > #{destination_path}")
end
destination_path
end | ruby | def archive(directory, id, destination_path)
Dir.chdir(@directory) do
FileUtils.mkdir_p(File.dirname(destination_path))
run("git archive --format=tar #{id} -- #{directory} | xz -9e > #{destination_path}")
end
destination_path
end | [
"def",
"archive",
"(",
"directory",
",",
"id",
",",
"destination_path",
")",
"Dir",
".",
"chdir",
"(",
"@directory",
")",
"do",
"FileUtils",
".",
"mkdir_p",
"(",
"File",
".",
"dirname",
"(",
"destination_path",
")",
")",
"run",
"(",
"\"git archive --format=tar #{id} -- #{directory} | xz -9e > #{destination_path}\"",
")",
"end",
"destination_path",
"end"
] | archives version id of directory in destination_path | [
"archives",
"version",
"id",
"of",
"directory",
"in",
"destination_path"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/facades/git.rb#L152-L158 |
23,363 | moio/tetra | lib/tetra/ui/subcommand.rb | Tetra.Subcommand.configure_log_level | def configure_log_level(v, vv, vvv)
if vvv
log.level = ::Logger::DEBUG
elsif vv
log.level = ::Logger::INFO
elsif v
log.level = ::Logger::WARN
else
log.level = ::Logger::ERROR
end
end | ruby | def configure_log_level(v, vv, vvv)
if vvv
log.level = ::Logger::DEBUG
elsif vv
log.level = ::Logger::INFO
elsif v
log.level = ::Logger::WARN
else
log.level = ::Logger::ERROR
end
end | [
"def",
"configure_log_level",
"(",
"v",
",",
"vv",
",",
"vvv",
")",
"if",
"vvv",
"log",
".",
"level",
"=",
"::",
"Logger",
"::",
"DEBUG",
"elsif",
"vv",
"log",
".",
"level",
"=",
"::",
"Logger",
"::",
"INFO",
"elsif",
"v",
"log",
".",
"level",
"=",
"::",
"Logger",
"::",
"WARN",
"else",
"log",
".",
"level",
"=",
"::",
"Logger",
"::",
"ERROR",
"end",
"end"
] | maps verbosity options to log level | [
"maps",
"verbosity",
"options",
"to",
"log",
"level"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/ui/subcommand.rb#L27-L37 |
23,364 | moio/tetra | lib/tetra/ui/subcommand.rb | Tetra.Subcommand.bypass_parsing | def bypass_parsing(args)
log.level = ::Logger::WARN if args.delete "--verbose"
log.level = ::Logger::INFO if args.delete "--very-verbose"
log.level = ::Logger::DEBUG if args.delete "--very-very-verbose"
@options = args
end | ruby | def bypass_parsing(args)
log.level = ::Logger::WARN if args.delete "--verbose"
log.level = ::Logger::INFO if args.delete "--very-verbose"
log.level = ::Logger::DEBUG if args.delete "--very-very-verbose"
@options = args
end | [
"def",
"bypass_parsing",
"(",
"args",
")",
"log",
".",
"level",
"=",
"::",
"Logger",
"::",
"WARN",
"if",
"args",
".",
"delete",
"\"--verbose\"",
"log",
".",
"level",
"=",
"::",
"Logger",
"::",
"INFO",
"if",
"args",
".",
"delete",
"\"--very-verbose\"",
"log",
".",
"level",
"=",
"::",
"Logger",
"::",
"DEBUG",
"if",
"args",
".",
"delete",
"\"--very-very-verbose\"",
"@options",
"=",
"args",
"end"
] | override default option parsing to pass options to other commands | [
"override",
"default",
"option",
"parsing",
"to",
"pass",
"options",
"to",
"other",
"commands"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/ui/subcommand.rb#L40-L46 |
23,365 | moio/tetra | lib/tetra/ui/subcommand.rb | Tetra.Subcommand.format_path | def format_path(path, project)
full_path = (
if Pathname.new(path).relative?
File.join(project.full_path, path)
else
path
end
)
Pathname.new(full_path).relative_path_from(Pathname.new(Dir.pwd))
end | ruby | def format_path(path, project)
full_path = (
if Pathname.new(path).relative?
File.join(project.full_path, path)
else
path
end
)
Pathname.new(full_path).relative_path_from(Pathname.new(Dir.pwd))
end | [
"def",
"format_path",
"(",
"path",
",",
"project",
")",
"full_path",
"=",
"(",
"if",
"Pathname",
".",
"new",
"(",
"path",
")",
".",
"relative?",
"File",
".",
"join",
"(",
"project",
".",
"full_path",
",",
"path",
")",
"else",
"path",
"end",
")",
"Pathname",
".",
"new",
"(",
"full_path",
")",
".",
"relative_path_from",
"(",
"Pathname",
".",
"new",
"(",
"Dir",
".",
"pwd",
")",
")",
"end"
] | generates a version of path relative to the current directory | [
"generates",
"a",
"version",
"of",
"path",
"relative",
"to",
"the",
"current",
"directory"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/ui/subcommand.rb#L77-L86 |
23,366 | moio/tetra | lib/tetra/ui/subcommand.rb | Tetra.Subcommand.checking_exceptions | def checking_exceptions
yield
rescue Errno::EACCES => e
$stderr.puts e
rescue Errno::ENOENT => e
$stderr.puts e
rescue Errno::EEXIST => e
$stderr.puts e
rescue NoProjectDirectoryError => e
$stderr.puts "#{e.directory} is not a tetra project directory, see \"tetra init\""
rescue GitAlreadyInitedError
$stderr.puts "This directory is already a tetra project"
rescue ExecutionFailed => e
$stderr.puts "Failed to run `#{e.commandline}` (exit status #{e.status})"
rescue Interrupt
$stderr.puts "Execution interrupted by the user"
end | ruby | def checking_exceptions
yield
rescue Errno::EACCES => e
$stderr.puts e
rescue Errno::ENOENT => e
$stderr.puts e
rescue Errno::EEXIST => e
$stderr.puts e
rescue NoProjectDirectoryError => e
$stderr.puts "#{e.directory} is not a tetra project directory, see \"tetra init\""
rescue GitAlreadyInitedError
$stderr.puts "This directory is already a tetra project"
rescue ExecutionFailed => e
$stderr.puts "Failed to run `#{e.commandline}` (exit status #{e.status})"
rescue Interrupt
$stderr.puts "Execution interrupted by the user"
end | [
"def",
"checking_exceptions",
"yield",
"rescue",
"Errno",
"::",
"EACCES",
"=>",
"e",
"$stderr",
".",
"puts",
"e",
"rescue",
"Errno",
"::",
"ENOENT",
"=>",
"e",
"$stderr",
".",
"puts",
"e",
"rescue",
"Errno",
"::",
"EEXIST",
"=>",
"e",
"$stderr",
".",
"puts",
"e",
"rescue",
"NoProjectDirectoryError",
"=>",
"e",
"$stderr",
".",
"puts",
"\"#{e.directory} is not a tetra project directory, see \\\"tetra init\\\"\"",
"rescue",
"GitAlreadyInitedError",
"$stderr",
".",
"puts",
"\"This directory is already a tetra project\"",
"rescue",
"ExecutionFailed",
"=>",
"e",
"$stderr",
".",
"puts",
"\"Failed to run `#{e.commandline}` (exit status #{e.status})\"",
"rescue",
"Interrupt",
"$stderr",
".",
"puts",
"\"Execution interrupted by the user\"",
"end"
] | handles most fatal exceptions | [
"handles",
"most",
"fatal",
"exceptions"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/ui/subcommand.rb#L89-L105 |
23,367 | buildkite/buildbox-agent-ruby | lib/buildbox/canceler.rb | Buildbox.Canceler.process_map | def process_map
output = `ps -eo ppid,pid`
processes = {}
output.split("\n").each do |line|
if result = line.match(/(\d+)\s(\d+)/)
parent = result[1].to_i
child = result[2].to_i
processes[parent] ||= []
processes[parent] << child
end
end
processes
end | ruby | def process_map
output = `ps -eo ppid,pid`
processes = {}
output.split("\n").each do |line|
if result = line.match(/(\d+)\s(\d+)/)
parent = result[1].to_i
child = result[2].to_i
processes[parent] ||= []
processes[parent] << child
end
end
processes
end | [
"def",
"process_map",
"output",
"=",
"`",
"`",
"processes",
"=",
"{",
"}",
"output",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"each",
"do",
"|",
"line",
"|",
"if",
"result",
"=",
"line",
".",
"match",
"(",
"/",
"\\d",
"\\s",
"\\d",
"/",
")",
"parent",
"=",
"result",
"[",
"1",
"]",
".",
"to_i",
"child",
"=",
"result",
"[",
"2",
"]",
".",
"to_i",
"processes",
"[",
"parent",
"]",
"||=",
"[",
"]",
"processes",
"[",
"parent",
"]",
"<<",
"child",
"end",
"end",
"processes",
"end"
] | Generates a map of parent process and child processes. This method
will currently only work on unix. | [
"Generates",
"a",
"map",
"of",
"parent",
"process",
"and",
"child",
"processes",
".",
"This",
"method",
"will",
"currently",
"only",
"work",
"on",
"unix",
"."
] | cff8c7dec6eb120c6d36eb5907c556cb5d483c86 | https://github.com/buildkite/buildbox-agent-ruby/blob/cff8c7dec6eb120c6d36eb5907c556cb5d483c86/lib/buildbox/canceler.rb#L63-L78 |
23,368 | buildkite/buildbox-agent-ruby | lib/buildbox/command.rb | Buildbox.Command.read_io | def read_io(io)
data = ""
while true
begin
if Platform.windows?
# Windows doesn't support non-blocking reads on
# file descriptors or pipes so we have to get
# a bit more creative.
# Check if data is actually ready on this IO device.
# We have to do this since `readpartial` will actually block
# until data is available, which can cause blocking forever
# in some cases.
results = IO.select([io], nil, nil, 0.1)
break if !results || results[0].empty?
# Read!
data << io.readpartial(READ_CHUNK_SIZE)
else
# Do a simple non-blocking read on the IO object
data << io.read_nonblock(READ_CHUNK_SIZE)
end
rescue Exception => e
# The catch-all rescue here is to support multiple Ruby versions,
# since we use some Ruby 1.9 specific exceptions.
breakable = false
# EOFError from OSX, EIO is raised by ubuntu
if e.is_a?(EOFError) || e.is_a?(Errno::EIO)
# An `EOFError` means this IO object is done!
breakable = true
elsif defined?(IO::WaitReadable) && e.is_a?(IO::WaitReadable)
# IO::WaitReadable is only available on Ruby 1.9+
# An IO::WaitReadable means there may be more IO but this
# IO object is not ready to be read from yet. No problem,
# we read as much as we can, so we break.
breakable = true
elsif e.is_a?(Errno::EAGAIN) || e.is_a?(Errno::EWOULDBLOCK)
# Otherwise, we just look for the EAGAIN error which should be
# all that IO::WaitReadable does in Ruby 1.9.
breakable = true
end
# Break out if we're supposed to. Otherwise re-raise the error
# because it is a real problem.
break if breakable
raise
end
end
data
end | ruby | def read_io(io)
data = ""
while true
begin
if Platform.windows?
# Windows doesn't support non-blocking reads on
# file descriptors or pipes so we have to get
# a bit more creative.
# Check if data is actually ready on this IO device.
# We have to do this since `readpartial` will actually block
# until data is available, which can cause blocking forever
# in some cases.
results = IO.select([io], nil, nil, 0.1)
break if !results || results[0].empty?
# Read!
data << io.readpartial(READ_CHUNK_SIZE)
else
# Do a simple non-blocking read on the IO object
data << io.read_nonblock(READ_CHUNK_SIZE)
end
rescue Exception => e
# The catch-all rescue here is to support multiple Ruby versions,
# since we use some Ruby 1.9 specific exceptions.
breakable = false
# EOFError from OSX, EIO is raised by ubuntu
if e.is_a?(EOFError) || e.is_a?(Errno::EIO)
# An `EOFError` means this IO object is done!
breakable = true
elsif defined?(IO::WaitReadable) && e.is_a?(IO::WaitReadable)
# IO::WaitReadable is only available on Ruby 1.9+
# An IO::WaitReadable means there may be more IO but this
# IO object is not ready to be read from yet. No problem,
# we read as much as we can, so we break.
breakable = true
elsif e.is_a?(Errno::EAGAIN) || e.is_a?(Errno::EWOULDBLOCK)
# Otherwise, we just look for the EAGAIN error which should be
# all that IO::WaitReadable does in Ruby 1.9.
breakable = true
end
# Break out if we're supposed to. Otherwise re-raise the error
# because it is a real problem.
break if breakable
raise
end
end
data
end | [
"def",
"read_io",
"(",
"io",
")",
"data",
"=",
"\"\"",
"while",
"true",
"begin",
"if",
"Platform",
".",
"windows?",
"# Windows doesn't support non-blocking reads on",
"# file descriptors or pipes so we have to get",
"# a bit more creative.",
"# Check if data is actually ready on this IO device.",
"# We have to do this since `readpartial` will actually block",
"# until data is available, which can cause blocking forever",
"# in some cases.",
"results",
"=",
"IO",
".",
"select",
"(",
"[",
"io",
"]",
",",
"nil",
",",
"nil",
",",
"0.1",
")",
"break",
"if",
"!",
"results",
"||",
"results",
"[",
"0",
"]",
".",
"empty?",
"# Read!",
"data",
"<<",
"io",
".",
"readpartial",
"(",
"READ_CHUNK_SIZE",
")",
"else",
"# Do a simple non-blocking read on the IO object",
"data",
"<<",
"io",
".",
"read_nonblock",
"(",
"READ_CHUNK_SIZE",
")",
"end",
"rescue",
"Exception",
"=>",
"e",
"# The catch-all rescue here is to support multiple Ruby versions,",
"# since we use some Ruby 1.9 specific exceptions.",
"breakable",
"=",
"false",
"# EOFError from OSX, EIO is raised by ubuntu",
"if",
"e",
".",
"is_a?",
"(",
"EOFError",
")",
"||",
"e",
".",
"is_a?",
"(",
"Errno",
"::",
"EIO",
")",
"# An `EOFError` means this IO object is done!",
"breakable",
"=",
"true",
"elsif",
"defined?",
"(",
"IO",
"::",
"WaitReadable",
")",
"&&",
"e",
".",
"is_a?",
"(",
"IO",
"::",
"WaitReadable",
")",
"# IO::WaitReadable is only available on Ruby 1.9+",
"# An IO::WaitReadable means there may be more IO but this",
"# IO object is not ready to be read from yet. No problem,",
"# we read as much as we can, so we break.",
"breakable",
"=",
"true",
"elsif",
"e",
".",
"is_a?",
"(",
"Errno",
"::",
"EAGAIN",
")",
"||",
"e",
".",
"is_a?",
"(",
"Errno",
"::",
"EWOULDBLOCK",
")",
"# Otherwise, we just look for the EAGAIN error which should be",
"# all that IO::WaitReadable does in Ruby 1.9.",
"breakable",
"=",
"true",
"end",
"# Break out if we're supposed to. Otherwise re-raise the error",
"# because it is a real problem.",
"break",
"if",
"breakable",
"raise",
"end",
"end",
"data",
"end"
] | Reads data from an IO object while it can, returning the data it reads.
When it encounters a case when it can't read anymore, it returns the
data.
@return [String] | [
"Reads",
"data",
"from",
"an",
"IO",
"object",
"while",
"it",
"can",
"returning",
"the",
"data",
"it",
"reads",
".",
"When",
"it",
"encounters",
"a",
"case",
"when",
"it",
"can",
"t",
"read",
"anymore",
"it",
"returns",
"the",
"data",
"."
] | cff8c7dec6eb120c6d36eb5907c556cb5d483c86 | https://github.com/buildkite/buildbox-agent-ruby/blob/cff8c7dec6eb120c6d36eb5907c556cb5d483c86/lib/buildbox/command.rb#L164-L218 |
23,369 | jantman/serverspec-extended-types | lib/serverspec_extended_types/virtualenv.rb | Serverspec::Type.Virtualenv.virtualenv? | def virtualenv?
pip_path = ::File.join(@name, 'bin', 'pip')
python_path = ::File.join(@name, 'bin', 'python')
act_path = ::File.join(@name, 'bin', 'activate')
cmd = "grep -q 'export VIRTUAL_ENV' #{act_path}"
@runner.check_file_is_executable(pip_path, 'owner') and
@runner.check_file_is_executable(python_path, 'owner') and
@runner.check_file_is_readable(act_path, 'owner') and
@runner.run_command(cmd).exit_status.to_i == 0
end | ruby | def virtualenv?
pip_path = ::File.join(@name, 'bin', 'pip')
python_path = ::File.join(@name, 'bin', 'python')
act_path = ::File.join(@name, 'bin', 'activate')
cmd = "grep -q 'export VIRTUAL_ENV' #{act_path}"
@runner.check_file_is_executable(pip_path, 'owner') and
@runner.check_file_is_executable(python_path, 'owner') and
@runner.check_file_is_readable(act_path, 'owner') and
@runner.run_command(cmd).exit_status.to_i == 0
end | [
"def",
"virtualenv?",
"pip_path",
"=",
"::",
"File",
".",
"join",
"(",
"@name",
",",
"'bin'",
",",
"'pip'",
")",
"python_path",
"=",
"::",
"File",
".",
"join",
"(",
"@name",
",",
"'bin'",
",",
"'python'",
")",
"act_path",
"=",
"::",
"File",
".",
"join",
"(",
"@name",
",",
"'bin'",
",",
"'activate'",
")",
"cmd",
"=",
"\"grep -q 'export VIRTUAL_ENV' #{act_path}\"",
"@runner",
".",
"check_file_is_executable",
"(",
"pip_path",
",",
"'owner'",
")",
"and",
"@runner",
".",
"check_file_is_executable",
"(",
"python_path",
",",
"'owner'",
")",
"and",
"@runner",
".",
"check_file_is_readable",
"(",
"act_path",
",",
"'owner'",
")",
"and",
"@runner",
".",
"run_command",
"(",
"cmd",
")",
".",
"exit_status",
".",
"to_i",
"==",
"0",
"end"
] | Test whether this appears to be a working venv
Tests performed:
- venv_path/bin/pip executable by owner?
- venv_path/bin/python executable by owner?
- venv_path/bin/activate readable by owner?
- 'export VIRTUAL_ENV' in venv_path/bin/activate?
@example
describe virtualenv('/path/to/venv') do
it { should be_virtualenv }
end
@api public
@return [Boolean] | [
"Test",
"whether",
"this",
"appears",
"to",
"be",
"a",
"working",
"venv"
] | 28437dcccc403ab71abe8bf481ec4d22d4eed395 | https://github.com/jantman/serverspec-extended-types/blob/28437dcccc403ab71abe8bf481ec4d22d4eed395/lib/serverspec_extended_types/virtualenv.rb#L30-L39 |
23,370 | moio/tetra | lib/tetra/facades/process_runner.rb | Tetra.ProcessRunner.run_interactive | def run_interactive(command)
log.debug "running `#{command}`"
success = system({}, command)
log.debug "`#{command}` exited with success #{success}"
fail ExecutionFailed.new(command, $CHILD_STATUS, nil, nil) unless success
end | ruby | def run_interactive(command)
log.debug "running `#{command}`"
success = system({}, command)
log.debug "`#{command}` exited with success #{success}"
fail ExecutionFailed.new(command, $CHILD_STATUS, nil, nil) unless success
end | [
"def",
"run_interactive",
"(",
"command",
")",
"log",
".",
"debug",
"\"running `#{command}`\"",
"success",
"=",
"system",
"(",
"{",
"}",
",",
"command",
")",
"log",
".",
"debug",
"\"`#{command}` exited with success #{success}\"",
"fail",
"ExecutionFailed",
".",
"new",
"(",
"command",
",",
"$CHILD_STATUS",
",",
"nil",
",",
"nil",
")",
"unless",
"success",
"end"
] | runs an interactive executable in a subshell | [
"runs",
"an",
"interactive",
"executable",
"in",
"a",
"subshell"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/facades/process_runner.rb#L38-L43 |
23,371 | moio/tetra | lib/tetra/project.rb | Tetra.Project.merge_new_content | def merge_new_content(new_content, path, comment, kind)
from_directory do
log.debug "merging new content to #{path} of kind #{kind}"
already_existing = File.exist?(path)
generated_comment = "tetra: generated-#{kind}"
whole_comment = [comment, generated_comment].join("\n\n")
if already_existing
unless @git.latest_id(generated_comment)
log.debug "committing new file"
@git.commit_file(path, whole_comment)
end
log.debug "moving #{path} to #{path}.tetra_user_edited"
File.rename(path, "#{path}.tetra_user_edited")
end
previous_id = @git.latest_id(generated_comment)
File.open(path, "w") { |io| io.write(new_content) }
log.debug "committing new content: #{comment}"
@git.commit_file(path, whole_comment)
if already_existing
# 3-way merge
conflict_count = @git.merge_with_id(path, "#{path}.tetra_user_edited", previous_id)
File.delete("#{path}.tetra_user_edited")
@git.commit_file(path, "User changes merged back") if conflict_count == 0
return conflict_count
end
return 0
end
end | ruby | def merge_new_content(new_content, path, comment, kind)
from_directory do
log.debug "merging new content to #{path} of kind #{kind}"
already_existing = File.exist?(path)
generated_comment = "tetra: generated-#{kind}"
whole_comment = [comment, generated_comment].join("\n\n")
if already_existing
unless @git.latest_id(generated_comment)
log.debug "committing new file"
@git.commit_file(path, whole_comment)
end
log.debug "moving #{path} to #{path}.tetra_user_edited"
File.rename(path, "#{path}.tetra_user_edited")
end
previous_id = @git.latest_id(generated_comment)
File.open(path, "w") { |io| io.write(new_content) }
log.debug "committing new content: #{comment}"
@git.commit_file(path, whole_comment)
if already_existing
# 3-way merge
conflict_count = @git.merge_with_id(path, "#{path}.tetra_user_edited", previous_id)
File.delete("#{path}.tetra_user_edited")
@git.commit_file(path, "User changes merged back") if conflict_count == 0
return conflict_count
end
return 0
end
end | [
"def",
"merge_new_content",
"(",
"new_content",
",",
"path",
",",
"comment",
",",
"kind",
")",
"from_directory",
"do",
"log",
".",
"debug",
"\"merging new content to #{path} of kind #{kind}\"",
"already_existing",
"=",
"File",
".",
"exist?",
"(",
"path",
")",
"generated_comment",
"=",
"\"tetra: generated-#{kind}\"",
"whole_comment",
"=",
"[",
"comment",
",",
"generated_comment",
"]",
".",
"join",
"(",
"\"\\n\\n\"",
")",
"if",
"already_existing",
"unless",
"@git",
".",
"latest_id",
"(",
"generated_comment",
")",
"log",
".",
"debug",
"\"committing new file\"",
"@git",
".",
"commit_file",
"(",
"path",
",",
"whole_comment",
")",
"end",
"log",
".",
"debug",
"\"moving #{path} to #{path}.tetra_user_edited\"",
"File",
".",
"rename",
"(",
"path",
",",
"\"#{path}.tetra_user_edited\"",
")",
"end",
"previous_id",
"=",
"@git",
".",
"latest_id",
"(",
"generated_comment",
")",
"File",
".",
"open",
"(",
"path",
",",
"\"w\"",
")",
"{",
"|",
"io",
"|",
"io",
".",
"write",
"(",
"new_content",
")",
"}",
"log",
".",
"debug",
"\"committing new content: #{comment}\"",
"@git",
".",
"commit_file",
"(",
"path",
",",
"whole_comment",
")",
"if",
"already_existing",
"# 3-way merge",
"conflict_count",
"=",
"@git",
".",
"merge_with_id",
"(",
"path",
",",
"\"#{path}.tetra_user_edited\"",
",",
"previous_id",
")",
"File",
".",
"delete",
"(",
"\"#{path}.tetra_user_edited\"",
")",
"@git",
".",
"commit_file",
"(",
"path",
",",
"\"User changes merged back\"",
")",
"if",
"conflict_count",
"==",
"0",
"return",
"conflict_count",
"end",
"return",
"0",
"end",
"end"
] | replaces content in path with new_content, commits using
comment and 3-way merges new and old content with the previous
version of file of the same kind, if it exists.
returns the number of conflicts | [
"replaces",
"content",
"in",
"path",
"with",
"new_content",
"commits",
"using",
"comment",
"and",
"3",
"-",
"way",
"merges",
"new",
"and",
"old",
"content",
"with",
"the",
"previous",
"version",
"of",
"file",
"of",
"the",
"same",
"kind",
"if",
"it",
"exists",
".",
"returns",
"the",
"number",
"of",
"conflicts"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/project.rb#L110-L144 |
23,372 | moio/tetra | lib/tetra/project.rb | Tetra.Project.src_archive | def src_archive
from_directory do
Find.find(File.join("packages", name)) do |file|
if File.file?(file) && file.match(/\.(spec)|(sh)|(patch)$/).nil?
return File.basename(file)
end
end
nil
end
end | ruby | def src_archive
from_directory do
Find.find(File.join("packages", name)) do |file|
if File.file?(file) && file.match(/\.(spec)|(sh)|(patch)$/).nil?
return File.basename(file)
end
end
nil
end
end | [
"def",
"src_archive",
"from_directory",
"do",
"Find",
".",
"find",
"(",
"File",
".",
"join",
"(",
"\"packages\"",
",",
"name",
")",
")",
"do",
"|",
"file",
"|",
"if",
"File",
".",
"file?",
"(",
"file",
")",
"&&",
"file",
".",
"match",
"(",
"/",
"\\.",
"/",
")",
".",
"nil?",
"return",
"File",
".",
"basename",
"(",
"file",
")",
"end",
"end",
"nil",
"end",
"end"
] | returns the name of the source archive file, if any | [
"returns",
"the",
"name",
"of",
"the",
"source",
"archive",
"file",
"if",
"any"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/project.rb#L186-L195 |
23,373 | mikejmoore/docker-swarm-sdk | lib/docker-swarm.rb | Docker.Swarm.authenticate! | def authenticate!(options = {}, connection = self.connection)
creds = options.to_json
connection.post('/auth', {}, :body => creds)
@creds = creds
true
rescue Docker::Error::ServerError, Docker::Error::UnauthorizedError
raise Docker::Error::AuthenticationError
end | ruby | def authenticate!(options = {}, connection = self.connection)
creds = options.to_json
connection.post('/auth', {}, :body => creds)
@creds = creds
true
rescue Docker::Error::ServerError, Docker::Error::UnauthorizedError
raise Docker::Error::AuthenticationError
end | [
"def",
"authenticate!",
"(",
"options",
"=",
"{",
"}",
",",
"connection",
"=",
"self",
".",
"connection",
")",
"creds",
"=",
"options",
".",
"to_json",
"connection",
".",
"post",
"(",
"'/auth'",
",",
"{",
"}",
",",
":body",
"=>",
"creds",
")",
"@creds",
"=",
"creds",
"true",
"rescue",
"Docker",
"::",
"Error",
"::",
"ServerError",
",",
"Docker",
"::",
"Error",
"::",
"UnauthorizedError",
"raise",
"Docker",
"::",
"Error",
"::",
"AuthenticationError",
"end"
] | Login to the Docker registry. | [
"Login",
"to",
"the",
"Docker",
"registry",
"."
] | 7f69f295900af880211d6a3a830eff0458df5526 | https://github.com/mikejmoore/docker-swarm-sdk/blob/7f69f295900af880211d6a3a830eff0458df5526/lib/docker-swarm.rb#L116-L123 |
23,374 | mikejmoore/docker-swarm-sdk | lib/docker-swarm.rb | Docker.Swarm.validate_version! | def validate_version!
Docker.info
true
rescue Docker::Error::DockerError
raise Docker::Error::VersionError, "Expected API Version: #{API_VERSION}"
end | ruby | def validate_version!
Docker.info
true
rescue Docker::Error::DockerError
raise Docker::Error::VersionError, "Expected API Version: #{API_VERSION}"
end | [
"def",
"validate_version!",
"Docker",
".",
"info",
"true",
"rescue",
"Docker",
"::",
"Error",
"::",
"DockerError",
"raise",
"Docker",
"::",
"Error",
"::",
"VersionError",
",",
"\"Expected API Version: #{API_VERSION}\"",
"end"
] | When the correct version of Docker is installed, returns true. Otherwise,
raises a VersionError. | [
"When",
"the",
"correct",
"version",
"of",
"Docker",
"is",
"installed",
"returns",
"true",
".",
"Otherwise",
"raises",
"a",
"VersionError",
"."
] | 7f69f295900af880211d6a3a830eff0458df5526 | https://github.com/mikejmoore/docker-swarm-sdk/blob/7f69f295900af880211d6a3a830eff0458df5526/lib/docker-swarm.rb#L127-L132 |
23,375 | moio/tetra | spec/spec_helper.rb | Tetra.Mockers.create_mock_project | def create_mock_project
@project_path = File.join("spec", "data", "test-project")
Tetra::Project.init(@project_path, false)
@project = Tetra::Project.new(@project_path)
end | ruby | def create_mock_project
@project_path = File.join("spec", "data", "test-project")
Tetra::Project.init(@project_path, false)
@project = Tetra::Project.new(@project_path)
end | [
"def",
"create_mock_project",
"@project_path",
"=",
"File",
".",
"join",
"(",
"\"spec\"",
",",
"\"data\"",
",",
"\"test-project\"",
")",
"Tetra",
"::",
"Project",
".",
"init",
"(",
"@project_path",
",",
"false",
")",
"@project",
"=",
"Tetra",
"::",
"Project",
".",
"new",
"(",
"@project_path",
")",
"end"
] | creates a minimal tetra project | [
"creates",
"a",
"minimal",
"tetra",
"project"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/spec/spec_helper.rb#L28-L32 |
23,376 | moio/tetra | spec/spec_helper.rb | Tetra.Mockers.create_mock_executable | def create_mock_executable(executable_name)
Dir.chdir(@project_path) do
dir = mock_executable_dir(executable_name)
FileUtils.mkdir_p(dir)
executable_path = mock_executable_path(executable_name)
File.open(executable_path, "w") { |io| io.puts "echo $0 $*>test_out" }
File.chmod(0777, executable_path)
executable_path
end
end | ruby | def create_mock_executable(executable_name)
Dir.chdir(@project_path) do
dir = mock_executable_dir(executable_name)
FileUtils.mkdir_p(dir)
executable_path = mock_executable_path(executable_name)
File.open(executable_path, "w") { |io| io.puts "echo $0 $*>test_out" }
File.chmod(0777, executable_path)
executable_path
end
end | [
"def",
"create_mock_executable",
"(",
"executable_name",
")",
"Dir",
".",
"chdir",
"(",
"@project_path",
")",
"do",
"dir",
"=",
"mock_executable_dir",
"(",
"executable_name",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"dir",
")",
"executable_path",
"=",
"mock_executable_path",
"(",
"executable_name",
")",
"File",
".",
"open",
"(",
"executable_path",
",",
"\"w\"",
")",
"{",
"|",
"io",
"|",
"io",
".",
"puts",
"\"echo $0 $*>test_out\"",
"}",
"File",
".",
"chmod",
"(",
"0777",
",",
"executable_path",
")",
"executable_path",
"end",
"end"
] | creates an executable in kit that will print its parameters
in a test_out file for checking. Returns mocked executable
full path | [
"creates",
"an",
"executable",
"in",
"kit",
"that",
"will",
"print",
"its",
"parameters",
"in",
"a",
"test_out",
"file",
"for",
"checking",
".",
"Returns",
"mocked",
"executable",
"full",
"path"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/spec/spec_helper.rb#L42-L51 |
23,377 | moio/tetra | lib/tetra/pom_getter.rb | Tetra.PomGetter.get_pom_from_jar | def get_pom_from_jar(file)
log.debug("Attempting unpack of #{file} to find a POM")
begin
Zip::File.foreach(file) do |entry|
if entry.name =~ %r{/pom.xml$}
log.info("pom.xml found in #{file}##{entry.name}")
return entry.get_input_stream.read, :found_in_jar
end
end
rescue Zip::Error
log.warn("#{file} does not seem to be a valid jar archive, skipping")
rescue TypeError
log.warn("#{file} seems to be a valid jar archive but is corrupt, skipping")
end
nil
end | ruby | def get_pom_from_jar(file)
log.debug("Attempting unpack of #{file} to find a POM")
begin
Zip::File.foreach(file) do |entry|
if entry.name =~ %r{/pom.xml$}
log.info("pom.xml found in #{file}##{entry.name}")
return entry.get_input_stream.read, :found_in_jar
end
end
rescue Zip::Error
log.warn("#{file} does not seem to be a valid jar archive, skipping")
rescue TypeError
log.warn("#{file} seems to be a valid jar archive but is corrupt, skipping")
end
nil
end | [
"def",
"get_pom_from_jar",
"(",
"file",
")",
"log",
".",
"debug",
"(",
"\"Attempting unpack of #{file} to find a POM\"",
")",
"begin",
"Zip",
"::",
"File",
".",
"foreach",
"(",
"file",
")",
"do",
"|",
"entry",
"|",
"if",
"entry",
".",
"name",
"=~",
"%r{",
"}",
"log",
".",
"info",
"(",
"\"pom.xml found in #{file}##{entry.name}\"",
")",
"return",
"entry",
".",
"get_input_stream",
".",
"read",
",",
":found_in_jar",
"end",
"end",
"rescue",
"Zip",
"::",
"Error",
"log",
".",
"warn",
"(",
"\"#{file} does not seem to be a valid jar archive, skipping\"",
")",
"rescue",
"TypeError",
"log",
".",
"warn",
"(",
"\"#{file} seems to be a valid jar archive but is corrupt, skipping\"",
")",
"end",
"nil",
"end"
] | returns a pom embedded in a jar file | [
"returns",
"a",
"pom",
"embedded",
"in",
"a",
"jar",
"file"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/pom_getter.rb#L20-L35 |
23,378 | moio/tetra | lib/tetra/pom_getter.rb | Tetra.PomGetter.get_pom_from_sha1 | def get_pom_from_sha1(file)
log.debug("Attempting SHA1 POM lookup for #{file}")
begin
if File.file?(file)
site = MavenWebsite.new
sha1 = Digest::SHA1.hexdigest File.read(file)
results = site.search_by_sha1(sha1).select { |result| result["ec"].include?(".pom") }
result = results.first
unless result.nil?
log.info("pom.xml for #{file} found on search.maven.org for sha1 #{sha1}\
(#{result['g']}:#{result['a']}:#{result['v']})"
)
group_id, artifact_id, version = site.get_maven_id_from result
return site.download_pom(group_id, artifact_id, version), :found_via_sha1
end
end
rescue NotFoundOnMavenWebsiteError
log.warn("Got a 404 error while looking for #{file}'s SHA1 in search.maven.org")
end
nil
end | ruby | def get_pom_from_sha1(file)
log.debug("Attempting SHA1 POM lookup for #{file}")
begin
if File.file?(file)
site = MavenWebsite.new
sha1 = Digest::SHA1.hexdigest File.read(file)
results = site.search_by_sha1(sha1).select { |result| result["ec"].include?(".pom") }
result = results.first
unless result.nil?
log.info("pom.xml for #{file} found on search.maven.org for sha1 #{sha1}\
(#{result['g']}:#{result['a']}:#{result['v']})"
)
group_id, artifact_id, version = site.get_maven_id_from result
return site.download_pom(group_id, artifact_id, version), :found_via_sha1
end
end
rescue NotFoundOnMavenWebsiteError
log.warn("Got a 404 error while looking for #{file}'s SHA1 in search.maven.org")
end
nil
end | [
"def",
"get_pom_from_sha1",
"(",
"file",
")",
"log",
".",
"debug",
"(",
"\"Attempting SHA1 POM lookup for #{file}\"",
")",
"begin",
"if",
"File",
".",
"file?",
"(",
"file",
")",
"site",
"=",
"MavenWebsite",
".",
"new",
"sha1",
"=",
"Digest",
"::",
"SHA1",
".",
"hexdigest",
"File",
".",
"read",
"(",
"file",
")",
"results",
"=",
"site",
".",
"search_by_sha1",
"(",
"sha1",
")",
".",
"select",
"{",
"|",
"result",
"|",
"result",
"[",
"\"ec\"",
"]",
".",
"include?",
"(",
"\".pom\"",
")",
"}",
"result",
"=",
"results",
".",
"first",
"unless",
"result",
".",
"nil?",
"log",
".",
"info",
"(",
"\"pom.xml for #{file} found on search.maven.org for sha1 #{sha1}\\\n (#{result['g']}:#{result['a']}:#{result['v']})\"",
")",
"group_id",
",",
"artifact_id",
",",
"version",
"=",
"site",
".",
"get_maven_id_from",
"result",
"return",
"site",
".",
"download_pom",
"(",
"group_id",
",",
"artifact_id",
",",
"version",
")",
",",
":found_via_sha1",
"end",
"end",
"rescue",
"NotFoundOnMavenWebsiteError",
"log",
".",
"warn",
"(",
"\"Got a 404 error while looking for #{file}'s SHA1 in search.maven.org\"",
")",
"end",
"nil",
"end"
] | returns a pom from search.maven.org with a jar sha1 search | [
"returns",
"a",
"pom",
"from",
"search",
".",
"maven",
".",
"org",
"with",
"a",
"jar",
"sha1",
"search"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/pom_getter.rb#L38-L58 |
23,379 | moio/tetra | lib/tetra/pom_getter.rb | Tetra.PomGetter.get_pom_from_heuristic | def get_pom_from_heuristic(filename)
begin
log.debug("Attempting heuristic POM search for #{filename}")
site = MavenWebsite.new
filename = cleanup_name(filename)
version_matcher = VersionMatcher.new
my_artifact_id, my_version = version_matcher.split_version(filename)
log.debug("Guessed artifact id: #{my_artifact_id}, version: #{my_version}")
result = site.search_by_name(my_artifact_id).first
log.debug("Artifact id search result: #{result}")
unless result.nil?
group_id, artifact_id, = site.get_maven_id_from result
results = site.search_by_group_id_and_artifact_id(group_id, artifact_id)
log.debug("All versions: #{results}")
their_versions = results.map { |doc| doc["v"] }
best_matched_version = (
if !my_version.nil?
version_matcher.best_match(my_version, their_versions)
else
their_versions.max
end
)
best_matched_result = (results.select { |r| r["v"] == best_matched_version }).first
group_id, artifact_id, version = site.get_maven_id_from(best_matched_result)
log.warn("pom.xml for #{filename} found on search.maven.org with heuristic search\
(#{group_id}:#{artifact_id}:#{version})"
)
return site.download_pom(group_id, artifact_id, version), :found_via_heuristic
end
rescue NotFoundOnMavenWebsiteError
log.warn("Got a 404 error while looking for #{filename} heuristically in search.maven.org")
end
nil
end | ruby | def get_pom_from_heuristic(filename)
begin
log.debug("Attempting heuristic POM search for #{filename}")
site = MavenWebsite.new
filename = cleanup_name(filename)
version_matcher = VersionMatcher.new
my_artifact_id, my_version = version_matcher.split_version(filename)
log.debug("Guessed artifact id: #{my_artifact_id}, version: #{my_version}")
result = site.search_by_name(my_artifact_id).first
log.debug("Artifact id search result: #{result}")
unless result.nil?
group_id, artifact_id, = site.get_maven_id_from result
results = site.search_by_group_id_and_artifact_id(group_id, artifact_id)
log.debug("All versions: #{results}")
their_versions = results.map { |doc| doc["v"] }
best_matched_version = (
if !my_version.nil?
version_matcher.best_match(my_version, their_versions)
else
their_versions.max
end
)
best_matched_result = (results.select { |r| r["v"] == best_matched_version }).first
group_id, artifact_id, version = site.get_maven_id_from(best_matched_result)
log.warn("pom.xml for #{filename} found on search.maven.org with heuristic search\
(#{group_id}:#{artifact_id}:#{version})"
)
return site.download_pom(group_id, artifact_id, version), :found_via_heuristic
end
rescue NotFoundOnMavenWebsiteError
log.warn("Got a 404 error while looking for #{filename} heuristically in search.maven.org")
end
nil
end | [
"def",
"get_pom_from_heuristic",
"(",
"filename",
")",
"begin",
"log",
".",
"debug",
"(",
"\"Attempting heuristic POM search for #{filename}\"",
")",
"site",
"=",
"MavenWebsite",
".",
"new",
"filename",
"=",
"cleanup_name",
"(",
"filename",
")",
"version_matcher",
"=",
"VersionMatcher",
".",
"new",
"my_artifact_id",
",",
"my_version",
"=",
"version_matcher",
".",
"split_version",
"(",
"filename",
")",
"log",
".",
"debug",
"(",
"\"Guessed artifact id: #{my_artifact_id}, version: #{my_version}\"",
")",
"result",
"=",
"site",
".",
"search_by_name",
"(",
"my_artifact_id",
")",
".",
"first",
"log",
".",
"debug",
"(",
"\"Artifact id search result: #{result}\"",
")",
"unless",
"result",
".",
"nil?",
"group_id",
",",
"artifact_id",
",",
"=",
"site",
".",
"get_maven_id_from",
"result",
"results",
"=",
"site",
".",
"search_by_group_id_and_artifact_id",
"(",
"group_id",
",",
"artifact_id",
")",
"log",
".",
"debug",
"(",
"\"All versions: #{results}\"",
")",
"their_versions",
"=",
"results",
".",
"map",
"{",
"|",
"doc",
"|",
"doc",
"[",
"\"v\"",
"]",
"}",
"best_matched_version",
"=",
"(",
"if",
"!",
"my_version",
".",
"nil?",
"version_matcher",
".",
"best_match",
"(",
"my_version",
",",
"their_versions",
")",
"else",
"their_versions",
".",
"max",
"end",
")",
"best_matched_result",
"=",
"(",
"results",
".",
"select",
"{",
"|",
"r",
"|",
"r",
"[",
"\"v\"",
"]",
"==",
"best_matched_version",
"}",
")",
".",
"first",
"group_id",
",",
"artifact_id",
",",
"version",
"=",
"site",
".",
"get_maven_id_from",
"(",
"best_matched_result",
")",
"log",
".",
"warn",
"(",
"\"pom.xml for #{filename} found on search.maven.org with heuristic search\\\n (#{group_id}:#{artifact_id}:#{version})\"",
")",
"return",
"site",
".",
"download_pom",
"(",
"group_id",
",",
"artifact_id",
",",
"version",
")",
",",
":found_via_heuristic",
"end",
"rescue",
"NotFoundOnMavenWebsiteError",
"log",
".",
"warn",
"(",
"\"Got a 404 error while looking for #{filename} heuristically in search.maven.org\"",
")",
"end",
"nil",
"end"
] | returns a pom from search.maven.org with a heuristic name search | [
"returns",
"a",
"pom",
"from",
"search",
".",
"maven",
".",
"org",
"with",
"a",
"heuristic",
"name",
"search"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/pom_getter.rb#L61-L97 |
23,380 | moio/tetra | lib/tetra/packages/scriptable.rb | Tetra.Scriptable._to_script | def _to_script(project)
project.from_directory do
script_lines = [
"#!/bin/bash",
"set -xe",
"PROJECT_PREFIX=`readlink -e .`",
"cd #{project.latest_dry_run_directory}"
] + aliases(project) + project.build_script_lines
new_content = script_lines.join("\n") + "\n"
result_dir = File.join(project.packages_dir, project.name)
FileUtils.mkdir_p(result_dir)
result_path = File.join(result_dir, "build.sh")
conflict_count = project.merge_new_content(new_content, result_path, "Build script generated",
"script")
[result_path, conflict_count]
end
end | ruby | def _to_script(project)
project.from_directory do
script_lines = [
"#!/bin/bash",
"set -xe",
"PROJECT_PREFIX=`readlink -e .`",
"cd #{project.latest_dry_run_directory}"
] + aliases(project) + project.build_script_lines
new_content = script_lines.join("\n") + "\n"
result_dir = File.join(project.packages_dir, project.name)
FileUtils.mkdir_p(result_dir)
result_path = File.join(result_dir, "build.sh")
conflict_count = project.merge_new_content(new_content, result_path, "Build script generated",
"script")
[result_path, conflict_count]
end
end | [
"def",
"_to_script",
"(",
"project",
")",
"project",
".",
"from_directory",
"do",
"script_lines",
"=",
"[",
"\"#!/bin/bash\"",
",",
"\"set -xe\"",
",",
"\"PROJECT_PREFIX=`readlink -e .`\"",
",",
"\"cd #{project.latest_dry_run_directory}\"",
"]",
"+",
"aliases",
"(",
"project",
")",
"+",
"project",
".",
"build_script_lines",
"new_content",
"=",
"script_lines",
".",
"join",
"(",
"\"\\n\"",
")",
"+",
"\"\\n\"",
"result_dir",
"=",
"File",
".",
"join",
"(",
"project",
".",
"packages_dir",
",",
"project",
".",
"name",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"result_dir",
")",
"result_path",
"=",
"File",
".",
"join",
"(",
"result_dir",
",",
"\"build.sh\"",
")",
"conflict_count",
"=",
"project",
".",
"merge_new_content",
"(",
"new_content",
",",
"result_path",
",",
"\"Build script generated\"",
",",
"\"script\"",
")",
"[",
"result_path",
",",
"conflict_count",
"]",
"end",
"end"
] | returns a build script for this package | [
"returns",
"a",
"build",
"script",
"for",
"this",
"package"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/packages/scriptable.rb#L7-L26 |
23,381 | moio/tetra | lib/tetra/packages/scriptable.rb | Tetra.Scriptable.aliases | def aliases(project)
kit = Tetra::Kit.new(project)
aliases = []
ant_path = kit.find_executable("ant")
ant_commandline = Tetra::Ant.commandline("$PROJECT_PREFIX", ant_path)
aliases << "alias ant='#{ant_commandline}'"
mvn_path = kit.find_executable("mvn")
mvn_commandline = Tetra::Mvn.commandline("$PROJECT_PREFIX", mvn_path)
aliases << "alias mvn='#{mvn_commandline} -o'"
aliases
end | ruby | def aliases(project)
kit = Tetra::Kit.new(project)
aliases = []
ant_path = kit.find_executable("ant")
ant_commandline = Tetra::Ant.commandline("$PROJECT_PREFIX", ant_path)
aliases << "alias ant='#{ant_commandline}'"
mvn_path = kit.find_executable("mvn")
mvn_commandline = Tetra::Mvn.commandline("$PROJECT_PREFIX", mvn_path)
aliases << "alias mvn='#{mvn_commandline} -o'"
aliases
end | [
"def",
"aliases",
"(",
"project",
")",
"kit",
"=",
"Tetra",
"::",
"Kit",
".",
"new",
"(",
"project",
")",
"aliases",
"=",
"[",
"]",
"ant_path",
"=",
"kit",
".",
"find_executable",
"(",
"\"ant\"",
")",
"ant_commandline",
"=",
"Tetra",
"::",
"Ant",
".",
"commandline",
"(",
"\"$PROJECT_PREFIX\"",
",",
"ant_path",
")",
"aliases",
"<<",
"\"alias ant='#{ant_commandline}'\"",
"mvn_path",
"=",
"kit",
".",
"find_executable",
"(",
"\"mvn\"",
")",
"mvn_commandline",
"=",
"Tetra",
"::",
"Mvn",
".",
"commandline",
"(",
"\"$PROJECT_PREFIX\"",
",",
"mvn_path",
")",
"aliases",
"<<",
"\"alias mvn='#{mvn_commandline} -o'\"",
"aliases",
"end"
] | setup aliases for adjusted versions of the packaging tools | [
"setup",
"aliases",
"for",
"adjusted",
"versions",
"of",
"the",
"packaging",
"tools"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/packages/scriptable.rb#L29-L42 |
23,382 | moio/tetra | lib/tetra/project_initer.rb | Tetra.ProjectIniter.template_files | def template_files(include_bundled_software)
result = {
"kit" => ".",
"packages" => ".",
"src" => "."
}
if include_bundled_software
Dir.chdir(TEMPLATE_PATH) do
Dir.glob(File.join("bundled", "*")).each do |file|
result[file] = "kit"
end
end
end
result
end | ruby | def template_files(include_bundled_software)
result = {
"kit" => ".",
"packages" => ".",
"src" => "."
}
if include_bundled_software
Dir.chdir(TEMPLATE_PATH) do
Dir.glob(File.join("bundled", "*")).each do |file|
result[file] = "kit"
end
end
end
result
end | [
"def",
"template_files",
"(",
"include_bundled_software",
")",
"result",
"=",
"{",
"\"kit\"",
"=>",
"\".\"",
",",
"\"packages\"",
"=>",
"\".\"",
",",
"\"src\"",
"=>",
"\".\"",
"}",
"if",
"include_bundled_software",
"Dir",
".",
"chdir",
"(",
"TEMPLATE_PATH",
")",
"do",
"Dir",
".",
"glob",
"(",
"File",
".",
"join",
"(",
"\"bundled\"",
",",
"\"*\"",
")",
")",
".",
"each",
"do",
"|",
"file",
"|",
"result",
"[",
"file",
"]",
"=",
"\"kit\"",
"end",
"end",
"end",
"result",
"end"
] | returns a hash that maps filenames that should be copied from TEMPLATE_PATH
to the value directory | [
"returns",
"a",
"hash",
"that",
"maps",
"filenames",
"that",
"should",
"be",
"copied",
"from",
"TEMPLATE_PATH",
"to",
"the",
"value",
"directory"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/project_initer.rb#L50-L66 |
23,383 | moio/tetra | lib/tetra/project_initer.rb | Tetra.ProjectIniter.commit_source_archive | def commit_source_archive(file, message)
from_directory do
result_dir = File.join(packages_dir, name)
FileUtils.mkdir_p(result_dir)
result_path = File.join(result_dir, File.basename(file))
FileUtils.cp(file, result_path)
@git.commit_file(result_path, "Source archive added")
unarchiver = if file =~ /\.zip$/
Tetra::Unzip.new
else
Tetra::Tar.new
end
Dir.glob(File.join("src", "*")).each { |f| FileUtils.rm_rf(f) }
unarchiver.decompress(file, "src")
commit_sources(message, true)
end
end | ruby | def commit_source_archive(file, message)
from_directory do
result_dir = File.join(packages_dir, name)
FileUtils.mkdir_p(result_dir)
result_path = File.join(result_dir, File.basename(file))
FileUtils.cp(file, result_path)
@git.commit_file(result_path, "Source archive added")
unarchiver = if file =~ /\.zip$/
Tetra::Unzip.new
else
Tetra::Tar.new
end
Dir.glob(File.join("src", "*")).each { |f| FileUtils.rm_rf(f) }
unarchiver.decompress(file, "src")
commit_sources(message, true)
end
end | [
"def",
"commit_source_archive",
"(",
"file",
",",
"message",
")",
"from_directory",
"do",
"result_dir",
"=",
"File",
".",
"join",
"(",
"packages_dir",
",",
"name",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"result_dir",
")",
"result_path",
"=",
"File",
".",
"join",
"(",
"result_dir",
",",
"File",
".",
"basename",
"(",
"file",
")",
")",
"FileUtils",
".",
"cp",
"(",
"file",
",",
"result_path",
")",
"@git",
".",
"commit_file",
"(",
"result_path",
",",
"\"Source archive added\"",
")",
"unarchiver",
"=",
"if",
"file",
"=~",
"/",
"\\.",
"/",
"Tetra",
"::",
"Unzip",
".",
"new",
"else",
"Tetra",
"::",
"Tar",
".",
"new",
"end",
"Dir",
".",
"glob",
"(",
"File",
".",
"join",
"(",
"\"src\"",
",",
"\"*\"",
")",
")",
".",
"each",
"{",
"|",
"f",
"|",
"FileUtils",
".",
"rm_rf",
"(",
"f",
")",
"}",
"unarchiver",
".",
"decompress",
"(",
"file",
",",
"\"src\"",
")",
"commit_sources",
"(",
"message",
",",
"true",
")",
"end",
"end"
] | adds a source archive at the project, both in original and unpacked forms | [
"adds",
"a",
"source",
"archive",
"at",
"the",
"project",
"both",
"in",
"original",
"and",
"unpacked",
"forms"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/project_initer.rb#L69-L88 |
23,384 | jantman/serverspec-extended-types | lib/serverspec_extended_types/http_get.rb | Serverspec.Type.http_get | def http_get(port, host_header, path, timeout_sec=10, protocol='http', bypass_ssl_verify=false)
Http_Get.new(port, host_header, path, timeout_sec, protocol, bypass_ssl_verify)
end | ruby | def http_get(port, host_header, path, timeout_sec=10, protocol='http', bypass_ssl_verify=false)
Http_Get.new(port, host_header, path, timeout_sec, protocol, bypass_ssl_verify)
end | [
"def",
"http_get",
"(",
"port",
",",
"host_header",
",",
"path",
",",
"timeout_sec",
"=",
"10",
",",
"protocol",
"=",
"'http'",
",",
"bypass_ssl_verify",
"=",
"false",
")",
"Http_Get",
".",
"new",
"(",
"port",
",",
"host_header",
",",
"path",
",",
"timeout_sec",
",",
"protocol",
",",
"bypass_ssl_verify",
")",
"end"
] | ServerSpec Type wrapper for http_get
@example
describe http_get(80, 'myhostname', '/') do
# tests here
end
@param port [Int] the port to connect to HTTP over
@param host_header [String] the value to set in the 'Host' HTTP request header
@param path [String] the URI/path to request from the server
@param timeout_sec [Int] how many seconds to allow request to run before timing out and setting @timed_out_status to True
@param protocol [String] the protocol to connect to the server (default 'http', can be 'https')
@param bypass_ssl_verify [Boolean] if true, SSL verification will be bypassed (useful for self-signed certificates)
@api public
@return [Serverspec::Type::Http_Get] | [
"ServerSpec",
"Type",
"wrapper",
"for",
"http_get"
] | 28437dcccc403ab71abe8bf481ec4d22d4eed395 | https://github.com/jantman/serverspec-extended-types/blob/28437dcccc403ab71abe8bf481ec4d22d4eed395/lib/serverspec_extended_types/http_get.rb#L215-L217 |
23,385 | moio/tetra | lib/tetra/generatable.rb | Tetra.Generatable.generate | def generate(template_name, object_binding)
erb = ERB.new(File.read(File.join(template_path, template_name)), nil, "<>")
erb.result(object_binding)
end | ruby | def generate(template_name, object_binding)
erb = ERB.new(File.read(File.join(template_path, template_name)), nil, "<>")
erb.result(object_binding)
end | [
"def",
"generate",
"(",
"template_name",
",",
"object_binding",
")",
"erb",
"=",
"ERB",
".",
"new",
"(",
"File",
".",
"read",
"(",
"File",
".",
"join",
"(",
"template_path",
",",
"template_name",
")",
")",
",",
"nil",
",",
"\"<>\"",
")",
"erb",
".",
"result",
"(",
"object_binding",
")",
"end"
] | generates content from an ERB template and an object binding | [
"generates",
"content",
"from",
"an",
"ERB",
"template",
"and",
"an",
"object",
"binding"
] | de06d766502b885bd62bd7cd9dc8da678abd7cb0 | https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/generatable.rb#L12-L15 |
23,386 | acquia/fluent-plugin-sumologic-cloud-syslog | lib/sumologic_cloud_syslog/logger.rb | SumologicCloudSyslog.Logger.log | def log(severity, message, time: nil)
time ||= Time.now
m = SumologicCloudSyslog::Message.new
# Include authentication header
m.structured_data << @default_structured_data
# Adjust header with current timestamp and severity
m.header = @default_header.dup
m.header.severity = severity
m.header.timestamp = time
yield m.header if block_given?
m.msg = message
transport.write(m.to_s)
end | ruby | def log(severity, message, time: nil)
time ||= Time.now
m = SumologicCloudSyslog::Message.new
# Include authentication header
m.structured_data << @default_structured_data
# Adjust header with current timestamp and severity
m.header = @default_header.dup
m.header.severity = severity
m.header.timestamp = time
yield m.header if block_given?
m.msg = message
transport.write(m.to_s)
end | [
"def",
"log",
"(",
"severity",
",",
"message",
",",
"time",
":",
"nil",
")",
"time",
"||=",
"Time",
".",
"now",
"m",
"=",
"SumologicCloudSyslog",
"::",
"Message",
".",
"new",
"# Include authentication header",
"m",
".",
"structured_data",
"<<",
"@default_structured_data",
"# Adjust header with current timestamp and severity",
"m",
".",
"header",
"=",
"@default_header",
".",
"dup",
"m",
".",
"header",
".",
"severity",
"=",
"severity",
"m",
".",
"header",
".",
"timestamp",
"=",
"time",
"yield",
"m",
".",
"header",
"if",
"block_given?",
"m",
".",
"msg",
"=",
"message",
"transport",
".",
"write",
"(",
"m",
".",
"to_s",
")",
"end"
] | Send log message with severity to Sumologic | [
"Send",
"log",
"message",
"with",
"severity",
"to",
"Sumologic"
] | 9e4e741fe0ad5ed518739acf95bbe5df64d959d9 | https://github.com/acquia/fluent-plugin-sumologic-cloud-syslog/blob/9e4e741fe0ad5ed518739acf95bbe5df64d959d9/lib/sumologic_cloud_syslog/logger.rb#L61-L79 |
23,387 | poise/poise-languages | lib/poise_languages/utils.rb | PoiseLanguages.Utils.shelljoin | def shelljoin(cmd, whitelist: SHELLJOIN_WHITELIST)
cmd.map do |str|
if whitelist.any? {|pat| str =~ pat }
str
else
Shellwords.shellescape(str)
end
end.join(' ')
end | ruby | def shelljoin(cmd, whitelist: SHELLJOIN_WHITELIST)
cmd.map do |str|
if whitelist.any? {|pat| str =~ pat }
str
else
Shellwords.shellescape(str)
end
end.join(' ')
end | [
"def",
"shelljoin",
"(",
"cmd",
",",
"whitelist",
":",
"SHELLJOIN_WHITELIST",
")",
"cmd",
".",
"map",
"do",
"|",
"str",
"|",
"if",
"whitelist",
".",
"any?",
"{",
"|",
"pat",
"|",
"str",
"=~",
"pat",
"}",
"str",
"else",
"Shellwords",
".",
"shellescape",
"(",
"str",
")",
"end",
"end",
".",
"join",
"(",
"' '",
")",
"end"
] | An improved version of Shellwords.shelljoin that doesn't escape a few
things.
@param cmd [Array<String>] Command array to join.
@param whitelist [Array<Regexp>] Array of patterns to whitelist.
@return [String] | [
"An",
"improved",
"version",
"of",
"Shellwords",
".",
"shelljoin",
"that",
"doesn",
"t",
"escape",
"a",
"few",
"things",
"."
] | cdce222faaf6263b13f4b026992600b6ee3d1ff4 | https://github.com/poise/poise-languages/blob/cdce222faaf6263b13f4b026992600b6ee3d1ff4/lib/poise_languages/utils.rb#L36-L44 |
23,388 | poise/poise-languages | lib/poise_languages/utils.rb | PoiseLanguages.Utils.absolute_command | def absolute_command(cmd, path: nil)
was_array = cmd.is_a?(Array)
cmd = if was_array
cmd.dup
else
Shellwords.split(cmd)
end
# Don't try to touch anything if the first value looks like a flag or a path.
if cmd.first && !cmd.first.start_with?('-') && !cmd.first.include?(::File::SEPARATOR)
# If which returns false, just leave it I guess.
cmd[0] = which(cmd.first, path: path) || cmd.first
end
cmd = shelljoin(cmd) unless was_array
cmd
end | ruby | def absolute_command(cmd, path: nil)
was_array = cmd.is_a?(Array)
cmd = if was_array
cmd.dup
else
Shellwords.split(cmd)
end
# Don't try to touch anything if the first value looks like a flag or a path.
if cmd.first && !cmd.first.start_with?('-') && !cmd.first.include?(::File::SEPARATOR)
# If which returns false, just leave it I guess.
cmd[0] = which(cmd.first, path: path) || cmd.first
end
cmd = shelljoin(cmd) unless was_array
cmd
end | [
"def",
"absolute_command",
"(",
"cmd",
",",
"path",
":",
"nil",
")",
"was_array",
"=",
"cmd",
".",
"is_a?",
"(",
"Array",
")",
"cmd",
"=",
"if",
"was_array",
"cmd",
".",
"dup",
"else",
"Shellwords",
".",
"split",
"(",
"cmd",
")",
"end",
"# Don't try to touch anything if the first value looks like a flag or a path.",
"if",
"cmd",
".",
"first",
"&&",
"!",
"cmd",
".",
"first",
".",
"start_with?",
"(",
"'-'",
")",
"&&",
"!",
"cmd",
".",
"first",
".",
"include?",
"(",
"::",
"File",
"::",
"SEPARATOR",
")",
"# If which returns false, just leave it I guess.",
"cmd",
"[",
"0",
"]",
"=",
"which",
"(",
"cmd",
".",
"first",
",",
"path",
":",
"path",
")",
"||",
"cmd",
".",
"first",
"end",
"cmd",
"=",
"shelljoin",
"(",
"cmd",
")",
"unless",
"was_array",
"cmd",
"end"
] | Convert the executable in a string or array command to an absolute path.
@param cmd [String, Array<String>] Command to fix up.
@param path [String, nil] Replacement $PATH for executable lookup.
@return [String, Array<String>] | [
"Convert",
"the",
"executable",
"in",
"a",
"string",
"or",
"array",
"command",
"to",
"an",
"absolute",
"path",
"."
] | cdce222faaf6263b13f4b026992600b6ee3d1ff4 | https://github.com/poise/poise-languages/blob/cdce222faaf6263b13f4b026992600b6ee3d1ff4/lib/poise_languages/utils.rb#L51-L65 |
23,389 | danielgerlag/workflow_rb | workflow_rb/lib/workflow_rb/services/workflow_builder.rb | WorkflowRb.StepBuilder.then | def then(body, &setup)
new_step = WorkflowStep.new
new_step.body = body
@workflow_builder.add_step(new_step)
new_builder = StepBuilder.new(@workflow_builder, new_step)
if body.kind_of?(Class)
new_step.name = body.name
end
if setup
setup.call(new_builder)
end
new_outcome = StepOutcome.new
new_outcome.next_step = new_step.id
new_outcome.value = nil
@step.outcomes << new_outcome
new_builder
end | ruby | def then(body, &setup)
new_step = WorkflowStep.new
new_step.body = body
@workflow_builder.add_step(new_step)
new_builder = StepBuilder.new(@workflow_builder, new_step)
if body.kind_of?(Class)
new_step.name = body.name
end
if setup
setup.call(new_builder)
end
new_outcome = StepOutcome.new
new_outcome.next_step = new_step.id
new_outcome.value = nil
@step.outcomes << new_outcome
new_builder
end | [
"def",
"then",
"(",
"body",
",",
"&",
"setup",
")",
"new_step",
"=",
"WorkflowStep",
".",
"new",
"new_step",
".",
"body",
"=",
"body",
"@workflow_builder",
".",
"add_step",
"(",
"new_step",
")",
"new_builder",
"=",
"StepBuilder",
".",
"new",
"(",
"@workflow_builder",
",",
"new_step",
")",
"if",
"body",
".",
"kind_of?",
"(",
"Class",
")",
"new_step",
".",
"name",
"=",
"body",
".",
"name",
"end",
"if",
"setup",
"setup",
".",
"call",
"(",
"new_builder",
")",
"end",
"new_outcome",
"=",
"StepOutcome",
".",
"new",
"new_outcome",
".",
"next_step",
"=",
"new_step",
".",
"id",
"new_outcome",
".",
"value",
"=",
"nil",
"@step",
".",
"outcomes",
"<<",
"new_outcome",
"new_builder",
"end"
] | Adds a new step to the workflow
@param body [Class] the step body implementation class | [
"Adds",
"a",
"new",
"step",
"to",
"the",
"workflow"
] | 5a4d8326a2f797ac0fc4802f358831d72bcc4f0f | https://github.com/danielgerlag/workflow_rb/blob/5a4d8326a2f797ac0fc4802f358831d72bcc4f0f/workflow_rb/lib/workflow_rb/services/workflow_builder.rb#L67-L88 |
23,390 | danielgerlag/workflow_rb | workflow_rb/lib/workflow_rb/services/workflow_builder.rb | WorkflowRb.StepBuilder.input | def input(step_property, &value)
mapping = IOMapping.new
mapping.property = step_property
mapping.value = value
@step.inputs << mapping
self
end | ruby | def input(step_property, &value)
mapping = IOMapping.new
mapping.property = step_property
mapping.value = value
@step.inputs << mapping
self
end | [
"def",
"input",
"(",
"step_property",
",",
"&",
"value",
")",
"mapping",
"=",
"IOMapping",
".",
"new",
"mapping",
".",
"property",
"=",
"step_property",
"mapping",
".",
"value",
"=",
"value",
"@step",
".",
"inputs",
"<<",
"mapping",
"self",
"end"
] | Map workflow instance data to a property on the step
@param step_property [Symbol] the attribute on the step body class | [
"Map",
"workflow",
"instance",
"data",
"to",
"a",
"property",
"on",
"the",
"step"
] | 5a4d8326a2f797ac0fc4802f358831d72bcc4f0f | https://github.com/danielgerlag/workflow_rb/blob/5a4d8326a2f797ac0fc4802f358831d72bcc4f0f/workflow_rb/lib/workflow_rb/services/workflow_builder.rb#L105-L111 |
23,391 | 1and1/rijndael | lib/rijndael/base.rb | Rijndael.Base.decrypt | def decrypt(encrypted)
fail ArgumentError, 'No cipher text supplied.' if encrypted.nil? || encrypted.empty?
matches = CIPHER_PATTERN.match(encrypted)
fail ArgumentError, 'Cipher text has an unsupported format.' if matches.nil?
cipher = self.class.cipher
cipher.decrypt
cipher.key = Base64.decode64(@key)
cipher.iv = Base64.decode64(matches[1])
decrypted = cipher.update(Base64.decode64(matches[2]))
decrypted << cipher.final
end | ruby | def decrypt(encrypted)
fail ArgumentError, 'No cipher text supplied.' if encrypted.nil? || encrypted.empty?
matches = CIPHER_PATTERN.match(encrypted)
fail ArgumentError, 'Cipher text has an unsupported format.' if matches.nil?
cipher = self.class.cipher
cipher.decrypt
cipher.key = Base64.decode64(@key)
cipher.iv = Base64.decode64(matches[1])
decrypted = cipher.update(Base64.decode64(matches[2]))
decrypted << cipher.final
end | [
"def",
"decrypt",
"(",
"encrypted",
")",
"fail",
"ArgumentError",
",",
"'No cipher text supplied.'",
"if",
"encrypted",
".",
"nil?",
"||",
"encrypted",
".",
"empty?",
"matches",
"=",
"CIPHER_PATTERN",
".",
"match",
"(",
"encrypted",
")",
"fail",
"ArgumentError",
",",
"'Cipher text has an unsupported format.'",
"if",
"matches",
".",
"nil?",
"cipher",
"=",
"self",
".",
"class",
".",
"cipher",
"cipher",
".",
"decrypt",
"cipher",
".",
"key",
"=",
"Base64",
".",
"decode64",
"(",
"@key",
")",
"cipher",
".",
"iv",
"=",
"Base64",
".",
"decode64",
"(",
"matches",
"[",
"1",
"]",
")",
"decrypted",
"=",
"cipher",
".",
"update",
"(",
"Base64",
".",
"decode64",
"(",
"matches",
"[",
"2",
"]",
")",
")",
"decrypted",
"<<",
"cipher",
".",
"final",
"end"
] | This method expects a base64 encoded cipher text and decrypts it.
@param encrypted [String] Cipher text.
@return [String] Plain text. | [
"This",
"method",
"expects",
"a",
"base64",
"encoded",
"cipher",
"text",
"and",
"decrypts",
"it",
"."
] | 8eee6e72381dc7e84cd2bd19ca96c2d0202d8034 | https://github.com/1and1/rijndael/blob/8eee6e72381dc7e84cd2bd19ca96c2d0202d8034/lib/rijndael/base.rb#L56-L70 |
23,392 | acquia/fluent-plugin-sumologic-cloud-syslog | lib/fluent/plugin/out_sumologic_cloud_syslog.rb | Fluent.SumologicCloudSyslogOutput.logger | def logger(tag)
# Try to reuse existing logger
@loggers[tag] ||= new_logger(tag)
# Create new logger if old one is closed
if @loggers[tag].closed?
@loggers[tag] = new_logger(tag)
end
@loggers[tag]
end | ruby | def logger(tag)
# Try to reuse existing logger
@loggers[tag] ||= new_logger(tag)
# Create new logger if old one is closed
if @loggers[tag].closed?
@loggers[tag] = new_logger(tag)
end
@loggers[tag]
end | [
"def",
"logger",
"(",
"tag",
")",
"# Try to reuse existing logger",
"@loggers",
"[",
"tag",
"]",
"||=",
"new_logger",
"(",
"tag",
")",
"# Create new logger if old one is closed",
"if",
"@loggers",
"[",
"tag",
"]",
".",
"closed?",
"@loggers",
"[",
"tag",
"]",
"=",
"new_logger",
"(",
"tag",
")",
"end",
"@loggers",
"[",
"tag",
"]",
"end"
] | Get logger for given tag | [
"Get",
"logger",
"for",
"given",
"tag"
] | 9e4e741fe0ad5ed518739acf95bbe5df64d959d9 | https://github.com/acquia/fluent-plugin-sumologic-cloud-syslog/blob/9e4e741fe0ad5ed518739acf95bbe5df64d959d9/lib/fluent/plugin/out_sumologic_cloud_syslog.rb#L72-L82 |
23,393 | MartinJNash/Royce | lib/royce/methods.rb | Royce.Methods.add_role | def add_role name
if allowed_role? name
return if has_role? name
role = Role.find_by(name: name.to_s)
roles << role
end
end | ruby | def add_role name
if allowed_role? name
return if has_role? name
role = Role.find_by(name: name.to_s)
roles << role
end
end | [
"def",
"add_role",
"name",
"if",
"allowed_role?",
"name",
"return",
"if",
"has_role?",
"name",
"role",
"=",
"Role",
".",
"find_by",
"(",
"name",
":",
"name",
".",
"to_s",
")",
"roles",
"<<",
"role",
"end",
"end"
] | These methods are included in all User instances | [
"These",
"methods",
"are",
"included",
"in",
"all",
"User",
"instances"
] | aa8e5bc2573ff3166a2002f42e3b181b23b530fc | https://github.com/MartinJNash/Royce/blob/aa8e5bc2573ff3166a2002f42e3b181b23b530fc/lib/royce/methods.rb#L30-L36 |
23,394 | norman/utf8_utils | lib/utf8_utils.rb | UTF8Utils.StringExt.tidy_bytes | def tidy_bytes(force = false)
if force
return unpack("C*").map do |b|
tidy_byte(b)
end.flatten.compact.pack("C*").unpack("U*").pack("U*")
end
bytes = unpack("C*")
conts_expected = 0
last_lead = 0
bytes.each_index do |i|
byte = bytes[i]
is_ascii = byte < 128
is_cont = byte > 127 && byte < 192
is_lead = byte > 191 && byte < 245
is_unused = byte > 240
is_restricted = byte > 244
# Impossible or highly unlikely byte? Clean it.
if is_unused || is_restricted
bytes[i] = tidy_byte(byte)
elsif is_cont
# Not expecting contination byte? Clean up. Otherwise, now expect one less.
conts_expected == 0 ? bytes[i] = tidy_byte(byte) : conts_expected -= 1
else
if conts_expected > 0
# Expected continuation, but got ASCII or leading? Clean backwards up to
# the leading byte.
(1..(i - last_lead)).each {|j| bytes[i - j] = tidy_byte(bytes[i - j])}
conts_expected = 0
end
if is_lead
# Final byte is leading? Clean it.
if i == bytes.length - 1
bytes[i] = tidy_byte(bytes.last)
else
# Valid leading byte? Expect continuations determined by position of
# first zero bit, with max of 3.
conts_expected = byte < 224 ? 1 : byte < 240 ? 2 : 3
last_lead = i
end
end
end
end
bytes.empty? ? "" : bytes.flatten.compact.pack("C*").unpack("U*").pack("U*")
end | ruby | def tidy_bytes(force = false)
if force
return unpack("C*").map do |b|
tidy_byte(b)
end.flatten.compact.pack("C*").unpack("U*").pack("U*")
end
bytes = unpack("C*")
conts_expected = 0
last_lead = 0
bytes.each_index do |i|
byte = bytes[i]
is_ascii = byte < 128
is_cont = byte > 127 && byte < 192
is_lead = byte > 191 && byte < 245
is_unused = byte > 240
is_restricted = byte > 244
# Impossible or highly unlikely byte? Clean it.
if is_unused || is_restricted
bytes[i] = tidy_byte(byte)
elsif is_cont
# Not expecting contination byte? Clean up. Otherwise, now expect one less.
conts_expected == 0 ? bytes[i] = tidy_byte(byte) : conts_expected -= 1
else
if conts_expected > 0
# Expected continuation, but got ASCII or leading? Clean backwards up to
# the leading byte.
(1..(i - last_lead)).each {|j| bytes[i - j] = tidy_byte(bytes[i - j])}
conts_expected = 0
end
if is_lead
# Final byte is leading? Clean it.
if i == bytes.length - 1
bytes[i] = tidy_byte(bytes.last)
else
# Valid leading byte? Expect continuations determined by position of
# first zero bit, with max of 3.
conts_expected = byte < 224 ? 1 : byte < 240 ? 2 : 3
last_lead = i
end
end
end
end
bytes.empty? ? "" : bytes.flatten.compact.pack("C*").unpack("U*").pack("U*")
end | [
"def",
"tidy_bytes",
"(",
"force",
"=",
"false",
")",
"if",
"force",
"return",
"unpack",
"(",
"\"C*\"",
")",
".",
"map",
"do",
"|",
"b",
"|",
"tidy_byte",
"(",
"b",
")",
"end",
".",
"flatten",
".",
"compact",
".",
"pack",
"(",
"\"C*\"",
")",
".",
"unpack",
"(",
"\"U*\"",
")",
".",
"pack",
"(",
"\"U*\"",
")",
"end",
"bytes",
"=",
"unpack",
"(",
"\"C*\"",
")",
"conts_expected",
"=",
"0",
"last_lead",
"=",
"0",
"bytes",
".",
"each_index",
"do",
"|",
"i",
"|",
"byte",
"=",
"bytes",
"[",
"i",
"]",
"is_ascii",
"=",
"byte",
"<",
"128",
"is_cont",
"=",
"byte",
">",
"127",
"&&",
"byte",
"<",
"192",
"is_lead",
"=",
"byte",
">",
"191",
"&&",
"byte",
"<",
"245",
"is_unused",
"=",
"byte",
">",
"240",
"is_restricted",
"=",
"byte",
">",
"244",
"# Impossible or highly unlikely byte? Clean it.",
"if",
"is_unused",
"||",
"is_restricted",
"bytes",
"[",
"i",
"]",
"=",
"tidy_byte",
"(",
"byte",
")",
"elsif",
"is_cont",
"# Not expecting contination byte? Clean up. Otherwise, now expect one less.",
"conts_expected",
"==",
"0",
"?",
"bytes",
"[",
"i",
"]",
"=",
"tidy_byte",
"(",
"byte",
")",
":",
"conts_expected",
"-=",
"1",
"else",
"if",
"conts_expected",
">",
"0",
"# Expected continuation, but got ASCII or leading? Clean backwards up to",
"# the leading byte.",
"(",
"1",
"..",
"(",
"i",
"-",
"last_lead",
")",
")",
".",
"each",
"{",
"|",
"j",
"|",
"bytes",
"[",
"i",
"-",
"j",
"]",
"=",
"tidy_byte",
"(",
"bytes",
"[",
"i",
"-",
"j",
"]",
")",
"}",
"conts_expected",
"=",
"0",
"end",
"if",
"is_lead",
"# Final byte is leading? Clean it.",
"if",
"i",
"==",
"bytes",
".",
"length",
"-",
"1",
"bytes",
"[",
"i",
"]",
"=",
"tidy_byte",
"(",
"bytes",
".",
"last",
")",
"else",
"# Valid leading byte? Expect continuations determined by position of",
"# first zero bit, with max of 3.",
"conts_expected",
"=",
"byte",
"<",
"224",
"?",
"1",
":",
"byte",
"<",
"240",
"?",
"2",
":",
"3",
"last_lead",
"=",
"i",
"end",
"end",
"end",
"end",
"bytes",
".",
"empty?",
"?",
"\"\"",
":",
"bytes",
".",
"flatten",
".",
"compact",
".",
"pack",
"(",
"\"C*\"",
")",
".",
"unpack",
"(",
"\"U*\"",
")",
".",
"pack",
"(",
"\"U*\"",
")",
"end"
] | Attempt to replace invalid UTF-8 bytes with valid ones. This method
naively assumes if you have invalid UTF8 bytes, they are either Windows
CP-1252 or ISO8859-1. In practice this isn't a bad assumption, but may not
always work.
Passing +true+ will forcibly tidy all bytes, assuming that the string's
encoding is CP-1252 or ISO-8859-1. | [
"Attempt",
"to",
"replace",
"invalid",
"UTF",
"-",
"8",
"bytes",
"with",
"valid",
"ones",
".",
"This",
"method",
"naively",
"assumes",
"if",
"you",
"have",
"invalid",
"UTF8",
"bytes",
"they",
"are",
"either",
"Windows",
"CP",
"-",
"1252",
"or",
"ISO8859",
"-",
"1",
".",
"In",
"practice",
"this",
"isn",
"t",
"a",
"bad",
"assumption",
"but",
"may",
"not",
"always",
"work",
"."
] | 878add7657dfe4cd6a24fb0de2690883fe289c6c | https://github.com/norman/utf8_utils/blob/878add7657dfe4cd6a24fb0de2690883fe289c6c/lib/utf8_utils.rb#L51-L99 |
23,395 | jgraichen/paginate-responder | spec/support/05-setup-and-teardown-adapter.rb | SetupAndTeardownAdapter.ClassMethods.setup | def setup(*methods, &block)
methods.each do |method|
if method.to_s =~ /^setup_(with_controller|fixtures|controller_request_and_response)$/
prepend_before { __send__ method }
else
before { __send__ method }
end
end
before(&block) if block
end | ruby | def setup(*methods, &block)
methods.each do |method|
if method.to_s =~ /^setup_(with_controller|fixtures|controller_request_and_response)$/
prepend_before { __send__ method }
else
before { __send__ method }
end
end
before(&block) if block
end | [
"def",
"setup",
"(",
"*",
"methods",
",",
"&",
"block",
")",
"methods",
".",
"each",
"do",
"|",
"method",
"|",
"if",
"method",
".",
"to_s",
"=~",
"/",
"/",
"prepend_before",
"{",
"__send__",
"method",
"}",
"else",
"before",
"{",
"__send__",
"method",
"}",
"end",
"end",
"before",
"(",
"block",
")",
"if",
"block",
"end"
] | Wraps `setup` calls from within Rails' testing framework in `before`
hooks. | [
"Wraps",
"setup",
"calls",
"from",
"within",
"Rails",
"testing",
"framework",
"in",
"before",
"hooks",
"."
] | 15fd3ec0a5f9f39812a0e91eeacab6be87791b00 | https://github.com/jgraichen/paginate-responder/blob/15fd3ec0a5f9f39812a0e91eeacab6be87791b00/spec/support/05-setup-and-teardown-adapter.rb#L7-L16 |
23,396 | jiananlu/faked_csv | lib/faked_csv/config.rb | FakedCSV.Config.parse | def parse
if @config["rows"].nil? || @config["rows"].to_i < 0
@row_count = 100 # default value
else
@row_count = @config["rows"].to_i
end
@fields = []
if @config["fields"].nil? || @config["fields"].empty?
raise "need 'fields' in the config file and at least 1 field in it"
end
@config["fields"].each do |cfg|
field = {}
if cfg["name"].nil?
raise "field needs a name"
end
field[:name] = cfg["name"].to_s
if cfg["type"].nil? || cfg["type"].empty?
raise "field needs a type"
end
field[:type] = cfg["type"].to_s
unless cfg["inject"].nil? || cfg["inject"].empty? || !cfg["inject"].kind_of?(Array)
field[:inject] = cfg["inject"].uniq # get rid of duplicates
end
unless cfg["rotate"].nil?
field[:rotate] = _validate_rotate cfg["rotate"]
end
case field[:type]
when /inc:int/i
field[:type] = :inc_int
field[:start] = cfg["start"].nil? ? 1 : cfg["start"].to_i
field[:step] = cfg["step"].nil? ? 1 : cfg["step"].to_i
when /rand:int/i
field[:type] = :rand_int
if cfg["range"].nil?
# no range specified? use the default range: [0, 100]
field[:min], field[:max] = 0, 100
else
field[:min], field[:max] = _min_max cfg["range"]
end
when /rand:float/i
field[:type] = :rand_float
if cfg["range"].nil?
# no range specified? use the default range: [0, 1]
field[:min], field[:max] = 0, 1
else
field[:min], field[:max] = _min_max cfg["range"]
end
field[:precision] = cfg["precision"].nil? ? 1 : cfg["precision"].to_i
when /rand:char/i
field[:type] = :rand_char
field[:length] = cfg["length"].nil? ? 10 : cfg["length"]
field[:format] = cfg["format"]
when /fixed/i
field[:type] = :fixed
raise "need values for fixed type" if cfg["values"].nil?
field[:values] = cfg["values"]
when /faker:\S+/i
field[:type] = cfg["type"]
else
raise "unsupported type: #{field[:type]}. supported types: #{_supported_types}"
end
fields << field
end
end | ruby | def parse
if @config["rows"].nil? || @config["rows"].to_i < 0
@row_count = 100 # default value
else
@row_count = @config["rows"].to_i
end
@fields = []
if @config["fields"].nil? || @config["fields"].empty?
raise "need 'fields' in the config file and at least 1 field in it"
end
@config["fields"].each do |cfg|
field = {}
if cfg["name"].nil?
raise "field needs a name"
end
field[:name] = cfg["name"].to_s
if cfg["type"].nil? || cfg["type"].empty?
raise "field needs a type"
end
field[:type] = cfg["type"].to_s
unless cfg["inject"].nil? || cfg["inject"].empty? || !cfg["inject"].kind_of?(Array)
field[:inject] = cfg["inject"].uniq # get rid of duplicates
end
unless cfg["rotate"].nil?
field[:rotate] = _validate_rotate cfg["rotate"]
end
case field[:type]
when /inc:int/i
field[:type] = :inc_int
field[:start] = cfg["start"].nil? ? 1 : cfg["start"].to_i
field[:step] = cfg["step"].nil? ? 1 : cfg["step"].to_i
when /rand:int/i
field[:type] = :rand_int
if cfg["range"].nil?
# no range specified? use the default range: [0, 100]
field[:min], field[:max] = 0, 100
else
field[:min], field[:max] = _min_max cfg["range"]
end
when /rand:float/i
field[:type] = :rand_float
if cfg["range"].nil?
# no range specified? use the default range: [0, 1]
field[:min], field[:max] = 0, 1
else
field[:min], field[:max] = _min_max cfg["range"]
end
field[:precision] = cfg["precision"].nil? ? 1 : cfg["precision"].to_i
when /rand:char/i
field[:type] = :rand_char
field[:length] = cfg["length"].nil? ? 10 : cfg["length"]
field[:format] = cfg["format"]
when /fixed/i
field[:type] = :fixed
raise "need values for fixed type" if cfg["values"].nil?
field[:values] = cfg["values"]
when /faker:\S+/i
field[:type] = cfg["type"]
else
raise "unsupported type: #{field[:type]}. supported types: #{_supported_types}"
end
fields << field
end
end | [
"def",
"parse",
"if",
"@config",
"[",
"\"rows\"",
"]",
".",
"nil?",
"||",
"@config",
"[",
"\"rows\"",
"]",
".",
"to_i",
"<",
"0",
"@row_count",
"=",
"100",
"# default value",
"else",
"@row_count",
"=",
"@config",
"[",
"\"rows\"",
"]",
".",
"to_i",
"end",
"@fields",
"=",
"[",
"]",
"if",
"@config",
"[",
"\"fields\"",
"]",
".",
"nil?",
"||",
"@config",
"[",
"\"fields\"",
"]",
".",
"empty?",
"raise",
"\"need 'fields' in the config file and at least 1 field in it\"",
"end",
"@config",
"[",
"\"fields\"",
"]",
".",
"each",
"do",
"|",
"cfg",
"|",
"field",
"=",
"{",
"}",
"if",
"cfg",
"[",
"\"name\"",
"]",
".",
"nil?",
"raise",
"\"field needs a name\"",
"end",
"field",
"[",
":name",
"]",
"=",
"cfg",
"[",
"\"name\"",
"]",
".",
"to_s",
"if",
"cfg",
"[",
"\"type\"",
"]",
".",
"nil?",
"||",
"cfg",
"[",
"\"type\"",
"]",
".",
"empty?",
"raise",
"\"field needs a type\"",
"end",
"field",
"[",
":type",
"]",
"=",
"cfg",
"[",
"\"type\"",
"]",
".",
"to_s",
"unless",
"cfg",
"[",
"\"inject\"",
"]",
".",
"nil?",
"||",
"cfg",
"[",
"\"inject\"",
"]",
".",
"empty?",
"||",
"!",
"cfg",
"[",
"\"inject\"",
"]",
".",
"kind_of?",
"(",
"Array",
")",
"field",
"[",
":inject",
"]",
"=",
"cfg",
"[",
"\"inject\"",
"]",
".",
"uniq",
"# get rid of duplicates",
"end",
"unless",
"cfg",
"[",
"\"rotate\"",
"]",
".",
"nil?",
"field",
"[",
":rotate",
"]",
"=",
"_validate_rotate",
"cfg",
"[",
"\"rotate\"",
"]",
"end",
"case",
"field",
"[",
":type",
"]",
"when",
"/",
"/i",
"field",
"[",
":type",
"]",
"=",
":inc_int",
"field",
"[",
":start",
"]",
"=",
"cfg",
"[",
"\"start\"",
"]",
".",
"nil?",
"?",
"1",
":",
"cfg",
"[",
"\"start\"",
"]",
".",
"to_i",
"field",
"[",
":step",
"]",
"=",
"cfg",
"[",
"\"step\"",
"]",
".",
"nil?",
"?",
"1",
":",
"cfg",
"[",
"\"step\"",
"]",
".",
"to_i",
"when",
"/",
"/i",
"field",
"[",
":type",
"]",
"=",
":rand_int",
"if",
"cfg",
"[",
"\"range\"",
"]",
".",
"nil?",
"# no range specified? use the default range: [0, 100]",
"field",
"[",
":min",
"]",
",",
"field",
"[",
":max",
"]",
"=",
"0",
",",
"100",
"else",
"field",
"[",
":min",
"]",
",",
"field",
"[",
":max",
"]",
"=",
"_min_max",
"cfg",
"[",
"\"range\"",
"]",
"end",
"when",
"/",
"/i",
"field",
"[",
":type",
"]",
"=",
":rand_float",
"if",
"cfg",
"[",
"\"range\"",
"]",
".",
"nil?",
"# no range specified? use the default range: [0, 1]",
"field",
"[",
":min",
"]",
",",
"field",
"[",
":max",
"]",
"=",
"0",
",",
"1",
"else",
"field",
"[",
":min",
"]",
",",
"field",
"[",
":max",
"]",
"=",
"_min_max",
"cfg",
"[",
"\"range\"",
"]",
"end",
"field",
"[",
":precision",
"]",
"=",
"cfg",
"[",
"\"precision\"",
"]",
".",
"nil?",
"?",
"1",
":",
"cfg",
"[",
"\"precision\"",
"]",
".",
"to_i",
"when",
"/",
"/i",
"field",
"[",
":type",
"]",
"=",
":rand_char",
"field",
"[",
":length",
"]",
"=",
"cfg",
"[",
"\"length\"",
"]",
".",
"nil?",
"?",
"10",
":",
"cfg",
"[",
"\"length\"",
"]",
"field",
"[",
":format",
"]",
"=",
"cfg",
"[",
"\"format\"",
"]",
"when",
"/",
"/i",
"field",
"[",
":type",
"]",
"=",
":fixed",
"raise",
"\"need values for fixed type\"",
"if",
"cfg",
"[",
"\"values\"",
"]",
".",
"nil?",
"field",
"[",
":values",
"]",
"=",
"cfg",
"[",
"\"values\"",
"]",
"when",
"/",
"\\S",
"/i",
"field",
"[",
":type",
"]",
"=",
"cfg",
"[",
"\"type\"",
"]",
"else",
"raise",
"\"unsupported type: #{field[:type]}. supported types: #{_supported_types}\"",
"end",
"fields",
"<<",
"field",
"end",
"end"
] | prepare the json config and generate the fields | [
"prepare",
"the",
"json",
"config",
"and",
"generate",
"the",
"fields"
] | d30520dc71efb6171908bddbdf28b4fb61203ca0 | https://github.com/jiananlu/faked_csv/blob/d30520dc71efb6171908bddbdf28b4fb61203ca0/lib/faked_csv/config.rb#L19-L90 |
23,397 | subakva/haproxy-tools | lib/haproxy/parser.rb | HAProxy.Parser.parse_server_attributes | def parse_server_attributes(value)
parts = value.to_s.split(/\s/)
current_name = nil
pairs = parts.each_with_object({}) { |part, attrs|
if SERVER_ATTRIBUTE_NAMES.include?(part)
current_name = part
attrs[current_name] = []
elsif current_name.nil?
raise "Invalid server attribute: #{part}"
else
attrs[current_name] << part
end
}
clean_parsed_server_attributes(pairs)
end | ruby | def parse_server_attributes(value)
parts = value.to_s.split(/\s/)
current_name = nil
pairs = parts.each_with_object({}) { |part, attrs|
if SERVER_ATTRIBUTE_NAMES.include?(part)
current_name = part
attrs[current_name] = []
elsif current_name.nil?
raise "Invalid server attribute: #{part}"
else
attrs[current_name] << part
end
}
clean_parsed_server_attributes(pairs)
end | [
"def",
"parse_server_attributes",
"(",
"value",
")",
"parts",
"=",
"value",
".",
"to_s",
".",
"split",
"(",
"/",
"\\s",
"/",
")",
"current_name",
"=",
"nil",
"pairs",
"=",
"parts",
".",
"each_with_object",
"(",
"{",
"}",
")",
"{",
"|",
"part",
",",
"attrs",
"|",
"if",
"SERVER_ATTRIBUTE_NAMES",
".",
"include?",
"(",
"part",
")",
"current_name",
"=",
"part",
"attrs",
"[",
"current_name",
"]",
"=",
"[",
"]",
"elsif",
"current_name",
".",
"nil?",
"raise",
"\"Invalid server attribute: #{part}\"",
"else",
"attrs",
"[",
"current_name",
"]",
"<<",
"part",
"end",
"}",
"clean_parsed_server_attributes",
"(",
"pairs",
")",
"end"
] | Parses server attributes from the server value. I couldn't manage to get treetop to do
this.
Types of server attributes to support:
ipv4, boolean, string, integer, time (us, ms, s, m, h, d), url, source attributes
BUG: If an attribute value matches an attribute name, the parser will assume that a new
attribute value has started. I don't know how haproxy itself handles that situation. | [
"Parses",
"server",
"attributes",
"from",
"the",
"server",
"value",
".",
"I",
"couldn",
"t",
"manage",
"to",
"get",
"treetop",
"to",
"do",
"this",
"."
] | 1edf787aca21513312581cefb7f349d41ad859e4 | https://github.com/subakva/haproxy-tools/blob/1edf787aca21513312581cefb7f349d41ad859e4/lib/haproxy/parser.rb#L199-L214 |
23,398 | subakva/haproxy-tools | lib/haproxy/parser.rb | HAProxy.Parser.clean_parsed_server_attributes | def clean_parsed_server_attributes(pairs)
pairs.each do |k, v|
pairs[k] = if v.empty?
true
else
v.join(" ")
end
end
end | ruby | def clean_parsed_server_attributes(pairs)
pairs.each do |k, v|
pairs[k] = if v.empty?
true
else
v.join(" ")
end
end
end | [
"def",
"clean_parsed_server_attributes",
"(",
"pairs",
")",
"pairs",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"pairs",
"[",
"k",
"]",
"=",
"if",
"v",
".",
"empty?",
"true",
"else",
"v",
".",
"join",
"(",
"\" \"",
")",
"end",
"end",
"end"
] | Converts attributes with no values to true, and combines everything else into space-
separated strings. | [
"Converts",
"attributes",
"with",
"no",
"values",
"to",
"true",
"and",
"combines",
"everything",
"else",
"into",
"space",
"-",
"separated",
"strings",
"."
] | 1edf787aca21513312581cefb7f349d41ad859e4 | https://github.com/subakva/haproxy-tools/blob/1edf787aca21513312581cefb7f349d41ad859e4/lib/haproxy/parser.rb#L218-L226 |
23,399 | ploubser/JSON-Grep | lib/parser/parser.rb | JGrep.Parser.parse | def parse(substatement = nil, token_index = 0)
p_token = nil
if substatement
c_token, c_token_value = substatement[token_index]
else
c_token, c_token_value = @scanner.get_token
end
parenth = 0
until c_token.nil?
if substatement
token_index += 1
n_token, n_token_value = substatement[token_index]
else
@scanner.token_index += 1
n_token, n_token_value = @scanner.get_token
end
next if n_token == " "
case c_token
when "and"
unless (n_token =~ /not|statement|\(|\+|-/) || (scanner.token_index == scanner.arguments.size)
raise "Error at column #{scanner.token_index}. \nExpected 'not', 'statement' or '('. Found '#{n_token_value}'"
end
raise "Error at column #{scanner.token_index}. \n Expression cannot start with 'and'" if p_token.nil?
raise "Error at column #{scanner.token_index}. \n #{p_token} cannot be followed by 'and'" if %w[and or].include?(p_token)
when "or"
unless (n_token =~ /not|statement|\(|\+|-/) || (scanner.token_index == scanner.arguments.size)
raise "Error at column #{scanner.token_index}. \nExpected 'not', 'statement', '('. Found '#{n_token_value}'"
end
raise "Error at column #{scanner.token_index}. \n Expression cannot start with 'or'" if p_token.nil?
raise "Error at column #{scanner.token_index}. \n #{p_token} cannot be followed by 'or'" if %w[and or].include?(p_token)
when "not"
unless n_token =~ /statement|\(|not|\+|-/
raise "Error at column #{scanner.token_index}. \nExpected 'statement' or '('. Found '#{n_token_value}'"
end
when "statement"
if c_token_value.is_a? Array
raise "Error at column #{scanner.token_index}\nError, cannot define '[' in a '[...]' block." if substatement
parse(c_token_value, 0)
end
if c_token_value =~ /!=/
c_token_value = c_token_value.gsub("!=", "=")
@execution_stack << {"not" => "not"}
end
if !n_token.nil? && !n_token.match(/and|or|\)/)
raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', ')'. Found '#{n_token_value}'"
end
when "+"
if !n_token.nil? && !n_token.match(/and|or|\)/)
raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', ')'. Found '#{n_token_value}'"
end
when "-"
if !n_token.nil? && !n_token.match(/and|or|\)/)
raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', ')'. Found '#{n_token_value}'"
end
when ")"
if !n_token.nil? && !n_token =~ /|and|or|not|\(/
raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', 'not' or '('. Found '#{n_token_value}'"
end
parenth += 1
when "("
unless n_token =~ /statement|not|\(|\+|-/
raise "Error at column #{scanner.token_index}. \nExpected 'statement', '(', not. Found '#{n_token_value}'"
end
parenth -= 1
else
raise "Unexpected token found at column #{scanner.token_index}. '#{c_token_value}'"
end
unless n_token == " " || substatement
@execution_stack << {c_token => c_token_value}
end
p_token = c_token
c_token = n_token
c_token_value = n_token_value
end
return if substatement
raise "Error. Missing parentheses ')'." if parenth < 0
raise "Error. Missing parentheses '('." if parenth > 0
end | ruby | def parse(substatement = nil, token_index = 0)
p_token = nil
if substatement
c_token, c_token_value = substatement[token_index]
else
c_token, c_token_value = @scanner.get_token
end
parenth = 0
until c_token.nil?
if substatement
token_index += 1
n_token, n_token_value = substatement[token_index]
else
@scanner.token_index += 1
n_token, n_token_value = @scanner.get_token
end
next if n_token == " "
case c_token
when "and"
unless (n_token =~ /not|statement|\(|\+|-/) || (scanner.token_index == scanner.arguments.size)
raise "Error at column #{scanner.token_index}. \nExpected 'not', 'statement' or '('. Found '#{n_token_value}'"
end
raise "Error at column #{scanner.token_index}. \n Expression cannot start with 'and'" if p_token.nil?
raise "Error at column #{scanner.token_index}. \n #{p_token} cannot be followed by 'and'" if %w[and or].include?(p_token)
when "or"
unless (n_token =~ /not|statement|\(|\+|-/) || (scanner.token_index == scanner.arguments.size)
raise "Error at column #{scanner.token_index}. \nExpected 'not', 'statement', '('. Found '#{n_token_value}'"
end
raise "Error at column #{scanner.token_index}. \n Expression cannot start with 'or'" if p_token.nil?
raise "Error at column #{scanner.token_index}. \n #{p_token} cannot be followed by 'or'" if %w[and or].include?(p_token)
when "not"
unless n_token =~ /statement|\(|not|\+|-/
raise "Error at column #{scanner.token_index}. \nExpected 'statement' or '('. Found '#{n_token_value}'"
end
when "statement"
if c_token_value.is_a? Array
raise "Error at column #{scanner.token_index}\nError, cannot define '[' in a '[...]' block." if substatement
parse(c_token_value, 0)
end
if c_token_value =~ /!=/
c_token_value = c_token_value.gsub("!=", "=")
@execution_stack << {"not" => "not"}
end
if !n_token.nil? && !n_token.match(/and|or|\)/)
raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', ')'. Found '#{n_token_value}'"
end
when "+"
if !n_token.nil? && !n_token.match(/and|or|\)/)
raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', ')'. Found '#{n_token_value}'"
end
when "-"
if !n_token.nil? && !n_token.match(/and|or|\)/)
raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', ')'. Found '#{n_token_value}'"
end
when ")"
if !n_token.nil? && !n_token =~ /|and|or|not|\(/
raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', 'not' or '('. Found '#{n_token_value}'"
end
parenth += 1
when "("
unless n_token =~ /statement|not|\(|\+|-/
raise "Error at column #{scanner.token_index}. \nExpected 'statement', '(', not. Found '#{n_token_value}'"
end
parenth -= 1
else
raise "Unexpected token found at column #{scanner.token_index}. '#{c_token_value}'"
end
unless n_token == " " || substatement
@execution_stack << {c_token => c_token_value}
end
p_token = c_token
c_token = n_token
c_token_value = n_token_value
end
return if substatement
raise "Error. Missing parentheses ')'." if parenth < 0
raise "Error. Missing parentheses '('." if parenth > 0
end | [
"def",
"parse",
"(",
"substatement",
"=",
"nil",
",",
"token_index",
"=",
"0",
")",
"p_token",
"=",
"nil",
"if",
"substatement",
"c_token",
",",
"c_token_value",
"=",
"substatement",
"[",
"token_index",
"]",
"else",
"c_token",
",",
"c_token_value",
"=",
"@scanner",
".",
"get_token",
"end",
"parenth",
"=",
"0",
"until",
"c_token",
".",
"nil?",
"if",
"substatement",
"token_index",
"+=",
"1",
"n_token",
",",
"n_token_value",
"=",
"substatement",
"[",
"token_index",
"]",
"else",
"@scanner",
".",
"token_index",
"+=",
"1",
"n_token",
",",
"n_token_value",
"=",
"@scanner",
".",
"get_token",
"end",
"next",
"if",
"n_token",
"==",
"\" \"",
"case",
"c_token",
"when",
"\"and\"",
"unless",
"(",
"n_token",
"=~",
"/",
"\\(",
"\\+",
"/",
")",
"||",
"(",
"scanner",
".",
"token_index",
"==",
"scanner",
".",
"arguments",
".",
"size",
")",
"raise",
"\"Error at column #{scanner.token_index}. \\nExpected 'not', 'statement' or '('. Found '#{n_token_value}'\"",
"end",
"raise",
"\"Error at column #{scanner.token_index}. \\n Expression cannot start with 'and'\"",
"if",
"p_token",
".",
"nil?",
"raise",
"\"Error at column #{scanner.token_index}. \\n #{p_token} cannot be followed by 'and'\"",
"if",
"%w[",
"and",
"or",
"]",
".",
"include?",
"(",
"p_token",
")",
"when",
"\"or\"",
"unless",
"(",
"n_token",
"=~",
"/",
"\\(",
"\\+",
"/",
")",
"||",
"(",
"scanner",
".",
"token_index",
"==",
"scanner",
".",
"arguments",
".",
"size",
")",
"raise",
"\"Error at column #{scanner.token_index}. \\nExpected 'not', 'statement', '('. Found '#{n_token_value}'\"",
"end",
"raise",
"\"Error at column #{scanner.token_index}. \\n Expression cannot start with 'or'\"",
"if",
"p_token",
".",
"nil?",
"raise",
"\"Error at column #{scanner.token_index}. \\n #{p_token} cannot be followed by 'or'\"",
"if",
"%w[",
"and",
"or",
"]",
".",
"include?",
"(",
"p_token",
")",
"when",
"\"not\"",
"unless",
"n_token",
"=~",
"/",
"\\(",
"\\+",
"/",
"raise",
"\"Error at column #{scanner.token_index}. \\nExpected 'statement' or '('. Found '#{n_token_value}'\"",
"end",
"when",
"\"statement\"",
"if",
"c_token_value",
".",
"is_a?",
"Array",
"raise",
"\"Error at column #{scanner.token_index}\\nError, cannot define '[' in a '[...]' block.\"",
"if",
"substatement",
"parse",
"(",
"c_token_value",
",",
"0",
")",
"end",
"if",
"c_token_value",
"=~",
"/",
"/",
"c_token_value",
"=",
"c_token_value",
".",
"gsub",
"(",
"\"!=\"",
",",
"\"=\"",
")",
"@execution_stack",
"<<",
"{",
"\"not\"",
"=>",
"\"not\"",
"}",
"end",
"if",
"!",
"n_token",
".",
"nil?",
"&&",
"!",
"n_token",
".",
"match",
"(",
"/",
"\\)",
"/",
")",
"raise",
"\"Error at column #{scanner.token_index}. \\nExpected 'and', 'or', ')'. Found '#{n_token_value}'\"",
"end",
"when",
"\"+\"",
"if",
"!",
"n_token",
".",
"nil?",
"&&",
"!",
"n_token",
".",
"match",
"(",
"/",
"\\)",
"/",
")",
"raise",
"\"Error at column #{scanner.token_index}. \\nExpected 'and', 'or', ')'. Found '#{n_token_value}'\"",
"end",
"when",
"\"-\"",
"if",
"!",
"n_token",
".",
"nil?",
"&&",
"!",
"n_token",
".",
"match",
"(",
"/",
"\\)",
"/",
")",
"raise",
"\"Error at column #{scanner.token_index}. \\nExpected 'and', 'or', ')'. Found '#{n_token_value}'\"",
"end",
"when",
"\")\"",
"if",
"!",
"n_token",
".",
"nil?",
"&&",
"!",
"n_token",
"=~",
"/",
"\\(",
"/",
"raise",
"\"Error at column #{scanner.token_index}. \\nExpected 'and', 'or', 'not' or '('. Found '#{n_token_value}'\"",
"end",
"parenth",
"+=",
"1",
"when",
"\"(\"",
"unless",
"n_token",
"=~",
"/",
"\\(",
"\\+",
"/",
"raise",
"\"Error at column #{scanner.token_index}. \\nExpected 'statement', '(', not. Found '#{n_token_value}'\"",
"end",
"parenth",
"-=",
"1",
"else",
"raise",
"\"Unexpected token found at column #{scanner.token_index}. '#{c_token_value}'\"",
"end",
"unless",
"n_token",
"==",
"\" \"",
"||",
"substatement",
"@execution_stack",
"<<",
"{",
"c_token",
"=>",
"c_token_value",
"}",
"end",
"p_token",
"=",
"c_token",
"c_token",
"=",
"n_token",
"c_token_value",
"=",
"n_token_value",
"end",
"return",
"if",
"substatement",
"raise",
"\"Error. Missing parentheses ')'.\"",
"if",
"parenth",
"<",
"0",
"raise",
"\"Error. Missing parentheses '('.\"",
"if",
"parenth",
">",
"0",
"end"
] | Parse the input string, one token at a time a contruct the call stack | [
"Parse",
"the",
"input",
"string",
"one",
"token",
"at",
"a",
"time",
"a",
"contruct",
"the",
"call",
"stack"
] | 3d96a6bb6d090d3fcb956e5d8aef96b493034115 | https://github.com/ploubser/JSON-Grep/blob/3d96a6bb6d090d3fcb956e5d8aef96b493034115/lib/parser/parser.rb#L13-L114 |
Subsets and Splits